SDK 參考
完整的 @beeuni/sdk API — 客戶端方法、模組、輪次和分發。
工件
從 @beeuni/sdk 匯入 listArtifacts、createArtifact 和 updateArtifact,用於列出、釋出和更新文件與網頁。通過 readArtifactFile 和 saveArtifact 讀取、儲存內容。分享及命令列用法見工件。
setProjectSpaceTabs(projectId, spaceId, tabs) 按順序替換 Chat 之後的標籤頁,最多 20 個。服務端會檢查編輯權限和每個標籤頁的引用。
訂閱賬號資源新增 usage、usage_checked_at 和 provider_account 欄位。refreshAccountSecretUsage(accountId, secretId) 讀取服務商提供的套餐用量,API key 賬號沒有訂閱用量。
此頁面介紹完整的 @beeuni/sdk API 介面:每個客戶端方法、不依賴框架的模組、輪次輔助函式,以及軟體包的釋出方式。使用 SDK 開始,並參閱 Sessions 深入瞭解對話生命週期。
成果資料夾 API
用 listArtifactFolders、createArtifactFolder、updateArtifactFolder 和 deleteArtifactFolder 管理資料夾。React 應用程式可使用 useArtifactFolders 和 useArtifactFolderMutations。用 parent_folder_id 指定上層資料夾,用 folder_id 指定成果所在的資料夾。設為 null 表示放在最外層。
呼叫 listArtifacts 時,傳入 folder_id: 'root' 只會列出未放入資料夾的成果。省略 folder_id 時,不依資料夾篩選。
AI 代理清單和語音輸入
開啟 channels 後,須以使用者登入權杖或個人存取權杖使用 AI 代理清單。p.agentDirectory.list() 會列出你可以傳訊息的 AI 代理,p.spaces.dm(name) 則會開啟與該代理的私訊。要用 p.agentDirectory.setPaused(name, paused) 暫停或恢復 AI 代理,還需要更新該代理觸發器的權限。
p.dictation.info() 會傳回語音輸入是否可用、每分鐘價格和錄音上限。p.dictation.transcribe(audio) 將錄音轉成文字,並傳回時間長度和扣除的積分;不會傳送訊息。
客戶端
createBeeuni(config) 返回一個客戶端。每個方法都是對平臺 API 的型別化呼叫。project(id) 和 session(pid, sid) 控制代碼會繫結 ID,因此無需重複傳入。
const beeuni = createBeeuni({ backendUrl, getToken });
beeuni.accounts; // account / team operations
beeuni.accountInvites; // invite accept/decline by token alone
beeuni.projects; // top-level project operations
beeuni.connectors; // Connector calls scoped by an agent-minted token
beeuni.connector(slug); // one connector in the token's scope → see p.connector(slug)
beeuni.project(id); // id-bound project handle
beeuni.session(pid, sid); // id-bound session handle → see Sessions
beeuni.github; // GitHub App install + repo linking (account-scoped)
beeuni.billing; // credits, subscription, tier, transactions
beeuni.sandboxShares; // public share links for a sandbox port
beeuni.connectStatus; // easy-connect status
beeuni.validateToken; // pasted-API-key check
beeuni.config; // platform config in effect
beeuni.runtime(); // runtime REST compatibility client
帳戶 — beeuni.accounts
| 方法 | 說明 |
|---|---|
list() · get(accountId) |
所屬帳戶 · 單個帳戶 |
create({ name }) · updateName(accountId, name) |
建立 · 重新命名帳戶 |
branding.get(accountId) · branding.update(accountId, { app_name }) · branding.uploadAsset(accountId, kind, file) · branding.removeAsset(accountId, kind) · branding.reset(accountId) |
組織品牌設定(Enterprise):自定義徽標、圖示、favicon 和產品名稱;kind 為 logo · icon · favicon,或深色方案變體的 logo_dark · icon_dark · favicon_dark |
members(accountId) · invite(accountId, input) |
列出成員 · 邀請成員 |
updateMemberRole(accountId, userId, role) · removeMember(accountId, userId) |
分配帳戶角色 · 移除成員 |
invites(accountId) |
待處理邀請 |
cancelInvite(accountId, inviteId) · resendInvite(accountId, inviteId) |
取消 · 重新發送待處理邀請 |
leave(accountId) |
離開帳戶 |
accounts.tokens 會簽發帳戶範圍的 API 金鑰(beeuni_pat_...)。完整權杖模型請參閱 SDK 身分驗證。
| 方法 | 說明 |
|---|---|
tokens.list(accountId?, options?) |
列出 API 金鑰——整個帳戶的金鑰,或使用 { mine: true } 僅列出你自己的金鑰 |
tokens.create(input) |
簽發一個金鑰——{ accountId?, name, expiresAt?, projectId? } |
tokens.revoke(tokenId, accountId?) |
撤銷一個金鑰 |
accounts.audit 是企業審計日誌。它將經過身分驗證的 API 請求與語義對話、連接器、審批和電腦事件結合起來。
| 方法 | 說明 |
|---|---|
audit.log(accountId, filters?) |
按專案、對話、執行者、來源、結果、請求、關聯、資源、操作或時間列出事件 |
audit.export(accountId, filters?) |
將相同的篩選事件流匯出為 CSV 或 JSONL |
audit.webhooks.list/create/update/remove(...) |
管理用於集中式事件流的已簽名 SIEM webhook |
每個事件都包含 project_id、session_id、actor_type、source、outcome、request_id、trace_id 和 correlation_id(如果操作提供了這些資訊)。API 不會在集中式事件中儲存請求正文、提示詞、機密、憑據或原始連接器引數。連接器事件可以包含長度受限的引數預覽,其中會對疑似憑據的欄位和無法解析的資料進行脫敏。
存取分配
Beeuni 只有一種授權記錄:分配。它將一個主體(user、group、service_account 或 pending)繫結到一個角色和一個範圍(account 或一個 project),也可以進一步限定到一個物件(agent、skill、secret、app 或 trigger),並可選擇攜帶一個 expires_at。群組存取、按資源存取和自定義角色繫結都屬於分配。模型詳見 帳戶與存取。
規範的 REST 介面如下:
| 方法 + 路徑 | 功能 |
|---|---|
GET /v1/accounts/{accountId}/iam/assignments |
列出分配,可按主體、範圍、物件或角色篩選 |
POST /v1/accounts/{accountId}/iam/assignments |
建立一個分配 |
DELETE /v1/accounts/{accountId}/iam/assignments/{assignmentId} |
撤銷一個分配 |
GET /v1/accounts/{accountId}/iam/permissions |
以資料形式提供權限目錄 |
GET /v1/accounts/{accountId}/iam/roles · …/roles/{roleId}/permissions |
角色 · 單個角色的權限 |
SDK 將它們公開為 listAssignments、createAssignment、revokeAssignment 和 listPermissions。目錄行包含 action、scope_type、resource_type、delegable、description、area、level 和 implies——請讀取這些欄位,而不是硬編碼操作字串。
分配自定義角色需要帳戶的 rbac 權限;沒有該權限時,路由會返回帶有 code: "entitlement_required" 的 402。
帳戶邀請 — beeuni.accountInvites
僅憑邀請權杖即可存取——受邀者可能尚未成為成員。
| 方法 | 說明 |
|---|---|
listMine() |
列出傳送到你郵箱的所有待處理、未過期邀請,並包含工作區及其授予的任何專案 |
describe(inviteId) · accept(inviteId) · decline(inviteId) |
預覽 · 接受 · 拒絕邀請 |
專案 — beeuni.projects
| 方法 | 說明 |
|---|---|
list() · listForAccount(accountId) |
你的專案 · 帳戶中的專案 |
get(id) · detail(id) |
摘要 · 完整詳情 |
create(input) · createRepo(input) |
從現有 repo_url · 新建空 GitHub 儲存庫 |
provision(input) |
在新的 Beeuni 管理儲存庫上建立專案,並使用入門模板初始化——{ name, account_id?, seed_starter?, starter_template?, idempotency_key? } |
update(id, input) · archive(id) |
更新設定 · 歸檔 |
llmCatalog(id) · modelPicker(id) |
完整 · 緊湊模型目錄,用於選擇器 |
sandboxTemplates(id) · sandboxHealth(id) |
沙箱構建模板 · 構建健康狀況 |
sessions(id) · createSession(id, input?) |
列出可見對話 · 建立對話 |
provision 會建立新專案;它不會啟動現有專案的沙箱。請改為啟動對話——參閱 Sessions。
如果請求可能重複傳送,例如重新整理頁面、開啟第二個標籤頁或在超時後重試,請提供 idempotency_key(冪等鍵)。不提供時,每次呼叫 provision 都會新建託管儲存庫和專案。同一次建立操作應始終使用相同的冪等鍵,重複請求會返回首次建立的專案(201、相同的 project_id、push_token: null)。
冪等鍵用於識別建立操作,不用於比較請求內容。使用同一個鍵提交不同的 name,仍會返回第一個專案並忽略新名稱。建立另一個專案時,請使用新的冪等鍵。不提供冪等鍵時,即使名稱相同,也可以建立第二個專案。
如果重複請求到達時,首次建立尚未完成,會返回 409 和 code: 'provision_in_flight',不返回 project_id。首次建立仍可能回滾,請使用相同的冪等鍵重試。
project(id).sessions.list({ scope: 'project' }) 是面向具有專案管理權限的呼叫者的生命週期清單。它會增加可存取但不可用、預熱中和軟刪除的對話,並附帶所有權和執行時狀態後設資料。兩種列表範圍都會省略呼叫者無法開啟的所有對話。
sessions.list 和 sessions.listPage 也接受層級和歸因篩選條件。不提供這些條件時,列表保持扁平且不變。
| 選項 | 說明 |
|---|---|
parent: 'root' |
僅頂層對話。每行都包含 child_count。 |
parent: '<sessionId>' |
該對話的子對話,按最新優先排序。 |
startedBy: 'me' | 'others' | 'automated' |
按相對於呼叫者的 initiator 篩選。 |
q |
在呼叫者可以開啟的每個對話中,對標題、啟動器標籤、觸發器 slug 和對話 ID 字首執行不區分大小寫的搜尋。使用 parent: 'root' 時,通過子對話匹配的根對話具有 search_match: 'child'。 |
每個對話行都有 parent_session_id 和 initiator({ type: 'member' | 'trigger' | 'channel' | 'api' | 'system', id, label })。initiator 標識啟動整個執行的人員;子對話會複製其父對話的值。sessionParentId(session) 會讀取 parent_session_id,然後讀取舊版 metadata.spawned_by_session。游標僅對簽發它的篩選條件集有效。
GitHub — beeuni.github
帳戶範圍的 GitHub App 安裝和儲存庫連結,而非專案範圍的操作。
| 方法 | 說明 |
|---|---|
getInstallation(accountId) · listInstallations(accountId) |
此帳戶的安裝 · 使用者可存取的安裝 |
saveInstallation(input) · deleteInstallation(accountId, installationId?) |
記錄 · 解除安裝關聯 |
listLinkableInstallations(input) |
已授權的 GitHub 使用者可關聯的安裝;每個條目包含 linked_to_other_accounts,表示持有該安裝的其他 Beeuni 帳戶數量,絕不包含其名稱 |
listRepositories(accountId, installationId?) · listRepositoryBranches(...) |
安裝可存取的儲存庫 · 分支和 GitHub 預設分支 |
linkRepository(input) |
使用已授權的 GitHub 安裝將儲存庫匯入為專案。 |
replaceProjectRepository({ project_id, repo_url, expected_repo_url, github_token }) |
替換現有專案的 GitHub 儲存庫。使用具有 Contents 讀寫權限的 github_token,或使用 installation_id 加上臨時的 github_user_token 來驗證組織管理員權限,並通過 GitHub App 僅授權此儲存庫。copy_shared_secrets_from_project_id 加上 copy_shared_secret_identifiers 會在同一事務中複製選定的共享執行時金鑰。過期的 expected_repo_url 返回 409。舊儲存庫仍保留在 GitHub 上。新對話使用替換後的儲存庫;現有對話保留其檢出內容。 |
此列表僅包含真實的帳戶連線。“Beeuni managed”不在其中——它是下文的例項後端。
計費 — beeuni.billing
讀取額度、訂閱、套餐等級和交易歷史。通過 Beeuni 結賬和賬單管理處理付款及額度購買。
| 方法 | 說明 |
|---|---|
accountState(accountId?) · accountStateMinimal(accountId?) |
完整 · 最簡計費狀態 |
transactions(params?) · transactionsSummary(params?) |
歷史記錄 · 彙總總額 |
creditBreakdown(accountId?) · usageHistory(params?) |
按來源劃分的額度餘額 · 隨時間變化的用量 |
sessionCosts.list(options?) · sessionCosts.get(sessionId, options?) |
分頁對話費用記錄 · 單個對話的詳細賬目 |
tierConfigurations() |
可用套餐等級 |
checkout.createSession(input) · checkout.confirmSession(sessionId, accountId?) |
已棄用。 以 ENDPOINT_RETIRED 拒絕。將在下一個主要版本中移除。 |
subscription.createPortalSession(...) · subscription.cancel(...) · subscription.reactivate(...) |
開啟客戶門戶 · 取消 · 重新啟用 |
subscription.cancelScheduledChange(...) · prorationPreview(...) |
取消 · 預覽套餐變更 |
subscription.scheduleDowngrade(...) |
已棄用。 以 ENDPOINT_RETIRED 拒絕。請在客戶門戶中更改套餐。將在下一個主要版本中移除。 |
credits.purchase(input) · credits.autoTopupSettings(...) · credits.configureAutoTopup(...) |
一次性購買 · 讀取 · 設定自動充值 |
sessionCosts.list() 接受 accountId、projectId、limit 和 offset。
每行合併已結算的 LLM 費用和已計費的沙箱計算費用。
sessionCosts.get() 額外提供模型用量及區分 LLM/計算費用的賬目。
列表包含無關聯對話費用的對賬總額。
沙箱共享 — beeuni.sandboxShares
針對一個對外開放的沙箱埠的公開共享連結。作用範圍是沙箱,而非專案。
| 方法 | 說明 |
|---|---|
list(sandboxId) |
有效共享連結 |
create(input) |
建立一個 — { sandboxId, port, ttl?, label? } |
revoke(sandboxId, token) |
撤銷一個 |
通知 — beeuni.notifications
呼叫者在所有帳戶和專案中的通知。每位已登入使用者都有一個收件箱、一條偏好設定記錄,以及其瀏覽器的 Web Push 訂閱。每個方法都需要個人憑據:服務帳戶會收到 403。
通知對已登入使用者開放。通過通知偏好和對話關注設定控制接收方式。
const page = await beeuni.notifications.list({ limit: 20 });
await beeuni.notifications.markRead({ ids: [page.notifications[0].id] });
await beeuni.notifications.updatePreferences({ kinds: { turn_done: { push: false } } });
| 方法 | 說明 |
|---|---|
list({ limit?, before? }, { signal? }) |
最新一頁:{ notifications, unread_count, next_before }。limit 為 1 到 50(預設 20)。將 next_before 作為 before 傳入以獲取下一頁。呼叫者不再可見的記錄會被排除。失敗時不會呼叫宿主錯誤處理程序。 |
markRead({ ids }) · markRead({ all: true }) · markRead({ sessionId }) |
將 1 到 100 條記錄、所有記錄或某個對話的所有記錄標為已讀。僅更改呼叫者的記錄。返回 { updated, unread_count }。 |
preferences() · updatePreferences({ kinds }) |
讀取 · 更改每種型別的推送和電子郵件選項。返回 { kinds, email_available }。補丁僅更改其中指定的型別和渠道。 |
webPushPublicKey() |
{ public_key }:用於 pushManager.subscribe 的 applicationServerKey |
registerWebPushSubscription({ endpoint, keys }) |
向此瀏覽器傳送推送。需要瀏覽器登入:個人權杖會收到 403。未知推送服務上的端點會收到 400。 |
unregisterWebPushSubscription(endpoint, { signal? }) |
停止向此瀏覽器推送。返回 { deleted }。 |
registerDeviceToken(input) · unregisterDeviceToken(token, { signal? }) |
註冊 · 移除原生應用的 Expo 推送權杖 |
型別(InboxNotificationKind,列於 INBOX_NOTIFICATION_KINDS):
| 型別 | 傳送時機 | 推送 | 電子郵件(預設) |
|---|---|---|---|
turn_done |
你發起或關注的輪次結束 | 開啟 | 關閉 |
turn_error |
該輪次因錯誤而結束 | 開啟 | 開啟,彙總傳送 |
question |
代理提出問題 | 開啟 | 開啟,彙總傳送 |
permission |
代理請求權限 | 開啟 | 關閉 |
shared |
有人與你共享了對話 | 開啟 | 開啟,彙總傳送 |
automation_failed |
你關注的自動化開始失敗 | 開啟 | 開啟,立即傳送 |
automation_recovered |
該自動化恢復正常 | 開啟 | 關閉 |
DEFAULT_NOTIFICATION_PREFERENCES 儲存這些預設值。收件箱記錄始終會寫入;偏好設定僅決定推送和電子郵件。彙總郵件列出收到 15 分鐘後仍未讀的記錄,每小時最多傳送一封。當 email_available 為 false 時,隱藏電子郵件列。
每條記錄的 url 會開啟其主題。其 ?notification=<id> 查詢引數讓頁面將該記錄標為已讀。
對話控制代碼包含呼叫者對單個對話的關注狀態:
| 方法 | 說明 |
|---|---|
session(pid, sid).watch() |
{ watching }:呼叫者是否會收到此對話的通知 |
session(pid, sid).setWatch(watching) |
false 為呼叫者靜音此對話,true 重新關注它。向對話傳送提示會關注該對話,但絕不會取消靜音。 |
session(pid, sid).presence({ tab_id, active, alerts? }, { keepalive? }) |
報告已開啟的標籤頁。alerts: true 表示標籤頁自行顯示通知,使用期間不再發送手機和 Web Push 提醒。keepalive 允許離線報告在頁面關閉後繼續傳送。 |
專案控制代碼 — beeuni.project(id)
繫結專案 ID;所有子資源都依附於它。
const p = beeuni.project(projectId);
await p.detail();
await p.update({ name });
await p.llmCatalog();
| 方法 | 用途 |
|---|---|
get · detail · update · archive |
讀取 · 完整詳情 · 更新 · 歸檔 |
llmCatalog · modelPicker · sandboxHealth |
讀取模型和沙箱構建 |
onboardingComplete |
將專案入門引導標記為已完成 |
validateManifest(raw) |
在服務端驗證 beeuni.yaml(或舊版 beeuni.toml)清單 |
gitToken() |
生成新的限定作用域的 git 推送權杖(自帶儲存庫使用 409) |
setAgentScope(agentName, scope) |
在清單中設定代理允許使用的金鑰和連接器——這是第二重繫結,不是角色 |
p.skills — 專案技能
p.skills.create({ name, description?, body? }) 直接向預設分支提交技能檔案,
不需要呼叫模型。body 為 Markdown 正文;留空或省略時使用起始模板。
p.skills.remove({ folder: 'skills/my-skill', confirm: true }) 刪除選定的
專案技能目錄,包括對該目錄的修改,並移除相應的註冊資訊和 agent 授權。
共享工具、依賴和其他技能會保留,託管的系統技能不能刪除。
此操作需要同時具備技能和 agent 的寫入權限,且必須傳入 confirm: true。
p.keys — 專案 API 金鑰
p.keys.list() 列出金鑰,不回傳金鑰值。p.keys.create({ name, actsAs?, scopes?, expiresAt? }) 只在建立時回傳金鑰值。p.keys.revoke(keyId) 撤銷金鑰;傳入 { deleteRevoked: true } 可刪除已撤銷的金鑰。金鑰可以代表自己、代理或機器人。完整權限只涵蓋支援這類金鑰的專案端點,也不能超過該身分目前擁有的權限。具備完整權限或 project.session.start 的自訂金鑰可以建立工作階段,並向該身分有權使用的任何工作階段傳送訊息。
使用專案金鑰驗證 Beeuni 用戶端後,呼叫 p.sessions.create({ agent_name: "worker" })。如需附上第一則訊息,可傳入 initial_prompt。向可存取的工作階段傳送訊息時,使用與其他憑證相同的訊息佇列。
import { mintWireMessageId } from "@beeuni/sdk";
const { session_id } = await p.sessions.create({ agent_name: "worker" });
await beeuni.session(projectId, session_id).prompts.create({
clientMessageId: crypto.randomUUID(),
messageId: mintWireMessageId(),
remintOnDelivery: true,
parts: [{ type: "text", text: "Keep it brief." }],
});
p.tokens — 專案 CLI 權杖
建立對話時自動生成,作為 BEEUNI_TOKEN;也可手動生成。
| 方法 | 用途 |
|---|---|
list() |
專案 API 金鑰 |
create(input?) |
生成新金鑰 |
revoke(tokenId) |
撤銷金鑰 |
p.setupLinks — 代理生成的設定連結
使用者開啟此連結即可輸入金鑰或連線應用,無需擁有完整的 專案存取權限。
| 方法 | 用途 |
|---|---|
requestSecret(input) · requestConnector(input) |
用於收集金鑰的連結 · 連線應用 |
p.apps — Apps(釋出、機器、卷)
由專案功能 apps 控制。指南:SDK → Apps。
| 方法 | 用途 |
|---|---|
list() · get(appId) · create(input) · update(appId, input) · remove(appId) |
資源清單和生命週期;create 接受 uses,update 還接受 labels |
deployments.* · artifacts.* · access.* · rollback · start · stop |
部署、構件、存取策略、流量和執行時 |
machines.list/start/stop/restart/destroy · scale(appId, count) · exec(appId, input) |
每個程序組的機器;exec 需要 project.app.admin |
volumes.list/create/update/destroy/snapshots/snapshot/restore/fork |
持久卷、每日快照、恢復、分叉 |
token(appId) |
有效期為 15 分鐘的登入權杖;應用不支援 member_tokens 時返回 409 app_capability_unsupported |
p.secrets — 專案金鑰
| 方法 | 用途 |
|---|---|
list() · upsert(input) |
列出後設資料 · 建立或更新只寫值和交付策略 |
setStrategy(identifier, strategy, options?) |
更改暴露方式及其主機列表 |
broker(identifier, request) |
執行經對話授權、受策略約束的 HTTPS 請求 |
remove(identifier) |
刪除金鑰 |
setPersonal(name, value) · removePersonal(name) |
設定 · 移除使用者級覆蓋值 |
setGitCredential(input) |
設定 git 身分驗證憑據 |
預設使用 strategy: runtime 和 consumer: sandbox,把金鑰明文以環境變數提供給對話。
使用 strategy: egress 和 consumer: network 時,對話只會取得金鑰代碼。Beeuni 在沙盒外將它換成實際值,僅用於策略中列出的 HTTPS 主機。
broker 策略不會將金鑰明文寫入對話環境。獲授權的對話仍可讀取網站登入資訊。broker(...) 需要限定於該對話的權杖和有效的對話代碼。
p.access — 專案分配、邀請、請求
這裡的每個方法都讀取或寫入此專案作用域內的分配。專案
角色為 manager 和 member。
| 方法 | 用途 |
|---|---|
list() · invite(email, role) |
擁有存取權限的主體 · 邀請使用者 |
update(userId, role) · revoke(userId) |
分配專案角色 · 撤銷分配 |
pendingInvites() · requests() |
未完成的邀請 · 待處理的存取請求 |
resendInvite(inviteId) · revokeInvite(inviteId) · approveRequest(id) · rejectRequest(id) |
重新發送/撤銷邀請 · 批准/拒絕請求 |
groupGrants() · attachGroupGrant(...) · updateGroupGrant(...) · detachGroupGrant(...) |
相同的分配,但主體為 group |
p.access.resourceGrants 是物件分配檢視:它將
主體的範圍限定為專案中的一個物件,而不是整個專案。Beeuni
目前對代理和技能強制執行物件分配。代理預設不開放
——只有分配中指定了成員本人或其所屬的某個
組,該成員才能存取它。物件分配本身不賦予任何權限,對
專案管理員和成員施加同樣的限制。
| 方法 | 用途 |
|---|---|
resourceGrants.list() |
此專案中的物件分配 |
resourceGrants.create(input) |
將一個物件分配給使用者或組 |
resourceGrants.remove(grantId) |
撤銷一項物件分配 |
p.connector(slug) — 單個連接器
| 方法 | 用途 |
|---|---|
run(action, args, options?) |
操作的輸出;丟擲 ConnectorCallError 或 ConnectorApprovalPendingError——參見錯誤 |
call(action, args, options?) |
原始呼叫結果;202 以 ok: false 完成解析 |
describe() · describe(action) |
帶輸入和輸出模式的連接器 · 單個操作 |
accounts() |
此呼叫者可用來執行它的帳戶,預設帳戶排在首位 |
paginate(action, args, { next, maxPages? }) |
遍歷每頁輸出的非同步迭代器;頁數超過 maxPages(預設 100)時丟擲帶有 nextArgs 的 ConnectorPageLimitError——參見分頁 |
uploadAttachment(content, input) |
將 connector 設為此 slug 的 p.connectors.uploadAttachment |
options:account、approvalContext、timeoutMs(預設 90 000)、signal。使用來自 beeuni connectors types 的檔案後,引數和輸出都具有型別。
p.connectors — 工具連接器
| 方法 | 用途 |
|---|---|
catalog() · tools() |
可呼叫的 Connector 目錄 · 扁平化的 <connector>.<action> 工具 |
search(query, options?) · describe(tool) |
查詢 · 檢查單個可呼叫工具 |
call(tool, args?, options?) |
通過服務端閘道器呼叫一個 <connector>.<action> 工具。options.account 指定以哪個帳戶執行——見下文。 |
accounts(slug) |
此呼叫者可用來呼叫 slug 的帳戶,預設帳戶排在首位——即 options.account 的匹配物件 |
uploadAttachment(content, input) |
為 input.connector 暫存位元組;返回 ref({ $beeuni_attachment }),供放入後續呼叫的引數中——參見附加檔案 |
list() · config(connectorId) |
已設定的連接器 · 單個連接器的設定 |
create(input) |
新增連接器 |
auth.discover(input) |
從 OpenAPI 規範、Postman 集合或端點預覽身分驗證 |
remove(connectorId) · sync() |
刪除連接器 · 重新同步連接器 |
setName(connectorId, name) · setSensitive(connectorId, sensitive) |
重新命名 · 標記為敏感(額外的審批控制) |
setAuthorizationStrategy(slug, strategy) |
@deprecated。仍會呼叫路由;該路由不執行任何操作,僅返回 {ok:true, deprecated:true},不做任何更改。現在,每個連線上的 owner_type 就是完整的存取規則。 |
setCredentialMode(connectorId, mode) · setCredential(connectorId, input) |
切換來源 · 設定憑據值 |
policies.get(connectorId) · policies.set(connectorId, policies) |
讀取 · 替換其工具策略 |
policySets.list(slug) · policySets.upsert(slug, name, input?) |
列出 · 建立或更新命名規則集 |
policySets.rename(slug, name, newName) · policySets.remove(slug, name) |
重新命名 · 刪除規則集 |
agents(slug) · rulesMatrix() |
檢視代理及其規則集 · 檢視所有代理與連接器的規則 |
setOAuth2ClientCredentials(slug, input) |
設定共享帳戶的 OAuth2 客戶端憑據 |
connections.list() · connections.reconcile(input) |
列出 · 建立/更新已連線的帳戶 |
connections.updateCredential(connectionId, input) |
輪換連線憑據 |
connections.revoke(connectionId) · connections.activate(connectionId) |
停用 · 恢復連線 |
connections.setDefault(connectionId) |
將其設為所屬所有者作用域的預設連線 |
connections.rename(connectionId, label) |
僅更改標籤;帳戶仍保持授權。每個連線都攜帶 connected_as,即其獲得授權時所用的身分。 |
p.connectors.discover 提供預設連接器目錄,可瀏覽 Beeuni 應用與渠道、廠商 MCP 服務和其他應用整合。
| 方法 | 用途 |
|---|---|
discover.list(query?, cursor?) · discover.detail(id) |
搜尋 OpenAPI/MCP/GraphQL/CLI 條目 · 單個條目的詳情 |
discover.sections(options?) |
瀏覽分類和熱門條目 |
discover.tools(id, way?) |
檢視某種連線方式提供的工具 |
discover.install(input) |
將目錄條目新增到專案 |
連接器定義工具、提供商應用和策略。connections
儲存其已連線的帳戶——一個連接器可以並列持有多個帳戶。
對話可以通過 connector_bindings: { alias: { connection_id } } 為每次呼叫固定一個帳戶,
也可以通過 call(tool, args, { account }) 為單次呼叫指定一個帳戶。憑據始終加密儲存,
並按請求解析。
請通過 connections 管理連線授權。已廢棄的
authorizations 和 profiles 名稱不屬於當前 SDK 介面。
帳戶與呼叫時檢查
每個連線都有一個 owner_type:project(共享——連接器授予的任何人都可存取,
包括使用者或服務帳戶)或 member(私有——只有其所有者可存取,且只能在私有對話中存取;服務帳戶永遠無法存取)。共享帳戶可以進一步限制到群組和人員:
connections.list() 在 shared_with 中返回其授權範圍,而
connectionSharedWithEveryone(connection) 會回答專案中的所有人是否都可以使用它。受限帳戶對其指定的人員遵循私有規則,而 usable: false 會標記一個帳戶,使呼叫者只能看到並管理它。使用 createAssignment / revokeAssignment 授予或撤銷權限
(object: { type: 'connection', id })——參見
選擇誰可以使用共享帳戶。
p.connectors.accounts(slug) 列出呼叫者可以存取的所有帳戶,
預設帳戶排在首位:
const accounts = await beeuni.project(projectId).connectors.accounts('stripe-read');
// [{ connection_id, label, owner_type, is_default }, ...]
await beeuni.project(projectId).connectors.call(
'stripe-read.get_balance',
{},
{ account: 'My Stripe' }, // a connection id, a label, or the words `me` / `project`
);
未指定帳戶的呼叫會先解析為呼叫者自己的預設私有帳戶,然後解析為專案的預設共享帳戶。無法解析的指定帳戶會通過 connector_not_connected 被拒絕——絕不會靜默替換,並且拒絕資訊會列出 requested_account 和 available_accounts。每次成功呼叫都會返回其使用的帳戶:
result.account = { connection_id, label, owner_type }。
現在已不再有建立對話時的連接器檢查。過去,當所需連接器沒有可用連線時,對話會被 409 CONNECTOR_CONNECTION_REQUIRED 拒絕;該拒絕已取消(require_connectors 不再生效——參見
p.sessions)。連接器是否可用改為在呼叫時檢查。呼叫返回 connector_not_connected 時,如果能為呼叫者生成授權連結,響應會包含 connect_url。使用者可點選對話記錄中的連線按鈕開啟該連結,完成授權。
p.policies — 專案策略
| 方法 | 說明 |
|---|---|
list() · set(policies) |
專案策略 · 替換整個策略集 |
p.triggers — cron、Webhook、監控和事件自動化
觸發器會按計劃、通過入站 Webhook、受監控的命令或連接器上的應用事件啟動代理任務。參見 觸發器,瞭解對話策略和負載模板化。
| 方法 | 說明 |
|---|---|
list() |
所有觸發器 |
eventTypes({ connector }) |
連接器可以觸發的應用事件({ provider, app, event_types });未知連接器返回 404;其提供商沒有事件源時返回 409 event_source_unavailable |
create(input) |
建立一個觸發器 |
update(triggerId, input) |
編輯觸發器 |
remove(triggerId) |
刪除觸發器 |
fire(triggerId, { payload?, dryRun? }) |
立即執行,可傳入測試資料;dryRun: true 只檢查過濾條件和渲染後的提示詞,不啟動對話 |
runs(triggerId, options?) |
按時間倒序列出該觸發器的執行記錄 |
projectRuns(options?) |
列出專案內的執行記錄 |
replay(triggerId, runId, options?) |
使用已儲存的資料和當前觸發器設定重新執行 |
setActivation(paused) |
暫停或恢復專案中的所有觸發器 |
create(input) 接受 { name, type: 'cron' | 'webhook' | 'monitor' | 'event', prompt_template, slug?, agent?, model?, enabled?, session_mode?, session_id?, cron?, run_at?, timezone?, max_lateness?, max_runs_per_hour?, max_runs_per_day?, filter?, secret_env?, connector?, event?, event_source?, event_account?, event_config?, session_access? }。其中 name 和 prompt_template 為必填項。
cron/run_at 互斥(type: 'cron');secret_env(Webhook HMAC 金鑰)適用於 type: 'webhook'。
event 觸發器需要 connector(連接器 slug)和 event(來自 eventTypes 的型別 ID)。event_account 為可選項:該連接器的一個共享帳戶的標籤;null 或省略時使用連接器的預設共享帳戶。
eventTypes 和 eventApps 會將介面卡報告為 source;provider 是已棄用的別名。
每個列出的觸發器都包含 event: { connector, account, connected_as, type, config, source, provider, app, status: 'active' | 'needs_connection' | 'error' | 'pending', error, last_event_at } | null。提示範本會讀取事件的 {{ event.data.<field> }},以及 event.id、event.type、event.app、
event.connector 和 event.occurred_at。
session_access 控制誰可以開啟觸發器建立的對話。它是
{ mode: 'private' | 'members' | 'project', memberIds: string[], groupIds: string[] },預設為 private。這項設定儲存在目前的帳戶,不會寫入 beeuni.yaml 清單。只更新
session_access 不會建立 Git 提交。固定的對話會保留自己的共享設定。專案管理員始終可以開啟觸發器建立的對話,包括使用 private 或選定成員存取權限的對話。
session_access 只控制誰可以開啟此觸發器建立的對話,不會改變使用者的角色,也不會授予角色中未允許的權限。參見
帳戶與存取權限。
p.files — 儲存庫檔案(讀取)
只讀存取專案的 Git 樹。要在執行中的對話內讀取和寫入檔案,請使用對話的檔案操作——參見下方模組中的 檔案。
| 方法 | 說明 |
|---|---|
listDirectory({ ref?, path? }) |
一層資料夾:{ entries: [{ path, type, size? }], truncated }。用於構建目錄樹;每個資料夾最多完整返回 5,000 個條目。 |
list(options?) · read(path, ref?) |
路徑下的所有檔案(遞迴),達到 1,000 個時截斷(截斷時響應會攜帶 X-Beeuni-Truncated: 1)· Git 引用處某個檔案的內容 |
search(query, { content?, ref?, limit? }) |
在整個儲存庫中搜索檔名,或使用 content: true 搜尋內容 |
archive(options?) · history(path) |
下載 tarball · 某個檔案的 Git 歷史 |
p.git — 歷史記錄
| 方法 | 說明 |
|---|---|
commits() |
提交日誌 |
commit(sha) · commitDiff(sha) |
某次提交 · 其差異 |
branches() · versionDiff(from, to) |
分支 · 兩個引用之間的差異 |
p.changeRequests — 生命週期與合併
變更請求(CR)用於將對話的工作合併到預設分支。
| 方法 | 說明 |
|---|---|
list() · get(crId) |
未關閉的 CR · 某個 CR |
diff(crId) · mergePreview(crId) |
其差異 · 預覽合併結果 |
open(input) · merge(crId, input?) |
開啟 · 合併 CR |
close(crId, input?) · reopen(crId, input?) |
不合併直接關閉 · 重新開啟已關閉的 CR |
requestChanges(crId, input) |
記錄反饋,可選擇將其傳回發起對話 |
p.sessions — 以及對話控制代碼
| 方法 | 用途 |
|---|---|
list() |
專案的對話 |
create(input?) |
建立對話 |
session(sid) |
對話控制代碼(與 beeuni.session(id, sid) 相同) |
對話控制代碼是執行時的核心 — 參見 對話。
create(input) 接受以連接器連線 slug 為鍵的 connector_bindings。
每個值指定一個 connection_id。它還接受 secrets,用於
縮小後端來源金鑰的範圍。require_connectors 已棄用且
不生效:仍接受該欄位(不會因舊客戶端傳送該欄位而拒絕請求),
但沒有任何邏輯讀取它 — 建立對話時,絕不會因某個連接器
沒有可用帳戶而拒絕對話。參見帳戶與呼叫時
門控。
p.approvals — 連接器審批收件箱
受連接器門控、等待決策的待處理操作 — 為
權限審批體驗提供支援(APPROVE / ASK / BLOCK)。
| 方法 | 用途 |
|---|---|
list(options?) · sessionsNeedingInput(options?) |
待處理審批 · 因等待決策而阻塞的對話 |
resolve(executionId, decision, options?) |
批准或拒絕一項 — decision: 'approve' | 'deny'、options: { note?: string } |
審批可能包含 expires_at。過期後再處理會返回 409,錯誤碼為 expired。
批准前請先檢查呼叫引數。
匯出的 bulkActReviewItems(projectId, { ids, verdict }) 接受原生審批 ID
和連接器呼叫 ID(call:<execution-id>)。連接器呼叫支援 approve 和 reject。
請逐項檢查 results:某一項被拒絕不會阻止其他項處理。updated 和
review_items 只統計原生審批記錄,連接器呼叫是否處理成功以 results 為準。
舊版服務端可能不返回 results 或過期時間。
p.gateway — LLM 可觀測性
此專案模型流量的請求日誌、成本/延遲彙總、預算和閘道器 API 金鑰。
| 方法 | 用途 |
|---|---|
logs(opts?) · log(logId) |
請求日誌條目 · 單個日誌條目 |
overview(days?) · series(days?) · breakdown(days?) · sessions(days?) · errors(days?) |
時間視窗內的彙總、每對話成本和錯誤 |
budgets() · setBudget(input) · deleteBudget(budgetId) |
讀取 · 建立/編輯 · 移除預算 |
keys() · createKey(name) · revokeKey(keyId) |
列出 · 生成 · 撤銷閘道器 API 金鑰 |
playground(prompt, models) |
在最多 6 個模型上運行同一條提示詞 |
routing.get() · routing.set(policy) · routing.reset() |
讀取 · 替換 · 繼承路由策略 |
routing.preview(input) |
解析路由,不呼叫模型 |
路由策略包含預設模型、視覺模型和有序的
回退鏈,每個模型最多嘗試一次;fallbackOn 為
transient 或 any-error。
只有當前模型在返回任何輸出之前失敗,閘道器才會 轉到下一個回退模型:
transient:網路錯誤、超時、任何5xx,或402、403、429。any-error:所有失敗,包括400。
開始輸出後如果失敗,不會再切換模型。使用自己的提供商金鑰(BYOK)時, 預設不會回退到由 Beeuni 計費的模型。只有專案設定的回退鏈中包含這類模型, 且額度充足時,才會切換。每個回退模型使用各自的預設生成引數。
p.channels — Slack / 電子郵件 / 語音
連接器介面,讓代理能夠充當 Slack 應用、電子郵件地址, 或加入即時語音通話。
| 方法 | 用途 |
|---|---|
slack.installation() · slack.mode() · slack.manifest() |
當前安裝 · 模式 · 應用清單 |
slack.connect(input) · slack.disconnect() |
連線 · 斷開連線 |
slack.getFile(url) · slack.uploadFile(input) |
通過伺服器代理下載 · 上傳檔案 |
email.installation(connectorSlug?) · email.mode() |
當前安裝 · 模式 |
email.connect(input) · email.disconnect(...) · email.updatePolicy(input) |
連線 · 斷開連線 · 更新發送/回覆策略 |
voice.setBotName(name) |
在進行中的通話中重新命名機器人 |
p.modelDefaults — 預設模型偏好設定
帳戶、代理和專案範圍的模型預設設定,由閘道器解析。
| 方法 | 用途 |
|---|---|
get() · set(input) · clear(params) |
讀取 · 設定預設值 · 清除覆蓋設定 |
p.setDefaultAgent — 專案預設代理
p.setDefaultAgent(agentName) 檢查代理是否已宣告並啟用,
然後將其設為專案 beeuni.yaml 中的 default_agent。新對話
優先使用該代理,除非使用者選擇其他代理。
p.updateFeatureFlag — 功能標誌
p.updateFeatureFlag(feature, enabled) 為專案開啟或關閉一個功能標誌。
傳入 enabled: null 可清除覆蓋設定並回退到
平臺預設值。它呼叫規範的 PATCH /v1/projects/:id/features。
feature 是 FEATURE_FLAG_KEYS 中的一個(從 @beeuni/sdk 匯出,型別為
FeatureFlagKey)。呼叫者需要專案的 project.settings.write
權限;否則路由返回 403。
標誌關閉時,所有受該標誌門控的路由都以相同方式拒絕請求:HTTP 403,
附帶 { error, code: "feature_disabled", feature }。使用 isFeatureDisabledError(error)
據此執行分支邏輯,使用 featureDisabledKey(error) 讀取標誌鍵 — 切勿
匹配訊息文本。
p.updateExperimentalFeature(feature, enabled) 是已棄用的別名。它
仍呼叫已棄用的路由別名 PATCH /v1/projects/:id/experimental,
以便固定使用較舊已部署 API 的呼叫方繼續正常執行。新程式碼中請使用
p.updateFeatureFlag。
p.sandbox — 模板與快照構建
專案控制代碼上 sandboxHealth/sandboxTemplates 之外的沙箱構建設定:
Dockerfile/映象/預熱池模板及其快照構建。
| 方法 | 用途 |
|---|---|
list() · snapshots() |
此專案的沙箱 · 已構建的快照 |
rebuildSnapshot(slug?) · fixWithAgent() |
重建快照 · 請求代理修復失敗的構建 |
createTemplate(input) · updateTemplate(...) · removeTemplate(...) · buildTemplate(...) |
新增 · 編輯 · 刪除 · 構建模板 |
備用存取方式
beeuni.runtime() 返回當前活動沙箱的 REST 客戶端,包含完整的型別定義。
在由 createScopedBeeuni 建立的客戶端(@beeuni/sdk/server)上,它會丟擲異常
— 在多租戶伺服器中,共用程序級執行環境設定可能存取到其他請求的沙箱,
造成跨租戶資料洩露。請改用對話範圍的
beeuni.session(pid, sid).runtime(先呼叫 ensureReady()),它會
解析該對話自己的沙箱。
模組
這些模組為客戶端和 React hooks 提供不依賴框架的基礎功能。 需要直接呼叫單個操作、使用純輔助函式或僅適用於 Node 的功能時,可以按需匯入。 每個模組都標有穩定性級別,供你選擇。
| 層級 | 含義 |
|---|---|
| 標準入口 | 從根入口 @beeuni/sdk 匯入。所有新程式碼都應使用此入口。 |
| 受支援 | 專用子路徑(@beeuni/sdk/react、@beeuni/sdk/server)。正式支援,未棄用。 |
| 內部 | 不受 semver 約束。不要在宿主程式碼中匯入。 |
根入口是標準入口。下面所有不依賴框架的名稱都可以直接從 @beeuni/sdk 匯入:
import { files, getSessionHealth, getClient, authenticatedFetch, backendApi } from '@beeuni/sdk';
標準模組
| 模組 | 功能 |
|---|---|
| 檔案 | 工作區檔案操作:列出、讀取、搜尋、寫入 |
| 對話執行時 | 健康探測及預覽/代理 URL 構建器 |
| 執行環境客戶端 | 帶有完整型別定義的執行環境 REST 客戶端 |
| 認證 | authenticatedFetch 和權杖存取器 |
| Projects REST | 客戶端封裝所使用的原始 REST 函式 |
| API 客戶端 | backendApi,底層型別化 HTTP 客戶端 |
| 輪次 | 將訊息分組為輪次,以及費用和狀態計算 — 參見輪次 |
| 對話記錄 | formatTranscript,客戶端 Markdown 匯出 |
| 輸入編輯器列表 | 對話輸入編輯器的代理和模型列表:提供哪些選項、執行哪個選項 |
檔案
import { files } from '@beeuni/sdk';
const tree = await files.list('/workspace/src');
const { content } = await files.read('/workspace/README.md');
const hits = await files.findText('TODO');
await files.upload(file, '/workspace/uploads', file.name, {
onProgress: ({ loadedBytes, totalBytes }) => {
console.log(`${loadedBytes}/${totalBytes}`);
},
});
超過 64 KiB 的上傳內容會以經過驗證的分塊跨越沙箱邊界。每個分塊到達對話檔案系統後,都會呼叫進度回呼。
uploadNativeFile({ uri, name, type? }, targetPath, baseUrl) 通過一次請求從 React Native 上傳裝置檔案。執行時從 uri 流式傳輸位元組,因此這些位元組不會進入 JS 堆。它使用與 files.upload 相同的認證、截止時間和 401 重放機制。不進行分塊。
fetchProjectArchive、fetchCostExportCsv 和沙箱版本呼叫通過同一傳輸層傳送。失敗時會丟擲帶有 status 的 ApiError。
files.write(path, blob) 替換 path 處的檔案;如果 path 是資料夾,則會失敗。files.create(path) 建立空檔案,且絕不覆蓋:當 path 處已存在檔案或資料夾時,它會丟擲 FileExistsError(status 409、code 'FILE_EXISTS')。
import { FileExistsError, files } from '@beeuni/sdk';
try {
await files.create('/workspace/notes.md');
} catch (error) {
if (error instanceof FileExistsError) console.log(`${error.path} already exists`);
else throw error;
}
files 面向全域性當前活動的沙箱。如果宿主同時執行多個對話,請改為在對話控制代碼上呼叫 s.files。它始終面向該對話自己的沙箱。參見對話。
對話執行時輔助函式
import { getSessionHealth, isRuntimeReady } from '@beeuni/sdk';
const result = await getSessionHealth();
if (result.ok && isRuntimeReady(result.health)) {
// the session is ready
}
getSessionHealth 不會因非 2xx 狀態而丟擲異常。它返回 { status, ok, health, body },由你決定狀態的含義。同一模組還匯出 URL 輔助函式,用於將代理的 localhost 輸出改寫為可存取的代理 URL:detectLocalhostUrls、rewriteLocalhostUrl、proxyLocalhostUrl、parseLocalhostUrl 和 buildWebProxyUrl。
執行環境 客戶端
import { getClient } from '@beeuni/sdk';
const client = getClient();
const { data } = await client.session.list({ limit: 100 });
getClient() 返回活動沙箱的型別化 執行環境 v2 相容客戶端,已注入認證資訊。當宿主執行多個對話時,應優先使用限定於單個對話的同一客戶端 beeuni.session(pid, sid).runtime,而不是全域性的 getClient()。
認證輔助函式
import { authenticatedFetch, getAuthToken } from '@beeuni/sdk';
const res = await authenticatedFetch(`${backendUrl}/projects`);
const token = await getAuthToken();
權杖來自你傳給 createBeeuni 的 getToken 函式。檔案、對話和客戶端封裝已處理認證,大多數應用無需直接使用此模組。
API 客戶端
import { backendApi } from '@beeuni/sdk';
const data = await backendApi.get('/some/endpoint');
await backendApi.post('/some/endpoint', { name: 'x' });
backendApi 是所有 REST 函式的基礎型別化 HTTP 客戶端。僅在端點尚無型別化封裝時使用它。
輸入編輯器的代理和模型列表
使用與 Beeuni Web 應用相同的規則,構建對話輸入編輯器的代理選擇器和模型選擇器。每個函式都是純函式:先通過客戶端獲取輸入,再將其傳入。
import {
composerSelectableAgents,
createModelVisibility,
flattenModels,
modelInDefaultView,
pickerProviderList,
projectConfigAgentsToRuntimeAgents,
resolveComposerAgent,
resolveComposerModel,
resolveModelDefault,
} from '@beeuni/sdk';
// Agents: the roster, the picker list, and the agent the send carries.
const roster = projectConfigAgentsToRuntimeAgents(detail.config);
const pickerAgents = composerSelectableAgents(roster, { enableProjects: false });
const agent = resolveComposerAgent({
agents: roster,
boundAgent: session?.agent,
defaultAgent: detail.config.default_agent,
selectedAgent: pick,
});
if (agent.disabled) {
// no accessible agent: refuse the send
}
// Models: gateway projects read /model-picker, native projects merge the
// catalog synthesis with the running sandbox's provider list.
const gatewayEnabled = detail.project.experimental?.llm_gateway === true;
const providers = pickerProviderList({
gatewayEnabled,
modelPicker,
runtimeProviders,
llmCatalogProviders,
secretNames,
});
const models = flattenModels(providers, { providerMode: gatewayEnabled ? 'gateway' : 'native' });
const isVisible = createModelVisibility({ catalogModels: models });
const defaultView = models.filter(
(m) => m.enabled !== false && modelInDefaultView(m, { search: '', isStoreVisible: isVisible, selected }),
);
const { model, explicit } = resolveComposerModel({
models,
picks: [sessionPick],
serverDefault: resolveModelDefault(modelDefaults, agent.selected ?? undefined),
providers,
});
當輸入編輯器使用預設設定時,resolveComposerModel 返回 explicit: undefined。model 是用於顯示和傳送的鍵。每個扁平化模型的 id 是選擇操作儲存的引用;modelRefToKey(ref, gatewayEnabled) 將已儲存的引用(對話固定項、頻道繫結、觸發器的 model)讀回為鍵。
受支援的子路徑
| 子路徑 | 功能 |
|---|---|
@beeuni/sdk/react |
React hooks — 參見 React hooks |
@beeuni/sdk/server |
多租戶後端的請求級設定 |
@beeuni/sdk/genui/fence |
識別內容塊,不載入可選依賴. 生成式介面 |
@beeuni/sdk/genui |
解析器、元件目錄和 Markdown 轉換. 生成式介面 |
@beeuni/sdk/genui/react |
無預設樣式的 React 渲染器及預設 HTML 元件. 生成式介面 |
@beeuni/sdk/wire-message-id |
僅包含 執行環境 傳輸訊息 ID 時鐘(單個模組,無匯入)。根入口匯出相同的名稱 |
@beeuni/sdk/iam-actions |
匯入現行的專案權限及其 workspace.* 別名,無須載入用戶端 |
傳輸訊息 ID
提示的 messageId 是它在對話記錄中的位置。執行環境 按 msg_ + 48 位時鐘(Date.now() * 0x1000,低 48 位)+ 14 個 base62 字元對訊息排序,時鐘每 2^36 毫秒(約 2.2 年)迴繞一次。切勿手動編碼。
import { mintWireMessageId } from '@beeuni/sdk';
// `after`: the ids already in this session's transcript.
const messageId = mintWireMessageId({ after: transcriptIds });
生成時先將時間設為兩分鐘前,再提升到 after 中最多超前一小時的最新 ID 之上一個時鐘刻度。呼叫方若以時鐘而非 ID 儲存最新位置,則使用 mintWireMessageIdAbove({ nowMs, newestKnownTime }),返回 { id, time }。newestWireIdClock(ids) 查詢該時鐘。所有比較都在環上進行,因此迴繞兩側的 ID 仍保持真實順序。
48 位時鐘約每 2.2 年迴繞一次,因此切勿用 > 或 <= 比較兩個時鐘:剛回繞後生成的 ID 在數值上小於剛回繞前生成的 ID。請使用 wireIdClockDelta(clock, reference),即環上的有符號距離(當 clock 在前時為正),並使用 maxWireIdClock(clocks) 找出多個值中最新的一個:
import { maxWireIdClock, wireIdClockDelta } from '@beeuni/sdk/wire-message-id';
const floor = maxWireIdClock([transcriptNewest, deliveredNewest]);
const stale = floor !== null && wireIdClockDelta(clientClock, floor) <= 0n;
服務端隔離
createBeeuni 將其設定(包括權杖函式)儲存在一個程序級變數中。這適用於瀏覽器標籤頁、CLI 或單租戶伺服器。但對於處理不同使用者併發請求的 Node 伺服器,這並不安全,因為最後一次 createBeeuni 呼叫會覆蓋所有進行中請求的設定。@beeuni/sdk/server 通過按請求隔離解決此問題:
import { createScopedBeeuni } from '@beeuni/sdk/server';
export async function handler(req: Request) {
const beeuni = createScopedBeeuni({ backendUrl, getToken: () => tokenFor(req) });
return beeuni.projects.list();
}
createScopedBeeuni 和 runWithBeeuni 使用 Node 的 AsyncLocalStorage 按請求隔離設定。切勿在瀏覽器打包程式碼中匯入 @beeuni/sdk/server — 它會靜態引入 node:async_hooks。
限定作用域客戶端的頂層 runtime() 會丟擲異常(它會解析到另一個租戶的沙箱)。在 await s.ensureReady() 之後,通過 beeuni.session(pid, sid).runtime 存取特定對話的執行時。
輪次
將對話訊息分組為輪次並對每個訊息部分進行分類的普通函式。用它們構建自定義聊天渲染器,替代 apps/web 中的參考渲染器。不依賴 React 或 DOM — 每個匯出項都是普通函式或型別,可從任何宿主安全呼叫。
import { classifyPart, classifyTurn, toolInfo, toolViewModel } from '@beeuni/sdk';
對部分進行分類
classifyPart(part) 將 Beeuni 對話記錄格式(beeuni.transcript.v1、BEEUNI_TRANSCRIPT_SCHEMA)的 12 種片段型別之一規範化為
ClassifiedPart——一個以 kind 為鍵的聯合型別。每個變體都已解析出渲染器所需的欄位:工具狀態、解析後的 JSON 輸出、影像檢測。
import { classifyPart, type ClassifiedPart } from '@beeuni/sdk';
for (const part of message.parts) {
const classified: ClassifiedPart = classifyPart(part);
switch (classified.kind) {
case 'text':
render(classified.text);
break;
case 'tool':
render(classified.tool.title, classified.tool.status);
break;
}
}
kind |
結構 |
|---|---|
text |
{ id, text, synthetic }——跳過 synthetic 片段;它們標記 shell 模式的合成提示 |
reasoning |
{ id, text } |
tool |
{ id, tool: ToolView } |
file |
{ id, filename?, mime, url, isImage, isPdf } |
subtask |
{ id, description, agent, prompt, model? } |
patch |
{ id, hash, files, fileCount } |
snapshot |
{ id, snapshot } |
agent |
{ id, name } |
retry |
{ id, attempt, message, createdAt } |
compaction |
{ id, auto, overflow, tailStartId? } |
step |
{ id, phase: 'start' | 'finish', snapshot?, reason?, cost?, tokens? } |
unknown |
{ raw }——此 SDK 版本不認識的片段型別 |
無法識別的傳輸片段會在執行時降級為 unknown,而不是丟擲異常。這讓舊版客戶端能夠與新版伺服器通訊。
工具片段被分類為 ToolView:
interface ToolView {
name: string;
title: string;
status: 'pending' | 'running' | 'done' | 'error';
input?: Record<string, unknown>;
output?: string;
error?: string;
outputParsed?: unknown; // JSON.parse(output) when it parses, capped at 256KB
outputText?: string; // the raw output text, always present
kind?: ToolKind; // toolKind(name): the action, whatever the harness calls the tool
files?: ToolFile[]; // the files a file tool read, wrote or changed: path, patch, additions/deletions
diff?: string; // a unified diff of the change
diagnostics?: Record<string, unknown[]>; // language-server diagnostics, keyed by file path
answers?: string[][]; // the answers to a `question`, one list per question
childSessionId?: string; // the child session a delegating call (`task`) runs
}
toToolView(part) 從訊息部分生成工具檢視。通過標準化欄位,在不同對話中呈現一致的介面。
某些工具(web_search、image_search、連接器呼叫)即使 JSON 正文包含 success: false,也會報告 state.status: 'completed'。classifyPart 會檢測這種情況,並同樣將 ToolView.status 設為 'error'。
classifyTurn(message) 對一條助手訊息的每個片段進行分類,並返回一個包含三個欄位的 ClassifiedTurn:
parts——分類後的各個片段error——來自message.info.error(如果有)isEmpty——當該輪次沒有錯誤,也沒有包含可見內容的片段時為 true
工具後設資料
toolKind(name) 按操作型別分類工具。inputPath(input) 從 filePath、file_path 或 path 讀取檔案路徑。
toolKind('write'); // 'write'
inputPath({ path: 'app.py' }); // 'app.py'
還有兩個查詢函式都用於描述工具。不要混淆它們。
toolInfo(name)——不涉及圖示,返回{ label, category }。classifyPart在內部使用它。ToolCategory為'shell' | 'files' | 'search' | 'edit' | 'web' | 'task' | 'other'。getToolInfo(name, input)——包含圖示資訊,為參考工具卡片 UI 返回{ icon, title, subtitle }。副標題來自工具的輸入,例如檔案路徑或搜尋查詢。
toolInfo('bash'); // { label: 'Shell', category: 'shell' }
getToolInfo('write', { filePath: '/workspace/main.go' });
// { icon: 'file-pen', title: 'Write', subtitle: 'main.go /workspace' }
這兩個函式都匹配工具名稱字首,因此 Beeuni 的外掛工具系列(agent_*、session_*、task_*、trigger_*、project_*、pty_*)無需更新登錄檔即可解析。未知工具名稱絕不會丟擲異常——它會回退為 humanizeToolName(name),類別為 'other'。
工具檢視模型
toolViewModel(classifiedTool) 將已分類的工具片段對映為專為某個工具系列構建的結構。UI 隨後可以對其進行專門渲染,而不是作為通用 JSON 資料塊顯示。
const vm = toolViewModel(classifiedTool);
if (vm.kind === 'shell') {
render(vm.command, vm.stdout, vm.exitCode);
}
kind |
結構 | 工具 |
|---|---|---|
web-search |
{ query, results?, answer?, error? } |
web_search、image_search |
shell |
{ command, stdout?, exitCode? } |
bash |
file-read |
{ path, preview? } |
read |
file-write |
{ path, preview? } |
write |
file-edit |
{ path, diff?: DiffLine[] } |
edit、morph_edit |
search |
{ pattern, matches?: SearchMatch[] } |
grep、glob |
task |
{ description, agent? } |
task |
todo |
{ items: TodoItem[] } |
todowrite |
question |
{ questions: QuestionItem[], answers? } |
question、ask |
generic |
{ label, inputPretty?, outputPretty? } |
其餘所有工具,始終可安全渲染 |
DiffLine 為 { type: 'added' | 'removed' | 'unchanged', text }。字串欄位設有上限,避免單次大型工具輸出破壞渲染:格式化 JSON 限為 4000 個字元,執行差異比較前限為 256KB。
將訊息分組為輪次
一個輪次將一條使用者訊息與回答它的助手訊息配對。它是聊天 UI 作為一次互動渲染的單位。
import { groupMessagesIntoTurns, collectTurnParts, type TurnLike } from '@beeuni/sdk';
const turns: TurnLike[] = groupMessagesIntoTurns(messages);
for (const turn of turns) {
const parts = collectTurnParts(turn);
}
groupMessagesIntoTurns 將每條助手訊息關聯到其父級使用者訊息。缺少父級連結時,它會回退到訊息順序。它還會將孤立的助手訊息——沒有父級且出現在所有使用者訊息之前的訊息——附加到第一個輪次,而不是最後一個。
相關輔助函式:
findLastTextPart(parts)——該輪次的最終回覆文本turnHasSteps(parts)——如果存在tool、compaction、snapshot或patch片段,則為 trueisShellMode(turn)/getShellModePart(turn)——由一個合成提示驅動一次bash呼叫的輪次
型別守衛
通過 type 收窄片段型別:
import { isTextPart, isToolPart, getPartText } from '@beeuni/sdk';
if (isTextPart(part)) {
// part.type narrowed to 'text'
}
const text = getPartText(part); // works for 'text' and 'reasoning' parts
還提供:isReasoningPart、isFilePart、isAgentPart、isCompactionPart、isSnapshotPart、isPatchPart、isStepPart(step-start 和 step-finish)。
狀態和錯誤
import { getWorkingState, getTurnStatus, formatDuration } from '@beeuni/sdk';
const status = getTurnStatus(parts, childMessages); // "Running commands..."
formatDuration(4300); // "4s" — durations under 1s return ''
getTurnStatus 掃描一個輪次的片段,查詢最後一條狀態行。當最後一個片段是正在執行的 task 委派時,傳入 childMessages,使狀態顯示子代理的實際活動,而不是通用的“正在委派…”狀態行。
import { getTurnError, getChildSessionError, unwrapError } from '@beeuni/sdk';
getTurnError(turn); // the first assistant error, unwrapped
getChildSessionError(childMessages); // newest error in a sub-agent's messages
unwrapError(rawError); // normalizes double-JSON and mixed error shapes
費用和 token 總數
import { sessionLogThreadMetrics, formatTokens } from '@beeuni/sdk';
const metrics = sessionLogThreadMetrics(thread);
const charges = await beeuni.session(projectId, sessionId).cost();
console.log(charges);
formatTokens(metrics.tokens.input); // "12k" for 12345
用 beeuni.session(projectId, sessionId).cost() 讀取已結算的模型與計算資源費用,金額來自平臺賬單記錄。sessionLogThreadMetrics(thread) 返回訊息數和 token 用量,其 cost 為 null。token 數不等於實際扣費。用 s.modelUsage() 讀取實際響應的模型和各輪次的模型費用。
子對話和待處理請求
專案對話的對話樹(根對話及其生成的子代理對話)來自其 runtime_sessions 列表。這些輔助函式讀取該列表,優先使用當前欄位名,併兼容舊版欄位名:
import { directSubsessions, projectSessionForRuntimeId, rootRuntimeSession, runtimeSessionsOf } from '@beeuni/sdk';
const root = rootRuntimeSession(projectSession); // the root conversation id
const children = directSubsessions(projectSession); // its subagent conversations
const owner = projectSessionForRuntimeId(projectSessions, childId); // the session a conversation belongs to
task 工具呼叫會委派給子對話。這些輔助函式將父輪次與該子對話自身的訊息關聯起來。
import { getChildSessionId, getChildSessionToolParts } from '@beeuni/sdk';
const childId = getChildSessionId(taskToolPart);
const steps = getChildSessionToolParts(childMessages);
將待處理的權限或問題請求與其工具呼叫匹配,並找出在請求處於活動狀態時應隱藏哪些工具片段:
import { getPermissionForTool, getHiddenToolParts, isToolPartHidden } from '@beeuni/sdk';
const permission = getPermissionForTool(permissions, callID);
const hidden = getHiddenToolParts(activePermission, activeQuestion);
格式化和列表
import { getFilename, getDirectory, relativizePath, stripAnsi } from '@beeuni/sdk';
getFilename('/workspace/src/main.go'); // "main.go"
getDirectory('/workspace/src/main.go'); // "/workspace/src"
relativizePath('/workspace/src/main.go', '/workspace'); // "src/main.go"
對話列表輔助函式操作相同的對話資料:
import { sortSessions, childMapByParent, allDescendantIds } from '@beeuni/sdk';
sessions.sort(sortSessions(Date.now())); // pins sessions updated in the last 60s
const childMap = childMapByParent(sessions);
const descendants = allDescendantIds(childMap, sessionId);
重試狀態:當 status.type === 'retry' 時,getRetryInfo(sessionStatus) 返回 { attempt, message, next, details? },其中 message 最多保留 60 個字元。若錯誤包含結構化的 LLM 閘道器資訊,details 會保留最終提供商、閘道器錯誤碼、請求 ID、處理建議、上游狀態,以及按順序排列的候選失敗資訊。每個候選失敗資訊包含 attempt、provider、routeModel、resolvedModel、stage,以及可選的 status、code 和 message。舊版純文本重試返回 details: undefined。
getRetryMessage(sessionStatus) 返回解析後的完整錯誤訊息。即使執行時僅保留了這條訊息,閘道器的彙總資訊仍包含請求 ID,以及每個候選的提供商、解析後的模型、HTTP 狀態、錯誤碼和長度受限的訊息。
結構型別
分組和狀態函式接受最小結構型別 —
PartLike、MessageInfoLike、TurnLike、ToolStateLike、
SessionStatusLike — 而非具體的對話記錄型別。
只要符合必需欄位,你自己的訊息和片段結構就會原樣傳遞。
classifyPart 和 classifyTurn 是例外。
它們以 Beeuni 的 Part 聯合型別(beeuni.transcript.v1)為型別依據,因此其
窮盡性檢查會在構建時發現新的片段型別。
分發
npm install @beeuni/sdk
此包以編譯後的 ESM 形式釋出,並提供完整的 TypeScript 型別宣告。
react 和 @tanstack/react-query 是可選的對等依賴。如果
使用 @beeuni/sdk/react,請同時安裝兩者。
import { createBeeuni } from '@beeuni/sdk'; // framework-free core
import { useSession } from '@beeuni/sdk/react'; // optional React layer
import { createScopedBeeuni } from '@beeuni/sdk/server'; // Node and Bun servers
入口與穩定性
根入口 @beeuni/sdk 是標準入口。它匯出完整的
無框架依賴介面,可在瀏覽器、Node 18+、Bun 和邊緣
執行時中執行。
| 入口 | 級別 | 約定 |
|---|---|---|
@beeuni/sdk |
標準 | 無框架依賴。絕不匯入 React 或 node:*。 |
@beeuni/sdk/react |
受支援 | React hooks. |
@beeuni/sdk/server |
受支援 | 通過 node:async_hooks 為 Node 和 Bun 伺服器提供按請求隔離的設定。切勿將其打包到瀏覽器中。 |
@beeuni/sdk/genui/fence |
— | 識別內容塊,不載入可選依賴. 生成式介面 |
@beeuni/sdk/genui |
— | 解析器、元件目錄和 Markdown 轉換. 生成式介面 |
@beeuni/sdk/genui/react |
— | 無預設樣式的 React 渲染器及預設 HTML 元件. 生成式介面 |
舊版子路徑(/projects-client、/turns、/files 等) |
已棄用 | 仍可使用。每個子路徑都從根入口重新匯出。請改為從根入口匯入。 |
CDN 包
此包還提供兩個由 tsup 構建的瀏覽器包:一個 ESM 包
(dist/beeuni.esm.min.js)和一個定義了 window.Beeuni 的 IIFE 全域性包(dist/beeuni.global.js)。
<script src="https://unpkg.com/@beeuni/sdk/dist/beeuni.global.js"></script>
<script>
const beeuni = Beeuni.createBeeuni({
backendUrl: 'https://api.beeuni.ai/v1',
getToken: async () => KEY,
});
</script>
window.Beeuni 暴露的根入口與 npm 匯入相同:
Beeuni.createBeeuni、Beeuni.classifyTurn、Beeuni.ApiError。
另請參閱
- SDK — 安裝並建立你的第一個對話。
- 對話 — 生命週期、流式傳輸和錯誤處理。
- React hooks — 基於這些模組構建的響應式層。
工作目錄準備
對話啟動時不會自動檢出專案儲存庫。設定 workspace.repos 可在對話分支上複製專案儲存庫,並可指定 path 和 sparse 目錄。設定 workspace.setup 可在複製後執行命令;每一步可寫為命令字串或 { run, cwd }。這些步驟在啟動後於後臺執行。複製需要 project.gitops.read。舊的 repository_access 和 workspace.project_repository 設定已忽略。工具、金鑰和連接器仍需分別授權。
提供商和模型存取
讀取 beeuni.projects.modelAccess(projectId)。使用 beeuni.projects.setModelAccess(projectId, { target: 'provider' | 'model', id, enabled }) 更改一個目標。
對於 Beeuni Managed Models,使用提供商 ID beeuni;對於 BYOK、Codex 和自定義提供商,使用目錄中的提供商 ID。對於模型,使用完整的閘道器傳輸 ID。停用提供商會涵蓋未來的模型,並保留各模型的偏好設定和已儲存的憑據。
停用當前預設模型及其提供商之前,必須先指定替代項(409 cannot_disable_default)。直接向已停用目標傳送的閘道器請求會失敗,並返回 model_disabled 或 provider_disabled。現有正在處理的上游請求會正常完成。當專案使用執行框架的原生模型連線而非閘道器時,響應中的 enforced 欄位為 false。
React 使用方使用 @beeuni/sdk/react 中的 useModelAccess(projectId)。其 setEnabled(change) 變更操作會重新整理管理目錄和對話選擇器。
Capture — beeuni.capture
讀取組織帳戶的螢幕錄製、輸入操作和可選音訊。權限與網頁相同。
const capture = beeuni.capture.account(accountId);
await capture.workspace.get();
await capture.search({ q: 'invoice', limit: 5 });
await capture.devices.list();
await capture.timeline.days();
成員可讀取自己的時間線。檢視其他成員需要 capture.read_all;修改錄製規則或管理裝置需要 capture.manage。共享對話和自動執行的對話不能讀取個人時間線。
capture.devices.list() 還返回裝置健康狀態 health 與診斷資訊 diagnostics,包括更新失敗原因、作業系統與內部版本、同步、策略和硬體資訊。
工件相容介面
工件評論、活動記錄、線上狀態和多人即時編輯已移除。相關 SDK 函式、型別和 hooks 保留為已棄用匯出,供現有程式碼繼續匯入;介面返回 HTTP 410,錯誤碼為 ENDPOINT_RETIRED。新整合請使用工件內容和版本記錄介面。