@arbidocs/sdk 0.4.166 → 0.4.168

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs2, { readFileSync } from 'fs';
2
2
  import path2, { dirname, resolve } from 'path';
3
3
  import os2 from 'os';
4
- import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, encryptionKeypairFromSigningKey, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, sealedBoxDecrypt, decodeSecureMailKey, openSecureMail, secureMailClaim, changePassword, readSessionClaims } from '@arbidocs/client';
4
+ import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, encryptionKeypairFromSigningKey, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, sealedBoxDecrypt, decodeSecureMailKey, openSecureMail, secureMailClaim, createSessionManager, authRequestError, changePassword, openCallKeyOf, decryptCallTitle, generateCallKey, encryptCallTitle, sealCallKeyForPeers, openSealedCallKey, readSessionClaims } from '@arbidocs/client';
5
5
  import { execSync, spawn } from 'child_process';
6
6
  import { createHash } from 'crypto';
7
7
  import { fileURLToPath } from 'url';
@@ -3746,7 +3746,7 @@ var FileConfigStore = class {
3746
3746
  return creds;
3747
3747
  }
3748
3748
  /**
3749
- * Returns a SessionStorageProvider backed by this store's
3749
+ * Returns a SessionPersistence backed by this store's
3750
3750
  * credentials file. Used to wire the auto-relogin middleware in
3751
3751
  * `@arbidocs/client` to the Node-side file store — without this, the
3752
3752
  * middleware falls back to IndexedDB which does not exist in Node
@@ -3758,7 +3758,7 @@ var FileConfigStore = class {
3758
3758
  * credentials file on successful re-login so the next CLI
3759
3759
  * invocation picks it up.
3760
3760
  */
3761
- getSessionStorageProvider() {
3761
+ getSessionPersistence() {
3762
3762
  const b64decode = (b64) => typeof Buffer !== "undefined" ? new Uint8Array(Buffer.from(b64, "base64")) : Uint8Array.from(atob(b64), (c2) => c2.charCodeAt(0));
3763
3763
  const b64encode = (bytes) => typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : btoa(String.fromCharCode(...bytes));
3764
3764
  const getCreds = () => this.getCredentials();
@@ -3999,7 +3999,7 @@ function buildClientOptions(config, store, email) {
3999
3999
  baseUrl: config.baseUrl,
4000
4000
  deploymentDomain: config.deploymentDomain,
4001
4001
  credentials: "omit",
4002
- sessionStorage: store?.getSessionStorageProvider?.(),
4002
+ persistence: store?.getSessionPersistence?.(),
4003
4003
  userEmail: email
4004
4004
  };
4005
4005
  }
@@ -5051,14 +5051,14 @@ async function* listPaginated(arbi, options = {}) {
5051
5051
  lookahead = 1
5052
5052
  } = options;
5053
5053
  const fetchPage = async (pageOffset, limit) => {
5054
- const query = {
5054
+ const query2 = {
5055
5055
  limit,
5056
5056
  offset: pageOffset,
5057
5057
  order
5058
5058
  };
5059
- if (fields) query.fields = fields;
5059
+ if (fields) query2.fields = fields;
5060
5060
  const { data, error } = await arbi.fetch.GET("/v1/document/list", {
5061
- params: { query },
5061
+ params: { query: query2 },
5062
5062
  signal
5063
5063
  });
5064
5064
  if (error) {
@@ -5164,20 +5164,20 @@ async function uploadUrl(arbi, urls, shared = false, configExtId) {
5164
5164
  );
5165
5165
  }
5166
5166
  async function uploadDocuments(arbi, files, options = {}) {
5167
- const query = {};
5168
- if (options.shared !== void 0) query.shared = options.shared;
5169
- if (options.folder) query.folder = sanitizeFolderPath(options.folder);
5170
- if (options.configExtId) query.config_ext_id = options.configExtId;
5171
- if (options.wpType) query.wp_type = options.wpType;
5172
- if (options.versionOf) query.version_of = options.versionOf;
5173
- if (options.tagExtId) query.tag_ext_id = options.tagExtId;
5174
- if (options.workspaceExtId) query.workspace_ext_id = options.workspaceExtId;
5167
+ const query2 = {};
5168
+ if (options.shared !== void 0) query2.shared = options.shared;
5169
+ if (options.folder) query2.folder = sanitizeFolderPath(options.folder);
5170
+ if (options.configExtId) query2.config_ext_id = options.configExtId;
5171
+ if (options.wpType) query2.wp_type = options.wpType;
5172
+ if (options.versionOf) query2.version_of = options.versionOf;
5173
+ if (options.tagExtId) query2.tag_ext_id = options.tagExtId;
5174
+ if (options.workspaceExtId) query2.workspace_ext_id = options.workspaceExtId;
5175
5175
  if (options.derivedFrom) {
5176
- query.derived_from = options.derivedFrom.docId;
5177
- query.derived_role = options.derivedFrom.role;
5176
+ query2.derived_from = options.derivedFrom.docId;
5177
+ query2.derived_role = options.derivedFrom.role;
5178
5178
  }
5179
5179
  const result = await arbi.fetch.POST("/v1/document/upload", {
5180
- params: { query },
5180
+ params: { query: query2 },
5181
5181
  ...options.onProgress ? { fetch: progressFetch(options.onProgress) } : {},
5182
5182
  // The schema types the files as strings; they go as multipart parts.
5183
5183
  body: { files },
@@ -5603,18 +5603,27 @@ async function listHouseTemplateCandidates(arbi) {
5603
5603
  // src/operations/workspaces.ts
5604
5604
  var workspaces_exports = {};
5605
5605
  __export(workspaces_exports, {
5606
+ EXTERNAL_ACCESS_SECONDS: () => EXTERNAL_ACCESS_SECONDS,
5606
5607
  addWorkspaceMembers: () => addWorkspaceMembers,
5608
+ addWorkspaceMembersBody: () => addWorkspaceMembersBody,
5607
5609
  addWorkspaceUsers: () => addWorkspaceUsers,
5610
+ cancelWorkspaceTransfer: () => cancelWorkspaceTransfer,
5608
5611
  copyDocuments: () => copyDocuments,
5609
5612
  createWorkspace: () => createWorkspace,
5610
5613
  deleteWorkspaces: () => deleteWorkspaces,
5614
+ exportWorkspaceData: () => exportWorkspaceData,
5611
5615
  getWorkspaceActivity: () => getWorkspaceActivity,
5616
+ getWorkspaceTransfer: () => getWorkspaceTransfer,
5612
5617
  grantTemporaryWorkspaceAccess: () => grantTemporaryWorkspaceAccess,
5618
+ listWorkspaceTransfers: () => listWorkspaceTransfers,
5613
5619
  listWorkspaceUsers: () => listWorkspaceUsers,
5614
5620
  listWorkspaces: () => listWorkspaces,
5621
+ planWorkspaceTransfer: () => planWorkspaceTransfer,
5615
5622
  primeWorkspaceKey: () => primeWorkspaceKey,
5616
5623
  removeWorkspaceUsers: () => removeWorkspaceUsers,
5624
+ resumeWorkspaceTransfer: () => resumeWorkspaceTransfer,
5617
5625
  setUserRole: () => setUserRole,
5626
+ startWorkspaceTransfer: () => startWorkspaceTransfer,
5618
5627
  updateWorkspace: () => updateWorkspace
5619
5628
  });
5620
5629
  async function listWorkspaces(arbi) {
@@ -5651,9 +5660,16 @@ async function updateWorkspace(arbi, body) {
5651
5660
  async function listWorkspaceUsers(arbi) {
5652
5661
  return requireData(await arbi.fetch.GET("/v1/workspace/users"), "Failed to fetch workspace users");
5653
5662
  }
5663
+ var EXTERNAL_ACCESS_SECONDS = 86400;
5664
+ function addWorkspaceMembersBody(request) {
5665
+ return {
5666
+ ...request,
5667
+ access_duration_seconds: request.access_duration_seconds ?? EXTERNAL_ACCESS_SECONDS
5668
+ };
5669
+ }
5654
5670
  async function addWorkspaceMembers(arbi, request) {
5655
5671
  return requireData(
5656
- await arbi.fetch.POST("/v1/workspace/users", { body: request }),
5672
+ await arbi.fetch.POST("/v1/workspace/users", { body: addWorkspaceMembersBody(request) }),
5657
5673
  "Failed to add users"
5658
5674
  );
5659
5675
  }
@@ -5661,13 +5677,15 @@ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, co
5661
5677
  const invite = confirmInvite ? { confirm_invite: true } : {};
5662
5678
  return requireData(
5663
5679
  await arbi.fetch.POST("/v1/workspace/users", {
5664
- body: target ? {
5665
- emails,
5666
- role,
5667
- workspace_ext_id: target.workspaceExtId,
5668
- workspace_key: target.workspaceKey,
5669
- ...invite
5670
- } : { emails, role, ...invite }
5680
+ body: addWorkspaceMembersBody(
5681
+ target ? {
5682
+ emails,
5683
+ role,
5684
+ workspace_ext_id: target.workspaceExtId,
5685
+ workspace_key: target.workspaceKey,
5686
+ ...invite
5687
+ } : { emails, role, ...invite }
5688
+ )
5671
5689
  }),
5672
5690
  "Failed to add users"
5673
5691
  );
@@ -5675,13 +5693,13 @@ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, co
5675
5693
  async function grantTemporaryWorkspaceAccess(arbi, params) {
5676
5694
  return requireData(
5677
5695
  await arbi.fetch.POST("/v1/workspace/users", {
5678
- body: {
5696
+ body: addWorkspaceMembersBody({
5679
5697
  emails: params.emails,
5680
5698
  role: params.role ?? "collaborator",
5681
5699
  workspace_ext_id: params.workspaceExtId,
5682
5700
  workspace_key: params.workspaceKey,
5683
5701
  session_pubkey_b64: params.sessionPubkeyB64
5684
- }
5702
+ })
5685
5703
  }),
5686
5704
  "Failed to grant temporary access"
5687
5705
  );
@@ -5737,6 +5755,63 @@ async function primeWorkspaceKey(arbi, workspaceExtId, sessionSealedKey) {
5737
5755
  "Failed to prime the workspace key"
5738
5756
  );
5739
5757
  }
5758
+ async function planWorkspaceTransfer(arbi, scope, mode) {
5759
+ return requireData(
5760
+ await arbi.fetch.POST("/v1/workspace/transfer/plan", { body: { scope, mode } }),
5761
+ "Failed to plan the transfer"
5762
+ );
5763
+ }
5764
+ async function startWorkspaceTransfer(arbi, params) {
5765
+ return requireData(
5766
+ await arbi.fetch.POST("/v1/workspace/transfer", {
5767
+ body: {
5768
+ scope: params.scope,
5769
+ mode: params.mode,
5770
+ target_workspace_ext_id: params.targetWorkspaceId,
5771
+ target_workspace_key: params.targetWorkspaceKey,
5772
+ on_conflict: params.onConflict ?? "skip"
5773
+ }
5774
+ }),
5775
+ "Failed to start the transfer"
5776
+ );
5777
+ }
5778
+ async function resumeWorkspaceTransfer(arbi, transferId, targetWorkspaceKey) {
5779
+ return requireData(
5780
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/resume", {
5781
+ params: { path: { transfer_ext_id: transferId } },
5782
+ body: { target_workspace_key: targetWorkspaceKey }
5783
+ }),
5784
+ "Failed to resume the transfer"
5785
+ );
5786
+ }
5787
+ async function cancelWorkspaceTransfer(arbi, transferId) {
5788
+ return requireData(
5789
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/cancel", {
5790
+ params: { path: { transfer_ext_id: transferId } }
5791
+ }),
5792
+ "Failed to cancel the transfer"
5793
+ );
5794
+ }
5795
+ async function getWorkspaceTransfer(arbi, transferId) {
5796
+ return requireData(
5797
+ await arbi.fetch.GET("/v1/workspace/transfer/{transfer_ext_id}", {
5798
+ params: { path: { transfer_ext_id: transferId } }
5799
+ }),
5800
+ "Failed to fetch the transfer"
5801
+ );
5802
+ }
5803
+ async function listWorkspaceTransfers(arbi) {
5804
+ return requireData(
5805
+ await arbi.fetch.GET("/v1/workspace/transfer", {}),
5806
+ "Failed to list transfers"
5807
+ );
5808
+ }
5809
+ async function exportWorkspaceData(arbi, scope) {
5810
+ return requireData(
5811
+ await arbi.fetch.POST("/v1/workspace/export", { body: { scope } }),
5812
+ "Failed to export the workspace"
5813
+ );
5814
+ }
5740
5815
 
5741
5816
  // src/operations/conversations.ts
5742
5817
  var conversations_exports = {};
@@ -5815,24 +5890,29 @@ async function updateConversationAssistantMode(arbi, conversationId, assistantMo
5815
5890
  // src/operations/assistant.ts
5816
5891
  var assistant_exports = {};
5817
5892
  __export(assistant_exports, {
5893
+ AssistantTurnRefused: () => AssistantTurnRefused,
5818
5894
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
5819
- buildFactsContextTool: () => buildFactsContextTool,
5820
- buildRetrievalChunkTool: () => buildRetrievalChunkTool,
5821
- buildRetrievalFullContextTool: () => buildRetrievalFullContextTool,
5822
- buildRetrievalTocTool: () => buildRetrievalTocTool,
5823
- cancelAssistantRun: () => cancelAssistantRun,
5895
+ SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
5896
+ cancelRun: () => cancelRun,
5824
5897
  filterSkills: () => filterSkills,
5898
+ interject: () => interject,
5825
5899
  isSharedSkill: () => isSharedSkill,
5826
5900
  listCommands: () => listCommands,
5827
5901
  listSkills: () => listSkills,
5902
+ openRunStream: () => openRunStream,
5903
+ openTurnStream: () => openTurnStream,
5828
5904
  parseSlashCommand: () => parseSlashCommand,
5829
5905
  parseSlashTokenInProgress: () => parseSlashTokenInProgress,
5830
5906
  queryAssistant: () => queryAssistant,
5831
- respondToAgent: () => respondToAgent,
5907
+ quotaExceededFrom: () => quotaExceededFrom,
5908
+ quotaFromStreamError: () => quotaFromStreamError,
5832
5909
  retrieve: () => retrieve,
5833
5910
  searchChunks: () => searchChunks,
5911
+ transcribe: () => transcribe,
5834
5912
  uploadSkill: () => uploadSkill
5835
5913
  });
5914
+
5915
+ // src/chat/turn-request.ts
5836
5916
  function buildRetrievalChunkTool(docIds, searchMode) {
5837
5917
  return {
5838
5918
  name: "retrieval_chunk",
@@ -5864,12 +5944,70 @@ function buildRetrievalTocTool(docIds) {
5864
5944
  tool_responses: {}
5865
5945
  };
5866
5946
  }
5947
+ function selectFullContextDocument(docIds, pinnedDocumentId) {
5948
+ if (pinnedDocumentId && docIds.includes(pinnedDocumentId)) {
5949
+ return {
5950
+ fullContextDocId: pinnedDocumentId,
5951
+ chunkRetrievalDocIds: docIds.filter((id) => id !== pinnedDocumentId)
5952
+ };
5953
+ }
5954
+ return { fullContextDocId: null, chunkRetrievalDocIds: [...docIds] };
5955
+ }
5956
+ function buildDocumentTools(selection) {
5957
+ return {
5958
+ retrieval_chunk: buildRetrievalChunkTool(selection.chunkRetrievalDocIds),
5959
+ retrieval_full_context: buildRetrievalFullContextTool(
5960
+ selection.fullContextDocId ? [selection.fullContextDocId] : []
5961
+ )
5962
+ };
5963
+ }
5964
+ var PA_PREFIX = "/pa ";
5965
+ function turnTools(request, activeArtifactExtId) {
5966
+ const facts = request.factIds ? { facts_context: buildFactsContextTool(request.factIds) } : {};
5967
+ if (request.tools) return { ...facts, ...request.tools };
5968
+ if (request.personalAgent) {
5969
+ return {
5970
+ personal_agent: {
5971
+ name: "personal_agent",
5972
+ description: "personal agent",
5973
+ tool_args: { task: request.question },
5974
+ tool_responses: {}
5975
+ }
5976
+ };
5977
+ }
5978
+ if (!request.docIds) return { ...facts };
5979
+ const selection = selectFullContextDocument(request.docIds, request.pinnedDocumentId);
5980
+ const documents = activeArtifactExtId && selection.fullContextDocId === activeArtifactExtId ? { ...selection, fullContextDocId: null } : selection;
5981
+ return { ...buildDocumentTools(documents), ...facts };
5982
+ }
5983
+ function buildTurnRequest(request) {
5984
+ const pa2 = request.personalAgent === true;
5985
+ const activeArtifactExtId = pa2 ? null : request.activeArtifactExtId ?? null;
5986
+ const input = pa2 && !request.question.startsWith(PA_PREFIX) ? `${PA_PREFIX}${request.question}` : request.question;
5987
+ return {
5988
+ input,
5989
+ workspace_ext_id: request.workspaceId,
5990
+ stream: true,
5991
+ background: false,
5992
+ store: true,
5993
+ tools: turnTools(request, activeArtifactExtId),
5994
+ ...request.agentId ? { agent_ext_id: request.agentId } : {},
5995
+ ...request.previousResponseId ? { previous_response_id: request.previousResponseId } : {},
5996
+ ...request.conversationId ? { conversation_ext_id: request.conversationId } : {},
5997
+ ...request.model && !pa2 ? { model: request.model } : {},
5998
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5999
+ ...request.mentions && request.mentions.length > 0 ? { mentions: request.mentions } : {},
6000
+ ...request.assistantMode ? { assistant_mode: request.assistantMode } : {}
6001
+ };
6002
+ }
6003
+
6004
+ // src/operations/assistant.ts
5867
6005
  var MAX_RETRIEVE_DOC_IDS = 5e3;
5868
6006
  async function retrieve(options) {
5869
6007
  const {
5870
6008
  arbi,
5871
6009
  workspaceId,
5872
- query,
6010
+ query: query2,
5873
6011
  docIds,
5874
6012
  searchMode,
5875
6013
  fullContextDocIds,
@@ -5887,7 +6025,7 @@ async function retrieve(options) {
5887
6025
  tools.retrieval_toc = buildRetrievalTocTool(tocDocIds);
5888
6026
  }
5889
6027
  const body = {
5890
- input: query,
6028
+ input: query2,
5891
6029
  workspace_ext_id: workspaceId,
5892
6030
  stream: false,
5893
6031
  background: false,
@@ -5940,48 +6078,120 @@ function searchChunks(result) {
5940
6078
  return Array.from(byId3.values()).sort((a2, b2) => b2.score - a2.score);
5941
6079
  }
5942
6080
  async function queryAssistant(options) {
5943
- const {
5944
- workspaceId,
5945
- question,
5946
- docIds,
5947
- previousResponseId,
5948
- conversationId,
5949
- assistantMode,
5950
- agentId,
5951
- model,
5952
- mentions,
5953
- signal,
5954
- activeArtifactExtId,
5955
- ...auth
5956
- } = options;
5957
- const body = {
5958
- input: question,
5959
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5960
- workspace_ext_id: workspaceId,
5961
- ...agentId ? { agent_ext_id: agentId } : {},
5962
- stream: true,
5963
- background: false,
5964
- store: true,
5965
- tools: agentId ? {} : {
5966
- retrieval_chunk: buildRetrievalChunkTool(docIds),
5967
- retrieval_full_context: buildRetrievalFullContextTool([])
5968
- },
5969
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5970
- ...conversationId ? { conversation_ext_id: conversationId } : {},
5971
- ...assistantMode ? { assistant_mode: assistantMode } : {},
5972
- ...model ? { model } : {},
5973
- ...mentions && mentions.length > 0 ? { mentions } : {}
5974
- };
6081
+ const { baseUrl, accessToken, signal, ...request } = options;
5975
6082
  return authenticatedFetch({
5976
- ...auth,
6083
+ baseUrl,
6084
+ accessToken,
5977
6085
  path: "/v1/assistant/query",
5978
6086
  method: "POST",
5979
- body: JSON.stringify(body),
6087
+ body: JSON.stringify(buildTurnRequest(request)),
5980
6088
  headers: { "Content-Type": "application/json" },
5981
6089
  signal
5982
6090
  });
5983
6091
  }
5984
- async function respondToAgent(arbi, assistantMessageExtId, answer) {
6092
+ var AssistantTurnRefused = class extends ArbiApiError {
6093
+ /** Set when the refusal is the project's used-up AI usage. */
6094
+ quota;
6095
+ constructor(message, status, quota = null) {
6096
+ super(message, void 0, status);
6097
+ this.name = "AssistantTurnRefused";
6098
+ this.quota = quota;
6099
+ }
6100
+ };
6101
+ var SESSION_EXPIRED_MESSAGE = "Token has expired. Please log in again.";
6102
+ function quotaExceededFrom(detail) {
6103
+ if (!detail || typeof detail !== "object") return null;
6104
+ const d2 = detail;
6105
+ if (d2.code !== "QUOTA_EXCEEDED") return null;
6106
+ return {
6107
+ spend: Number(d2.spend ?? 0),
6108
+ budget: Number(d2.budget ?? 0),
6109
+ projectExtId: d2.project_ext_id ?? null,
6110
+ ...typeof d2.message === "string" ? { message: d2.message } : {}
6111
+ };
6112
+ }
6113
+ var LITELLM_BUDGET_RE = /ExceededBudget:\s*End User=(?<project>[^\s]+)\s+over budget\.\s*Spend=(?<spend>[0-9.]+),\s*Budget=(?<budget>[0-9.]+)/;
6114
+ function quotaFromStreamError(error) {
6115
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
6116
+ if (!message.includes("ExceededBudget")) return null;
6117
+ const match = message.match(LITELLM_BUDGET_RE);
6118
+ if (!match?.groups) return null;
6119
+ const spend = usdToGbp(Number(match.groups.spend));
6120
+ const budget = usdToGbp(Number(match.groups.budget));
6121
+ if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6122
+ return { spend, budget, projectExtId: match.groups.project ?? null };
6123
+ }
6124
+ async function readDetail(response) {
6125
+ try {
6126
+ return (await response.json())?.detail;
6127
+ } catch {
6128
+ return void 0;
6129
+ }
6130
+ }
6131
+ async function refusal(response) {
6132
+ const { status } = response;
6133
+ if (status === 409) {
6134
+ const detail2 = await readDetail(response);
6135
+ return new AssistantTurnRefused(
6136
+ detailText(detail2) || "This message has failed. Please retry from the previous message.",
6137
+ status
6138
+ );
6139
+ }
6140
+ if (status === 503) {
6141
+ return new AssistantTurnRefused(
6142
+ "The selected LLM is not responding. Please retry again in a minute or select another model.",
6143
+ status
6144
+ );
6145
+ }
6146
+ if (status === 402) {
6147
+ const detail2 = await readDetail(response);
6148
+ const quota = quotaExceededFrom(detail2);
6149
+ const message = quota?.message ?? (typeof detail2 === "string" ? detail2 : void 0) ?? detail2?.message ?? "This project's AI usage for this month is used up.";
6150
+ return new AssistantTurnRefused(
6151
+ message || "This project's AI usage for this month is used up.",
6152
+ status,
6153
+ quota
6154
+ );
6155
+ }
6156
+ const detail = await readDetail(response);
6157
+ return new AssistantTurnRefused(
6158
+ detailText(detail) || `HTTP error! status: ${status}`,
6159
+ status
6160
+ );
6161
+ }
6162
+ async function openTurnStream(auth, body, signal) {
6163
+ const response = await fetch(`${auth.baseUrl}/v1/assistant/query`, {
6164
+ method: "POST",
6165
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${auth.accessToken}` },
6166
+ body: JSON.stringify(body),
6167
+ signal,
6168
+ credentials: "include"
6169
+ });
6170
+ if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6171
+ if (!response.ok || !response.body) throw await refusal(response);
6172
+ return response;
6173
+ }
6174
+ async function openRunStream(auth, responseId, signal) {
6175
+ const response = await fetch(
6176
+ `${auth.baseUrl}/v1/assistant/run/${encodeURIComponent(responseId)}/stream`,
6177
+ {
6178
+ method: "GET",
6179
+ headers: { Authorization: `Bearer ${auth.accessToken}` },
6180
+ signal,
6181
+ credentials: "include"
6182
+ }
6183
+ );
6184
+ if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6185
+ if (!response.ok || !response.body) {
6186
+ throw new ArbiApiError(
6187
+ response.status === 404 ? "This run is no longer active." : `HTTP ${response.status}`,
6188
+ void 0,
6189
+ response.status
6190
+ );
6191
+ }
6192
+ return response;
6193
+ }
6194
+ async function interject(arbi, assistantMessageExtId, answer) {
5985
6195
  return requireData(
5986
6196
  await arbi.fetch.POST("/v1/assistant/interject", {
5987
6197
  body: { assistant_message_ext_id: assistantMessageExtId, answer }
@@ -6015,6 +6225,22 @@ async function listCommands(arbi) {
6015
6225
  );
6016
6226
  return result.commands;
6017
6227
  }
6228
+ async function transcribe(arbi, audio) {
6229
+ const result = requireData(
6230
+ await arbi.fetch.POST("/v1/assistant/transcribe", {
6231
+ // The generated type of a multipart binary field is `string`; the value is the Blob, sent as
6232
+ // real form data (openapi-fetch would JSON-encode a plain object).
6233
+ body: { audio },
6234
+ bodySerializer: (body) => {
6235
+ const form = new FormData();
6236
+ form.append("audio", body.audio, "voice-input.webm");
6237
+ return form;
6238
+ }
6239
+ }),
6240
+ "Failed to transcribe the recording"
6241
+ );
6242
+ return result.text;
6243
+ }
6018
6244
  function parseSlashCommand(input) {
6019
6245
  const m2 = /^\s*\/([a-zA-Z0-9_-]+)(?:\s+([\s\S]*))?$/.exec(input);
6020
6246
  if (!m2) return null;
@@ -6024,8 +6250,8 @@ function parseSlashTokenInProgress(buffer) {
6024
6250
  const m2 = /^\s*\/([a-zA-Z0-9_-]*)$/.exec(buffer);
6025
6251
  return m2 ? m2[1].toLowerCase() : null;
6026
6252
  }
6027
- function filterSkills(items, query, pinned = []) {
6028
- const q2 = query.toLowerCase();
6253
+ function filterSkills(items, query2, pinned = []) {
6254
+ const q2 = query2.toLowerCase();
6029
6255
  const pinnedSet = new Set(pinned);
6030
6256
  const key = (s2) => (s2.slug ?? s2.name).toLowerCase();
6031
6257
  const matched = q2 ? items.filter((s2) => key(s2).includes(q2)) : items.slice();
@@ -6040,7 +6266,7 @@ function filterSkills(items, query, pinned = []) {
6040
6266
  });
6041
6267
  return matched;
6042
6268
  }
6043
- async function cancelAssistantRun(auth, responseId) {
6269
+ async function cancelRun(auth, responseId) {
6044
6270
  await authenticatedFetch({
6045
6271
  ...auth,
6046
6272
  path: `/v1/assistant/run/${encodeURIComponent(responseId)}/cancel`,
@@ -6066,6 +6292,7 @@ async function submitBackgroundQuery(options) {
6066
6292
  conversationId,
6067
6293
  mentions,
6068
6294
  activeArtifactExtId,
6295
+ fullContext = true,
6069
6296
  ...auth
6070
6297
  } = options;
6071
6298
  const tools = {};
@@ -6076,12 +6303,13 @@ async function submitBackgroundQuery(options) {
6076
6303
  tool_args: { doc_ext_ids: docIds },
6077
6304
  tool_responses: {}
6078
6305
  };
6079
- tools.retrieval_full_context = {
6080
- name: "retrieval_full_context",
6081
- description: "retrieval full context",
6082
- tool_args: { doc_ext_ids: docIds },
6083
- tool_responses: {}
6084
- };
6306
+ if (fullContext)
6307
+ tools.retrieval_full_context = {
6308
+ name: "retrieval_full_context",
6309
+ description: "retrieval full context",
6310
+ tool_args: { doc_ext_ids: docIds },
6311
+ tool_responses: {}
6312
+ };
6085
6313
  }
6086
6314
  const body = {
6087
6315
  input: question,
@@ -6165,13 +6393,13 @@ var TAG_FIELD_TYPES = [
6165
6393
  "select",
6166
6394
  "person"
6167
6395
  ];
6168
- async function listTags(arbi, query = {}) {
6396
+ async function listTags(arbi, query2 = {}) {
6169
6397
  const params = {};
6170
- if (query.kind) params.kind = query.kind;
6171
- if (query.parentId) params.parent = query.parentId;
6172
- if (query.ids?.length) params.ids = query.ids;
6173
- if (query.include?.length) params.include = query.include;
6174
- if (query.linksLimit !== void 0) params.links_limit = query.linksLimit;
6398
+ if (query2.kind) params.kind = query2.kind;
6399
+ if (query2.parentId) params.parent = query2.parentId;
6400
+ if (query2.ids?.length) params.ids = query2.ids;
6401
+ if (query2.include?.length) params.include = query2.include;
6402
+ if (query2.linksLimit !== void 0) params.links_limit = query2.linksLimit;
6175
6403
  return requireData(
6176
6404
  await arbi.fetch.GET(
6177
6405
  "/v1/tag/",
@@ -7553,7 +7781,6 @@ async function getFileContent(auth, fileId) {
7553
7781
  var sessions_exports = {};
7554
7782
  __export(sessions_exports, {
7555
7783
  listSessions: () => listSessions,
7556
- logoutAllSessions: () => logoutAllSessions,
7557
7784
  terminateSession: () => terminateSession
7558
7785
  });
7559
7786
  async function listSessions(arbi) {
@@ -7568,12 +7795,6 @@ async function terminateSession(arbi, sessionId) {
7568
7795
  "Failed to end session"
7569
7796
  );
7570
7797
  }
7571
- async function logoutAllSessions(arbi) {
7572
- requireOk(
7573
- await arbi.fetch.POST("/v1/user/logout", { params: { query: { all_sessions: true } } }),
7574
- "Failed to sign out of all sessions"
7575
- );
7576
- }
7577
7798
 
7578
7799
  // src/operations/profile.ts
7579
7800
  var profile_exports = {};
@@ -7647,7 +7868,7 @@ __export(identity_exports, {
7647
7868
  remove: () => remove,
7648
7869
  startSession: () => startSession
7649
7870
  });
7650
- function refusal(apiError) {
7871
+ function refusal2(apiError) {
7651
7872
  const detail = apiError?.detail;
7652
7873
  if (typeof detail === "string") return { message: detail };
7653
7874
  if (detail && typeof detail === "object" && !Array.isArray(detail)) {
@@ -7660,12 +7881,12 @@ function refusal(apiError) {
7660
7881
  return {};
7661
7882
  }
7662
7883
  function identityErrorCode(error) {
7663
- return error instanceof ArbiApiError ? refusal(error.apiError).code : void 0;
7884
+ return error instanceof ArbiApiError ? refusal2(error.apiError).code : void 0;
7664
7885
  }
7665
7886
  function unwrap(result, fallback) {
7666
7887
  if (result.error || result.data === void 0) {
7667
7888
  throw new ArbiApiError(
7668
- refusal(result.error).message ?? fallback,
7889
+ refusal2(result.error).message ?? fallback,
7669
7890
  result.error,
7670
7891
  result.response?.status
7671
7892
  );
@@ -7735,13 +7956,13 @@ __export(projects_exports, {
7735
7956
  updateProject: () => updateProject
7736
7957
  });
7737
7958
  async function listProjects(arbi, filters = {}) {
7738
- const query = {};
7739
- if (filters.stage) query.stage = filters.stage;
7740
- if (filters.leadUser) query.lead_user = filters.leadUser;
7959
+ const query2 = {};
7960
+ if (filters.stage) query2.stage = filters.stage;
7961
+ if (filters.leadUser) query2.lead_user = filters.leadUser;
7741
7962
  return requireData(
7742
7963
  await arbi.fetch.GET(
7743
7964
  "/v1/user/projects/",
7744
- Object.keys(query).length ? { params: { query } } : void 0
7965
+ Object.keys(query2).length ? { params: { query: query2 } } : void 0
7745
7966
  ),
7746
7967
  "Failed to fetch projects"
7747
7968
  );
@@ -7755,12 +7976,12 @@ async function createProject(arbi, name, plan = "free", details = {}) {
7755
7976
  );
7756
7977
  }
7757
7978
  async function listProjectEvents(arbi, projectExtId, options = {}) {
7758
- const query = {};
7759
- if (options.kind) query.kind = options.kind;
7760
- if (options.limit !== void 0) query.limit = options.limit;
7979
+ const query2 = {};
7980
+ if (options.kind) query2.kind = options.kind;
7981
+ if (options.limit !== void 0) query2.limit = options.limit;
7761
7982
  return requireData(
7762
7983
  await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/events", {
7763
- params: { path: { project_ext_id: projectExtId }, query }
7984
+ params: { path: { project_ext_id: projectExtId }, query: query2 }
7764
7985
  }),
7765
7986
  "Failed to fetch project events"
7766
7987
  );
@@ -9522,150 +9743,858 @@ async function cancelPublicBooking(baseUrl, slug, token) {
9522
9743
  if (!res.ok) throw await bookingError(res);
9523
9744
  }
9524
9745
 
9525
- // src/arbi.ts
9526
- function tokenExpiresWithin(token, seconds) {
9527
- const expiresAt = readSessionClaims(token)?.expiresAt;
9528
- return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
9746
+ // src/operations/calls.ts
9747
+ var calls_exports = {};
9748
+ __export(calls_exports, {
9749
+ CallApiError: () => CallApiError,
9750
+ WEBINAR_MODERATORS: () => WEBINAR_MODERATORS,
9751
+ WEBINAR_TEAM: () => WEBINAR_TEAM,
9752
+ askQuestion: () => askQuestion,
9753
+ callError: () => callError,
9754
+ cancelCall: () => cancelCall,
9755
+ commitRecordingPart: () => commitRecordingPart,
9756
+ createCall: () => createCall,
9757
+ createCallInviteLink: () => createCallInviteLink,
9758
+ createRecordingTrack: () => createRecordingTrack,
9759
+ decideKnock: () => decideKnock,
9760
+ declineCall: () => declineCall,
9761
+ deleteQuestion: () => deleteQuestion,
9762
+ deleteRecording: () => deleteRecording,
9763
+ deleteRecordingMedia: () => deleteRecordingMedia,
9764
+ demoteFromStage: () => demoteFromStage,
9765
+ downloadRecordingPart: () => downloadRecordingPart,
9766
+ fetchCallToken: () => fetchCallToken,
9767
+ getCall: () => getCall,
9768
+ getCallRecording: () => getCallRecording,
9769
+ getCallsConfig: () => getCallsConfig,
9770
+ getOrCreateCallChat: () => getOrCreateCallChat,
9771
+ getRecordingQuota: () => getRecordingQuota,
9772
+ getWebinar: () => getWebinar,
9773
+ isQuotaError: () => isQuotaError,
9774
+ knockCall: () => knockCall,
9775
+ listCallInviteLinks: () => listCallInviteLinks,
9776
+ listCallRecordings: () => listCallRecordings,
9777
+ listQuestions: () => listQuestions,
9778
+ muteCallParticipant: () => muteCallParticipant,
9779
+ pollKnock: () => pollKnock,
9780
+ postChatTranscriptLine: () => postChatTranscriptLine,
9781
+ presignRecordingPart: () => presignRecordingPart,
9782
+ promoteToStage: () => promoteToStage,
9783
+ quotaNeedsWarning: () => quotaNeedsWarning,
9784
+ recordingStateFrom: () => recordingStateFrom,
9785
+ recordingStateOfCall: () => recordingStateOfCall,
9786
+ removeCallParticipant: () => removeCallParticipant,
9787
+ revokeCallInviteLink: () => revokeCallInviteLink,
9788
+ ringCall: () => ringCall,
9789
+ setCallTranscription: () => setCallTranscription,
9790
+ setRecordingExpiry: () => setRecordingExpiry,
9791
+ setWebinarHand: () => setWebinarHand,
9792
+ startCallRecording: () => startCallRecording,
9793
+ stopCallRecording: () => stopCallRecording,
9794
+ transcribeCallSegment: () => transcribeCallSegment,
9795
+ transcribeRecordingPart: () => transcribeRecordingPart,
9796
+ transcriptionStateFrom: () => transcriptionStateFrom,
9797
+ updateCall: () => updateCall,
9798
+ updateQuestion: () => updateQuestion,
9799
+ updateWebinar: () => updateWebinar,
9800
+ voteQuestion: () => voteQuestion
9801
+ });
9802
+
9803
+ // src/transcription-hints.ts
9804
+ var LANGUAGE_PATTERN = /^[a-z]{2}$/;
9805
+ var PROMPT_MAX_CHARS = 500;
9806
+ var PROMPT_CONTEXT_CHARS = 200;
9807
+ function continuityPrompt(previous) {
9808
+ const text = previous?.replace(/\s+/g, " ").trim();
9809
+ if (!text) return void 0;
9810
+ if (text.length <= PROMPT_CONTEXT_CHARS) return text;
9811
+ const tail = text.slice(-PROMPT_CONTEXT_CHARS);
9812
+ const space = tail.indexOf(" ");
9813
+ const trimmed = space >= 0 && space < tail.length - 1 ? tail.slice(space + 1) : tail;
9814
+ return trimmed || void 0;
9815
+ }
9816
+ function appendTranscriptionHints(form, hints) {
9817
+ if (hints.language && LANGUAGE_PATTERN.test(hints.language)) {
9818
+ form.append("language", hints.language);
9819
+ }
9820
+ const prompt = hints.prompt?.trim().slice(0, PROMPT_MAX_CHARS);
9821
+ if (prompt) form.append("prompt", prompt);
9529
9822
  }
9530
- var Arbi = class {
9531
- client = null;
9532
- loginResult = null;
9533
- userProfile = null;
9534
- profileListeners = /* @__PURE__ */ new Set();
9535
- currentWorkspaceId = null;
9536
- /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
9537
- wrappedKeys = /* @__PURE__ */ new Map();
9538
- /** Workspaces whose key this server session holds (`workspaces.open`), keyed per session key. */
9539
- openedWorkspaces = /* @__PURE__ */ new Map();
9540
- openedForSessionKey = null;
9541
- chatCryptoContext = null;
9542
- /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
9543
- chatRings = /* @__PURE__ */ new Map();
9544
- sessionExpiredListeners = /* @__PURE__ */ new Set();
9545
- options;
9546
- constructor(options) {
9547
- this.options = options;
9548
- if (options.session) {
9549
- this.client = options.session.client;
9550
- this.loginResult = options.session.login;
9551
- this.userProfile = options.session.login.profile ?? null;
9552
- this.currentWorkspaceId = options.session.workspaceId ?? null;
9553
- }
9554
- }
9555
- // ── Lifecycle ───────────────────────────────────────────────────────────
9556
- /**
9557
- * The deployment domain the user's keys are derived for: `deploymentDomain` when given,
9558
- * otherwise the hostname of `url`. Signing and password changes re-derive keys with it, so a
9559
- * host that needs it (the document tools' e-signing) reads it here rather than recomputing it.
9560
- */
9561
- getDeploymentDomain() {
9562
- return this.options.deploymentDomain ?? new URL(this.options.url).hostname;
9563
- }
9564
- /** Initialize the SDK client and sodium crypto. Called automatically by login(). */
9565
- async init() {
9566
- if (this.client) return this.client;
9567
- const domain = this.getDeploymentDomain();
9568
- this.client = createArbiClient({
9569
- baseUrl: this.options.url,
9570
- deploymentDomain: domain,
9571
- credentials: this.options.credentials ?? "omit",
9572
- // A silent re-login rotates the server session key: keep ours in step, or the next
9573
- // workspace open would seal the key for a session the server no longer has.
9574
- onReloginSuccess: ({ serverSessionKey }) => {
9575
- if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
9576
- },
9577
- onSessionExpired: () => this.expireSession()
9578
- });
9579
- await this.client.crypto.initSodium();
9580
- return this.client;
9581
- }
9582
- /**
9583
- * Request a verification email for registration.
9584
- * The user will receive an email with a 3-word verification code.
9585
- */
9586
- async requestVerification(email) {
9587
- const client = await this.init();
9588
- await client.fetch.POST("/v1/user/verify-email", { body: { email } });
9589
- }
9590
- /**
9591
- * Register a new account using the verification code received by email.
9592
- */
9593
- async register(params) {
9594
- const client = await this.init();
9595
- await client.auth.register(params);
9596
- }
9597
- /**
9598
- * Log in with email and password.
9599
- * Initializes the SDK client if not already done.
9600
- */
9601
- async login(email, password) {
9602
- const client = await this.init();
9603
- this.loginResult = await client.auth.login({ email, password });
9604
- this.userProfile = this.loginResult.profile ?? null;
9605
- }
9606
- /**
9607
- * Recover a session using a stored signing private key (base64).
9608
- * Useful for session recovery without re-entering the password.
9609
- */
9610
- async loginWithKey(email, signingPrivateKeyBase64) {
9611
- const client = await this.init();
9612
- const signingPrivateKey = client.crypto.base64ToBytes(signingPrivateKeyBase64);
9613
- this.loginResult = await client.auth.loginWithKey({ email, signingPrivateKey });
9614
- this.userProfile = this.loginResult.profile ?? null;
9615
- }
9616
- /** Recover browser authentication using the encrypted signing key already in IndexedDB. */
9617
- async restoreSession(email) {
9618
- const client = await this.init();
9619
- const saved = await client.storage.getSession();
9620
- if (!saved?.signingPrivateKey) return false;
9621
- this.loginResult = await client.auth.loginWithKey({
9622
- email,
9623
- signingPrivateKey: saved.signingPrivateKey
9624
- });
9625
- this.userProfile = this.loginResult.profile ?? null;
9626
- return true;
9823
+
9824
+ // src/operations/call-errors.ts
9825
+ var CallApiError = class extends ArbiApiError {
9826
+ code;
9827
+ constructor(message, status, code, apiError) {
9828
+ super(message, apiError ?? (code ? { detail: code } : void 0), status);
9829
+ this.name = "CallApiError";
9830
+ this.code = code;
9627
9831
  }
9628
- /** Remember the wrapped keys of workspaces the server just returned. */
9629
- rememberWorkspaces(workspaces) {
9630
- for (const ws of workspaces) {
9631
- if (ws.wrapped_key) this.wrappedKeys.set(ws.external_id, ws.wrapped_key);
9632
- }
9633
- return workspaces;
9832
+ };
9833
+ var CODE_TEXT = {
9834
+ // calls
9835
+ locked: "This call is locked.",
9836
+ knock_required: "The host has to let you in.",
9837
+ invalid_invite: "This invitation is no longer valid. Ask the host for a new one.",
9838
+ stale_link: "This call link is no longer valid. Ask for a new one.",
9839
+ cancelled: "This call was cancelled.",
9840
+ not_a_contact: "You can only call people in your contacts.",
9841
+ workspace_locked: "Only members of the thread\u2019s workspace can join this call.",
9842
+ agent_not_allowed: "Agents cannot take part in calls.",
9843
+ thread_not_shared: "Calls can only be started in shared threads.",
9844
+ contact_has_no_email: "This contact has no e-mail address to send a link to.",
9845
+ contact_registered: "This contact has an ARBI account: ring them instead.",
9846
+ invalid_link: "The call link is not valid.",
9847
+ host_only: "Only the host can do that.",
9848
+ // transcription
9849
+ transcription_off: "Transcription is off.",
9850
+ speaker_mismatch: "Only the speaker (or a member, for a workspace guest) can store this line.",
9851
+ // recording
9852
+ storage_quota_exceeded: "The storage quota is full: recording stopped.",
9853
+ already_recording: "The call is already being recorded.",
9854
+ recording_stopped: "The recording has stopped.",
9855
+ recording_active: "Stop the recording first.",
9856
+ composite_needs_video: "This recording has no video.",
9857
+ not_a_member: "Only members of the meeting chat can open this recording.",
9858
+ part_committed: "That part is already stored.",
9859
+ part_not_uploaded: "The part did not reach the storage.",
9860
+ size_mismatch: "The uploaded part has the wrong size.",
9861
+ // webinars
9862
+ moderator_only: "Only the host or a co-host can do that.",
9863
+ team_only: "Only the host and panelists can do that.",
9864
+ host_not_demotable: "The host stays on stage.",
9865
+ on_stage: "You are already on stage.",
9866
+ own_question: "You cannot upvote your own question.",
9867
+ question_dismissed: "This question was dismissed.",
9868
+ question_not_open: "This question is no longer open.",
9869
+ webinar_not_live: "The webinar has not started yet.",
9870
+ not_on_stage: "Only people on stage can do that."
9871
+ };
9872
+ var TRANSCRIBE_STATUS_TEXT = {
9873
+ 413: "That audio clip is too large to transcribe.",
9874
+ 429: "Transcribing too fast \u2014 slowing down.",
9875
+ 502: "The transcriber did not answer.",
9876
+ 503: "Transcription is not available on this server."
9877
+ };
9878
+ function callError(error, status, fallback, options = {}) {
9879
+ const detail = apiErrorDetail(error);
9880
+ const quota = !!options.quota && (status === 507 || status === 402);
9881
+ const code = (detail && /^[a-z_]+$/.test(detail) ? detail : void 0) ?? (quota ? "storage_quota_exceeded" : void 0);
9882
+ const message = code && (options.texts?.[code] ?? CODE_TEXT[code]) || (status !== void 0 ? options.statusTexts?.[status] : void 0) || detail || `${fallback} (${status ?? "?"})`;
9883
+ return new CallApiError(message, status, code, error);
9884
+ }
9885
+ function isQuotaError(err) {
9886
+ if (!(err instanceof CallApiError)) return false;
9887
+ return err.code === "storage_quota_exceeded" || err.status === 507 || err.status === 402;
9888
+ }
9889
+ async function unwrapCall(result, fallback, options) {
9890
+ const { data, error, response } = await result;
9891
+ if (error !== void 0 || !response.ok) {
9892
+ throw callError(error, response.status, fallback, options);
9634
9893
  }
9635
- /**
9636
- * A workspace's wrapped key: from the cache when a list or create already returned it, else from
9637
- * a fresh workspace list (a workspace created or shared since the last list).
9638
- */
9639
- async wrappedKeyFor(workspaceId, refresh2 = false) {
9640
- const cached = refresh2 ? void 0 : this.wrappedKeys.get(workspaceId);
9641
- if (cached) return { wrappedKey: cached, fromCache: true };
9642
- this.wrappedKeys.delete(workspaceId);
9643
- this.rememberWorkspaces(await listWorkspaces(this.requireClient()));
9644
- const wrappedKey = this.wrappedKeys.get(workspaceId);
9645
- if (!wrappedKey) {
9646
- throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
9647
- }
9648
- return { wrappedKey, fromCache: false };
9894
+ return data;
9895
+ }
9896
+
9897
+ // src/operations/call-webinars.ts
9898
+ var WEBINAR_MODERATORS = /* @__PURE__ */ new Set(["host", "cohost"]);
9899
+ var WEBINAR_TEAM = /* @__PURE__ */ new Set(["host", "cohost", "panelist"]);
9900
+ var query = (linkVersion) => linkVersion == null ? void 0 : { link_version: linkVersion };
9901
+ var webinarParams = (callExtId, linkVersion) => ({
9902
+ params: { path: { call_ext_id: callExtId }, query: query(linkVersion) }
9903
+ });
9904
+ var stageParams = (callExtId, identity, linkVersion) => ({
9905
+ params: { path: { call_ext_id: callExtId, identity }, query: query(linkVersion) }
9906
+ });
9907
+ var questionParams = (callExtId, questionExtId, linkVersion) => ({
9908
+ params: {
9909
+ path: { call_ext_id: callExtId, question_ext_id: questionExtId },
9910
+ query: query(linkVersion)
9649
9911
  }
9650
- /**
9651
- * Run `withKey` with the workspace's wrapped key. A cached key that no longer works (access was
9652
- * re-granted with a new key) is dropped and the call retried once with a fresh list.
9653
- */
9654
- async withWrappedKey(workspaceId, withKey) {
9655
- const { wrappedKey, fromCache } = await this.wrappedKeyFor(workspaceId);
9656
- try {
9657
- return await withKey(wrappedKey);
9658
- } catch (error) {
9659
- if (!fromCache) throw error;
9660
- const fresh = await this.wrappedKeyFor(workspaceId, true);
9661
- return withKey(fresh.wrappedKey);
9662
- }
9912
+ });
9913
+ function getWebinar(arbi, callExtId, linkVersion) {
9914
+ return unwrapCall(
9915
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/webinar", webinarParams(callExtId, linkVersion)),
9916
+ "Could not read the webinar"
9917
+ );
9918
+ }
9919
+ function updateWebinar(arbi, callExtId, body, linkVersion) {
9920
+ return unwrapCall(
9921
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/webinar", {
9922
+ ...webinarParams(callExtId, linkVersion),
9923
+ body
9924
+ }),
9925
+ "Could not update the webinar"
9926
+ );
9927
+ }
9928
+ function setWebinarHand(arbi, callExtId, raised, linkVersion) {
9929
+ return unwrapCall(
9930
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/hand", {
9931
+ ...webinarParams(callExtId, linkVersion),
9932
+ body: { raised }
9933
+ }),
9934
+ raised ? "Could not raise your hand" : "Could not lower your hand"
9935
+ );
9936
+ }
9937
+ async function promoteToStage(arbi, callExtId, identity, linkVersion) {
9938
+ await unwrapCall(
9939
+ arbi.fetch.POST(
9940
+ "/v1/calls/{call_ext_id}/webinar/stage/{identity}",
9941
+ stageParams(callExtId, identity, linkVersion)
9942
+ ),
9943
+ "Could not bring them on stage"
9944
+ );
9945
+ }
9946
+ async function demoteFromStage(arbi, callExtId, identity, linkVersion) {
9947
+ await unwrapCall(
9948
+ arbi.fetch.DELETE(
9949
+ "/v1/calls/{call_ext_id}/webinar/stage/{identity}",
9950
+ stageParams(callExtId, identity, linkVersion)
9951
+ ),
9952
+ "Could not move them to the audience"
9953
+ );
9954
+ }
9955
+ function listQuestions(arbi, callExtId, linkVersion) {
9956
+ return unwrapCall(
9957
+ arbi.fetch.GET(
9958
+ "/v1/calls/{call_ext_id}/webinar/questions",
9959
+ webinarParams(callExtId, linkVersion)
9960
+ ),
9961
+ "Could not load the questions"
9962
+ );
9963
+ }
9964
+ function askQuestion(arbi, callExtId, bodyCiphertext, linkVersion) {
9965
+ return unwrapCall(
9966
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/questions", {
9967
+ ...webinarParams(callExtId, linkVersion),
9968
+ body: { body: bodyCiphertext }
9969
+ }),
9970
+ "Could not ask the question"
9971
+ );
9972
+ }
9973
+ function voteQuestion(arbi, callExtId, questionExtId, up, linkVersion) {
9974
+ return unwrapCall(
9975
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}/vote", {
9976
+ ...questionParams(callExtId, questionExtId, linkVersion),
9977
+ body: { up }
9978
+ }),
9979
+ "Could not vote"
9980
+ );
9981
+ }
9982
+ function updateQuestion(arbi, callExtId, questionExtId, body, linkVersion) {
9983
+ return unwrapCall(
9984
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}", {
9985
+ ...questionParams(callExtId, questionExtId, linkVersion),
9986
+ body
9987
+ }),
9988
+ "Could not update the question"
9989
+ );
9990
+ }
9991
+ async function deleteQuestion(arbi, callExtId, questionExtId, linkVersion) {
9992
+ await unwrapCall(
9993
+ arbi.fetch.DELETE(
9994
+ "/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}",
9995
+ questionParams(callExtId, questionExtId, linkVersion)
9996
+ ),
9997
+ "Could not delete the question"
9998
+ );
9999
+ }
10000
+
10001
+ // src/operations/calls.ts
10002
+ var RECORDING = { quota: true };
10003
+ var TRANSCRIBE = { statusTexts: TRANSCRIBE_STATUS_TEXT };
10004
+ var callPath = (callExtId) => ({ params: { path: { call_ext_id: callExtId } } });
10005
+ var recPath = (callExtId, recordingExtId) => ({
10006
+ params: { path: { call_ext_id: callExtId, recording_ext_id: recordingExtId } }
10007
+ });
10008
+ var trackPath = (callExtId, recordingExtId, trackExtId) => ({
10009
+ params: {
10010
+ path: { call_ext_id: callExtId, recording_ext_id: recordingExtId, track_ext_id: trackExtId }
9663
10011
  }
9664
- /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
9665
- async sealWorkspaceKey(workspaceId) {
9666
- const client = this.requireClient();
9667
- const lr2 = this.requireLogin();
9668
- return this.withWrappedKey(
10012
+ });
10013
+ function getCallsConfig(arbi) {
10014
+ return unwrapCall(arbi.fetch.GET("/v1/calls/config"), "Could not read the calls config");
10015
+ }
10016
+ function createCall(arbi, body) {
10017
+ return unwrapCall(arbi.fetch.POST("/v1/calls", { body }), "Could not create the call");
10018
+ }
10019
+ function getCall(arbi, callExtId) {
10020
+ return unwrapCall(
10021
+ arbi.fetch.GET("/v1/calls/{call_ext_id}", callPath(callExtId)),
10022
+ "Could not open the call"
10023
+ );
10024
+ }
10025
+ function updateCall(arbi, callExtId, body) {
10026
+ return unwrapCall(
10027
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}", {
10028
+ ...callPath(callExtId),
10029
+ body
10030
+ }),
10031
+ "Could not update the call"
10032
+ );
10033
+ }
10034
+ async function cancelCall(arbi, callExtId) {
10035
+ await unwrapCall(
10036
+ arbi.fetch.DELETE("/v1/calls/{call_ext_id}", callPath(callExtId)),
10037
+ "Could not cancel the call"
10038
+ );
10039
+ }
10040
+ function fetchCallToken(arbi, callExtId, linkVersion, inviteToken) {
10041
+ return unwrapCall(
10042
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/token", {
10043
+ ...callPath(callExtId),
10044
+ body: {
10045
+ link_version: linkVersion ?? null,
10046
+ ...inviteToken ? { invite_token: inviteToken } : {}
10047
+ }
10048
+ }),
10049
+ "Could not join the call"
10050
+ );
10051
+ }
10052
+ async function ringCall(arbi, callExtId, sealedKeys, linkVersion) {
10053
+ await unwrapCall(
10054
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/ring", {
10055
+ ...callPath(callExtId),
10056
+ body: { sealed_keys: sealedKeys, link_version: linkVersion ?? null }
10057
+ }),
10058
+ "Could not ring"
10059
+ );
10060
+ }
10061
+ async function declineCall(arbi, callExtId) {
10062
+ await unwrapCall(
10063
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/decline", callPath(callExtId)),
10064
+ "Could not decline"
10065
+ );
10066
+ }
10067
+ function knockCall(arbi, callExtId, linkVersion) {
10068
+ return unwrapCall(
10069
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/knock", {
10070
+ ...callPath(callExtId),
10071
+ body: { link_version: linkVersion }
10072
+ }),
10073
+ "Could not ask to join"
10074
+ );
10075
+ }
10076
+ function pollKnock(arbi, callExtId, knockId) {
10077
+ return unwrapCall(
10078
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/knock/{knock_id}", {
10079
+ params: { path: { call_ext_id: callExtId, knock_id: knockId } }
10080
+ }),
10081
+ "Could not check the request"
10082
+ );
10083
+ }
10084
+ async function decideKnock(arbi, callExtId, knockId, admit) {
10085
+ await unwrapCall(
10086
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/knock/{knock_id}", {
10087
+ params: { path: { call_ext_id: callExtId, knock_id: knockId } },
10088
+ body: { admit }
10089
+ }),
10090
+ "Could not answer the request"
10091
+ );
10092
+ }
10093
+ async function getOrCreateCallChat(arbi, callExtId, body) {
10094
+ const { data, error, response } = await arbi.fetch.POST("/v1/calls/{call_ext_id}/chat", {
10095
+ ...callPath(callExtId),
10096
+ // A thread call's meeting thread takes no body.
10097
+ ...body ? { body } : {}
10098
+ });
10099
+ if (response.status === 409) {
10100
+ throw new CallApiError(
10101
+ "Open the call's workspace to keep its meeting chat.",
10102
+ 409,
10103
+ "workspace_required",
10104
+ error
10105
+ );
10106
+ }
10107
+ if (error !== void 0 || !response.ok || !data) {
10108
+ throw callError(error, response.status, "Could not open the meeting chat");
10109
+ }
10110
+ return data;
10111
+ }
10112
+ function createCallInviteLink(arbi, callExtId, body) {
10113
+ return unwrapCall(
10114
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/invite-links", { ...callPath(callExtId), body }),
10115
+ "Could not send the invitation"
10116
+ );
10117
+ }
10118
+ function listCallInviteLinks(arbi, callExtId) {
10119
+ return unwrapCall(
10120
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/invite-links", callPath(callExtId)),
10121
+ "Could not list the invitations"
10122
+ );
10123
+ }
10124
+ async function revokeCallInviteLink(arbi, callExtId, inviteLinkExtId) {
10125
+ await unwrapCall(
10126
+ arbi.fetch.DELETE("/v1/calls/{call_ext_id}/invite-links/{invite_link_ext_id}", {
10127
+ params: { path: { call_ext_id: callExtId, invite_link_ext_id: inviteLinkExtId } }
10128
+ }),
10129
+ "Could not revoke the invitation"
10130
+ );
10131
+ }
10132
+ async function removeCallParticipant(arbi, callExtId, identity) {
10133
+ await unwrapCall(
10134
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/participants/{identity}/remove", {
10135
+ params: { path: { call_ext_id: callExtId, identity } }
10136
+ }),
10137
+ "Could not remove the participant"
10138
+ );
10139
+ }
10140
+ async function muteCallParticipant(arbi, callExtId, identity, track) {
10141
+ await unwrapCall(
10142
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/participants/{identity}/mute", {
10143
+ params: { path: { call_ext_id: callExtId, identity } },
10144
+ body: { track }
10145
+ }),
10146
+ track === "audio" ? "Could not mute the participant" : "Could not turn off the camera"
10147
+ );
10148
+ }
10149
+ function transcriptionStateFrom(value) {
10150
+ if (!value || typeof value !== "object") return null;
10151
+ const v2 = value;
10152
+ if (typeof v2.on !== "boolean") return null;
10153
+ return {
10154
+ on: v2.on,
10155
+ by_identity: typeof v2.by_identity === "string" ? v2.by_identity : null,
10156
+ by_name: typeof v2.by_name === "string" ? v2.by_name : null
10157
+ };
10158
+ }
10159
+ async function setCallTranscription(arbi, callExtId, on) {
10160
+ const data = await unwrapCall(
10161
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/transcription", {
10162
+ ...callPath(callExtId),
10163
+ body: { on }
10164
+ }),
10165
+ "Could not change transcription",
10166
+ { texts: { host_only: "Only the host can turn transcription on or off." } }
10167
+ );
10168
+ return transcriptionStateFrom(data);
10169
+ }
10170
+ function transcribeCallSegment(arbi, callExtId, params) {
10171
+ const ext = params.audio.type.includes("mp4") ? "m4a" : "webm";
10172
+ return unwrapCall(
10173
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/transcribe", {
10174
+ ...callPath(callExtId),
10175
+ // A multipart binary field is typed `string`; the runtime value is the Blob. openapi-fetch has
10176
+ // no multipart serialization, so build real FormData.
10177
+ body: {
10178
+ audio: params.audio,
10179
+ segment_id: params.segmentId,
10180
+ started_at: params.startedAt ?? null,
10181
+ link_version: params.linkVersion ?? null
10182
+ },
10183
+ bodySerializer: (body) => {
10184
+ const form = new FormData();
10185
+ form.append("audio", body.audio, `segment.${ext}`);
10186
+ form.append("segment_id", body.segment_id);
10187
+ if (body.started_at) form.append("started_at", body.started_at);
10188
+ if (body.link_version) form.append("link_version", String(body.link_version));
10189
+ appendTranscriptionHints(form, { language: params.language, prompt: params.prompt });
10190
+ return form;
10191
+ }
10192
+ }),
10193
+ "Could not transcribe",
10194
+ TRANSCRIBE
10195
+ );
10196
+ }
10197
+ function postChatTranscriptLine(arbi, chatExtId, body) {
10198
+ return unwrapCall(
10199
+ arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
10200
+ params: { path: { chat_ext_id: chatExtId } },
10201
+ body: { ...body, kind: "transcript", context_only: false }
10202
+ }),
10203
+ "Could not save the transcript",
10204
+ TRANSCRIBE
10205
+ );
10206
+ }
10207
+ function recordingStateFrom(value) {
10208
+ if (!value || typeof value !== "object") return null;
10209
+ const v2 = value;
10210
+ if (typeof v2.on !== "boolean") return null;
10211
+ const str2 = (x2) => typeof x2 === "string" && x2 ? x2 : null;
10212
+ return {
10213
+ on: v2.on,
10214
+ mode: v2.mode === "audio" || v2.mode === "audio_video" ? v2.mode : null,
10215
+ recording_ext_id: str2(v2.recording_ext_id),
10216
+ by_identity: str2(v2.by_identity),
10217
+ by_name: str2(v2.by_name),
10218
+ reason: str2(v2.reason),
10219
+ started_at: str2(v2.started_at)
10220
+ };
10221
+ }
10222
+ function recordingStateOfCall(call) {
10223
+ return recordingStateFrom(call.recording);
10224
+ }
10225
+ function quotaNeedsWarning(quota) {
10226
+ if (quota.near_limit) return true;
10227
+ return quota.remaining_mb != null && quota.remaining_mb < quota.min_start_mb;
10228
+ }
10229
+ function getRecordingQuota(arbi, callExtId) {
10230
+ return unwrapCall(
10231
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/recording/quota", callPath(callExtId)),
10232
+ "Could not read the storage quota",
10233
+ RECORDING
10234
+ );
10235
+ }
10236
+ async function startCallRecording(arbi, callExtId, mode) {
10237
+ const data = await unwrapCall(
10238
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recording", {
10239
+ ...callPath(callExtId),
10240
+ body: { mode }
10241
+ }),
10242
+ "Could not start recording",
10243
+ RECORDING
10244
+ );
10245
+ return recordingStateFrom(data);
10246
+ }
10247
+ async function stopCallRecording(arbi, callExtId) {
10248
+ const data = await unwrapCall(
10249
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recording/stop", callPath(callExtId)),
10250
+ "Could not stop recording",
10251
+ RECORDING
10252
+ );
10253
+ return recordingStateFrom(data);
10254
+ }
10255
+ function createRecordingTrack(arbi, callExtId, recordingExtId, body) {
10256
+ return unwrapCall(
10257
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks", {
10258
+ ...recPath(callExtId, recordingExtId),
10259
+ body
10260
+ }),
10261
+ "Could not start the recording track",
10262
+ RECORDING
10263
+ );
10264
+ }
10265
+ function presignRecordingPart(arbi, callExtId, recordingExtId, trackExtId, body) {
10266
+ return unwrapCall(
10267
+ arbi.fetch.POST(
10268
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks/{track_ext_id}/parts",
10269
+ { ...trackPath(callExtId, recordingExtId, trackExtId), body }
10270
+ ),
10271
+ "Could not upload a recording part",
10272
+ RECORDING
10273
+ );
10274
+ }
10275
+ async function commitRecordingPart(arbi, callExtId, recordingExtId, trackExtId, seq) {
10276
+ await unwrapCall(
10277
+ arbi.fetch.POST(
10278
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks/{track_ext_id}/parts/{seq}/commit",
10279
+ {
10280
+ params: {
10281
+ path: {
10282
+ call_ext_id: callExtId,
10283
+ recording_ext_id: recordingExtId,
10284
+ track_ext_id: trackExtId,
10285
+ seq
10286
+ }
10287
+ }
10288
+ }
10289
+ ),
10290
+ "Could not commit a recording part",
10291
+ RECORDING
10292
+ );
10293
+ }
10294
+ function listCallRecordings(arbi, callExtId) {
10295
+ return unwrapCall(
10296
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/recordings", callPath(callExtId)),
10297
+ "Could not list the recordings",
10298
+ RECORDING
10299
+ );
10300
+ }
10301
+ function getCallRecording(arbi, callExtId, recordingExtId) {
10302
+ return unwrapCall(
10303
+ arbi.fetch.GET(
10304
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}",
10305
+ recPath(callExtId, recordingExtId)
10306
+ ),
10307
+ "Could not open the recording",
10308
+ RECORDING
10309
+ );
10310
+ }
10311
+ function setRecordingExpiry(arbi, callExtId, recordingExtId, expiresAt) {
10312
+ return unwrapCall(
10313
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}", {
10314
+ ...recPath(callExtId, recordingExtId),
10315
+ body: { expires_at: expiresAt }
10316
+ }),
10317
+ "Could not change the expiry",
10318
+ RECORDING
10319
+ );
10320
+ }
10321
+ function deleteRecordingMedia(arbi, callExtId, recordingExtId) {
10322
+ return unwrapCall(
10323
+ arbi.fetch.DELETE(
10324
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/media",
10325
+ recPath(callExtId, recordingExtId)
10326
+ ),
10327
+ "Could not delete the recording media",
10328
+ RECORDING
10329
+ );
10330
+ }
10331
+ async function deleteRecording(arbi, callExtId, recordingExtId) {
10332
+ await unwrapCall(
10333
+ arbi.fetch.DELETE(
10334
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}",
10335
+ recPath(callExtId, recordingExtId)
10336
+ ),
10337
+ "Could not delete the recording",
10338
+ RECORDING
10339
+ );
10340
+ }
10341
+ function transcribeRecordingPart(arbi, callExtId, recordingExtId, params) {
10342
+ const ext = params.audio.type.includes("wav") ? "wav" : params.audio.type.includes("mp4") ? "m4a" : "webm";
10343
+ const seq = params.seq ?? null;
10344
+ const segment = params.segment ?? null;
10345
+ const segmentOffsetMs = Math.max(0, Math.round(params.segmentOffsetMs ?? 0));
10346
+ return unwrapCall(
10347
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/transcribe", {
10348
+ ...recPath(callExtId, recordingExtId),
10349
+ // A multipart binary field is typed `string`; the runtime value is the Blob. The generated
10350
+ // body types `seq` as required and lacks `language` / `prompt`: the serializer reads the real
10351
+ // values from `params`.
10352
+ body: {
10353
+ audio: params.audio,
10354
+ track_ext_id: params.trackExtId,
10355
+ seq: seq ?? 0,
10356
+ segment,
10357
+ segment_offset_ms: segmentOffsetMs
10358
+ },
10359
+ bodySerializer: (body) => {
10360
+ const form = new FormData();
10361
+ const name = seq != null ? `part-${seq}` : `piece-${segment ?? 0}`;
10362
+ form.append("audio", body.audio, `${name}.${ext}`);
10363
+ form.append("track_ext_id", body.track_ext_id);
10364
+ if (seq != null) form.append("seq", String(seq));
10365
+ if (segment != null) {
10366
+ form.append("segment", String(segment));
10367
+ form.append("segment_offset_ms", String(segmentOffsetMs));
10368
+ }
10369
+ appendTranscriptionHints(form, { language: params.language, prompt: params.prompt });
10370
+ return form;
10371
+ }
10372
+ }),
10373
+ "Could not transcribe the recording",
10374
+ { ...RECORDING, ...TRANSCRIBE }
10375
+ );
10376
+ }
10377
+ async function downloadRecordingPart(url) {
10378
+ const res = await fetch(url);
10379
+ if (!res.ok)
10380
+ throw new CallApiError(`Could not download the recording (${res.status})`, res.status);
10381
+ return new Uint8Array(await res.arrayBuffer());
10382
+ }
10383
+
10384
+ // src/arbi.ts
10385
+ function isAbort(error) {
10386
+ return error instanceof Error && error.name === "AbortError";
10387
+ }
10388
+ function tokenExpiresWithin(token, seconds) {
10389
+ const expiresAt = readSessionClaims(token)?.expiresAt;
10390
+ return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
10391
+ }
10392
+ var Arbi = class {
10393
+ client = null;
10394
+ loginResult = null;
10395
+ userProfile = null;
10396
+ profileListeners = /* @__PURE__ */ new Set();
10397
+ currentWorkspaceId = null;
10398
+ chatCryptoContext = null;
10399
+ /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
10400
+ chatRings = /* @__PURE__ */ new Map();
10401
+ sessionExpiredListeners = /* @__PURE__ */ new Set();
10402
+ signedInListeners = /* @__PURE__ */ new Set();
10403
+ /** The client is this instance's own (`init`), not a host's (`options.session`). */
10404
+ ownsClient = false;
10405
+ options;
10406
+ constructor(options) {
10407
+ this.options = options;
10408
+ if (options.session) {
10409
+ this.client = options.session.client;
10410
+ this.loginResult = options.session.login;
10411
+ this.userProfile = options.session.login?.profile ?? null;
10412
+ this.currentWorkspaceId = options.session.workspaceId ?? null;
10413
+ }
10414
+ }
10415
+ // ── Lifecycle ───────────────────────────────────────────────────────────
10416
+ /**
10417
+ * The deployment domain the user's keys are derived for: `deploymentDomain` when given,
10418
+ * otherwise the hostname of `url`. Signing and password changes re-derive keys with it, so a
10419
+ * host that needs it (the document tools' e-signing) reads it here rather than recomputing it.
10420
+ */
10421
+ getDeploymentDomain() {
10422
+ return this.options.deploymentDomain ?? new URL(this.options.url).hostname;
10423
+ }
10424
+ /** Initialize the SDK client and sodium crypto. Called automatically by login(). */
10425
+ async init() {
10426
+ if (this.client) return this.client;
10427
+ const domain = this.getDeploymentDomain();
10428
+ this.client = createArbiClient({
10429
+ baseUrl: this.options.url,
10430
+ deploymentDomain: domain,
10431
+ credentials: this.options.credentials ?? "omit",
10432
+ session: createSessionManager({ storage: this.options.sessionStorage }),
10433
+ // A silent re-login rotates the server session key: keep ours in step, or the next
10434
+ // workspace open would seal the key for a session the server no longer has.
10435
+ onReloginSuccess: ({ serverSessionKey }) => {
10436
+ if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
10437
+ }
10438
+ });
10439
+ this.ownsClient = true;
10440
+ this.client.auth.onSessionExpired(() => this.expireSession());
10441
+ await this.client.crypto.initSodium();
10442
+ return this.client;
10443
+ }
10444
+ /**
10445
+ * Request a verification email for registration. The user will receive an email with a link and
10446
+ * a 3-word verification code. Resolves to the server's confirmation; throws with its `detail`.
10447
+ */
10448
+ async requestVerification(email) {
10449
+ const client = await this.init();
10450
+ const { data, error, response } = await client.fetch.POST("/v1/user/verify-email", {
10451
+ body: { email }
10452
+ });
10453
+ if (error || !data) throw authRequestError("Verification", error, response.status);
10454
+ return data.detail;
10455
+ }
10456
+ /**
10457
+ * Register a new account with the verification code received by email (or, for an SSO account,
10458
+ * the provider's token as `verificationCode`). Resolves to the new identity key, for the recovery
10459
+ * key backup. Does not sign in: `login` follows.
10460
+ */
10461
+ async register(params) {
10462
+ const client = await this.init();
10463
+ return client.auth.register(params);
10464
+ }
10465
+ /**
10466
+ * Log in with email and password (and the SSO provider's token for an SSO account). Signs the
10467
+ * session in; resolves to the login, its response included. Initializes the client if needed.
10468
+ */
10469
+ async login(email, password, options = {}) {
10470
+ const client = await this.init();
10471
+ return this.signedIn(await client.auth.login({ email, password, ...options }));
10472
+ }
10473
+ /** This instance signed in (`login`, `loginWithKey`, `restore`, an SSO sign-in). */
10474
+ signedIn(login) {
10475
+ this.loginResult = login;
10476
+ this.userProfile = login.profile ?? null;
10477
+ for (const listener of [...this.signedInListeners]) listener(login);
10478
+ return login;
10479
+ }
10480
+ /**
10481
+ * Be told when this instance signs in, by whatever path (a sign-in page, a restored session).
10482
+ * Returns an unsubscribe.
10483
+ */
10484
+ onSignedIn(listener) {
10485
+ this.signedInListeners.add(listener);
10486
+ return () => this.signedInListeners.delete(listener);
10487
+ }
10488
+ /**
10489
+ * Sign in on this device while offline: the password must open the identity saved here at the
10490
+ * last login (see `ArbiClient.auth.unlock`).
10491
+ */
10492
+ async unlock(email, password) {
10493
+ const client = await this.init();
10494
+ await client.auth.unlock({ email, password });
10495
+ }
10496
+ /**
10497
+ * Single sign-on, after the provider (Auth0) signed the user in and handed over its token. The
10498
+ * account still has its own master password (the keys are derived from it); the provider's token
10499
+ * proves the identity:
10500
+ * - `status`: is there an account for this email, and how does it sign in (`new_user`,
10501
+ * `sso_exists`, `local_exists`), with the names the server knows;
10502
+ * - `register`: a new account (the token stands in for the verification code); resolves with the
10503
+ * identity key, for its backup; `login` follows (with the provider's name and picture);
10504
+ * - `login`: an SSO account signs in; `link`: a password account signs in with the token and is
10505
+ * linked to SSO from then on;
10506
+ * - `resendVerification`: the provider's verification email again (its user id).
10507
+ */
10508
+ sso = {
10509
+ status: async (params) => {
10510
+ const client = await this.init();
10511
+ const { data, error, response } = await client.fetch.POST("/v1/user/sso-status", {
10512
+ body: { sso_token: params.token, email: params.email, picture: params.picture }
10513
+ });
10514
+ if (error || !data) throw authRequestError("SSO status", error, response.status);
10515
+ return data;
10516
+ },
10517
+ register: (params) => this.register({
10518
+ email: params.email,
10519
+ password: params.password,
10520
+ verificationCode: params.token,
10521
+ firstName: params.firstName,
10522
+ lastName: params.lastName,
10523
+ picture: params.picture ?? void 0
10524
+ }),
10525
+ login: (params) => this.login(params.email, params.password, {
10526
+ ssoToken: params.token,
10527
+ profile: params.profile
10528
+ }),
10529
+ link: (params) => this.login(params.email, params.password, { ssoToken: params.token }),
10530
+ resendVerification: async (providerUserId) => {
10531
+ const client = await this.init();
10532
+ const { data, error, response } = await client.fetch.POST(
10533
+ "/v1/user/sso-send-verification-email",
10534
+ { body: { auth0_id: providerUserId } }
10535
+ );
10536
+ if (error || !data) throw authRequestError("Verification email", error, response.status);
10537
+ return data.detail ?? "";
10538
+ }
10539
+ };
10540
+ /**
10541
+ * Sign in with the account's identity key itself (a recovery key, a stored key; bytes or base64)
10542
+ * instead of the password. Resolves to the login, its response included.
10543
+ */
10544
+ async loginWithKey(email, signingPrivateKey, options = {}) {
10545
+ const client = await this.init();
10546
+ return this.signedIn(
10547
+ await client.auth.loginWithKey({
10548
+ email,
10549
+ signingPrivateKey: typeof signingPrivateKey === "string" ? client.crypto.base64ToBytes(signingPrivateKey) : signingPrivateKey,
10550
+ ...options
10551
+ })
10552
+ );
10553
+ }
10554
+ /**
10555
+ * Sign in again from the session kept on this device (`sessionStorage`): the account signed in
10556
+ * last, with its identity key from the encrypted store. False, and the kept session dropped,
10557
+ * when there is none to restore.
10558
+ */
10559
+ async restore() {
10560
+ const client = await this.init();
10561
+ const { signedIn, userEmail } = client.session.getState();
10562
+ if (!signedIn || !userEmail) return false;
10563
+ const saved = await client.storage.getSession().catch(() => null);
10564
+ if (!saved?.signingPrivateKey) {
10565
+ client.session.clear();
10566
+ return false;
10567
+ }
10568
+ await this.loginWithKey(userEmail, saved.signingPrivateKey);
10569
+ return true;
10570
+ }
10571
+ /**
10572
+ * Run `withKey` with the workspace's wrapped key (the client's, from the lists it has seen). A
10573
+ * remembered key that no longer works (access was re-granted with a new key) is read again and
10574
+ * the call retried once. Throws for a public workspace the user holds no key for.
10575
+ */
10576
+ async withWrappedKey(workspaceId, withKey) {
10577
+ const keys = this.requireClient().workspaceKeys;
10578
+ const required = (key) => {
10579
+ if (!key) throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
10580
+ return key;
10581
+ };
10582
+ const { wrappedKey, fromCache } = await keys.wrappedKey(workspaceId).catch((error) => {
10583
+ throw new ArbiError(error instanceof Error ? error.message : String(error));
10584
+ });
10585
+ try {
10586
+ return await withKey(required(wrappedKey));
10587
+ } catch (error) {
10588
+ if (!fromCache) throw error;
10589
+ const fresh = await keys.wrappedKey(workspaceId, { refresh: true });
10590
+ return withKey(required(fresh.wrappedKey));
10591
+ }
10592
+ }
10593
+ /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
10594
+ async sealWorkspaceKey(workspaceId) {
10595
+ const client = this.requireClient();
10596
+ const lr2 = this.requireLogin();
10597
+ return this.withWrappedKey(
9669
10598
  workspaceId,
9670
10599
  (wrappedKey) => generateEncryptedWorkspaceKey(
9671
10600
  client,
@@ -9677,28 +10606,13 @@ var Arbi = class {
9677
10606
  }
9678
10607
  /**
9679
10608
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
9680
- * the server or here): its key, sealed to this server session, is deposited with `/prime-key`.
9681
- * Idempotent: cached per server session (a re-login rotates it), concurrent calls share one
9682
- * request, and the current workspace is already open.
10609
+ * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
10610
+ * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
9683
10611
  */
9684
10612
  openWorkspace(workspaceId) {
9685
10613
  if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
9686
- const lr2 = this.requireLogin();
9687
- if (this.openedForSessionKey !== lr2.serverSessionKey) {
9688
- this.openedWorkspaces.clear();
9689
- this.openedForSessionKey = lr2.serverSessionKey;
9690
- }
9691
- const cached = this.openedWorkspaces.get(workspaceId);
9692
- if (cached) return cached;
9693
- const opening = this.sealWorkspaceKey(workspaceId).then(
9694
- (sealedKey) => primeWorkspaceKey(this.requireClient(), workspaceId, sealedKey)
9695
- );
9696
- this.openedWorkspaces.set(workspaceId, opening);
9697
- opening.catch(() => {
9698
- if (this.openedWorkspaces.get(workspaceId) === opening)
9699
- this.openedWorkspaces.delete(workspaceId);
9700
- });
9701
- return opening;
10614
+ this.requireLogin();
10615
+ return this.requireClient().workspaceKeys.prime(workspaceId);
9702
10616
  }
9703
10617
  /** The workspace a call names, opened for this session; `undefined` for the current one. */
9704
10618
  async targetWorkspace(workspaceId) {
@@ -9709,35 +10623,50 @@ var Arbi = class {
9709
10623
  /**
9710
10624
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
9711
10625
  * session's active workspace) and record it in the session. This is navigation: only the host's
9712
- * workspace switch calls it. Package code that needs another workspace calls
9713
- * `workspaces.open(id)` and passes the workspace to the request instead.
10626
+ * workspace switch (`useSwitchWorkspace` in `@arbidocs/react`) calls it. Package code that needs
10627
+ * another workspace calls `workspaces.open(id)` and passes the workspace to the request instead.
10628
+ *
10629
+ * Returns what the server opened: the workspace with its conversations and tags (not its
10630
+ * documents, which are listed page by page). A public workspace has no key and opens without one.
9714
10631
  */
9715
10632
  async selectWorkspace(workspaceId) {
9716
10633
  const client = this.requireClient();
9717
10634
  const lr2 = this.requireLogin();
9718
- const signingPrivateKeyBase64 = client.crypto.bytesToBase64(lr2.signingPrivateKey);
9719
- await this.withWrappedKey(workspaceId, async (wrappedKey) => {
9720
- const sealedKey = await selectWorkspace(
9721
- client,
9722
- workspaceId,
9723
- wrappedKey,
9724
- lr2.serverSessionKey,
9725
- signingPrivateKeyBase64
9726
- );
10635
+ const open = async (workspaceKey) => requireData(
9727
10636
  await client.fetch.POST("/v1/workspace/{workspace_ext_id}/open", {
9728
- params: { path: { workspace_ext_id: workspaceId } },
9729
- body: { workspace_key: sealedKey }
9730
- });
10637
+ params: { path: { workspace_ext_id: workspaceId }, query: { include_documents: false } },
10638
+ body: { workspace_key: workspaceKey }
10639
+ }),
10640
+ `Failed to open workspace ${workspaceId}`
10641
+ );
10642
+ const listed = await client.workspaceKeys.wrappedKey(workspaceId).catch((error) => {
10643
+ throw new ArbiError(error instanceof Error ? error.message : String(error));
9731
10644
  });
10645
+ const opened = !listed.wrappedKey ? await open("") : await this.withWrappedKey(
10646
+ workspaceId,
10647
+ async (wrappedKey) => open(
10648
+ await selectWorkspace(
10649
+ client,
10650
+ workspaceId,
10651
+ wrappedKey,
10652
+ lr2.serverSessionKey,
10653
+ client.crypto.bytesToBase64(lr2.signingPrivateKey)
10654
+ )
10655
+ )
10656
+ );
10657
+ client.session.setSelectedWorkspace(workspaceId);
9732
10658
  this.currentWorkspaceId = workspaceId;
10659
+ return opened;
9733
10660
  }
9734
10661
  /**
9735
10662
  * Subscribe to "the session cannot be recovered". Fires when a request failed with 401 or
9736
10663
  * "No active workspace" and neither a workspace re-open nor a silent re-login was possible
9737
10664
  * (the server refused; an unreachable server does not fire). The local session is already
9738
10665
  * cleared when it fires: show "Your session expired, sign in again". Returns an unsubscribe.
10666
+ * On a host's session it is the host client's expiry.
9739
10667
  */
9740
10668
  onSessionExpired(listener) {
10669
+ if (this.client && !this.ownsClient) return this.client.auth.onSessionExpired(listener);
9741
10670
  this.sessionExpiredListeners.add(listener);
9742
10671
  return () => this.sessionExpiredListeners.delete(listener);
9743
10672
  }
@@ -9749,16 +10678,15 @@ var Arbi = class {
9749
10678
  this.loginResult = null;
9750
10679
  this.userProfile = null;
9751
10680
  this.currentWorkspaceId = null;
9752
- this.wrappedKeys.clear();
9753
10681
  this.chatCryptoContext = null;
9754
10682
  this.chatRings.clear();
9755
- this.client?.session.clear();
9756
10683
  for (const listener of [...this.sessionExpiredListeners]) listener();
9757
10684
  }
9758
10685
  /**
9759
10686
  * Run a raw-fetch operation (streaming, multipart: no middleware) and, when it fails because
9760
10687
  * the token expired or the server lost the open workspace, recover once and run it again.
9761
- * `run` must read the auth headers itself so the retry carries the fresh token.
10688
+ * `run` must read the auth headers itself so the retry carries the fresh token. The client's
10689
+ * re-login is the one recovery: a refused one has already ended the session (`onSessionExpired`).
9762
10690
  */
9763
10691
  async recovering(run) {
9764
10692
  if (this.client && tokenExpiresWithin(this.client.session.getState().accessToken, 30)) {
@@ -9773,10 +10701,7 @@ var Arbi = class {
9773
10701
  if (!(error instanceof ArbiApiError) || !(noWorkspace || unauthorised)) throw error;
9774
10702
  const client = this.requireClient();
9775
10703
  const recovered = noWorkspace && await client.auth.reopenWorkspace() || await client.auth.relogin() !== null;
9776
- if (!recovered) {
9777
- this.expireSession();
9778
- throw new ArbiSessionExpiredError();
9779
- }
10704
+ if (!recovered) throw new ArbiSessionExpiredError();
9780
10705
  return run();
9781
10706
  }
9782
10707
  }
@@ -9784,10 +10709,14 @@ var Arbi = class {
9784
10709
  this.userProfile = profile;
9785
10710
  for (const listener of [...this.profileListeners]) listener(profile);
9786
10711
  }
9787
- /** Log out and clear internal state. */
9788
- async logout() {
10712
+ /**
10713
+ * Sign out: the server session ends (every session of the user with `everywhere`), the session
10714
+ * state is cleared and, with `everywhere`, so are the keys kept on this device (a single sign-out
10715
+ * keeps them for an offline unlock). Then this instance's own state is cleared.
10716
+ */
10717
+ async logout(options = {}) {
9789
10718
  if (this.client) {
9790
- await this.client.auth.logout();
10719
+ await this.client.auth.logout(options);
9791
10720
  }
9792
10721
  if (this.loginResult) {
9793
10722
  this.loginResult.signingPrivateKey.fill(0);
@@ -9796,11 +10725,17 @@ var Arbi = class {
9796
10725
  this.loginResult = null;
9797
10726
  this.userProfile = null;
9798
10727
  this.currentWorkspaceId = null;
9799
- this.wrappedKeys.clear();
9800
10728
  this.chatCryptoContext = null;
9801
10729
  this.chatRings.clear();
9802
10730
  }
9803
10731
  // ── Accessors ─────────────────────────────────────────────────────────
10732
+ /**
10733
+ * The session state this instance runs on (token, user, SSO mode, signed in), to read and
10734
+ * subscribe to; `null` before a client exists.
10735
+ */
10736
+ get session() {
10737
+ return this.client?.session ?? null;
10738
+ }
9804
10739
  /** Get the underlying ArbiClient (throws if not initialized). */
9805
10740
  getClient() {
9806
10741
  return this.requireClient();
@@ -10028,9 +10963,26 @@ var Arbi = class {
10028
10963
  * Idempotent and cached per server session. Navigation uses `selectWorkspace`.
10029
10964
  */
10030
10965
  open: (workspaceId) => this.openWorkspace(workspaceId),
10966
+ /**
10967
+ * A workspace's key sealed to this server session: what `POST /workspace/users` takes to give
10968
+ * someone (an agent) access, and what `/prime-key` deposits. Throws when the user holds no key
10969
+ * for it (a public workspace, or one they can see but never joined).
10970
+ */
10971
+ sealKey: (workspaceId) => this.sealWorkspaceKey(workspaceId),
10972
+ /**
10973
+ * A workspace's raw key, unwrapped with my identity (for content I encrypt under it myself,
10974
+ * such as a thread call's recording). Never sent anywhere.
10975
+ */
10976
+ key: (workspaceId) => this.withWrappedKey(
10977
+ workspaceId,
10978
+ async (wrappedKey) => unwrapWorkspaceKey(wrappedKey, this.requireLogin().signingPrivateKey)
10979
+ ),
10031
10980
  /** Hand this server session a workspace's key (sealed to the session) without opening it. */
10032
10981
  primeKey: (workspaceExtId, sessionSealedKey) => primeWorkspaceKey(this.requireClient(), workspaceExtId, sessionSealedKey),
10033
- list: async () => this.rememberWorkspaces(await listWorkspaces(this.requireClient())),
10982
+ list: async () => {
10983
+ const client = this.requireClient();
10984
+ return client.workspaceKeys.remember(await listWorkspaces(client));
10985
+ },
10034
10986
  create: async (name, projectExtId, description, isPublic) => {
10035
10987
  const client = this.requireClient();
10036
10988
  const lr2 = this.requireLogin();
@@ -10047,12 +10999,12 @@ var Arbi = class {
10047
10999
  description,
10048
11000
  isPublic
10049
11001
  );
10050
- this.rememberWorkspaces([created]);
11002
+ client.workspaceKeys.remember([created]);
10051
11003
  return created;
10052
11004
  },
10053
11005
  delete: async (workspaceIds) => {
10054
11006
  await deleteWorkspaces(this.requireClient(), workspaceIds);
10055
- for (const id of workspaceIds) this.wrappedKeys.delete(id);
11007
+ this.requireClient().workspaceKeys.forget(workspaceIds);
10056
11008
  },
10057
11009
  update: (body) => updateWorkspace(this.requireClient(), body),
10058
11010
  listUsers: () => listWorkspaceUsers(this.requireClient()),
@@ -10126,7 +11078,28 @@ var Arbi = class {
10126
11078
  targetWorkspaceId,
10127
11079
  docIds,
10128
11080
  targetWorkspaceKey
10129
- )
11081
+ ),
11082
+ /**
11083
+ * Download, copy or move a scope of the current workspace (`/v1/workspace/transfer*`): plan it,
11084
+ * run a copy or move into another workspace as a background job (its key is sealed here), follow,
11085
+ * resume or cancel the job, or export the scope's data for a download.
11086
+ */
11087
+ transfer: {
11088
+ plan: (scope, mode) => planWorkspaceTransfer(this.requireClient(), scope, mode),
11089
+ start: async (params) => startWorkspaceTransfer(this.requireClient(), {
11090
+ ...params,
11091
+ targetWorkspaceKey: await this.sealWorkspaceKey(params.targetWorkspaceId)
11092
+ }),
11093
+ resume: async (transferId, targetWorkspaceId) => resumeWorkspaceTransfer(
11094
+ this.requireClient(),
11095
+ transferId,
11096
+ await this.sealWorkspaceKey(targetWorkspaceId)
11097
+ ),
11098
+ cancel: (transferId) => cancelWorkspaceTransfer(this.requireClient(), transferId),
11099
+ get: (transferId) => getWorkspaceTransfer(this.requireClient(), transferId),
11100
+ list: () => listWorkspaceTransfers(this.requireClient()),
11101
+ exportData: (scope) => exportWorkspaceData(this.requireClient(), scope)
11102
+ }
10130
11103
  };
10131
11104
  // ── Documents ─────────────────────────────────────────────────────────
10132
11105
  documents = {
@@ -10245,7 +11218,10 @@ var Arbi = class {
10245
11218
  },
10246
11219
  getMessage: (messageId) => getMessage(this.requireClient(), messageId),
10247
11220
  deleteMessage: (messageId) => deleteMessage(this.requireClient(), messageId),
10248
- /** Post a human comment (no assistant run) — see `postConversationMessage`. */
11221
+ /**
11222
+ * Post a human comment (no assistant run) — see `postConversationMessage`. A thread in another
11223
+ * workspace than the current one works too: its key is handed to the session on demand.
11224
+ */
10249
11225
  postMessage: (body) => postConversationMessage(this.requireClient(), body),
10250
11226
  setAssistantMode: (conversationId, assistantMode) => updateConversationAssistantMode(
10251
11227
  this.requireClient(),
@@ -10329,7 +11305,79 @@ var Arbi = class {
10329
11305
  };
10330
11306
  // ── Assistant ─────────────────────────────────────────────────────────
10331
11307
  assistant = {
10332
- cancelRun: (responseId) => this.recovering(() => cancelAssistantRun(this.getAuthHeaders(), responseId)),
11308
+ /**
11309
+ * Ask the assistant: send one turn (the body is `buildTurnRequest`) and stream it into
11310
+ * `handlers`. Resolves with the accumulated result when the stream ends.
11311
+ *
11312
+ * The token is renewed before a long stream starts and once on a 401. A refusal (402 quota,
11313
+ * 409, 503, …) reaches `onError` as the server's words, a 402 quota also `onQuotaExceeded`,
11314
+ * and `ask` rejects with it; a dropped connection reaches `onError` as the `Error` and rejects
11315
+ * with it; an abort just rejects.
11316
+ */
11317
+ ask: async (request, handlers = {}) => {
11318
+ const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
11319
+ const body = buildTurnRequest({
11320
+ ...request,
11321
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
11322
+ });
11323
+ const refuse = (message, error = new Error(message)) => {
11324
+ onError?.(message);
11325
+ throw error;
11326
+ };
11327
+ let response;
11328
+ try {
11329
+ response = await this.recovering(
11330
+ () => openTurnStream(this.getAuthHeaders(), body, signal)
11331
+ );
11332
+ } catch (error) {
11333
+ if (isAbort(error)) throw error;
11334
+ if (error instanceof AssistantTurnRefused) {
11335
+ if (error.quota) onQuotaExceeded?.(error.quota);
11336
+ return refuse(error.message);
11337
+ }
11338
+ if (error instanceof ArbiSessionExpiredError || error instanceof ArbiApiError && error.status === 401) {
11339
+ const message = SESSION_EXPIRED_MESSAGE;
11340
+ return refuse(message, new ArbiSessionExpiredError(message));
11341
+ }
11342
+ onError?.(error);
11343
+ throw error;
11344
+ }
11345
+ try {
11346
+ return await streamSSE(response, {
11347
+ ...callbacks,
11348
+ onError: (message) => onError?.(message),
11349
+ onArbiError: (event) => {
11350
+ const quota = quotaExceededFrom(event);
11351
+ if (quota) onQuotaExceeded?.(quota);
11352
+ }
11353
+ });
11354
+ } catch (error) {
11355
+ if (!isAbort(error)) onError?.(error);
11356
+ throw error;
11357
+ }
11358
+ },
11359
+ /**
11360
+ * Attach to a running turn by its response id: replays its frames so far, then tails the live
11361
+ * ones until it ends. Rejects when the run is no longer active ("This run is no longer active.").
11362
+ */
11363
+ attachRun: async (responseId, handlers = {}) => {
11364
+ const { signal, ...callbacks } = handlers;
11365
+ const response = await this.recovering(
11366
+ () => openRunStream(this.getAuthHeaders(), responseId, signal)
11367
+ );
11368
+ return streamSSE(response, callbacks);
11369
+ },
11370
+ /**
11371
+ * Interject into a running turn: answer its question, steer it, or send a run-control command
11372
+ * (`/pause`, `/resume`, `/report`).
11373
+ */
11374
+ interject: (assistantMessageExtId, answer) => interject(this.requireClient(), assistantMessageExtId, answer),
11375
+ /** Stop a run on the server (closing its stream alone leaves it running). */
11376
+ cancel: (responseId) => this.recovering(() => cancelRun(this.getAuthHeaders(), responseId)),
11377
+ /** The backend's built-in slash commands (`/compact`, `/goal`, …), for a slash menu. */
11378
+ commands: () => listCommands(this.requireClient()),
11379
+ /** Transcribe a voice recording to text (empty when no speech was found). */
11380
+ transcribe: (audio) => transcribe(this.requireClient(), audio),
10333
11381
  /** Start a durable background turn; task options make its thread a work item. */
10334
11382
  submit: (question, options) => {
10335
11383
  const workspaceId = this.requireWorkspace();
@@ -10344,47 +11392,6 @@ var Arbi = class {
10344
11392
  },
10345
11393
  /** Read the status of a background turn. */
10346
11394
  getResponse: (id) => this.recovering(() => getResponse(this.getAuthHeaders(), id)),
10347
- /**
10348
- * Send a question to the RAG assistant with streaming support.
10349
- * Returns the accumulated result after the stream completes.
10350
- */
10351
- query: async (question, options) => {
10352
- const workspaceId = options.workspaceId ?? this.requireWorkspace();
10353
- const response = await this.recovering(
10354
- () => queryAssistant({
10355
- ...this.getAuthHeaders(),
10356
- workspaceId,
10357
- question,
10358
- agentId: options.agentId,
10359
- docIds: options.docIds,
10360
- previousResponseId: options.previousResponseId,
10361
- conversationId: options.conversationId,
10362
- assistantMode: options.assistantMode,
10363
- mentions: options.mentions,
10364
- model: options.model,
10365
- activeArtifactExtId: options.activeArtifactExtId,
10366
- signal: options.signal
10367
- })
10368
- );
10369
- const callbacks = {
10370
- onToken: options.onToken,
10371
- onStreamStart: options.onStreamStart,
10372
- onOutputItemDone: options.onOutputItemDone,
10373
- onError: options.onError,
10374
- onUserMessage: options.onUserMessage,
10375
- onMetadata: options.onMetadata,
10376
- onUserInputRequest: options.onUserInputRequest,
10377
- onArtifact: options.onArtifact,
10378
- onMailDraft: options.onMailDraft,
10379
- onElapsedTime: options.onElapsedTime,
10380
- onComplete: options.onComplete
10381
- };
10382
- return streamSSE(response, callbacks);
10383
- },
10384
- /**
10385
- * Respond to an agent's question during a human-in-the-loop workflow.
10386
- */
10387
- respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
10388
11395
  /** The skills the caller can run (own + shared marketplace), metadata only. */
10389
11396
  listSkills: (options) => listSkills(this.requireClient(), options),
10390
11397
  /**
@@ -10401,10 +11408,10 @@ var Arbi = class {
10401
11408
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
10402
11409
  * workspace; `searchChunks(result)` ranks the passages found.
10403
11410
  */
10404
- retrieve: (query, docIds, options) => retrieve({
11411
+ retrieve: (query2, docIds, options) => retrieve({
10405
11412
  arbi: this.requireClient(),
10406
11413
  workspaceId: this.requireWorkspace(),
10407
- query,
11414
+ query: query2,
10408
11415
  docIds,
10409
11416
  ...options
10410
11417
  })
@@ -10416,7 +11423,7 @@ var Arbi = class {
10416
11423
  * each tag's documents, facts and threads: `list({ kind: 'issue', include: ['links'] })` is the
10417
11424
  * issue table's rows (its columns: `tagKinds.get('issue')`).
10418
11425
  */
10419
- list: (query) => listTags(this.requireClient(), query),
11426
+ list: (query2) => listTags(this.requireClient(), query2),
10420
11427
  create: (options) => createTag(this.requireClient(), {
10421
11428
  ...options,
10422
11429
  workspaceId: options.workspaceId ?? this.requireWorkspace()
@@ -10512,7 +11519,7 @@ var Arbi = class {
10512
11519
  listHolidayCountries: () => this.withCalendarKeys((c2) => listHolidayCountries(c2)),
10513
11520
  addHolidays: (body) => this.withCalendarKeys((c2) => addHolidayCalendar(c2, body)),
10514
11521
  createRoom: (body) => this.withCalendarKeys((c2) => createRoom(c2, body)),
10515
- listRooms: (query) => this.withCalendarKeys((c2) => listRooms(c2, query)),
11522
+ listRooms: (query2) => this.withCalendarKeys((c2) => listRooms(c2, query2)),
10516
11523
  freeBusy: (body) => this.withCalendarKeys((c2) => getFreeBusy(c2, body)),
10517
11524
  findTime: (body) => this.withCalendarKeys((c2) => findTime(c2, body)),
10518
11525
  /**
@@ -10681,6 +11688,223 @@ var Arbi = class {
10681
11688
  /** Fetch, decrypt and size-check one attachment. */
10682
11689
  downloadAttachment: (file) => downloadChatAttachment(this.requireClient(), file)
10683
11690
  };
11691
+ // ── Calls ─────────────────────────────────────────────────────────────
11692
+ /** My copy of a call's key K from its row (sealed to me as creator or invitee), or null. */
11693
+ async callKeyOf(call) {
11694
+ return openCallKeyOf(call, (await this.requireChatCrypto()).encryptionKeypair.secretKey);
11695
+ }
11696
+ /** A call's title under K, in plaintext; null when it has none or it does not open. */
11697
+ async callTitleOf(call, key) {
11698
+ if (!call.title || !key) return null;
11699
+ return decryptCallTitle(call.title, key);
11700
+ }
11701
+ /**
11702
+ * Calls (LiveKit): one call system for thread, chat (DM / group), contacts and scheduled calls.
11703
+ * Each call has one random key K made in the creator's process; the server and the media server
11704
+ * only ever hold it sealed to people (or in a link's fragment). `start`, `open`, `answer` and
11705
+ * `resetLink` do the key work and hand back K with the call; everything else moves ciphertext.
11706
+ */
11707
+ calls = {
11708
+ /** The deployment's calls config (`enabled`, `transcription_available`, …). */
11709
+ config: () => getCallsConfig(this.requireClient()),
11710
+ get: (callExtId) => getCall(this.requireClient(), callExtId),
11711
+ /** Create a call row as is (a scheduled call's ciphertext made by the caller). */
11712
+ create: (body) => createCall(this.requireClient(), body),
11713
+ update: (callExtId, body) => updateCall(this.requireClient(), callExtId, body),
11714
+ cancel: (callExtId) => cancelCall(this.requireClient(), callExtId),
11715
+ /**
11716
+ * Start a call: a fresh K sealed to me and to each of `invitees` (people without a key are
11717
+ * skipped), the title under K. Returns K and `sealedKeys` (K per invitee: what `ring` takes).
11718
+ * A thread call is get-or-create: when the thread already has a running call, that one comes
11719
+ * back with my copy of its key, and `sealedKeys` are sealed to its key instead.
11720
+ *
11721
+ * A scheduled call has no thread or chat; a webinar (`mode: 'webinar'`) gives each invitee
11722
+ * their `roles` entry (attendee by default).
11723
+ */
11724
+ start: async (params) => {
11725
+ const client = this.requireClient();
11726
+ const me2 = await this.requireChatCrypto();
11727
+ const fresh = await generateCallKey();
11728
+ const sealed = await sealCallKeyForPeers(fresh, params.invitees, me2.userExtId);
11729
+ const roles = params.roles;
11730
+ const title = params.title?.trim();
11731
+ const call = await createCall(client, {
11732
+ ...params.threadExtId ? { thread_ext_id: params.threadExtId } : {},
11733
+ ...params.chatExtId ? { chat_ext_id: params.chatExtId } : {},
11734
+ mode: params.mode ?? "call",
11735
+ ...params.joinPolicy ? { join_policy: params.joinPolicy } : {},
11736
+ title: title ? await encryptCallTitle(title, fresh) : null,
11737
+ creator_sealed_key: await sealCallKey(fresh, bytesToBase64(me2.encryptionKeypair.publicKey)),
11738
+ invitees: Object.entries(sealed).map(([user_ext_id, sealed_key]) => ({
11739
+ user_ext_id,
11740
+ sealed_key,
11741
+ ...roles ? { role: roles[user_ext_id] ?? "attendee" } : {}
11742
+ }))
11743
+ });
11744
+ const reused = call.created === false;
11745
+ const key = reused ? await this.callKeyOf(call) : fresh;
11746
+ if (!key) throw new ArbiError("No key for the running call on this thread");
11747
+ const sealedKeys = reused ? await sealCallKeyForPeers(key, params.invitees, me2.userExtId) : sealed;
11748
+ return {
11749
+ call,
11750
+ key,
11751
+ title: await this.callTitleOf(call, key) ?? title ?? null,
11752
+ sealedKeys
11753
+ };
11754
+ },
11755
+ /**
11756
+ * Open a call by id (a link, the calendar, a notification): K from the link fragment when
11757
+ * given, else my sealed copy. Refuses a cancelled call and a call I hold no key for.
11758
+ */
11759
+ open: async (callExtId, linkKey) => {
11760
+ const call = await getCall(this.requireClient(), callExtId);
11761
+ if (call.cancelled)
11762
+ throw new CallApiError("This call was cancelled.", 410, "cancelled");
11763
+ const key = linkKey ?? await this.callKeyOf(call);
11764
+ if (!key) {
11765
+ throw new ArbiError("Open the full call link (it carries the key) to join this call.");
11766
+ }
11767
+ return { call, key, title: await this.callTitleOf(call, key) };
11768
+ },
11769
+ /** My copy of a call's K from its row, or null. */
11770
+ key: (call) => this.callKeyOf(call),
11771
+ /** A call's title in plaintext under K; null when it has none or it does not open. */
11772
+ title: (call, key) => this.callTitleOf(call, key),
11773
+ /** K sealed to each peer with a key (not to me): what `ring` and invitations take. */
11774
+ sealFor: async (key, peers) => sealCallKeyForPeers(key, peers, (await this.requireChatCrypto()).userExtId),
11775
+ /** Answer a ring: open K from its sealed blob and fetch a room token. */
11776
+ answer: async (ring) => {
11777
+ const me2 = await this.requireChatCrypto();
11778
+ const key = await openSealedCallKey(ring.sealed_key, me2.encryptionKeypair.secretKey);
11779
+ const token = await fetchCallToken(
11780
+ this.requireClient(),
11781
+ ring.call_ext_id,
11782
+ ring.link_version
11783
+ );
11784
+ return { key, token, title: ring.title ? await decryptCallTitle(ring.title, key) : null };
11785
+ },
11786
+ /**
11787
+ * A new link for a call I created: a fresh K re-sealed to me and every invitee with a key, the
11788
+ * title re-encrypted, and `link_version` bumped server-side so the old link stops working.
11789
+ */
11790
+ resetLink: async (call, title, invitees) => {
11791
+ const me2 = await this.requireChatCrypto();
11792
+ const key = await generateCallKey();
11793
+ const updated = await updateCall(this.requireClient(), call.external_id, {
11794
+ reset_link: true,
11795
+ creator_sealed_key: await sealCallKey(key, bytesToBase64(me2.encryptionKeypair.publicKey)),
11796
+ sealed_keys: await sealCallKeyForPeers(key, invitees, me2.userExtId),
11797
+ title: title ? await encryptCallTitle(title, key) : null
11798
+ });
11799
+ return { call: updated, key };
11800
+ },
11801
+ /**
11802
+ * Make a call's E2E meeting chat now: a fresh chat key sealed to me and to every member, and K
11803
+ * sealed to each member so they can always join. The existing chat when the call has one.
11804
+ */
11805
+ createChat: async (params) => {
11806
+ const me2 = await this.requireChatCrypto();
11807
+ const members = params.members.filter(
11808
+ (m2) => !!m2.encryption_public_key && m2.external_id !== me2.userExtId
11809
+ );
11810
+ const chatKey = await generateChatKey();
11811
+ try {
11812
+ const title = params.title?.trim();
11813
+ return await getOrCreateCallChat(this.requireClient(), params.callExtId, {
11814
+ title: title ? await encryptWithChatKey(title, chatKey) : null,
11815
+ creator_sealed_key: await sealChatKey(
11816
+ chatKey,
11817
+ bytesToBase64(me2.encryptionKeypair.publicKey)
11818
+ ),
11819
+ members: await Promise.all(
11820
+ members.map(async (m2) => ({
11821
+ user_ext_id: m2.external_id,
11822
+ sealed_key: await sealChatKey(chatKey, m2.encryption_public_key),
11823
+ call_sealed_key: await sealCallKey(params.callKey, m2.encryption_public_key)
11824
+ }))
11825
+ )
11826
+ });
11827
+ } finally {
11828
+ chatKey.fill(0);
11829
+ }
11830
+ },
11831
+ /** The call's meeting chat as is, made with `body` (an E2E chat) when it has none yet. */
11832
+ chat: (callExtId, body) => getOrCreateCallChat(this.requireClient(), callExtId, body),
11833
+ /** A room token; `inviteToken` (a personal invite link's `?i=`) admits with no lobby. */
11834
+ token: (callExtId, linkVersion, inviteToken) => fetchCallToken(this.requireClient(), callExtId, linkVersion, inviteToken),
11835
+ /** Ring users: `sealedKeys` maps each user ext id to K sealed to them (`sealFor`). */
11836
+ ring: (callExtId, sealedKeys, linkVersion) => ringCall(this.requireClient(), callExtId, sealedKeys, linkVersion),
11837
+ decline: (callExtId) => declineCall(this.requireClient(), callExtId),
11838
+ knock: (callExtId, linkVersion) => knockCall(this.requireClient(), callExtId, linkVersion),
11839
+ pollKnock: (callExtId, knockId) => pollKnock(this.requireClient(), callExtId, knockId),
11840
+ /** A host admits or turns away someone in the lobby. */
11841
+ decideKnock: (callExtId, knockId, admit) => decideKnock(this.requireClient(), callExtId, knockId, admit),
11842
+ removeParticipant: (callExtId, identity) => removeCallParticipant(this.requireClient(), callExtId, identity),
11843
+ muteParticipant: (callExtId, identity, track) => muteCallParticipant(this.requireClient(), callExtId, identity, track),
11844
+ /** Personal invite links for my unregistered contacts (register, then straight into the call). */
11845
+ inviteLinks: {
11846
+ create: (callExtId, body) => createCallInviteLink(this.requireClient(), callExtId, body),
11847
+ list: (callExtId) => listCallInviteLinks(this.requireClient(), callExtId),
11848
+ revoke: (callExtId, inviteLinkExtId) => revokeCallInviteLink(this.requireClient(), callExtId, inviteLinkExtId)
11849
+ },
11850
+ /** Live transcription: each client transcribes its own microphone; the host turns it on. */
11851
+ transcription: {
11852
+ set: (callExtId, on) => setCallTranscription(this.requireClient(), callExtId, on),
11853
+ transcribe: (callExtId, params) => transcribeCallSegment(this.requireClient(), callExtId, params),
11854
+ /** Store an (already encrypted) line in an E2E chat, idempotent per `dedupe_key`. */
11855
+ postChatLine: (chatExtId, body) => postChatTranscriptLine(this.requireClient(), chatExtId, body)
11856
+ },
11857
+ /** End-to-end encrypted recording: encrypted parts uploaded by each client, host-run. */
11858
+ recording: {
11859
+ quota: (callExtId) => getRecordingQuota(this.requireClient(), callExtId),
11860
+ start: (callExtId, mode) => startCallRecording(this.requireClient(), callExtId, mode),
11861
+ stop: (callExtId) => stopCallRecording(this.requireClient(), callExtId),
11862
+ createTrack: (callExtId, recordingExtId, body) => createRecordingTrack(this.requireClient(), callExtId, recordingExtId, body),
11863
+ presignPart: (callExtId, recordingExtId, trackExtId, body) => presignRecordingPart(
11864
+ this.requireClient(),
11865
+ callExtId,
11866
+ recordingExtId,
11867
+ trackExtId,
11868
+ body
11869
+ ),
11870
+ commitPart: (callExtId, recordingExtId, trackExtId, seq) => commitRecordingPart(
11871
+ this.requireClient(),
11872
+ callExtId,
11873
+ recordingExtId,
11874
+ trackExtId,
11875
+ seq
11876
+ ),
11877
+ list: (callExtId) => listCallRecordings(this.requireClient(), callExtId),
11878
+ get: (callExtId, recordingExtId) => getCallRecording(this.requireClient(), callExtId, recordingExtId),
11879
+ setExpiry: (callExtId, recordingExtId, expiresAt) => setRecordingExpiry(this.requireClient(), callExtId, recordingExtId, expiresAt),
11880
+ deleteMedia: (callExtId, recordingExtId) => deleteRecordingMedia(this.requireClient(), callExtId, recordingExtId),
11881
+ delete: (callExtId, recordingExtId) => deleteRecording(this.requireClient(), callExtId, recordingExtId),
11882
+ transcribe: (callExtId, recordingExtId, params) => transcribeRecordingPart(this.requireClient(), callExtId, recordingExtId, params),
11883
+ /** One part's ciphertext from its presigned GET. */
11884
+ downloadPart: (url) => downloadRecordingPart(url)
11885
+ },
11886
+ /** Webinars: a call with `mode = 'webinar'`. `linkVersion` for a link holder not yet admitted. */
11887
+ webinar: {
11888
+ get: (callExtId, linkVersion) => getWebinar(this.requireClient(), callExtId, linkVersion),
11889
+ update: (callExtId, body, linkVersion) => updateWebinar(this.requireClient(), callExtId, body, linkVersion),
11890
+ setHand: (callExtId, raised, linkVersion) => setWebinarHand(this.requireClient(), callExtId, raised, linkVersion),
11891
+ promote: (callExtId, identity, linkVersion) => promoteToStage(this.requireClient(), callExtId, identity, linkVersion),
11892
+ demote: (callExtId, identity, linkVersion) => demoteFromStage(this.requireClient(), callExtId, identity, linkVersion),
11893
+ questions: {
11894
+ list: (callExtId, linkVersion) => listQuestions(this.requireClient(), callExtId, linkVersion),
11895
+ ask: (callExtId, bodyCiphertext, linkVersion) => askQuestion(this.requireClient(), callExtId, bodyCiphertext, linkVersion),
11896
+ vote: (callExtId, questionExtId, up, linkVersion) => voteQuestion(this.requireClient(), callExtId, questionExtId, up, linkVersion),
11897
+ update: (callExtId, questionExtId, body, linkVersion) => updateQuestion(
11898
+ this.requireClient(),
11899
+ callExtId,
11900
+ questionExtId,
11901
+ body,
11902
+ linkVersion
11903
+ ),
11904
+ delete: (callExtId, questionExtId, linkVersion) => deleteQuestion(this.requireClient(), callExtId, questionExtId, linkVersion)
11905
+ }
11906
+ }
11907
+ };
10684
11908
  /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
10685
11909
  dm = {
10686
11910
  /**
@@ -10889,11 +12113,8 @@ var Arbi = class {
10889
12113
  currentId: () => readSessionClaims(this.client?.session.getState().accessToken)?.sessionId ?? null,
10890
12114
  /** End one of your own sessions now (not the one this device is on: that is `logout`). */
10891
12115
  terminate: (sessionId) => terminateSession(this.requireClient(), sessionId),
10892
- /** Sign out of every device on the server, then clear this instance. */
10893
- logoutAll: async () => {
10894
- await logoutAllSessions(this.requireClient());
10895
- await this.logout();
10896
- }
12116
+ /** Sign out of every device on the server, then clear this instance and this device. */
12117
+ logoutAll: () => this.logout({ everywhere: true })
10897
12118
  };
10898
12119
  // ── Internal guards ───────────────────────────────────────────────────
10899
12120
  requireClient() {
@@ -12099,6 +13320,571 @@ async function startDmListener(options) {
12099
13320
  };
12100
13321
  }
12101
13322
 
12102
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, calendar_exports as calendar, canTagHaveParent, cancelPublicBooking, chats_exports as chats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getChildTags, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isPresenceTag, isSharePointVendor, isSharedSkill, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, profile_exports as profile, progressFetch, projects_exports as projects, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, searchChunks, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
13323
+ // src/chat/output-item-reducer.ts
13324
+ function reasoningStep(arbi) {
13325
+ if (arbi?.step) return arbi.step;
13326
+ if (arbi?.model_recommendation) return "goal";
13327
+ if ((arbi?.label ?? "").startsWith("Goal check")) return "goal_progress";
13328
+ return "planning";
13329
+ }
13330
+ function isTraceItem(item) {
13331
+ if (item.type === "function_call" || item.type === "reasoning") return true;
13332
+ return item.type === "message" && (!!item.arbi?.step || !!item.arbi?.label);
13333
+ }
13334
+ function reduceOutputItem(steps, ev, assignIndex, resolveIndex) {
13335
+ const item = ev.item;
13336
+ if (!item || !isTraceItem(item)) return steps;
13337
+ if (!item.id) return steps;
13338
+ const arbi = item.arbi ?? {};
13339
+ const idx = steps.findIndex((s2) => s2._id === item.id);
13340
+ const index = assignIndex(item.id);
13341
+ const prev = idx !== -1 ? steps[idx] : void 0;
13342
+ const summaryText = item.type === "reasoning" && Array.isArray(item.summary) ? item.summary.map((c2) => c2.text).join("") : void 0;
13343
+ const isNarration = item.type === "message" && !arbi.step;
13344
+ const narrationText = isNarration && Array.isArray(item.content) ? item.content.map((c2) => c2.text).join("") : void 0;
13345
+ const next = {
13346
+ ...prev ?? {},
13347
+ type: "arbi.agent_step",
13348
+ _id: item.id,
13349
+ index,
13350
+ // First sighting wins: an item is re-emitted to attach its outcome once the
13351
+ // tool returns, and taking that later stamp would stretch the step to cover
13352
+ // its own execution and shrink the next one.
13353
+ t: prev?.t ?? ev.t ?? void 0,
13354
+ // A tool call has no lifecycle kind (it carries `detail`); everything else
13355
+ // that got this far is a declared or derived lifecycle step.
13356
+ step: item.type === "function_call" ? void 0 : reasoningStep(arbi),
13357
+ label: arbi.label ?? prev?.label,
13358
+ focus: focusUnlessRepeatsNarration(arbi.focus ?? prev?.focus, steps),
13359
+ // Reasoning items carry extended text as `summary` (a plan, a checklist);
13360
+ // function_call items (e.g. a sub-agent spawn marker) carry it as `arbi.content`
13361
+ // directly — a sub-agent's spawn task description, not a lifecycle summary.
13362
+ content: summaryText ?? narrationText ?? arbi.content ?? prev?.content,
13363
+ narration: isNarration || prev?.narration,
13364
+ reasoning: item.type === "reasoning" || prev?.reasoning,
13365
+ detail: arbi.detail ?? prev?.detail,
13366
+ outcome: arbi.outcome ?? prev?.outcome,
13367
+ guard_refused: guardRefused(arbi) || prev?.guard_refused || void 0,
13368
+ usage: arbi.usage ?? prev?.usage,
13369
+ step_tokens: arbi.step_tokens ?? prev?.step_tokens,
13370
+ step_gbp: arbi.step_gbp ?? prev?.step_gbp,
13371
+ total_tokens: arbi.total_tokens ?? prev?.total_tokens,
13372
+ context: arbi.context ?? prev?.context,
13373
+ parent_index: arbi.parent_id != null ? resolveIndex(arbi.parent_id) : prev?.parent_index,
13374
+ subagent: arbi.subagent ?? prev?.subagent,
13375
+ subagent_status: arbi.subagent_status ?? prev?.subagent_status,
13376
+ task_message_ext_id: arbi.task_message_ext_id ?? prev?.task_message_ext_id,
13377
+ model_recommendation: arbi.model_recommendation ?? prev?.model_recommendation,
13378
+ selected_model: arbi.selected_model ?? prev?.selected_model
13379
+ };
13380
+ if (idx !== -1) {
13381
+ const out = [...steps];
13382
+ out[idx] = next;
13383
+ return out;
13384
+ }
13385
+ return [...steps, next];
13386
+ }
13387
+ function guardRefused(arbi) {
13388
+ return arbi.guard_refused === true;
13389
+ }
13390
+ function focusUnlessRepeatsNarration(focus, steps) {
13391
+ const norm = (s2) => (s2 ?? "").replace(/\s+/g, " ").trim();
13392
+ const lastNarration = [...steps].reverse().find((s2) => s2.narration);
13393
+ if (!focus || !lastNarration || norm(focus) !== norm(lastNarration.content)) return focus;
13394
+ return void 0;
13395
+ }
13396
+ function createIndexAssigner(seed = []) {
13397
+ const byId3 = /* @__PURE__ */ new Map();
13398
+ let next = 0;
13399
+ for (const s2 of seed) {
13400
+ if (s2._id) {
13401
+ byId3.set(s2._id, s2.index);
13402
+ next = Math.max(next, s2.index);
13403
+ }
13404
+ }
13405
+ const assign = (id) => {
13406
+ const existing = byId3.get(id);
13407
+ if (existing != null) return existing;
13408
+ next += 1;
13409
+ byId3.set(id, next);
13410
+ return next;
13411
+ };
13412
+ const resolve2 = (id) => byId3.get(id);
13413
+ return { assign, resolve: resolve2 };
13414
+ }
13415
+
13416
+ // src/chat/agent-step-hydration.ts
13417
+ function hydrateV3(events) {
13418
+ let steps = [];
13419
+ for (const ev of events) {
13420
+ if (ev.type !== "response.output_item.done") continue;
13421
+ const { assign, resolve: resolve2 } = createIndexAssigner(steps);
13422
+ steps = reduceOutputItem(steps, ev, assign, resolve2);
13423
+ }
13424
+ return steps;
13425
+ }
13426
+ function hydrateV1(rawSteps) {
13427
+ const steps = [];
13428
+ for (const step of rawSteps) {
13429
+ if (step.step !== "tool_progress") {
13430
+ const progressIdx = steps.findIndex(
13431
+ (s2) => s2.index === step.index && s2.step === "tool_progress"
13432
+ );
13433
+ if (progressIdx !== -1) {
13434
+ steps[progressIdx] = { ...step };
13435
+ continue;
13436
+ }
13437
+ }
13438
+ const isFollowUp = step.step == null;
13439
+ if (isFollowUp) {
13440
+ const existing = steps.find((s2) => s2.index === step.index);
13441
+ if (existing) {
13442
+ for (const [key, value] of Object.entries(step)) {
13443
+ if (value != null && key !== "type" && key !== "t") {
13444
+ existing[key] = value;
13445
+ }
13446
+ }
13447
+ continue;
13448
+ }
13449
+ }
13450
+ steps.push({ ...step });
13451
+ }
13452
+ return steps;
13453
+ }
13454
+ function hydrateAgentSteps(message) {
13455
+ const tools = message.tools || message.meta?.tools;
13456
+ if (!tools) return void 0;
13457
+ const streamEvents = tools["stream_events"];
13458
+ if (!streamEvents || !("events" in streamEvents)) return void 0;
13459
+ const events = streamEvents.events;
13460
+ if (!Array.isArray(events) || events.length === 0) return void 0;
13461
+ const hasV3 = events.some(
13462
+ (e) => typeof e === "object" && e !== null && e.type === "response.output_item.done"
13463
+ );
13464
+ let steps;
13465
+ if (hasV3) {
13466
+ steps = hydrateV3(events);
13467
+ } else {
13468
+ const rawSteps = events.filter(
13469
+ (e) => typeof e === "object" && e !== null && e.type === "arbi.agent_step"
13470
+ );
13471
+ if (rawSteps.length === 0) return void 0;
13472
+ steps = hydrateV1(rawSteps);
13473
+ }
13474
+ if (steps.length === 0) return void 0;
13475
+ const completedEvent = events.find(
13476
+ (e) => typeof e === "object" && e !== null && e.type === "response.completed"
13477
+ );
13478
+ const totalElapsed = completedEvent?.t ?? null;
13479
+ const finalContext = completedEvent?.context ?? null;
13480
+ return { steps, totalElapsed, finalContext };
13481
+ }
13482
+
13483
+ // src/chat/agent-steps.ts
13484
+ function humanizeStep2(identifier) {
13485
+ const spaced = identifier.replace(/[_-]+/g, " ").trim();
13486
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
13487
+ }
13488
+ function getStepTool(step) {
13489
+ return step.detail?.[0]?.tool ?? void 0;
13490
+ }
13491
+ function resolveSummary(summary, docInfo) {
13492
+ return summary.replace(
13493
+ /\{(doc-[A-Za-z0-9]+)\}|(doc-[A-Za-z0-9]+)/g,
13494
+ (full, braced, bare) => {
13495
+ const docId = braced ?? bare ?? "";
13496
+ return docInfo[docId]?.name || (braced ? docId : full);
13497
+ }
13498
+ ).replace(/\(full\)/g, (match) => {
13499
+ const docIdMatch = summary.match(/\{(doc-[^}]+)\}/);
13500
+ if (docIdMatch) {
13501
+ const info = docInfo[docIdMatch[1]];
13502
+ if (info?.pages) return `(full \u2013 ${info.pages} pages)`;
13503
+ }
13504
+ return match;
13505
+ });
13506
+ }
13507
+ var DUPLICATE_OUTCOME = "duplicate";
13508
+ function isGuardRefused(step) {
13509
+ if (step.guard_refused === true) return true;
13510
+ return step.outcome === DUPLICATE_OUTCOME && !step.subagent;
13511
+ }
13512
+ function mergeAgentSteps(steps) {
13513
+ const byIndex = /* @__PURE__ */ new Map();
13514
+ for (const step of steps) {
13515
+ if (step.step === "tool_progress" && step.detail && step.detail.length === 1 && step.detail[0].message === "working" && !step.detail[0].label) {
13516
+ continue;
13517
+ }
13518
+ const existing = byIndex.get(step.index);
13519
+ if (!existing) {
13520
+ byIndex.set(step.index, step);
13521
+ continue;
13522
+ }
13523
+ byIndex.set(step.index, {
13524
+ ...existing,
13525
+ outcome: step.outcome ?? existing.outcome,
13526
+ guard_refused: step.guard_refused || existing.guard_refused || void 0,
13527
+ usage: step.usage ?? existing.usage,
13528
+ total_tokens: step.total_tokens ?? existing.total_tokens,
13529
+ step_tokens: step.step_tokens ?? existing.step_tokens,
13530
+ step_gbp: step.step_gbp ?? existing.step_gbp,
13531
+ context: step.context ?? existing.context,
13532
+ detail: existing.detail ?? step.detail
13533
+ });
13534
+ }
13535
+ return Array.from(byIndex.values()).filter((step) => !isGuardRefused(step)).sort((a2, b2) => a2.index - b2.index);
13536
+ }
13537
+ function topLevelAgentSteps(steps) {
13538
+ const merged = mergeAgentSteps(steps);
13539
+ const known = new Set(merged.map((s2) => s2.index));
13540
+ return merged.filter(
13541
+ (s2) => s2.parent_index == null || s2.parent_index === s2.index || !known.has(s2.parent_index)
13542
+ );
13543
+ }
13544
+ function formatTokens(n2) {
13545
+ if (n2 < 1e3) return `${n2}`;
13546
+ if (n2 < 1e4) return `${(n2 / 1e3).toFixed(1)}k`;
13547
+ return `${Math.round(n2 / 1e3)}k`;
13548
+ }
13549
+ function computeRunStats(steps) {
13550
+ const merged = mergeAgentSteps(steps);
13551
+ let toolCalls = 0;
13552
+ const running = /* @__PURE__ */ new Set();
13553
+ const terminated = /* @__PURE__ */ new Set();
13554
+ for (const s2 of merged) {
13555
+ if (s2.subagent_status === "running") running.add(s2.subagent ?? "");
13556
+ else if (s2.subagent_status === "done" || s2.subagent_status === "failed")
13557
+ terminated.add(s2.subagent ?? "");
13558
+ else if (s2.step == null && !s2.subagent_status) toolCalls += 1;
13559
+ }
13560
+ const handles = /* @__PURE__ */ new Set([...running, ...terminated]);
13561
+ return {
13562
+ toolCalls,
13563
+ subagents: handles.size,
13564
+ subagentsRunning: [...running].filter((h2) => !terminated.has(h2)).length
13565
+ };
13566
+ }
13567
+ function subagentJobLabel(task, maxLen = 42) {
13568
+ let t2 = (task || "").trim();
13569
+ if (!t2) return "Sub-agent";
13570
+ for (const stop of ["(", "\n", ". ", ": ", " \u2014 ", " - "]) {
13571
+ const i2 = t2.indexOf(stop);
13572
+ if (i2 > 8) t2 = t2.slice(0, i2).trim();
13573
+ }
13574
+ if (t2.length > maxLen) t2 = `${t2.slice(0, maxLen - 1).trimEnd()}\u2026`;
13575
+ return t2;
13576
+ }
13577
+ function extractSubagentLanes(steps) {
13578
+ const merged = mergeAgentSteps(steps);
13579
+ const order = [];
13580
+ const byHandle = /* @__PURE__ */ new Map();
13581
+ for (const s2 of merged) {
13582
+ const h2 = s2.subagent;
13583
+ if (!h2) continue;
13584
+ let e = byHandle.get(h2);
13585
+ if (!e) {
13586
+ e = { task: "", focus: "", status: "running", steps: 0 };
13587
+ byHandle.set(h2, e);
13588
+ order.push(h2);
13589
+ }
13590
+ if (s2.task_message_ext_id) e.taskMessageExtId = s2.task_message_ext_id;
13591
+ if (s2.subagent_status === "running") e.task = (s2.content || s2.focus || "").trim();
13592
+ else if (s2.subagent_status === "done") e.status = "done";
13593
+ else if (s2.subagent_status === "failed") e.status = "failed";
13594
+ else {
13595
+ e.steps += 1;
13596
+ if (s2.focus) e.focus = s2.focus.trim();
13597
+ }
13598
+ }
13599
+ return order.map((h2) => {
13600
+ const e = byHandle.get(h2);
13601
+ return {
13602
+ handle: h2,
13603
+ task: e.task,
13604
+ job: subagentJobLabel(e.task),
13605
+ focus: e.focus,
13606
+ status: e.status,
13607
+ steps: e.steps,
13608
+ taskMessageExtId: e.taskMessageExtId
13609
+ };
13610
+ });
13611
+ }
13612
+ function showFullForLabel(label) {
13613
+ const l2 = (label ?? "").trim();
13614
+ return l2.startsWith("Budget reached") || l2.startsWith("Goal") || l2.startsWith("Deep research");
13615
+ }
13616
+ function getStepDisplay(step, docInfo = {}) {
13617
+ const tool = getStepTool(step);
13618
+ if (step.narration) {
13619
+ const prose = step.content?.trim() || null;
13620
+ return {
13621
+ label: step.label || "Narration",
13622
+ summary: prose ? resolveSummary(prose, docInfo) : null,
13623
+ isMultiLine: true,
13624
+ details: []
13625
+ };
13626
+ }
13627
+ const firstDetail = step.detail?.[0];
13628
+ if (step.step) {
13629
+ if (step.step === "tool_progress") {
13630
+ const label3 = firstDetail?.label || step.label || tool && humanizeStep2(tool) || humanizeStep2(step.step);
13631
+ const message = firstDetail?.message || step.content || null;
13632
+ return {
13633
+ label: label3,
13634
+ summary: message ? resolveSummary(message, docInfo) : null,
13635
+ isMultiLine: !!message?.includes("\n"),
13636
+ details: []
13637
+ };
13638
+ }
13639
+ const label2 = step.label || humanizeStep2(step.step);
13640
+ const content2 = step.content?.trim() || null;
13641
+ const showFull = !!content2?.includes("\n") || showFullForLabel(step.label);
13642
+ return {
13643
+ label: label2,
13644
+ summary: content2 ? resolveSummary(content2, docInfo) : null,
13645
+ isMultiLine: showFull,
13646
+ details: []
13647
+ };
13648
+ }
13649
+ const label = step.label || firstDetail?.label || tool && humanizeStep2(tool) || `Step ${step.index}`;
13650
+ const summaries = (step.detail || []).map((d2) => d2.summary).filter(Boolean).map((s2) => resolveSummary(s2, docInfo));
13651
+ const focus = step.focus?.trim();
13652
+ const content = step.content?.trim() || null;
13653
+ const rest = [...summaries, ...content ? [resolveSummary(content, docInfo)] : []];
13654
+ const narrative = focus || rest.shift() || null;
13655
+ return {
13656
+ label,
13657
+ summary: narrative ? resolveSummary(narrative, docInfo) : null,
13658
+ isMultiLine: !!narrative?.includes("\n") || showFullForLabel(label),
13659
+ details: rest
13660
+ };
13661
+ }
13662
+ function getAgentStepLabel(step, docInfo = {}) {
13663
+ const { label, summary, isMultiLine } = getStepDisplay(step, docInfo);
13664
+ const narrative = summary && !isMultiLine && !step.reasoning ? summary : null;
13665
+ const text = narrative ? `${label} \u2014 ${narrative}` : label;
13666
+ return text.length > 120 ? `${text.slice(0, 119)}\u2026` : text;
13667
+ }
13668
+ function getCurrentStep(steps) {
13669
+ const merged = mergeAgentSteps(steps);
13670
+ const candidates = merged.length > 0 ? merged : steps;
13671
+ const isOwnSubstantiveStep = (s2) => {
13672
+ if (s2.subagent) return false;
13673
+ if (s2.narration) return false;
13674
+ const d2 = s2.detail?.[0];
13675
+ const isHeartbeat = s2.step === "tool_progress" && d2?.message === "working" && !d2?.label;
13676
+ return !isHeartbeat;
13677
+ };
13678
+ for (let i2 = candidates.length - 1; i2 >= 0; i2--) {
13679
+ if (isOwnSubstantiveStep(candidates[i2])) return candidates[i2];
13680
+ }
13681
+ for (let i2 = candidates.length - 1; i2 >= 0; i2--) {
13682
+ if (!candidates[i2].subagent) return candidates[i2];
13683
+ }
13684
+ return candidates[candidates.length - 1];
13685
+ }
13686
+
13687
+ // src/chat/subagent-branch.ts
13688
+ function getSubagentBranchRecord(message) {
13689
+ const entry = message.tools?.subagent;
13690
+ return entry?.record ?? null;
13691
+ }
13692
+ function findLeafForTaskMessage(threads, taskMessageExtId) {
13693
+ const thread = threads.find((t2) => t2.history.some((m2) => m2.external_id === taskMessageExtId));
13694
+ return thread?.leaf_message_ext_id ?? null;
13695
+ }
13696
+ function tailTaskMessageIndex(history) {
13697
+ const lastIndex = history.length - 1;
13698
+ if (lastIndex < 0) return -1;
13699
+ if (getSubagentBranchRecord(history[lastIndex])) return lastIndex;
13700
+ const secondLastIndex = lastIndex - 1;
13701
+ if (secondLastIndex >= 0 && getSubagentBranchRecord(history[secondLastIndex])) {
13702
+ return secondLastIndex;
13703
+ }
13704
+ return -1;
13705
+ }
13706
+ function findMainSiblingLeaf(threads, currentHistory) {
13707
+ const taskIndex = tailTaskMessageIndex(currentHistory);
13708
+ if (taskIndex <= 0) return null;
13709
+ const ancestorId = currentHistory[taskIndex - 1].external_id;
13710
+ if (!ancestorId) return null;
13711
+ const sibling = threads.find(
13712
+ (t2) => t2.history.some((m2) => m2.external_id === ancestorId) && tailTaskMessageIndex(t2.history) < 0
13713
+ );
13714
+ return sibling?.leaf_message_ext_id ?? null;
13715
+ }
13716
+ function sliceToSubagentThread(history) {
13717
+ const taskIndex = tailTaskMessageIndex(history);
13718
+ return taskIndex >= 0 ? history.slice(taskIndex) : history;
13719
+ }
13720
+ function newestThread(threads) {
13721
+ const lastAt = (t2) => Date.parse(t2.history.at(-1)?.created_at ?? "") || 0;
13722
+ return threads.reduce(
13723
+ (best, t2) => !best || lastAt(t2) > lastAt(best) ? t2 : best,
13724
+ void 0
13725
+ );
13726
+ }
13727
+ function pickMainThread(threads) {
13728
+ return newestThread(threads.filter((t2) => !t2.history.some((m2) => getSubagentBranchRecord(m2)))) ?? threads.find((t2) => tailTaskMessageIndex(t2.history) < 0) ?? threads[0];
13729
+ }
13730
+ function findSubagentRunId(threads, messageId) {
13731
+ for (const thread of threads) {
13732
+ const index = thread.history.findIndex((m2) => m2.external_id === messageId);
13733
+ if (index < 0) continue;
13734
+ const taskIndex = tailTaskMessageIndex(thread.history);
13735
+ if (taskIndex >= 0 && taskIndex <= index) {
13736
+ return getSubagentBranchRecord(thread.history[taskIndex])?.run_id ?? null;
13737
+ }
13738
+ }
13739
+ return null;
13740
+ }
13741
+
13742
+ // src/chat/reply-target.ts
13743
+ function findReplyTarget(threads, parentId) {
13744
+ if (!parentId) return null;
13745
+ const byId3 = /* @__PURE__ */ new Map();
13746
+ for (const thread of threads) {
13747
+ for (const message of thread.history) byId3.set(message.external_id, message);
13748
+ }
13749
+ let current = byId3.has(parentId) ? parentId : pickMainThread(threads)?.leaf_message_ext_id ?? null;
13750
+ while (current) {
13751
+ const message = byId3.get(current);
13752
+ if (!message) return null;
13753
+ if (message.status !== "failed") return current;
13754
+ current = message.parent_message_ext_id ?? null;
13755
+ }
13756
+ return null;
13757
+ }
13758
+
13759
+ // src/chat/stop-run.ts
13760
+ var STOP_ID_WAIT_MS = 5e3;
13761
+ var STOP_REPEAT_WINDOW_MS = 1e3;
13762
+ var RUN_ID = /^msg-[a-zA-Z0-9]{8}$/;
13763
+ function topLevelRunId(runId) {
13764
+ const root = runId.split(":")[0];
13765
+ return RUN_ID.test(root) ? root : null;
13766
+ }
13767
+ function getRunToCancel(threads, responseId) {
13768
+ const subagentRunId = findSubagentRunId(threads, responseId);
13769
+ return (subagentRunId && topLevelRunId(subagentRunId)) ?? topLevelRunId(responseId) ?? responseId;
13770
+ }
13771
+
13772
+ // src/chat/context-usage.ts
13773
+ function isNearAiUsageBudget(usage) {
13774
+ if (usage.budget_gbp == null || usage.spent_gbp == null || usage.budget_gbp <= 0) {
13775
+ return false;
13776
+ }
13777
+ return usage.spent_gbp / usage.budget_gbp >= 0.9;
13778
+ }
13779
+ function getContextUsedTokens(usage) {
13780
+ return usage.all_llm_calls?.last_input_tokens ?? usage.total_input;
13781
+ }
13782
+ function estimateDraftTokens(draftLength) {
13783
+ return Math.ceil(draftLength / 4);
13784
+ }
13785
+ function getContextUsedPercent(usage, draftLength = 0) {
13786
+ const usedTokens = getContextUsedTokens(usage) + estimateDraftTokens(draftLength);
13787
+ const usedPercent = usedTokens / usage.context_window * 100;
13788
+ return Math.min(100, Math.max(0, usedPercent));
13789
+ }
13790
+ function getContextRemainingPercent(usage, draftLength = 0) {
13791
+ return 100 - getContextUsedPercent(usage, draftLength);
13792
+ }
13793
+
13794
+ // src/chat/conversation-context.ts
13795
+ function extractDocumentIdsFromMessages(messageHistory) {
13796
+ if (!messageHistory || messageHistory.length === 0) return [];
13797
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
13798
+ const msg = messageHistory[i2];
13799
+ if (msg.role === "user" && msg.tools) {
13800
+ const documents = extractDocIdsFromTools(msg.tools);
13801
+ if (documents.length > 0) {
13802
+ return documents;
13803
+ }
13804
+ }
13805
+ }
13806
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
13807
+ const msg = messageHistory[i2];
13808
+ if (msg.role === "assistant" && msg.tools) {
13809
+ const documents = extractDocIdsFromTools(msg.tools);
13810
+ if (documents.length > 0) {
13811
+ return documents;
13812
+ }
13813
+ }
13814
+ }
13815
+ return [];
13816
+ }
13817
+ function extractFactIdsFromMessages(messageHistory) {
13818
+ if (!messageHistory || messageHistory.length === 0) return null;
13819
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
13820
+ const msg = messageHistory[i2];
13821
+ if (msg.role !== "user" || !msg.tools) continue;
13822
+ const tool = msg.tools.facts_context;
13823
+ if (tool?.name === "facts_context" && Array.isArray(tool.tool_args?.fact_ext_ids)) {
13824
+ return Array.from(new Set(tool.tool_args.fact_ext_ids));
13825
+ }
13826
+ }
13827
+ return null;
13828
+ }
13829
+ function extractDocIdsFromTools(tools) {
13830
+ const documents = [];
13831
+ try {
13832
+ const retrievalChunk = tools.retrieval_chunk;
13833
+ if (retrievalChunk && "tool_args" in retrievalChunk && "doc_ext_ids" in retrievalChunk.tool_args && retrievalChunk.tool_args.doc_ext_ids) {
13834
+ const docIds = retrievalChunk.tool_args.doc_ext_ids;
13835
+ if (Array.isArray(docIds)) {
13836
+ for (const docId of docIds) {
13837
+ documents.push({ docId, isPinned: false });
13838
+ }
13839
+ }
13840
+ }
13841
+ const retrievalFullContext = tools.retrieval_full_context;
13842
+ if (retrievalFullContext && "tool_args" in retrievalFullContext && "doc_ext_ids" in retrievalFullContext.tool_args && retrievalFullContext.tool_args.doc_ext_ids) {
13843
+ const docIds = retrievalFullContext.tool_args.doc_ext_ids;
13844
+ if (Array.isArray(docIds)) {
13845
+ for (const docId of docIds) {
13846
+ documents.push({ docId, isPinned: true });
13847
+ }
13848
+ }
13849
+ }
13850
+ if (documents.length > 0) {
13851
+ const uniqueDocuments = documents.reduce(
13852
+ (acc, doc) => {
13853
+ const existing = acc.find((d2) => d2.docId === doc.docId);
13854
+ if (existing) {
13855
+ existing.isPinned = existing.isPinned || doc.isPinned;
13856
+ } else {
13857
+ acc.push(doc);
13858
+ }
13859
+ return acc;
13860
+ },
13861
+ []
13862
+ );
13863
+ return uniqueDocuments;
13864
+ }
13865
+ } catch (error) {
13866
+ console.warn("Failed to extract document IDs from message tools:", error);
13867
+ }
13868
+ return [];
13869
+ }
13870
+
13871
+ // src/chat/run-attach.ts
13872
+ function getAttachableRunId(messages) {
13873
+ let nextQueued = null;
13874
+ for (let i2 = messages.length - 1; i2 >= 0; i2--) {
13875
+ const m2 = messages[i2];
13876
+ if (m2.role !== "assistant") continue;
13877
+ if (m2.status === "in_progress") return m2.external_id;
13878
+ if (m2.status !== "queued") break;
13879
+ nextQueued = m2.external_id;
13880
+ }
13881
+ return nextQueued;
13882
+ }
13883
+ function getRunToAttach(localGeneration, messages) {
13884
+ if (localGeneration?.isGenerating && localGeneration.abortController) return null;
13885
+ return getAttachableRunId(messages);
13886
+ }
13887
+
13888
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, CallApiError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, chats_exports as chats, computeRunStats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, consumeSSEStream, contacts_exports as contacts, continuityPrompt, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, createIndexAssigner, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
12103
13889
  //# sourceMappingURL=index.js.map
12104
13890
  //# sourceMappingURL=index.js.map