@arbidocs/sdk 0.4.167 → 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.cjs CHANGED
@@ -3755,7 +3755,7 @@ var FileConfigStore = class {
3755
3755
  return creds;
3756
3756
  }
3757
3757
  /**
3758
- * Returns a SessionStorageProvider backed by this store's
3758
+ * Returns a SessionPersistence backed by this store's
3759
3759
  * credentials file. Used to wire the auto-relogin middleware in
3760
3760
  * `@arbidocs/client` to the Node-side file store — without this, the
3761
3761
  * middleware falls back to IndexedDB which does not exist in Node
@@ -3767,7 +3767,7 @@ var FileConfigStore = class {
3767
3767
  * credentials file on successful re-login so the next CLI
3768
3768
  * invocation picks it up.
3769
3769
  */
3770
- getSessionStorageProvider() {
3770
+ getSessionPersistence() {
3771
3771
  const b64decode = (b64) => typeof Buffer !== "undefined" ? new Uint8Array(Buffer.from(b64, "base64")) : Uint8Array.from(atob(b64), (c2) => c2.charCodeAt(0));
3772
3772
  const b64encode = (bytes) => typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : btoa(String.fromCharCode(...bytes));
3773
3773
  const getCreds = () => this.getCredentials();
@@ -4008,7 +4008,7 @@ function buildClientOptions(config, store, email) {
4008
4008
  baseUrl: config.baseUrl,
4009
4009
  deploymentDomain: config.deploymentDomain,
4010
4010
  credentials: "omit",
4011
- sessionStorage: store?.getSessionStorageProvider?.(),
4011
+ persistence: store?.getSessionPersistence?.(),
4012
4012
  userEmail: email
4013
4013
  };
4014
4014
  }
@@ -5060,14 +5060,14 @@ async function* listPaginated(arbi, options = {}) {
5060
5060
  lookahead = 1
5061
5061
  } = options;
5062
5062
  const fetchPage = async (pageOffset, limit) => {
5063
- const query = {
5063
+ const query2 = {
5064
5064
  limit,
5065
5065
  offset: pageOffset,
5066
5066
  order
5067
5067
  };
5068
- if (fields) query.fields = fields;
5068
+ if (fields) query2.fields = fields;
5069
5069
  const { data, error } = await arbi.fetch.GET("/v1/document/list", {
5070
- params: { query },
5070
+ params: { query: query2 },
5071
5071
  signal
5072
5072
  });
5073
5073
  if (error) {
@@ -5173,20 +5173,20 @@ async function uploadUrl(arbi, urls, shared = false, configExtId) {
5173
5173
  );
5174
5174
  }
5175
5175
  async function uploadDocuments(arbi, files, options = {}) {
5176
- const query = {};
5177
- if (options.shared !== void 0) query.shared = options.shared;
5178
- if (options.folder) query.folder = sanitizeFolderPath(options.folder);
5179
- if (options.configExtId) query.config_ext_id = options.configExtId;
5180
- if (options.wpType) query.wp_type = options.wpType;
5181
- if (options.versionOf) query.version_of = options.versionOf;
5182
- if (options.tagExtId) query.tag_ext_id = options.tagExtId;
5183
- if (options.workspaceExtId) query.workspace_ext_id = options.workspaceExtId;
5176
+ const query2 = {};
5177
+ if (options.shared !== void 0) query2.shared = options.shared;
5178
+ if (options.folder) query2.folder = sanitizeFolderPath(options.folder);
5179
+ if (options.configExtId) query2.config_ext_id = options.configExtId;
5180
+ if (options.wpType) query2.wp_type = options.wpType;
5181
+ if (options.versionOf) query2.version_of = options.versionOf;
5182
+ if (options.tagExtId) query2.tag_ext_id = options.tagExtId;
5183
+ if (options.workspaceExtId) query2.workspace_ext_id = options.workspaceExtId;
5184
5184
  if (options.derivedFrom) {
5185
- query.derived_from = options.derivedFrom.docId;
5186
- query.derived_role = options.derivedFrom.role;
5185
+ query2.derived_from = options.derivedFrom.docId;
5186
+ query2.derived_role = options.derivedFrom.role;
5187
5187
  }
5188
5188
  const result = await arbi.fetch.POST("/v1/document/upload", {
5189
- params: { query },
5189
+ params: { query: query2 },
5190
5190
  ...options.onProgress ? { fetch: progressFetch(options.onProgress) } : {},
5191
5191
  // The schema types the files as strings; they go as multipart parts.
5192
5192
  body: { files },
@@ -5612,18 +5612,27 @@ async function listHouseTemplateCandidates(arbi) {
5612
5612
  // src/operations/workspaces.ts
5613
5613
  var workspaces_exports = {};
5614
5614
  __export(workspaces_exports, {
5615
+ EXTERNAL_ACCESS_SECONDS: () => EXTERNAL_ACCESS_SECONDS,
5615
5616
  addWorkspaceMembers: () => addWorkspaceMembers,
5617
+ addWorkspaceMembersBody: () => addWorkspaceMembersBody,
5616
5618
  addWorkspaceUsers: () => addWorkspaceUsers,
5619
+ cancelWorkspaceTransfer: () => cancelWorkspaceTransfer,
5617
5620
  copyDocuments: () => copyDocuments,
5618
5621
  createWorkspace: () => createWorkspace,
5619
5622
  deleteWorkspaces: () => deleteWorkspaces,
5623
+ exportWorkspaceData: () => exportWorkspaceData,
5620
5624
  getWorkspaceActivity: () => getWorkspaceActivity,
5625
+ getWorkspaceTransfer: () => getWorkspaceTransfer,
5621
5626
  grantTemporaryWorkspaceAccess: () => grantTemporaryWorkspaceAccess,
5627
+ listWorkspaceTransfers: () => listWorkspaceTransfers,
5622
5628
  listWorkspaceUsers: () => listWorkspaceUsers,
5623
5629
  listWorkspaces: () => listWorkspaces,
5630
+ planWorkspaceTransfer: () => planWorkspaceTransfer,
5624
5631
  primeWorkspaceKey: () => primeWorkspaceKey,
5625
5632
  removeWorkspaceUsers: () => removeWorkspaceUsers,
5633
+ resumeWorkspaceTransfer: () => resumeWorkspaceTransfer,
5626
5634
  setUserRole: () => setUserRole,
5635
+ startWorkspaceTransfer: () => startWorkspaceTransfer,
5627
5636
  updateWorkspace: () => updateWorkspace
5628
5637
  });
5629
5638
  async function listWorkspaces(arbi) {
@@ -5660,9 +5669,16 @@ async function updateWorkspace(arbi, body) {
5660
5669
  async function listWorkspaceUsers(arbi) {
5661
5670
  return requireData(await arbi.fetch.GET("/v1/workspace/users"), "Failed to fetch workspace users");
5662
5671
  }
5672
+ var EXTERNAL_ACCESS_SECONDS = 86400;
5673
+ function addWorkspaceMembersBody(request) {
5674
+ return {
5675
+ ...request,
5676
+ access_duration_seconds: request.access_duration_seconds ?? EXTERNAL_ACCESS_SECONDS
5677
+ };
5678
+ }
5663
5679
  async function addWorkspaceMembers(arbi, request) {
5664
5680
  return requireData(
5665
- await arbi.fetch.POST("/v1/workspace/users", { body: request }),
5681
+ await arbi.fetch.POST("/v1/workspace/users", { body: addWorkspaceMembersBody(request) }),
5666
5682
  "Failed to add users"
5667
5683
  );
5668
5684
  }
@@ -5670,13 +5686,15 @@ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, co
5670
5686
  const invite = confirmInvite ? { confirm_invite: true } : {};
5671
5687
  return requireData(
5672
5688
  await arbi.fetch.POST("/v1/workspace/users", {
5673
- body: target ? {
5674
- emails,
5675
- role,
5676
- workspace_ext_id: target.workspaceExtId,
5677
- workspace_key: target.workspaceKey,
5678
- ...invite
5679
- } : { emails, role, ...invite }
5689
+ body: addWorkspaceMembersBody(
5690
+ target ? {
5691
+ emails,
5692
+ role,
5693
+ workspace_ext_id: target.workspaceExtId,
5694
+ workspace_key: target.workspaceKey,
5695
+ ...invite
5696
+ } : { emails, role, ...invite }
5697
+ )
5680
5698
  }),
5681
5699
  "Failed to add users"
5682
5700
  );
@@ -5684,13 +5702,13 @@ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, co
5684
5702
  async function grantTemporaryWorkspaceAccess(arbi, params) {
5685
5703
  return requireData(
5686
5704
  await arbi.fetch.POST("/v1/workspace/users", {
5687
- body: {
5705
+ body: addWorkspaceMembersBody({
5688
5706
  emails: params.emails,
5689
5707
  role: params.role ?? "collaborator",
5690
5708
  workspace_ext_id: params.workspaceExtId,
5691
5709
  workspace_key: params.workspaceKey,
5692
5710
  session_pubkey_b64: params.sessionPubkeyB64
5693
- }
5711
+ })
5694
5712
  }),
5695
5713
  "Failed to grant temporary access"
5696
5714
  );
@@ -5746,6 +5764,63 @@ async function primeWorkspaceKey(arbi, workspaceExtId, sessionSealedKey) {
5746
5764
  "Failed to prime the workspace key"
5747
5765
  );
5748
5766
  }
5767
+ async function planWorkspaceTransfer(arbi, scope, mode) {
5768
+ return requireData(
5769
+ await arbi.fetch.POST("/v1/workspace/transfer/plan", { body: { scope, mode } }),
5770
+ "Failed to plan the transfer"
5771
+ );
5772
+ }
5773
+ async function startWorkspaceTransfer(arbi, params) {
5774
+ return requireData(
5775
+ await arbi.fetch.POST("/v1/workspace/transfer", {
5776
+ body: {
5777
+ scope: params.scope,
5778
+ mode: params.mode,
5779
+ target_workspace_ext_id: params.targetWorkspaceId,
5780
+ target_workspace_key: params.targetWorkspaceKey,
5781
+ on_conflict: params.onConflict ?? "skip"
5782
+ }
5783
+ }),
5784
+ "Failed to start the transfer"
5785
+ );
5786
+ }
5787
+ async function resumeWorkspaceTransfer(arbi, transferId, targetWorkspaceKey) {
5788
+ return requireData(
5789
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/resume", {
5790
+ params: { path: { transfer_ext_id: transferId } },
5791
+ body: { target_workspace_key: targetWorkspaceKey }
5792
+ }),
5793
+ "Failed to resume the transfer"
5794
+ );
5795
+ }
5796
+ async function cancelWorkspaceTransfer(arbi, transferId) {
5797
+ return requireData(
5798
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/cancel", {
5799
+ params: { path: { transfer_ext_id: transferId } }
5800
+ }),
5801
+ "Failed to cancel the transfer"
5802
+ );
5803
+ }
5804
+ async function getWorkspaceTransfer(arbi, transferId) {
5805
+ return requireData(
5806
+ await arbi.fetch.GET("/v1/workspace/transfer/{transfer_ext_id}", {
5807
+ params: { path: { transfer_ext_id: transferId } }
5808
+ }),
5809
+ "Failed to fetch the transfer"
5810
+ );
5811
+ }
5812
+ async function listWorkspaceTransfers(arbi) {
5813
+ return requireData(
5814
+ await arbi.fetch.GET("/v1/workspace/transfer", {}),
5815
+ "Failed to list transfers"
5816
+ );
5817
+ }
5818
+ async function exportWorkspaceData(arbi, scope) {
5819
+ return requireData(
5820
+ await arbi.fetch.POST("/v1/workspace/export", { body: { scope } }),
5821
+ "Failed to export the workspace"
5822
+ );
5823
+ }
5749
5824
 
5750
5825
  // src/operations/conversations.ts
5751
5826
  var conversations_exports = {};
@@ -5824,24 +5899,29 @@ async function updateConversationAssistantMode(arbi, conversationId, assistantMo
5824
5899
  // src/operations/assistant.ts
5825
5900
  var assistant_exports = {};
5826
5901
  __export(assistant_exports, {
5902
+ AssistantTurnRefused: () => AssistantTurnRefused,
5827
5903
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
5828
- buildFactsContextTool: () => buildFactsContextTool,
5829
- buildRetrievalChunkTool: () => buildRetrievalChunkTool,
5830
- buildRetrievalFullContextTool: () => buildRetrievalFullContextTool,
5831
- buildRetrievalTocTool: () => buildRetrievalTocTool,
5832
- cancelAssistantRun: () => cancelAssistantRun,
5904
+ SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
5905
+ cancelRun: () => cancelRun,
5833
5906
  filterSkills: () => filterSkills,
5907
+ interject: () => interject,
5834
5908
  isSharedSkill: () => isSharedSkill,
5835
5909
  listCommands: () => listCommands,
5836
5910
  listSkills: () => listSkills,
5911
+ openRunStream: () => openRunStream,
5912
+ openTurnStream: () => openTurnStream,
5837
5913
  parseSlashCommand: () => parseSlashCommand,
5838
5914
  parseSlashTokenInProgress: () => parseSlashTokenInProgress,
5839
5915
  queryAssistant: () => queryAssistant,
5840
- respondToAgent: () => respondToAgent,
5916
+ quotaExceededFrom: () => quotaExceededFrom,
5917
+ quotaFromStreamError: () => quotaFromStreamError,
5841
5918
  retrieve: () => retrieve,
5842
5919
  searchChunks: () => searchChunks,
5920
+ transcribe: () => transcribe,
5843
5921
  uploadSkill: () => uploadSkill
5844
5922
  });
5923
+
5924
+ // src/chat/turn-request.ts
5845
5925
  function buildRetrievalChunkTool(docIds, searchMode) {
5846
5926
  return {
5847
5927
  name: "retrieval_chunk",
@@ -5873,12 +5953,70 @@ function buildRetrievalTocTool(docIds) {
5873
5953
  tool_responses: {}
5874
5954
  };
5875
5955
  }
5956
+ function selectFullContextDocument(docIds, pinnedDocumentId) {
5957
+ if (pinnedDocumentId && docIds.includes(pinnedDocumentId)) {
5958
+ return {
5959
+ fullContextDocId: pinnedDocumentId,
5960
+ chunkRetrievalDocIds: docIds.filter((id) => id !== pinnedDocumentId)
5961
+ };
5962
+ }
5963
+ return { fullContextDocId: null, chunkRetrievalDocIds: [...docIds] };
5964
+ }
5965
+ function buildDocumentTools(selection) {
5966
+ return {
5967
+ retrieval_chunk: buildRetrievalChunkTool(selection.chunkRetrievalDocIds),
5968
+ retrieval_full_context: buildRetrievalFullContextTool(
5969
+ selection.fullContextDocId ? [selection.fullContextDocId] : []
5970
+ )
5971
+ };
5972
+ }
5973
+ var PA_PREFIX = "/pa ";
5974
+ function turnTools(request, activeArtifactExtId) {
5975
+ const facts = request.factIds ? { facts_context: buildFactsContextTool(request.factIds) } : {};
5976
+ if (request.tools) return { ...facts, ...request.tools };
5977
+ if (request.personalAgent) {
5978
+ return {
5979
+ personal_agent: {
5980
+ name: "personal_agent",
5981
+ description: "personal agent",
5982
+ tool_args: { task: request.question },
5983
+ tool_responses: {}
5984
+ }
5985
+ };
5986
+ }
5987
+ if (!request.docIds) return { ...facts };
5988
+ const selection = selectFullContextDocument(request.docIds, request.pinnedDocumentId);
5989
+ const documents = activeArtifactExtId && selection.fullContextDocId === activeArtifactExtId ? { ...selection, fullContextDocId: null } : selection;
5990
+ return { ...buildDocumentTools(documents), ...facts };
5991
+ }
5992
+ function buildTurnRequest(request) {
5993
+ const pa2 = request.personalAgent === true;
5994
+ const activeArtifactExtId = pa2 ? null : request.activeArtifactExtId ?? null;
5995
+ const input = pa2 && !request.question.startsWith(PA_PREFIX) ? `${PA_PREFIX}${request.question}` : request.question;
5996
+ return {
5997
+ input,
5998
+ workspace_ext_id: request.workspaceId,
5999
+ stream: true,
6000
+ background: false,
6001
+ store: true,
6002
+ tools: turnTools(request, activeArtifactExtId),
6003
+ ...request.agentId ? { agent_ext_id: request.agentId } : {},
6004
+ ...request.previousResponseId ? { previous_response_id: request.previousResponseId } : {},
6005
+ ...request.conversationId ? { conversation_ext_id: request.conversationId } : {},
6006
+ ...request.model && !pa2 ? { model: request.model } : {},
6007
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6008
+ ...request.mentions && request.mentions.length > 0 ? { mentions: request.mentions } : {},
6009
+ ...request.assistantMode ? { assistant_mode: request.assistantMode } : {}
6010
+ };
6011
+ }
6012
+
6013
+ // src/operations/assistant.ts
5876
6014
  var MAX_RETRIEVE_DOC_IDS = 5e3;
5877
6015
  async function retrieve(options) {
5878
6016
  const {
5879
6017
  arbi,
5880
6018
  workspaceId,
5881
- query,
6019
+ query: query2,
5882
6020
  docIds,
5883
6021
  searchMode,
5884
6022
  fullContextDocIds,
@@ -5896,7 +6034,7 @@ async function retrieve(options) {
5896
6034
  tools.retrieval_toc = buildRetrievalTocTool(tocDocIds);
5897
6035
  }
5898
6036
  const body = {
5899
- input: query,
6037
+ input: query2,
5900
6038
  workspace_ext_id: workspaceId,
5901
6039
  stream: false,
5902
6040
  background: false,
@@ -5949,48 +6087,120 @@ function searchChunks(result) {
5949
6087
  return Array.from(byId3.values()).sort((a2, b2) => b2.score - a2.score);
5950
6088
  }
5951
6089
  async function queryAssistant(options) {
5952
- const {
5953
- workspaceId,
5954
- question,
5955
- docIds,
5956
- previousResponseId,
5957
- conversationId,
5958
- assistantMode,
5959
- agentId,
5960
- model,
5961
- mentions,
5962
- signal,
5963
- activeArtifactExtId,
5964
- ...auth
5965
- } = options;
5966
- const body = {
5967
- input: question,
5968
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5969
- workspace_ext_id: workspaceId,
5970
- ...agentId ? { agent_ext_id: agentId } : {},
5971
- stream: true,
5972
- background: false,
5973
- store: true,
5974
- tools: agentId ? {} : {
5975
- retrieval_chunk: buildRetrievalChunkTool(docIds),
5976
- retrieval_full_context: buildRetrievalFullContextTool([])
5977
- },
5978
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5979
- ...conversationId ? { conversation_ext_id: conversationId } : {},
5980
- ...assistantMode ? { assistant_mode: assistantMode } : {},
5981
- ...model ? { model } : {},
5982
- ...mentions && mentions.length > 0 ? { mentions } : {}
5983
- };
6090
+ const { baseUrl, accessToken, signal, ...request } = options;
5984
6091
  return authenticatedFetch({
5985
- ...auth,
6092
+ baseUrl,
6093
+ accessToken,
5986
6094
  path: "/v1/assistant/query",
5987
6095
  method: "POST",
5988
- body: JSON.stringify(body),
6096
+ body: JSON.stringify(buildTurnRequest(request)),
5989
6097
  headers: { "Content-Type": "application/json" },
5990
6098
  signal
5991
6099
  });
5992
6100
  }
5993
- async function respondToAgent(arbi, assistantMessageExtId, answer) {
6101
+ var AssistantTurnRefused = class extends ArbiApiError {
6102
+ /** Set when the refusal is the project's used-up AI usage. */
6103
+ quota;
6104
+ constructor(message, status, quota = null) {
6105
+ super(message, void 0, status);
6106
+ this.name = "AssistantTurnRefused";
6107
+ this.quota = quota;
6108
+ }
6109
+ };
6110
+ var SESSION_EXPIRED_MESSAGE = "Token has expired. Please log in again.";
6111
+ function quotaExceededFrom(detail) {
6112
+ if (!detail || typeof detail !== "object") return null;
6113
+ const d2 = detail;
6114
+ if (d2.code !== "QUOTA_EXCEEDED") return null;
6115
+ return {
6116
+ spend: Number(d2.spend ?? 0),
6117
+ budget: Number(d2.budget ?? 0),
6118
+ projectExtId: d2.project_ext_id ?? null,
6119
+ ...typeof d2.message === "string" ? { message: d2.message } : {}
6120
+ };
6121
+ }
6122
+ var LITELLM_BUDGET_RE = /ExceededBudget:\s*End User=(?<project>[^\s]+)\s+over budget\.\s*Spend=(?<spend>[0-9.]+),\s*Budget=(?<budget>[0-9.]+)/;
6123
+ function quotaFromStreamError(error) {
6124
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
6125
+ if (!message.includes("ExceededBudget")) return null;
6126
+ const match = message.match(LITELLM_BUDGET_RE);
6127
+ if (!match?.groups) return null;
6128
+ const spend = usdToGbp(Number(match.groups.spend));
6129
+ const budget = usdToGbp(Number(match.groups.budget));
6130
+ if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6131
+ return { spend, budget, projectExtId: match.groups.project ?? null };
6132
+ }
6133
+ async function readDetail(response) {
6134
+ try {
6135
+ return (await response.json())?.detail;
6136
+ } catch {
6137
+ return void 0;
6138
+ }
6139
+ }
6140
+ async function refusal(response) {
6141
+ const { status } = response;
6142
+ if (status === 409) {
6143
+ const detail2 = await readDetail(response);
6144
+ return new AssistantTurnRefused(
6145
+ detailText(detail2) || "This message has failed. Please retry from the previous message.",
6146
+ status
6147
+ );
6148
+ }
6149
+ if (status === 503) {
6150
+ return new AssistantTurnRefused(
6151
+ "The selected LLM is not responding. Please retry again in a minute or select another model.",
6152
+ status
6153
+ );
6154
+ }
6155
+ if (status === 402) {
6156
+ const detail2 = await readDetail(response);
6157
+ const quota = quotaExceededFrom(detail2);
6158
+ const message = quota?.message ?? (typeof detail2 === "string" ? detail2 : void 0) ?? detail2?.message ?? "This project's AI usage for this month is used up.";
6159
+ return new AssistantTurnRefused(
6160
+ message || "This project's AI usage for this month is used up.",
6161
+ status,
6162
+ quota
6163
+ );
6164
+ }
6165
+ const detail = await readDetail(response);
6166
+ return new AssistantTurnRefused(
6167
+ detailText(detail) || `HTTP error! status: ${status}`,
6168
+ status
6169
+ );
6170
+ }
6171
+ async function openTurnStream(auth, body, signal) {
6172
+ const response = await fetch(`${auth.baseUrl}/v1/assistant/query`, {
6173
+ method: "POST",
6174
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${auth.accessToken}` },
6175
+ body: JSON.stringify(body),
6176
+ signal,
6177
+ credentials: "include"
6178
+ });
6179
+ if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6180
+ if (!response.ok || !response.body) throw await refusal(response);
6181
+ return response;
6182
+ }
6183
+ async function openRunStream(auth, responseId, signal) {
6184
+ const response = await fetch(
6185
+ `${auth.baseUrl}/v1/assistant/run/${encodeURIComponent(responseId)}/stream`,
6186
+ {
6187
+ method: "GET",
6188
+ headers: { Authorization: `Bearer ${auth.accessToken}` },
6189
+ signal,
6190
+ credentials: "include"
6191
+ }
6192
+ );
6193
+ if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6194
+ if (!response.ok || !response.body) {
6195
+ throw new ArbiApiError(
6196
+ response.status === 404 ? "This run is no longer active." : `HTTP ${response.status}`,
6197
+ void 0,
6198
+ response.status
6199
+ );
6200
+ }
6201
+ return response;
6202
+ }
6203
+ async function interject(arbi, assistantMessageExtId, answer) {
5994
6204
  return requireData(
5995
6205
  await arbi.fetch.POST("/v1/assistant/interject", {
5996
6206
  body: { assistant_message_ext_id: assistantMessageExtId, answer }
@@ -6024,6 +6234,22 @@ async function listCommands(arbi) {
6024
6234
  );
6025
6235
  return result.commands;
6026
6236
  }
6237
+ async function transcribe(arbi, audio) {
6238
+ const result = requireData(
6239
+ await arbi.fetch.POST("/v1/assistant/transcribe", {
6240
+ // The generated type of a multipart binary field is `string`; the value is the Blob, sent as
6241
+ // real form data (openapi-fetch would JSON-encode a plain object).
6242
+ body: { audio },
6243
+ bodySerializer: (body) => {
6244
+ const form = new FormData();
6245
+ form.append("audio", body.audio, "voice-input.webm");
6246
+ return form;
6247
+ }
6248
+ }),
6249
+ "Failed to transcribe the recording"
6250
+ );
6251
+ return result.text;
6252
+ }
6027
6253
  function parseSlashCommand(input) {
6028
6254
  const m2 = /^\s*\/([a-zA-Z0-9_-]+)(?:\s+([\s\S]*))?$/.exec(input);
6029
6255
  if (!m2) return null;
@@ -6033,8 +6259,8 @@ function parseSlashTokenInProgress(buffer) {
6033
6259
  const m2 = /^\s*\/([a-zA-Z0-9_-]*)$/.exec(buffer);
6034
6260
  return m2 ? m2[1].toLowerCase() : null;
6035
6261
  }
6036
- function filterSkills(items, query, pinned = []) {
6037
- const q2 = query.toLowerCase();
6262
+ function filterSkills(items, query2, pinned = []) {
6263
+ const q2 = query2.toLowerCase();
6038
6264
  const pinnedSet = new Set(pinned);
6039
6265
  const key = (s2) => (s2.slug ?? s2.name).toLowerCase();
6040
6266
  const matched = q2 ? items.filter((s2) => key(s2).includes(q2)) : items.slice();
@@ -6049,7 +6275,7 @@ function filterSkills(items, query, pinned = []) {
6049
6275
  });
6050
6276
  return matched;
6051
6277
  }
6052
- async function cancelAssistantRun(auth, responseId) {
6278
+ async function cancelRun(auth, responseId) {
6053
6279
  await authenticatedFetch({
6054
6280
  ...auth,
6055
6281
  path: `/v1/assistant/run/${encodeURIComponent(responseId)}/cancel`,
@@ -6075,6 +6301,7 @@ async function submitBackgroundQuery(options) {
6075
6301
  conversationId,
6076
6302
  mentions,
6077
6303
  activeArtifactExtId,
6304
+ fullContext = true,
6078
6305
  ...auth
6079
6306
  } = options;
6080
6307
  const tools = {};
@@ -6085,12 +6312,13 @@ async function submitBackgroundQuery(options) {
6085
6312
  tool_args: { doc_ext_ids: docIds },
6086
6313
  tool_responses: {}
6087
6314
  };
6088
- tools.retrieval_full_context = {
6089
- name: "retrieval_full_context",
6090
- description: "retrieval full context",
6091
- tool_args: { doc_ext_ids: docIds },
6092
- tool_responses: {}
6093
- };
6315
+ if (fullContext)
6316
+ tools.retrieval_full_context = {
6317
+ name: "retrieval_full_context",
6318
+ description: "retrieval full context",
6319
+ tool_args: { doc_ext_ids: docIds },
6320
+ tool_responses: {}
6321
+ };
6094
6322
  }
6095
6323
  const body = {
6096
6324
  input: question,
@@ -6174,13 +6402,13 @@ var TAG_FIELD_TYPES = [
6174
6402
  "select",
6175
6403
  "person"
6176
6404
  ];
6177
- async function listTags(arbi, query = {}) {
6405
+ async function listTags(arbi, query2 = {}) {
6178
6406
  const params = {};
6179
- if (query.kind) params.kind = query.kind;
6180
- if (query.parentId) params.parent = query.parentId;
6181
- if (query.ids?.length) params.ids = query.ids;
6182
- if (query.include?.length) params.include = query.include;
6183
- if (query.linksLimit !== void 0) params.links_limit = query.linksLimit;
6407
+ if (query2.kind) params.kind = query2.kind;
6408
+ if (query2.parentId) params.parent = query2.parentId;
6409
+ if (query2.ids?.length) params.ids = query2.ids;
6410
+ if (query2.include?.length) params.include = query2.include;
6411
+ if (query2.linksLimit !== void 0) params.links_limit = query2.linksLimit;
6184
6412
  return requireData(
6185
6413
  await arbi.fetch.GET(
6186
6414
  "/v1/tag/",
@@ -7562,7 +7790,6 @@ async function getFileContent(auth, fileId) {
7562
7790
  var sessions_exports = {};
7563
7791
  __export(sessions_exports, {
7564
7792
  listSessions: () => listSessions,
7565
- logoutAllSessions: () => logoutAllSessions,
7566
7793
  terminateSession: () => terminateSession
7567
7794
  });
7568
7795
  async function listSessions(arbi) {
@@ -7577,12 +7804,6 @@ async function terminateSession(arbi, sessionId) {
7577
7804
  "Failed to end session"
7578
7805
  );
7579
7806
  }
7580
- async function logoutAllSessions(arbi) {
7581
- requireOk(
7582
- await arbi.fetch.POST("/v1/user/logout", { params: { query: { all_sessions: true } } }),
7583
- "Failed to sign out of all sessions"
7584
- );
7585
- }
7586
7807
 
7587
7808
  // src/operations/profile.ts
7588
7809
  var profile_exports = {};
@@ -7656,7 +7877,7 @@ __export(identity_exports, {
7656
7877
  remove: () => remove,
7657
7878
  startSession: () => startSession
7658
7879
  });
7659
- function refusal(apiError) {
7880
+ function refusal2(apiError) {
7660
7881
  const detail = apiError?.detail;
7661
7882
  if (typeof detail === "string") return { message: detail };
7662
7883
  if (detail && typeof detail === "object" && !Array.isArray(detail)) {
@@ -7669,12 +7890,12 @@ function refusal(apiError) {
7669
7890
  return {};
7670
7891
  }
7671
7892
  function identityErrorCode(error) {
7672
- return error instanceof ArbiApiError ? refusal(error.apiError).code : void 0;
7893
+ return error instanceof ArbiApiError ? refusal2(error.apiError).code : void 0;
7673
7894
  }
7674
7895
  function unwrap(result, fallback) {
7675
7896
  if (result.error || result.data === void 0) {
7676
7897
  throw new ArbiApiError(
7677
- refusal(result.error).message ?? fallback,
7898
+ refusal2(result.error).message ?? fallback,
7678
7899
  result.error,
7679
7900
  result.response?.status
7680
7901
  );
@@ -7744,13 +7965,13 @@ __export(projects_exports, {
7744
7965
  updateProject: () => updateProject
7745
7966
  });
7746
7967
  async function listProjects(arbi, filters = {}) {
7747
- const query = {};
7748
- if (filters.stage) query.stage = filters.stage;
7749
- if (filters.leadUser) query.lead_user = filters.leadUser;
7968
+ const query2 = {};
7969
+ if (filters.stage) query2.stage = filters.stage;
7970
+ if (filters.leadUser) query2.lead_user = filters.leadUser;
7750
7971
  return requireData(
7751
7972
  await arbi.fetch.GET(
7752
7973
  "/v1/user/projects/",
7753
- Object.keys(query).length ? { params: { query } } : void 0
7974
+ Object.keys(query2).length ? { params: { query: query2 } } : void 0
7754
7975
  ),
7755
7976
  "Failed to fetch projects"
7756
7977
  );
@@ -7764,12 +7985,12 @@ async function createProject(arbi, name, plan = "free", details = {}) {
7764
7985
  );
7765
7986
  }
7766
7987
  async function listProjectEvents(arbi, projectExtId, options = {}) {
7767
- const query = {};
7768
- if (options.kind) query.kind = options.kind;
7769
- if (options.limit !== void 0) query.limit = options.limit;
7988
+ const query2 = {};
7989
+ if (options.kind) query2.kind = options.kind;
7990
+ if (options.limit !== void 0) query2.limit = options.limit;
7770
7991
  return requireData(
7771
7992
  await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/events", {
7772
- params: { path: { project_ext_id: projectExtId }, query }
7993
+ params: { path: { project_ext_id: projectExtId }, query: query2 }
7773
7994
  }),
7774
7995
  "Failed to fetch project events"
7775
7996
  );
@@ -9531,150 +9752,858 @@ async function cancelPublicBooking(baseUrl, slug, token) {
9531
9752
  if (!res.ok) throw await bookingError(res);
9532
9753
  }
9533
9754
 
9534
- // src/arbi.ts
9535
- function tokenExpiresWithin(token, seconds) {
9536
- const expiresAt = client.readSessionClaims(token)?.expiresAt;
9537
- return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
9755
+ // src/operations/calls.ts
9756
+ var calls_exports = {};
9757
+ __export(calls_exports, {
9758
+ CallApiError: () => CallApiError,
9759
+ WEBINAR_MODERATORS: () => WEBINAR_MODERATORS,
9760
+ WEBINAR_TEAM: () => WEBINAR_TEAM,
9761
+ askQuestion: () => askQuestion,
9762
+ callError: () => callError,
9763
+ cancelCall: () => cancelCall,
9764
+ commitRecordingPart: () => commitRecordingPart,
9765
+ createCall: () => createCall,
9766
+ createCallInviteLink: () => createCallInviteLink,
9767
+ createRecordingTrack: () => createRecordingTrack,
9768
+ decideKnock: () => decideKnock,
9769
+ declineCall: () => declineCall,
9770
+ deleteQuestion: () => deleteQuestion,
9771
+ deleteRecording: () => deleteRecording,
9772
+ deleteRecordingMedia: () => deleteRecordingMedia,
9773
+ demoteFromStage: () => demoteFromStage,
9774
+ downloadRecordingPart: () => downloadRecordingPart,
9775
+ fetchCallToken: () => fetchCallToken,
9776
+ getCall: () => getCall,
9777
+ getCallRecording: () => getCallRecording,
9778
+ getCallsConfig: () => getCallsConfig,
9779
+ getOrCreateCallChat: () => getOrCreateCallChat,
9780
+ getRecordingQuota: () => getRecordingQuota,
9781
+ getWebinar: () => getWebinar,
9782
+ isQuotaError: () => isQuotaError,
9783
+ knockCall: () => knockCall,
9784
+ listCallInviteLinks: () => listCallInviteLinks,
9785
+ listCallRecordings: () => listCallRecordings,
9786
+ listQuestions: () => listQuestions,
9787
+ muteCallParticipant: () => muteCallParticipant,
9788
+ pollKnock: () => pollKnock,
9789
+ postChatTranscriptLine: () => postChatTranscriptLine,
9790
+ presignRecordingPart: () => presignRecordingPart,
9791
+ promoteToStage: () => promoteToStage,
9792
+ quotaNeedsWarning: () => quotaNeedsWarning,
9793
+ recordingStateFrom: () => recordingStateFrom,
9794
+ recordingStateOfCall: () => recordingStateOfCall,
9795
+ removeCallParticipant: () => removeCallParticipant,
9796
+ revokeCallInviteLink: () => revokeCallInviteLink,
9797
+ ringCall: () => ringCall,
9798
+ setCallTranscription: () => setCallTranscription,
9799
+ setRecordingExpiry: () => setRecordingExpiry,
9800
+ setWebinarHand: () => setWebinarHand,
9801
+ startCallRecording: () => startCallRecording,
9802
+ stopCallRecording: () => stopCallRecording,
9803
+ transcribeCallSegment: () => transcribeCallSegment,
9804
+ transcribeRecordingPart: () => transcribeRecordingPart,
9805
+ transcriptionStateFrom: () => transcriptionStateFrom,
9806
+ updateCall: () => updateCall,
9807
+ updateQuestion: () => updateQuestion,
9808
+ updateWebinar: () => updateWebinar,
9809
+ voteQuestion: () => voteQuestion
9810
+ });
9811
+
9812
+ // src/transcription-hints.ts
9813
+ var LANGUAGE_PATTERN = /^[a-z]{2}$/;
9814
+ var PROMPT_MAX_CHARS = 500;
9815
+ var PROMPT_CONTEXT_CHARS = 200;
9816
+ function continuityPrompt(previous) {
9817
+ const text = previous?.replace(/\s+/g, " ").trim();
9818
+ if (!text) return void 0;
9819
+ if (text.length <= PROMPT_CONTEXT_CHARS) return text;
9820
+ const tail = text.slice(-PROMPT_CONTEXT_CHARS);
9821
+ const space = tail.indexOf(" ");
9822
+ const trimmed = space >= 0 && space < tail.length - 1 ? tail.slice(space + 1) : tail;
9823
+ return trimmed || void 0;
9824
+ }
9825
+ function appendTranscriptionHints(form, hints) {
9826
+ if (hints.language && LANGUAGE_PATTERN.test(hints.language)) {
9827
+ form.append("language", hints.language);
9828
+ }
9829
+ const prompt = hints.prompt?.trim().slice(0, PROMPT_MAX_CHARS);
9830
+ if (prompt) form.append("prompt", prompt);
9538
9831
  }
9539
- var Arbi = class {
9540
- client = null;
9541
- loginResult = null;
9542
- userProfile = null;
9543
- profileListeners = /* @__PURE__ */ new Set();
9544
- currentWorkspaceId = null;
9545
- /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
9546
- wrappedKeys = /* @__PURE__ */ new Map();
9547
- /** Workspaces whose key this server session holds (`workspaces.open`), keyed per session key. */
9548
- openedWorkspaces = /* @__PURE__ */ new Map();
9549
- openedForSessionKey = null;
9550
- chatCryptoContext = null;
9551
- /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
9552
- chatRings = /* @__PURE__ */ new Map();
9553
- sessionExpiredListeners = /* @__PURE__ */ new Set();
9554
- options;
9555
- constructor(options) {
9556
- this.options = options;
9557
- if (options.session) {
9558
- this.client = options.session.client;
9559
- this.loginResult = options.session.login;
9560
- this.userProfile = options.session.login.profile ?? null;
9561
- this.currentWorkspaceId = options.session.workspaceId ?? null;
9562
- }
9563
- }
9564
- // ── Lifecycle ───────────────────────────────────────────────────────────
9565
- /**
9566
- * The deployment domain the user's keys are derived for: `deploymentDomain` when given,
9567
- * otherwise the hostname of `url`. Signing and password changes re-derive keys with it, so a
9568
- * host that needs it (the document tools' e-signing) reads it here rather than recomputing it.
9569
- */
9570
- getDeploymentDomain() {
9571
- return this.options.deploymentDomain ?? new URL(this.options.url).hostname;
9572
- }
9573
- /** Initialize the SDK client and sodium crypto. Called automatically by login(). */
9574
- async init() {
9575
- if (this.client) return this.client;
9576
- const domain = this.getDeploymentDomain();
9577
- this.client = client.createArbiClient({
9578
- baseUrl: this.options.url,
9579
- deploymentDomain: domain,
9580
- credentials: this.options.credentials ?? "omit",
9581
- // A silent re-login rotates the server session key: keep ours in step, or the next
9582
- // workspace open would seal the key for a session the server no longer has.
9583
- onReloginSuccess: ({ serverSessionKey }) => {
9584
- if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
9585
- },
9586
- onSessionExpired: () => this.expireSession()
9587
- });
9588
- await this.client.crypto.initSodium();
9589
- return this.client;
9590
- }
9591
- /**
9592
- * Request a verification email for registration.
9593
- * The user will receive an email with a 3-word verification code.
9594
- */
9595
- async requestVerification(email) {
9596
- const client = await this.init();
9597
- await client.fetch.POST("/v1/user/verify-email", { body: { email } });
9598
- }
9599
- /**
9600
- * Register a new account using the verification code received by email.
9601
- */
9602
- async register(params) {
9603
- const client = await this.init();
9604
- await client.auth.register(params);
9605
- }
9606
- /**
9607
- * Log in with email and password.
9608
- * Initializes the SDK client if not already done.
9609
- */
9610
- async login(email, password) {
9611
- const client = await this.init();
9612
- this.loginResult = await client.auth.login({ email, password });
9613
- this.userProfile = this.loginResult.profile ?? null;
9614
- }
9615
- /**
9616
- * Recover a session using a stored signing private key (base64).
9617
- * Useful for session recovery without re-entering the password.
9618
- */
9619
- async loginWithKey(email, signingPrivateKeyBase64) {
9620
- const client = await this.init();
9621
- const signingPrivateKey = client.crypto.base64ToBytes(signingPrivateKeyBase64);
9622
- this.loginResult = await client.auth.loginWithKey({ email, signingPrivateKey });
9623
- this.userProfile = this.loginResult.profile ?? null;
9624
- }
9625
- /** Recover browser authentication using the encrypted signing key already in IndexedDB. */
9626
- async restoreSession(email) {
9627
- const client = await this.init();
9628
- const saved = await client.storage.getSession();
9629
- if (!saved?.signingPrivateKey) return false;
9630
- this.loginResult = await client.auth.loginWithKey({
9631
- email,
9632
- signingPrivateKey: saved.signingPrivateKey
9633
- });
9634
- this.userProfile = this.loginResult.profile ?? null;
9635
- return true;
9832
+
9833
+ // src/operations/call-errors.ts
9834
+ var CallApiError = class extends ArbiApiError {
9835
+ code;
9836
+ constructor(message, status, code, apiError) {
9837
+ super(message, apiError ?? (code ? { detail: code } : void 0), status);
9838
+ this.name = "CallApiError";
9839
+ this.code = code;
9636
9840
  }
9637
- /** Remember the wrapped keys of workspaces the server just returned. */
9638
- rememberWorkspaces(workspaces) {
9639
- for (const ws of workspaces) {
9640
- if (ws.wrapped_key) this.wrappedKeys.set(ws.external_id, ws.wrapped_key);
9641
- }
9642
- return workspaces;
9841
+ };
9842
+ var CODE_TEXT = {
9843
+ // calls
9844
+ locked: "This call is locked.",
9845
+ knock_required: "The host has to let you in.",
9846
+ invalid_invite: "This invitation is no longer valid. Ask the host for a new one.",
9847
+ stale_link: "This call link is no longer valid. Ask for a new one.",
9848
+ cancelled: "This call was cancelled.",
9849
+ not_a_contact: "You can only call people in your contacts.",
9850
+ workspace_locked: "Only members of the thread\u2019s workspace can join this call.",
9851
+ agent_not_allowed: "Agents cannot take part in calls.",
9852
+ thread_not_shared: "Calls can only be started in shared threads.",
9853
+ contact_has_no_email: "This contact has no e-mail address to send a link to.",
9854
+ contact_registered: "This contact has an ARBI account: ring them instead.",
9855
+ invalid_link: "The call link is not valid.",
9856
+ host_only: "Only the host can do that.",
9857
+ // transcription
9858
+ transcription_off: "Transcription is off.",
9859
+ speaker_mismatch: "Only the speaker (or a member, for a workspace guest) can store this line.",
9860
+ // recording
9861
+ storage_quota_exceeded: "The storage quota is full: recording stopped.",
9862
+ already_recording: "The call is already being recorded.",
9863
+ recording_stopped: "The recording has stopped.",
9864
+ recording_active: "Stop the recording first.",
9865
+ composite_needs_video: "This recording has no video.",
9866
+ not_a_member: "Only members of the meeting chat can open this recording.",
9867
+ part_committed: "That part is already stored.",
9868
+ part_not_uploaded: "The part did not reach the storage.",
9869
+ size_mismatch: "The uploaded part has the wrong size.",
9870
+ // webinars
9871
+ moderator_only: "Only the host or a co-host can do that.",
9872
+ team_only: "Only the host and panelists can do that.",
9873
+ host_not_demotable: "The host stays on stage.",
9874
+ on_stage: "You are already on stage.",
9875
+ own_question: "You cannot upvote your own question.",
9876
+ question_dismissed: "This question was dismissed.",
9877
+ question_not_open: "This question is no longer open.",
9878
+ webinar_not_live: "The webinar has not started yet.",
9879
+ not_on_stage: "Only people on stage can do that."
9880
+ };
9881
+ var TRANSCRIBE_STATUS_TEXT = {
9882
+ 413: "That audio clip is too large to transcribe.",
9883
+ 429: "Transcribing too fast \u2014 slowing down.",
9884
+ 502: "The transcriber did not answer.",
9885
+ 503: "Transcription is not available on this server."
9886
+ };
9887
+ function callError(error, status, fallback, options = {}) {
9888
+ const detail = apiErrorDetail(error);
9889
+ const quota = !!options.quota && (status === 507 || status === 402);
9890
+ const code = (detail && /^[a-z_]+$/.test(detail) ? detail : void 0) ?? (quota ? "storage_quota_exceeded" : void 0);
9891
+ const message = code && (options.texts?.[code] ?? CODE_TEXT[code]) || (status !== void 0 ? options.statusTexts?.[status] : void 0) || detail || `${fallback} (${status ?? "?"})`;
9892
+ return new CallApiError(message, status, code, error);
9893
+ }
9894
+ function isQuotaError(err) {
9895
+ if (!(err instanceof CallApiError)) return false;
9896
+ return err.code === "storage_quota_exceeded" || err.status === 507 || err.status === 402;
9897
+ }
9898
+ async function unwrapCall(result, fallback, options) {
9899
+ const { data, error, response } = await result;
9900
+ if (error !== void 0 || !response.ok) {
9901
+ throw callError(error, response.status, fallback, options);
9643
9902
  }
9644
- /**
9645
- * A workspace's wrapped key: from the cache when a list or create already returned it, else from
9646
- * a fresh workspace list (a workspace created or shared since the last list).
9647
- */
9648
- async wrappedKeyFor(workspaceId, refresh2 = false) {
9649
- const cached = refresh2 ? void 0 : this.wrappedKeys.get(workspaceId);
9650
- if (cached) return { wrappedKey: cached, fromCache: true };
9651
- this.wrappedKeys.delete(workspaceId);
9652
- this.rememberWorkspaces(await listWorkspaces(this.requireClient()));
9653
- const wrappedKey = this.wrappedKeys.get(workspaceId);
9654
- if (!wrappedKey) {
9655
- throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
9656
- }
9657
- return { wrappedKey, fromCache: false };
9903
+ return data;
9904
+ }
9905
+
9906
+ // src/operations/call-webinars.ts
9907
+ var WEBINAR_MODERATORS = /* @__PURE__ */ new Set(["host", "cohost"]);
9908
+ var WEBINAR_TEAM = /* @__PURE__ */ new Set(["host", "cohost", "panelist"]);
9909
+ var query = (linkVersion) => linkVersion == null ? void 0 : { link_version: linkVersion };
9910
+ var webinarParams = (callExtId, linkVersion) => ({
9911
+ params: { path: { call_ext_id: callExtId }, query: query(linkVersion) }
9912
+ });
9913
+ var stageParams = (callExtId, identity, linkVersion) => ({
9914
+ params: { path: { call_ext_id: callExtId, identity }, query: query(linkVersion) }
9915
+ });
9916
+ var questionParams = (callExtId, questionExtId, linkVersion) => ({
9917
+ params: {
9918
+ path: { call_ext_id: callExtId, question_ext_id: questionExtId },
9919
+ query: query(linkVersion)
9658
9920
  }
9659
- /**
9660
- * Run `withKey` with the workspace's wrapped key. A cached key that no longer works (access was
9661
- * re-granted with a new key) is dropped and the call retried once with a fresh list.
9662
- */
9663
- async withWrappedKey(workspaceId, withKey) {
9664
- const { wrappedKey, fromCache } = await this.wrappedKeyFor(workspaceId);
9665
- try {
9666
- return await withKey(wrappedKey);
9667
- } catch (error) {
9668
- if (!fromCache) throw error;
9669
- const fresh = await this.wrappedKeyFor(workspaceId, true);
9670
- return withKey(fresh.wrappedKey);
9671
- }
9921
+ });
9922
+ function getWebinar(arbi, callExtId, linkVersion) {
9923
+ return unwrapCall(
9924
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/webinar", webinarParams(callExtId, linkVersion)),
9925
+ "Could not read the webinar"
9926
+ );
9927
+ }
9928
+ function updateWebinar(arbi, callExtId, body, linkVersion) {
9929
+ return unwrapCall(
9930
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/webinar", {
9931
+ ...webinarParams(callExtId, linkVersion),
9932
+ body
9933
+ }),
9934
+ "Could not update the webinar"
9935
+ );
9936
+ }
9937
+ function setWebinarHand(arbi, callExtId, raised, linkVersion) {
9938
+ return unwrapCall(
9939
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/hand", {
9940
+ ...webinarParams(callExtId, linkVersion),
9941
+ body: { raised }
9942
+ }),
9943
+ raised ? "Could not raise your hand" : "Could not lower your hand"
9944
+ );
9945
+ }
9946
+ async function promoteToStage(arbi, callExtId, identity, linkVersion) {
9947
+ await unwrapCall(
9948
+ arbi.fetch.POST(
9949
+ "/v1/calls/{call_ext_id}/webinar/stage/{identity}",
9950
+ stageParams(callExtId, identity, linkVersion)
9951
+ ),
9952
+ "Could not bring them on stage"
9953
+ );
9954
+ }
9955
+ async function demoteFromStage(arbi, callExtId, identity, linkVersion) {
9956
+ await unwrapCall(
9957
+ arbi.fetch.DELETE(
9958
+ "/v1/calls/{call_ext_id}/webinar/stage/{identity}",
9959
+ stageParams(callExtId, identity, linkVersion)
9960
+ ),
9961
+ "Could not move them to the audience"
9962
+ );
9963
+ }
9964
+ function listQuestions(arbi, callExtId, linkVersion) {
9965
+ return unwrapCall(
9966
+ arbi.fetch.GET(
9967
+ "/v1/calls/{call_ext_id}/webinar/questions",
9968
+ webinarParams(callExtId, linkVersion)
9969
+ ),
9970
+ "Could not load the questions"
9971
+ );
9972
+ }
9973
+ function askQuestion(arbi, callExtId, bodyCiphertext, linkVersion) {
9974
+ return unwrapCall(
9975
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/questions", {
9976
+ ...webinarParams(callExtId, linkVersion),
9977
+ body: { body: bodyCiphertext }
9978
+ }),
9979
+ "Could not ask the question"
9980
+ );
9981
+ }
9982
+ function voteQuestion(arbi, callExtId, questionExtId, up, linkVersion) {
9983
+ return unwrapCall(
9984
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}/vote", {
9985
+ ...questionParams(callExtId, questionExtId, linkVersion),
9986
+ body: { up }
9987
+ }),
9988
+ "Could not vote"
9989
+ );
9990
+ }
9991
+ function updateQuestion(arbi, callExtId, questionExtId, body, linkVersion) {
9992
+ return unwrapCall(
9993
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}", {
9994
+ ...questionParams(callExtId, questionExtId, linkVersion),
9995
+ body
9996
+ }),
9997
+ "Could not update the question"
9998
+ );
9999
+ }
10000
+ async function deleteQuestion(arbi, callExtId, questionExtId, linkVersion) {
10001
+ await unwrapCall(
10002
+ arbi.fetch.DELETE(
10003
+ "/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}",
10004
+ questionParams(callExtId, questionExtId, linkVersion)
10005
+ ),
10006
+ "Could not delete the question"
10007
+ );
10008
+ }
10009
+
10010
+ // src/operations/calls.ts
10011
+ var RECORDING = { quota: true };
10012
+ var TRANSCRIBE = { statusTexts: TRANSCRIBE_STATUS_TEXT };
10013
+ var callPath = (callExtId) => ({ params: { path: { call_ext_id: callExtId } } });
10014
+ var recPath = (callExtId, recordingExtId) => ({
10015
+ params: { path: { call_ext_id: callExtId, recording_ext_id: recordingExtId } }
10016
+ });
10017
+ var trackPath = (callExtId, recordingExtId, trackExtId) => ({
10018
+ params: {
10019
+ path: { call_ext_id: callExtId, recording_ext_id: recordingExtId, track_ext_id: trackExtId }
9672
10020
  }
9673
- /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
9674
- async sealWorkspaceKey(workspaceId) {
9675
- const client = this.requireClient();
9676
- const lr2 = this.requireLogin();
9677
- return this.withWrappedKey(
10021
+ });
10022
+ function getCallsConfig(arbi) {
10023
+ return unwrapCall(arbi.fetch.GET("/v1/calls/config"), "Could not read the calls config");
10024
+ }
10025
+ function createCall(arbi, body) {
10026
+ return unwrapCall(arbi.fetch.POST("/v1/calls", { body }), "Could not create the call");
10027
+ }
10028
+ function getCall(arbi, callExtId) {
10029
+ return unwrapCall(
10030
+ arbi.fetch.GET("/v1/calls/{call_ext_id}", callPath(callExtId)),
10031
+ "Could not open the call"
10032
+ );
10033
+ }
10034
+ function updateCall(arbi, callExtId, body) {
10035
+ return unwrapCall(
10036
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}", {
10037
+ ...callPath(callExtId),
10038
+ body
10039
+ }),
10040
+ "Could not update the call"
10041
+ );
10042
+ }
10043
+ async function cancelCall(arbi, callExtId) {
10044
+ await unwrapCall(
10045
+ arbi.fetch.DELETE("/v1/calls/{call_ext_id}", callPath(callExtId)),
10046
+ "Could not cancel the call"
10047
+ );
10048
+ }
10049
+ function fetchCallToken(arbi, callExtId, linkVersion, inviteToken) {
10050
+ return unwrapCall(
10051
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/token", {
10052
+ ...callPath(callExtId),
10053
+ body: {
10054
+ link_version: linkVersion ?? null,
10055
+ ...inviteToken ? { invite_token: inviteToken } : {}
10056
+ }
10057
+ }),
10058
+ "Could not join the call"
10059
+ );
10060
+ }
10061
+ async function ringCall(arbi, callExtId, sealedKeys, linkVersion) {
10062
+ await unwrapCall(
10063
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/ring", {
10064
+ ...callPath(callExtId),
10065
+ body: { sealed_keys: sealedKeys, link_version: linkVersion ?? null }
10066
+ }),
10067
+ "Could not ring"
10068
+ );
10069
+ }
10070
+ async function declineCall(arbi, callExtId) {
10071
+ await unwrapCall(
10072
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/decline", callPath(callExtId)),
10073
+ "Could not decline"
10074
+ );
10075
+ }
10076
+ function knockCall(arbi, callExtId, linkVersion) {
10077
+ return unwrapCall(
10078
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/knock", {
10079
+ ...callPath(callExtId),
10080
+ body: { link_version: linkVersion }
10081
+ }),
10082
+ "Could not ask to join"
10083
+ );
10084
+ }
10085
+ function pollKnock(arbi, callExtId, knockId) {
10086
+ return unwrapCall(
10087
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/knock/{knock_id}", {
10088
+ params: { path: { call_ext_id: callExtId, knock_id: knockId } }
10089
+ }),
10090
+ "Could not check the request"
10091
+ );
10092
+ }
10093
+ async function decideKnock(arbi, callExtId, knockId, admit) {
10094
+ await unwrapCall(
10095
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/knock/{knock_id}", {
10096
+ params: { path: { call_ext_id: callExtId, knock_id: knockId } },
10097
+ body: { admit }
10098
+ }),
10099
+ "Could not answer the request"
10100
+ );
10101
+ }
10102
+ async function getOrCreateCallChat(arbi, callExtId, body) {
10103
+ const { data, error, response } = await arbi.fetch.POST("/v1/calls/{call_ext_id}/chat", {
10104
+ ...callPath(callExtId),
10105
+ // A thread call's meeting thread takes no body.
10106
+ ...body ? { body } : {}
10107
+ });
10108
+ if (response.status === 409) {
10109
+ throw new CallApiError(
10110
+ "Open the call's workspace to keep its meeting chat.",
10111
+ 409,
10112
+ "workspace_required",
10113
+ error
10114
+ );
10115
+ }
10116
+ if (error !== void 0 || !response.ok || !data) {
10117
+ throw callError(error, response.status, "Could not open the meeting chat");
10118
+ }
10119
+ return data;
10120
+ }
10121
+ function createCallInviteLink(arbi, callExtId, body) {
10122
+ return unwrapCall(
10123
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/invite-links", { ...callPath(callExtId), body }),
10124
+ "Could not send the invitation"
10125
+ );
10126
+ }
10127
+ function listCallInviteLinks(arbi, callExtId) {
10128
+ return unwrapCall(
10129
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/invite-links", callPath(callExtId)),
10130
+ "Could not list the invitations"
10131
+ );
10132
+ }
10133
+ async function revokeCallInviteLink(arbi, callExtId, inviteLinkExtId) {
10134
+ await unwrapCall(
10135
+ arbi.fetch.DELETE("/v1/calls/{call_ext_id}/invite-links/{invite_link_ext_id}", {
10136
+ params: { path: { call_ext_id: callExtId, invite_link_ext_id: inviteLinkExtId } }
10137
+ }),
10138
+ "Could not revoke the invitation"
10139
+ );
10140
+ }
10141
+ async function removeCallParticipant(arbi, callExtId, identity) {
10142
+ await unwrapCall(
10143
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/participants/{identity}/remove", {
10144
+ params: { path: { call_ext_id: callExtId, identity } }
10145
+ }),
10146
+ "Could not remove the participant"
10147
+ );
10148
+ }
10149
+ async function muteCallParticipant(arbi, callExtId, identity, track) {
10150
+ await unwrapCall(
10151
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/participants/{identity}/mute", {
10152
+ params: { path: { call_ext_id: callExtId, identity } },
10153
+ body: { track }
10154
+ }),
10155
+ track === "audio" ? "Could not mute the participant" : "Could not turn off the camera"
10156
+ );
10157
+ }
10158
+ function transcriptionStateFrom(value) {
10159
+ if (!value || typeof value !== "object") return null;
10160
+ const v2 = value;
10161
+ if (typeof v2.on !== "boolean") return null;
10162
+ return {
10163
+ on: v2.on,
10164
+ by_identity: typeof v2.by_identity === "string" ? v2.by_identity : null,
10165
+ by_name: typeof v2.by_name === "string" ? v2.by_name : null
10166
+ };
10167
+ }
10168
+ async function setCallTranscription(arbi, callExtId, on) {
10169
+ const data = await unwrapCall(
10170
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/transcription", {
10171
+ ...callPath(callExtId),
10172
+ body: { on }
10173
+ }),
10174
+ "Could not change transcription",
10175
+ { texts: { host_only: "Only the host can turn transcription on or off." } }
10176
+ );
10177
+ return transcriptionStateFrom(data);
10178
+ }
10179
+ function transcribeCallSegment(arbi, callExtId, params) {
10180
+ const ext = params.audio.type.includes("mp4") ? "m4a" : "webm";
10181
+ return unwrapCall(
10182
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/transcribe", {
10183
+ ...callPath(callExtId),
10184
+ // A multipart binary field is typed `string`; the runtime value is the Blob. openapi-fetch has
10185
+ // no multipart serialization, so build real FormData.
10186
+ body: {
10187
+ audio: params.audio,
10188
+ segment_id: params.segmentId,
10189
+ started_at: params.startedAt ?? null,
10190
+ link_version: params.linkVersion ?? null
10191
+ },
10192
+ bodySerializer: (body) => {
10193
+ const form = new FormData();
10194
+ form.append("audio", body.audio, `segment.${ext}`);
10195
+ form.append("segment_id", body.segment_id);
10196
+ if (body.started_at) form.append("started_at", body.started_at);
10197
+ if (body.link_version) form.append("link_version", String(body.link_version));
10198
+ appendTranscriptionHints(form, { language: params.language, prompt: params.prompt });
10199
+ return form;
10200
+ }
10201
+ }),
10202
+ "Could not transcribe",
10203
+ TRANSCRIBE
10204
+ );
10205
+ }
10206
+ function postChatTranscriptLine(arbi, chatExtId, body) {
10207
+ return unwrapCall(
10208
+ arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
10209
+ params: { path: { chat_ext_id: chatExtId } },
10210
+ body: { ...body, kind: "transcript", context_only: false }
10211
+ }),
10212
+ "Could not save the transcript",
10213
+ TRANSCRIBE
10214
+ );
10215
+ }
10216
+ function recordingStateFrom(value) {
10217
+ if (!value || typeof value !== "object") return null;
10218
+ const v2 = value;
10219
+ if (typeof v2.on !== "boolean") return null;
10220
+ const str2 = (x2) => typeof x2 === "string" && x2 ? x2 : null;
10221
+ return {
10222
+ on: v2.on,
10223
+ mode: v2.mode === "audio" || v2.mode === "audio_video" ? v2.mode : null,
10224
+ recording_ext_id: str2(v2.recording_ext_id),
10225
+ by_identity: str2(v2.by_identity),
10226
+ by_name: str2(v2.by_name),
10227
+ reason: str2(v2.reason),
10228
+ started_at: str2(v2.started_at)
10229
+ };
10230
+ }
10231
+ function recordingStateOfCall(call) {
10232
+ return recordingStateFrom(call.recording);
10233
+ }
10234
+ function quotaNeedsWarning(quota) {
10235
+ if (quota.near_limit) return true;
10236
+ return quota.remaining_mb != null && quota.remaining_mb < quota.min_start_mb;
10237
+ }
10238
+ function getRecordingQuota(arbi, callExtId) {
10239
+ return unwrapCall(
10240
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/recording/quota", callPath(callExtId)),
10241
+ "Could not read the storage quota",
10242
+ RECORDING
10243
+ );
10244
+ }
10245
+ async function startCallRecording(arbi, callExtId, mode) {
10246
+ const data = await unwrapCall(
10247
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recording", {
10248
+ ...callPath(callExtId),
10249
+ body: { mode }
10250
+ }),
10251
+ "Could not start recording",
10252
+ RECORDING
10253
+ );
10254
+ return recordingStateFrom(data);
10255
+ }
10256
+ async function stopCallRecording(arbi, callExtId) {
10257
+ const data = await unwrapCall(
10258
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recording/stop", callPath(callExtId)),
10259
+ "Could not stop recording",
10260
+ RECORDING
10261
+ );
10262
+ return recordingStateFrom(data);
10263
+ }
10264
+ function createRecordingTrack(arbi, callExtId, recordingExtId, body) {
10265
+ return unwrapCall(
10266
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks", {
10267
+ ...recPath(callExtId, recordingExtId),
10268
+ body
10269
+ }),
10270
+ "Could not start the recording track",
10271
+ RECORDING
10272
+ );
10273
+ }
10274
+ function presignRecordingPart(arbi, callExtId, recordingExtId, trackExtId, body) {
10275
+ return unwrapCall(
10276
+ arbi.fetch.POST(
10277
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks/{track_ext_id}/parts",
10278
+ { ...trackPath(callExtId, recordingExtId, trackExtId), body }
10279
+ ),
10280
+ "Could not upload a recording part",
10281
+ RECORDING
10282
+ );
10283
+ }
10284
+ async function commitRecordingPart(arbi, callExtId, recordingExtId, trackExtId, seq) {
10285
+ await unwrapCall(
10286
+ arbi.fetch.POST(
10287
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks/{track_ext_id}/parts/{seq}/commit",
10288
+ {
10289
+ params: {
10290
+ path: {
10291
+ call_ext_id: callExtId,
10292
+ recording_ext_id: recordingExtId,
10293
+ track_ext_id: trackExtId,
10294
+ seq
10295
+ }
10296
+ }
10297
+ }
10298
+ ),
10299
+ "Could not commit a recording part",
10300
+ RECORDING
10301
+ );
10302
+ }
10303
+ function listCallRecordings(arbi, callExtId) {
10304
+ return unwrapCall(
10305
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/recordings", callPath(callExtId)),
10306
+ "Could not list the recordings",
10307
+ RECORDING
10308
+ );
10309
+ }
10310
+ function getCallRecording(arbi, callExtId, recordingExtId) {
10311
+ return unwrapCall(
10312
+ arbi.fetch.GET(
10313
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}",
10314
+ recPath(callExtId, recordingExtId)
10315
+ ),
10316
+ "Could not open the recording",
10317
+ RECORDING
10318
+ );
10319
+ }
10320
+ function setRecordingExpiry(arbi, callExtId, recordingExtId, expiresAt) {
10321
+ return unwrapCall(
10322
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}", {
10323
+ ...recPath(callExtId, recordingExtId),
10324
+ body: { expires_at: expiresAt }
10325
+ }),
10326
+ "Could not change the expiry",
10327
+ RECORDING
10328
+ );
10329
+ }
10330
+ function deleteRecordingMedia(arbi, callExtId, recordingExtId) {
10331
+ return unwrapCall(
10332
+ arbi.fetch.DELETE(
10333
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/media",
10334
+ recPath(callExtId, recordingExtId)
10335
+ ),
10336
+ "Could not delete the recording media",
10337
+ RECORDING
10338
+ );
10339
+ }
10340
+ async function deleteRecording(arbi, callExtId, recordingExtId) {
10341
+ await unwrapCall(
10342
+ arbi.fetch.DELETE(
10343
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}",
10344
+ recPath(callExtId, recordingExtId)
10345
+ ),
10346
+ "Could not delete the recording",
10347
+ RECORDING
10348
+ );
10349
+ }
10350
+ function transcribeRecordingPart(arbi, callExtId, recordingExtId, params) {
10351
+ const ext = params.audio.type.includes("wav") ? "wav" : params.audio.type.includes("mp4") ? "m4a" : "webm";
10352
+ const seq = params.seq ?? null;
10353
+ const segment = params.segment ?? null;
10354
+ const segmentOffsetMs = Math.max(0, Math.round(params.segmentOffsetMs ?? 0));
10355
+ return unwrapCall(
10356
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/transcribe", {
10357
+ ...recPath(callExtId, recordingExtId),
10358
+ // A multipart binary field is typed `string`; the runtime value is the Blob. The generated
10359
+ // body types `seq` as required and lacks `language` / `prompt`: the serializer reads the real
10360
+ // values from `params`.
10361
+ body: {
10362
+ audio: params.audio,
10363
+ track_ext_id: params.trackExtId,
10364
+ seq: seq ?? 0,
10365
+ segment,
10366
+ segment_offset_ms: segmentOffsetMs
10367
+ },
10368
+ bodySerializer: (body) => {
10369
+ const form = new FormData();
10370
+ const name = seq != null ? `part-${seq}` : `piece-${segment ?? 0}`;
10371
+ form.append("audio", body.audio, `${name}.${ext}`);
10372
+ form.append("track_ext_id", body.track_ext_id);
10373
+ if (seq != null) form.append("seq", String(seq));
10374
+ if (segment != null) {
10375
+ form.append("segment", String(segment));
10376
+ form.append("segment_offset_ms", String(segmentOffsetMs));
10377
+ }
10378
+ appendTranscriptionHints(form, { language: params.language, prompt: params.prompt });
10379
+ return form;
10380
+ }
10381
+ }),
10382
+ "Could not transcribe the recording",
10383
+ { ...RECORDING, ...TRANSCRIBE }
10384
+ );
10385
+ }
10386
+ async function downloadRecordingPart(url) {
10387
+ const res = await fetch(url);
10388
+ if (!res.ok)
10389
+ throw new CallApiError(`Could not download the recording (${res.status})`, res.status);
10390
+ return new Uint8Array(await res.arrayBuffer());
10391
+ }
10392
+
10393
+ // src/arbi.ts
10394
+ function isAbort(error) {
10395
+ return error instanceof Error && error.name === "AbortError";
10396
+ }
10397
+ function tokenExpiresWithin(token, seconds) {
10398
+ const expiresAt = client.readSessionClaims(token)?.expiresAt;
10399
+ return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
10400
+ }
10401
+ var Arbi = class {
10402
+ client = null;
10403
+ loginResult = null;
10404
+ userProfile = null;
10405
+ profileListeners = /* @__PURE__ */ new Set();
10406
+ currentWorkspaceId = null;
10407
+ chatCryptoContext = null;
10408
+ /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
10409
+ chatRings = /* @__PURE__ */ new Map();
10410
+ sessionExpiredListeners = /* @__PURE__ */ new Set();
10411
+ signedInListeners = /* @__PURE__ */ new Set();
10412
+ /** The client is this instance's own (`init`), not a host's (`options.session`). */
10413
+ ownsClient = false;
10414
+ options;
10415
+ constructor(options) {
10416
+ this.options = options;
10417
+ if (options.session) {
10418
+ this.client = options.session.client;
10419
+ this.loginResult = options.session.login;
10420
+ this.userProfile = options.session.login?.profile ?? null;
10421
+ this.currentWorkspaceId = options.session.workspaceId ?? null;
10422
+ }
10423
+ }
10424
+ // ── Lifecycle ───────────────────────────────────────────────────────────
10425
+ /**
10426
+ * The deployment domain the user's keys are derived for: `deploymentDomain` when given,
10427
+ * otherwise the hostname of `url`. Signing and password changes re-derive keys with it, so a
10428
+ * host that needs it (the document tools' e-signing) reads it here rather than recomputing it.
10429
+ */
10430
+ getDeploymentDomain() {
10431
+ return this.options.deploymentDomain ?? new URL(this.options.url).hostname;
10432
+ }
10433
+ /** Initialize the SDK client and sodium crypto. Called automatically by login(). */
10434
+ async init() {
10435
+ if (this.client) return this.client;
10436
+ const domain = this.getDeploymentDomain();
10437
+ this.client = client.createArbiClient({
10438
+ baseUrl: this.options.url,
10439
+ deploymentDomain: domain,
10440
+ credentials: this.options.credentials ?? "omit",
10441
+ session: client.createSessionManager({ storage: this.options.sessionStorage }),
10442
+ // A silent re-login rotates the server session key: keep ours in step, or the next
10443
+ // workspace open would seal the key for a session the server no longer has.
10444
+ onReloginSuccess: ({ serverSessionKey }) => {
10445
+ if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
10446
+ }
10447
+ });
10448
+ this.ownsClient = true;
10449
+ this.client.auth.onSessionExpired(() => this.expireSession());
10450
+ await this.client.crypto.initSodium();
10451
+ return this.client;
10452
+ }
10453
+ /**
10454
+ * Request a verification email for registration. The user will receive an email with a link and
10455
+ * a 3-word verification code. Resolves to the server's confirmation; throws with its `detail`.
10456
+ */
10457
+ async requestVerification(email) {
10458
+ const client$1 = await this.init();
10459
+ const { data, error, response } = await client$1.fetch.POST("/v1/user/verify-email", {
10460
+ body: { email }
10461
+ });
10462
+ if (error || !data) throw client.authRequestError("Verification", error, response.status);
10463
+ return data.detail;
10464
+ }
10465
+ /**
10466
+ * Register a new account with the verification code received by email (or, for an SSO account,
10467
+ * the provider's token as `verificationCode`). Resolves to the new identity key, for the recovery
10468
+ * key backup. Does not sign in: `login` follows.
10469
+ */
10470
+ async register(params) {
10471
+ const client = await this.init();
10472
+ return client.auth.register(params);
10473
+ }
10474
+ /**
10475
+ * Log in with email and password (and the SSO provider's token for an SSO account). Signs the
10476
+ * session in; resolves to the login, its response included. Initializes the client if needed.
10477
+ */
10478
+ async login(email, password, options = {}) {
10479
+ const client = await this.init();
10480
+ return this.signedIn(await client.auth.login({ email, password, ...options }));
10481
+ }
10482
+ /** This instance signed in (`login`, `loginWithKey`, `restore`, an SSO sign-in). */
10483
+ signedIn(login) {
10484
+ this.loginResult = login;
10485
+ this.userProfile = login.profile ?? null;
10486
+ for (const listener of [...this.signedInListeners]) listener(login);
10487
+ return login;
10488
+ }
10489
+ /**
10490
+ * Be told when this instance signs in, by whatever path (a sign-in page, a restored session).
10491
+ * Returns an unsubscribe.
10492
+ */
10493
+ onSignedIn(listener) {
10494
+ this.signedInListeners.add(listener);
10495
+ return () => this.signedInListeners.delete(listener);
10496
+ }
10497
+ /**
10498
+ * Sign in on this device while offline: the password must open the identity saved here at the
10499
+ * last login (see `ArbiClient.auth.unlock`).
10500
+ */
10501
+ async unlock(email, password) {
10502
+ const client = await this.init();
10503
+ await client.auth.unlock({ email, password });
10504
+ }
10505
+ /**
10506
+ * Single sign-on, after the provider (Auth0) signed the user in and handed over its token. The
10507
+ * account still has its own master password (the keys are derived from it); the provider's token
10508
+ * proves the identity:
10509
+ * - `status`: is there an account for this email, and how does it sign in (`new_user`,
10510
+ * `sso_exists`, `local_exists`), with the names the server knows;
10511
+ * - `register`: a new account (the token stands in for the verification code); resolves with the
10512
+ * identity key, for its backup; `login` follows (with the provider's name and picture);
10513
+ * - `login`: an SSO account signs in; `link`: a password account signs in with the token and is
10514
+ * linked to SSO from then on;
10515
+ * - `resendVerification`: the provider's verification email again (its user id).
10516
+ */
10517
+ sso = {
10518
+ status: async (params) => {
10519
+ const client$1 = await this.init();
10520
+ const { data, error, response } = await client$1.fetch.POST("/v1/user/sso-status", {
10521
+ body: { sso_token: params.token, email: params.email, picture: params.picture }
10522
+ });
10523
+ if (error || !data) throw client.authRequestError("SSO status", error, response.status);
10524
+ return data;
10525
+ },
10526
+ register: (params) => this.register({
10527
+ email: params.email,
10528
+ password: params.password,
10529
+ verificationCode: params.token,
10530
+ firstName: params.firstName,
10531
+ lastName: params.lastName,
10532
+ picture: params.picture ?? void 0
10533
+ }),
10534
+ login: (params) => this.login(params.email, params.password, {
10535
+ ssoToken: params.token,
10536
+ profile: params.profile
10537
+ }),
10538
+ link: (params) => this.login(params.email, params.password, { ssoToken: params.token }),
10539
+ resendVerification: async (providerUserId) => {
10540
+ const client$1 = await this.init();
10541
+ const { data, error, response } = await client$1.fetch.POST(
10542
+ "/v1/user/sso-send-verification-email",
10543
+ { body: { auth0_id: providerUserId } }
10544
+ );
10545
+ if (error || !data) throw client.authRequestError("Verification email", error, response.status);
10546
+ return data.detail ?? "";
10547
+ }
10548
+ };
10549
+ /**
10550
+ * Sign in with the account's identity key itself (a recovery key, a stored key; bytes or base64)
10551
+ * instead of the password. Resolves to the login, its response included.
10552
+ */
10553
+ async loginWithKey(email, signingPrivateKey, options = {}) {
10554
+ const client = await this.init();
10555
+ return this.signedIn(
10556
+ await client.auth.loginWithKey({
10557
+ email,
10558
+ signingPrivateKey: typeof signingPrivateKey === "string" ? client.crypto.base64ToBytes(signingPrivateKey) : signingPrivateKey,
10559
+ ...options
10560
+ })
10561
+ );
10562
+ }
10563
+ /**
10564
+ * Sign in again from the session kept on this device (`sessionStorage`): the account signed in
10565
+ * last, with its identity key from the encrypted store. False, and the kept session dropped,
10566
+ * when there is none to restore.
10567
+ */
10568
+ async restore() {
10569
+ const client = await this.init();
10570
+ const { signedIn, userEmail } = client.session.getState();
10571
+ if (!signedIn || !userEmail) return false;
10572
+ const saved = await client.storage.getSession().catch(() => null);
10573
+ if (!saved?.signingPrivateKey) {
10574
+ client.session.clear();
10575
+ return false;
10576
+ }
10577
+ await this.loginWithKey(userEmail, saved.signingPrivateKey);
10578
+ return true;
10579
+ }
10580
+ /**
10581
+ * Run `withKey` with the workspace's wrapped key (the client's, from the lists it has seen). A
10582
+ * remembered key that no longer works (access was re-granted with a new key) is read again and
10583
+ * the call retried once. Throws for a public workspace the user holds no key for.
10584
+ */
10585
+ async withWrappedKey(workspaceId, withKey) {
10586
+ const keys = this.requireClient().workspaceKeys;
10587
+ const required = (key) => {
10588
+ if (!key) throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
10589
+ return key;
10590
+ };
10591
+ const { wrappedKey, fromCache } = await keys.wrappedKey(workspaceId).catch((error) => {
10592
+ throw new ArbiError(error instanceof Error ? error.message : String(error));
10593
+ });
10594
+ try {
10595
+ return await withKey(required(wrappedKey));
10596
+ } catch (error) {
10597
+ if (!fromCache) throw error;
10598
+ const fresh = await keys.wrappedKey(workspaceId, { refresh: true });
10599
+ return withKey(required(fresh.wrappedKey));
10600
+ }
10601
+ }
10602
+ /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
10603
+ async sealWorkspaceKey(workspaceId) {
10604
+ const client = this.requireClient();
10605
+ const lr2 = this.requireLogin();
10606
+ return this.withWrappedKey(
9678
10607
  workspaceId,
9679
10608
  (wrappedKey) => generateEncryptedWorkspaceKey(
9680
10609
  client,
@@ -9686,28 +10615,13 @@ var Arbi = class {
9686
10615
  }
9687
10616
  /**
9688
10617
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
9689
- * the server or here): its key, sealed to this server session, is deposited with `/prime-key`.
9690
- * Idempotent: cached per server session (a re-login rotates it), concurrent calls share one
9691
- * request, and the current workspace is already open.
10618
+ * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
10619
+ * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
9692
10620
  */
9693
10621
  openWorkspace(workspaceId) {
9694
10622
  if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
9695
- const lr2 = this.requireLogin();
9696
- if (this.openedForSessionKey !== lr2.serverSessionKey) {
9697
- this.openedWorkspaces.clear();
9698
- this.openedForSessionKey = lr2.serverSessionKey;
9699
- }
9700
- const cached = this.openedWorkspaces.get(workspaceId);
9701
- if (cached) return cached;
9702
- const opening = this.sealWorkspaceKey(workspaceId).then(
9703
- (sealedKey) => primeWorkspaceKey(this.requireClient(), workspaceId, sealedKey)
9704
- );
9705
- this.openedWorkspaces.set(workspaceId, opening);
9706
- opening.catch(() => {
9707
- if (this.openedWorkspaces.get(workspaceId) === opening)
9708
- this.openedWorkspaces.delete(workspaceId);
9709
- });
9710
- return opening;
10623
+ this.requireLogin();
10624
+ return this.requireClient().workspaceKeys.prime(workspaceId);
9711
10625
  }
9712
10626
  /** The workspace a call names, opened for this session; `undefined` for the current one. */
9713
10627
  async targetWorkspace(workspaceId) {
@@ -9718,35 +10632,50 @@ var Arbi = class {
9718
10632
  /**
9719
10633
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
9720
10634
  * session's active workspace) and record it in the session. This is navigation: only the host's
9721
- * workspace switch calls it. Package code that needs another workspace calls
9722
- * `workspaces.open(id)` and passes the workspace to the request instead.
10635
+ * workspace switch (`useSwitchWorkspace` in `@arbidocs/react`) calls it. Package code that needs
10636
+ * another workspace calls `workspaces.open(id)` and passes the workspace to the request instead.
10637
+ *
10638
+ * Returns what the server opened: the workspace with its conversations and tags (not its
10639
+ * documents, which are listed page by page). A public workspace has no key and opens without one.
9723
10640
  */
9724
10641
  async selectWorkspace(workspaceId) {
9725
10642
  const client = this.requireClient();
9726
10643
  const lr2 = this.requireLogin();
9727
- const signingPrivateKeyBase64 = client.crypto.bytesToBase64(lr2.signingPrivateKey);
9728
- await this.withWrappedKey(workspaceId, async (wrappedKey) => {
9729
- const sealedKey = await selectWorkspace(
9730
- client,
9731
- workspaceId,
9732
- wrappedKey,
9733
- lr2.serverSessionKey,
9734
- signingPrivateKeyBase64
9735
- );
10644
+ const open = async (workspaceKey) => requireData(
9736
10645
  await client.fetch.POST("/v1/workspace/{workspace_ext_id}/open", {
9737
- params: { path: { workspace_ext_id: workspaceId } },
9738
- body: { workspace_key: sealedKey }
9739
- });
10646
+ params: { path: { workspace_ext_id: workspaceId }, query: { include_documents: false } },
10647
+ body: { workspace_key: workspaceKey }
10648
+ }),
10649
+ `Failed to open workspace ${workspaceId}`
10650
+ );
10651
+ const listed = await client.workspaceKeys.wrappedKey(workspaceId).catch((error) => {
10652
+ throw new ArbiError(error instanceof Error ? error.message : String(error));
9740
10653
  });
10654
+ const opened = !listed.wrappedKey ? await open("") : await this.withWrappedKey(
10655
+ workspaceId,
10656
+ async (wrappedKey) => open(
10657
+ await selectWorkspace(
10658
+ client,
10659
+ workspaceId,
10660
+ wrappedKey,
10661
+ lr2.serverSessionKey,
10662
+ client.crypto.bytesToBase64(lr2.signingPrivateKey)
10663
+ )
10664
+ )
10665
+ );
10666
+ client.session.setSelectedWorkspace(workspaceId);
9741
10667
  this.currentWorkspaceId = workspaceId;
10668
+ return opened;
9742
10669
  }
9743
10670
  /**
9744
10671
  * Subscribe to "the session cannot be recovered". Fires when a request failed with 401 or
9745
10672
  * "No active workspace" and neither a workspace re-open nor a silent re-login was possible
9746
10673
  * (the server refused; an unreachable server does not fire). The local session is already
9747
10674
  * cleared when it fires: show "Your session expired, sign in again". Returns an unsubscribe.
10675
+ * On a host's session it is the host client's expiry.
9748
10676
  */
9749
10677
  onSessionExpired(listener) {
10678
+ if (this.client && !this.ownsClient) return this.client.auth.onSessionExpired(listener);
9750
10679
  this.sessionExpiredListeners.add(listener);
9751
10680
  return () => this.sessionExpiredListeners.delete(listener);
9752
10681
  }
@@ -9758,16 +10687,15 @@ var Arbi = class {
9758
10687
  this.loginResult = null;
9759
10688
  this.userProfile = null;
9760
10689
  this.currentWorkspaceId = null;
9761
- this.wrappedKeys.clear();
9762
10690
  this.chatCryptoContext = null;
9763
10691
  this.chatRings.clear();
9764
- this.client?.session.clear();
9765
10692
  for (const listener of [...this.sessionExpiredListeners]) listener();
9766
10693
  }
9767
10694
  /**
9768
10695
  * Run a raw-fetch operation (streaming, multipart: no middleware) and, when it fails because
9769
10696
  * the token expired or the server lost the open workspace, recover once and run it again.
9770
- * `run` must read the auth headers itself so the retry carries the fresh token.
10697
+ * `run` must read the auth headers itself so the retry carries the fresh token. The client's
10698
+ * re-login is the one recovery: a refused one has already ended the session (`onSessionExpired`).
9771
10699
  */
9772
10700
  async recovering(run) {
9773
10701
  if (this.client && tokenExpiresWithin(this.client.session.getState().accessToken, 30)) {
@@ -9782,10 +10710,7 @@ var Arbi = class {
9782
10710
  if (!(error instanceof ArbiApiError) || !(noWorkspace || unauthorised)) throw error;
9783
10711
  const client = this.requireClient();
9784
10712
  const recovered = noWorkspace && await client.auth.reopenWorkspace() || await client.auth.relogin() !== null;
9785
- if (!recovered) {
9786
- this.expireSession();
9787
- throw new ArbiSessionExpiredError();
9788
- }
10713
+ if (!recovered) throw new ArbiSessionExpiredError();
9789
10714
  return run();
9790
10715
  }
9791
10716
  }
@@ -9793,10 +10718,14 @@ var Arbi = class {
9793
10718
  this.userProfile = profile;
9794
10719
  for (const listener of [...this.profileListeners]) listener(profile);
9795
10720
  }
9796
- /** Log out and clear internal state. */
9797
- async logout() {
10721
+ /**
10722
+ * Sign out: the server session ends (every session of the user with `everywhere`), the session
10723
+ * state is cleared and, with `everywhere`, so are the keys kept on this device (a single sign-out
10724
+ * keeps them for an offline unlock). Then this instance's own state is cleared.
10725
+ */
10726
+ async logout(options = {}) {
9798
10727
  if (this.client) {
9799
- await this.client.auth.logout();
10728
+ await this.client.auth.logout(options);
9800
10729
  }
9801
10730
  if (this.loginResult) {
9802
10731
  this.loginResult.signingPrivateKey.fill(0);
@@ -9805,11 +10734,17 @@ var Arbi = class {
9805
10734
  this.loginResult = null;
9806
10735
  this.userProfile = null;
9807
10736
  this.currentWorkspaceId = null;
9808
- this.wrappedKeys.clear();
9809
10737
  this.chatCryptoContext = null;
9810
10738
  this.chatRings.clear();
9811
10739
  }
9812
10740
  // ── Accessors ─────────────────────────────────────────────────────────
10741
+ /**
10742
+ * The session state this instance runs on (token, user, SSO mode, signed in), to read and
10743
+ * subscribe to; `null` before a client exists.
10744
+ */
10745
+ get session() {
10746
+ return this.client?.session ?? null;
10747
+ }
9813
10748
  /** Get the underlying ArbiClient (throws if not initialized). */
9814
10749
  getClient() {
9815
10750
  return this.requireClient();
@@ -10037,9 +10972,26 @@ var Arbi = class {
10037
10972
  * Idempotent and cached per server session. Navigation uses `selectWorkspace`.
10038
10973
  */
10039
10974
  open: (workspaceId) => this.openWorkspace(workspaceId),
10975
+ /**
10976
+ * A workspace's key sealed to this server session: what `POST /workspace/users` takes to give
10977
+ * someone (an agent) access, and what `/prime-key` deposits. Throws when the user holds no key
10978
+ * for it (a public workspace, or one they can see but never joined).
10979
+ */
10980
+ sealKey: (workspaceId) => this.sealWorkspaceKey(workspaceId),
10981
+ /**
10982
+ * A workspace's raw key, unwrapped with my identity (for content I encrypt under it myself,
10983
+ * such as a thread call's recording). Never sent anywhere.
10984
+ */
10985
+ key: (workspaceId) => this.withWrappedKey(
10986
+ workspaceId,
10987
+ async (wrappedKey) => client.unwrapWorkspaceKey(wrappedKey, this.requireLogin().signingPrivateKey)
10988
+ ),
10040
10989
  /** Hand this server session a workspace's key (sealed to the session) without opening it. */
10041
10990
  primeKey: (workspaceExtId, sessionSealedKey) => primeWorkspaceKey(this.requireClient(), workspaceExtId, sessionSealedKey),
10042
- list: async () => this.rememberWorkspaces(await listWorkspaces(this.requireClient())),
10991
+ list: async () => {
10992
+ const client = this.requireClient();
10993
+ return client.workspaceKeys.remember(await listWorkspaces(client));
10994
+ },
10043
10995
  create: async (name, projectExtId, description, isPublic) => {
10044
10996
  const client = this.requireClient();
10045
10997
  const lr2 = this.requireLogin();
@@ -10056,12 +11008,12 @@ var Arbi = class {
10056
11008
  description,
10057
11009
  isPublic
10058
11010
  );
10059
- this.rememberWorkspaces([created]);
11011
+ client.workspaceKeys.remember([created]);
10060
11012
  return created;
10061
11013
  },
10062
11014
  delete: async (workspaceIds) => {
10063
11015
  await deleteWorkspaces(this.requireClient(), workspaceIds);
10064
- for (const id of workspaceIds) this.wrappedKeys.delete(id);
11016
+ this.requireClient().workspaceKeys.forget(workspaceIds);
10065
11017
  },
10066
11018
  update: (body) => updateWorkspace(this.requireClient(), body),
10067
11019
  listUsers: () => listWorkspaceUsers(this.requireClient()),
@@ -10135,7 +11087,28 @@ var Arbi = class {
10135
11087
  targetWorkspaceId,
10136
11088
  docIds,
10137
11089
  targetWorkspaceKey
10138
- )
11090
+ ),
11091
+ /**
11092
+ * Download, copy or move a scope of the current workspace (`/v1/workspace/transfer*`): plan it,
11093
+ * run a copy or move into another workspace as a background job (its key is sealed here), follow,
11094
+ * resume or cancel the job, or export the scope's data for a download.
11095
+ */
11096
+ transfer: {
11097
+ plan: (scope, mode) => planWorkspaceTransfer(this.requireClient(), scope, mode),
11098
+ start: async (params) => startWorkspaceTransfer(this.requireClient(), {
11099
+ ...params,
11100
+ targetWorkspaceKey: await this.sealWorkspaceKey(params.targetWorkspaceId)
11101
+ }),
11102
+ resume: async (transferId, targetWorkspaceId) => resumeWorkspaceTransfer(
11103
+ this.requireClient(),
11104
+ transferId,
11105
+ await this.sealWorkspaceKey(targetWorkspaceId)
11106
+ ),
11107
+ cancel: (transferId) => cancelWorkspaceTransfer(this.requireClient(), transferId),
11108
+ get: (transferId) => getWorkspaceTransfer(this.requireClient(), transferId),
11109
+ list: () => listWorkspaceTransfers(this.requireClient()),
11110
+ exportData: (scope) => exportWorkspaceData(this.requireClient(), scope)
11111
+ }
10139
11112
  };
10140
11113
  // ── Documents ─────────────────────────────────────────────────────────
10141
11114
  documents = {
@@ -10254,7 +11227,10 @@ var Arbi = class {
10254
11227
  },
10255
11228
  getMessage: (messageId) => getMessage(this.requireClient(), messageId),
10256
11229
  deleteMessage: (messageId) => deleteMessage(this.requireClient(), messageId),
10257
- /** Post a human comment (no assistant run) — see `postConversationMessage`. */
11230
+ /**
11231
+ * Post a human comment (no assistant run) — see `postConversationMessage`. A thread in another
11232
+ * workspace than the current one works too: its key is handed to the session on demand.
11233
+ */
10258
11234
  postMessage: (body) => postConversationMessage(this.requireClient(), body),
10259
11235
  setAssistantMode: (conversationId, assistantMode) => updateConversationAssistantMode(
10260
11236
  this.requireClient(),
@@ -10338,7 +11314,79 @@ var Arbi = class {
10338
11314
  };
10339
11315
  // ── Assistant ─────────────────────────────────────────────────────────
10340
11316
  assistant = {
10341
- cancelRun: (responseId) => this.recovering(() => cancelAssistantRun(this.getAuthHeaders(), responseId)),
11317
+ /**
11318
+ * Ask the assistant: send one turn (the body is `buildTurnRequest`) and stream it into
11319
+ * `handlers`. Resolves with the accumulated result when the stream ends.
11320
+ *
11321
+ * The token is renewed before a long stream starts and once on a 401. A refusal (402 quota,
11322
+ * 409, 503, …) reaches `onError` as the server's words, a 402 quota also `onQuotaExceeded`,
11323
+ * and `ask` rejects with it; a dropped connection reaches `onError` as the `Error` and rejects
11324
+ * with it; an abort just rejects.
11325
+ */
11326
+ ask: async (request, handlers = {}) => {
11327
+ const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
11328
+ const body = buildTurnRequest({
11329
+ ...request,
11330
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
11331
+ });
11332
+ const refuse = (message, error = new Error(message)) => {
11333
+ onError?.(message);
11334
+ throw error;
11335
+ };
11336
+ let response;
11337
+ try {
11338
+ response = await this.recovering(
11339
+ () => openTurnStream(this.getAuthHeaders(), body, signal)
11340
+ );
11341
+ } catch (error) {
11342
+ if (isAbort(error)) throw error;
11343
+ if (error instanceof AssistantTurnRefused) {
11344
+ if (error.quota) onQuotaExceeded?.(error.quota);
11345
+ return refuse(error.message);
11346
+ }
11347
+ if (error instanceof ArbiSessionExpiredError || error instanceof ArbiApiError && error.status === 401) {
11348
+ const message = SESSION_EXPIRED_MESSAGE;
11349
+ return refuse(message, new ArbiSessionExpiredError(message));
11350
+ }
11351
+ onError?.(error);
11352
+ throw error;
11353
+ }
11354
+ try {
11355
+ return await streamSSE(response, {
11356
+ ...callbacks,
11357
+ onError: (message) => onError?.(message),
11358
+ onArbiError: (event) => {
11359
+ const quota = quotaExceededFrom(event);
11360
+ if (quota) onQuotaExceeded?.(quota);
11361
+ }
11362
+ });
11363
+ } catch (error) {
11364
+ if (!isAbort(error)) onError?.(error);
11365
+ throw error;
11366
+ }
11367
+ },
11368
+ /**
11369
+ * Attach to a running turn by its response id: replays its frames so far, then tails the live
11370
+ * ones until it ends. Rejects when the run is no longer active ("This run is no longer active.").
11371
+ */
11372
+ attachRun: async (responseId, handlers = {}) => {
11373
+ const { signal, ...callbacks } = handlers;
11374
+ const response = await this.recovering(
11375
+ () => openRunStream(this.getAuthHeaders(), responseId, signal)
11376
+ );
11377
+ return streamSSE(response, callbacks);
11378
+ },
11379
+ /**
11380
+ * Interject into a running turn: answer its question, steer it, or send a run-control command
11381
+ * (`/pause`, `/resume`, `/report`).
11382
+ */
11383
+ interject: (assistantMessageExtId, answer) => interject(this.requireClient(), assistantMessageExtId, answer),
11384
+ /** Stop a run on the server (closing its stream alone leaves it running). */
11385
+ cancel: (responseId) => this.recovering(() => cancelRun(this.getAuthHeaders(), responseId)),
11386
+ /** The backend's built-in slash commands (`/compact`, `/goal`, …), for a slash menu. */
11387
+ commands: () => listCommands(this.requireClient()),
11388
+ /** Transcribe a voice recording to text (empty when no speech was found). */
11389
+ transcribe: (audio) => transcribe(this.requireClient(), audio),
10342
11390
  /** Start a durable background turn; task options make its thread a work item. */
10343
11391
  submit: (question, options) => {
10344
11392
  const workspaceId = this.requireWorkspace();
@@ -10353,47 +11401,6 @@ var Arbi = class {
10353
11401
  },
10354
11402
  /** Read the status of a background turn. */
10355
11403
  getResponse: (id) => this.recovering(() => getResponse(this.getAuthHeaders(), id)),
10356
- /**
10357
- * Send a question to the RAG assistant with streaming support.
10358
- * Returns the accumulated result after the stream completes.
10359
- */
10360
- query: async (question, options) => {
10361
- const workspaceId = options.workspaceId ?? this.requireWorkspace();
10362
- const response = await this.recovering(
10363
- () => queryAssistant({
10364
- ...this.getAuthHeaders(),
10365
- workspaceId,
10366
- question,
10367
- agentId: options.agentId,
10368
- docIds: options.docIds,
10369
- previousResponseId: options.previousResponseId,
10370
- conversationId: options.conversationId,
10371
- assistantMode: options.assistantMode,
10372
- mentions: options.mentions,
10373
- model: options.model,
10374
- activeArtifactExtId: options.activeArtifactExtId,
10375
- signal: options.signal
10376
- })
10377
- );
10378
- const callbacks = {
10379
- onToken: options.onToken,
10380
- onStreamStart: options.onStreamStart,
10381
- onOutputItemDone: options.onOutputItemDone,
10382
- onError: options.onError,
10383
- onUserMessage: options.onUserMessage,
10384
- onMetadata: options.onMetadata,
10385
- onUserInputRequest: options.onUserInputRequest,
10386
- onArtifact: options.onArtifact,
10387
- onMailDraft: options.onMailDraft,
10388
- onElapsedTime: options.onElapsedTime,
10389
- onComplete: options.onComplete
10390
- };
10391
- return streamSSE(response, callbacks);
10392
- },
10393
- /**
10394
- * Respond to an agent's question during a human-in-the-loop workflow.
10395
- */
10396
- respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
10397
11404
  /** The skills the caller can run (own + shared marketplace), metadata only. */
10398
11405
  listSkills: (options) => listSkills(this.requireClient(), options),
10399
11406
  /**
@@ -10410,10 +11417,10 @@ var Arbi = class {
10410
11417
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
10411
11418
  * workspace; `searchChunks(result)` ranks the passages found.
10412
11419
  */
10413
- retrieve: (query, docIds, options) => retrieve({
11420
+ retrieve: (query2, docIds, options) => retrieve({
10414
11421
  arbi: this.requireClient(),
10415
11422
  workspaceId: this.requireWorkspace(),
10416
- query,
11423
+ query: query2,
10417
11424
  docIds,
10418
11425
  ...options
10419
11426
  })
@@ -10425,7 +11432,7 @@ var Arbi = class {
10425
11432
  * each tag's documents, facts and threads: `list({ kind: 'issue', include: ['links'] })` is the
10426
11433
  * issue table's rows (its columns: `tagKinds.get('issue')`).
10427
11434
  */
10428
- list: (query) => listTags(this.requireClient(), query),
11435
+ list: (query2) => listTags(this.requireClient(), query2),
10429
11436
  create: (options) => createTag(this.requireClient(), {
10430
11437
  ...options,
10431
11438
  workspaceId: options.workspaceId ?? this.requireWorkspace()
@@ -10521,7 +11528,7 @@ var Arbi = class {
10521
11528
  listHolidayCountries: () => this.withCalendarKeys((c2) => listHolidayCountries(c2)),
10522
11529
  addHolidays: (body) => this.withCalendarKeys((c2) => addHolidayCalendar(c2, body)),
10523
11530
  createRoom: (body) => this.withCalendarKeys((c2) => createRoom(c2, body)),
10524
- listRooms: (query) => this.withCalendarKeys((c2) => listRooms(c2, query)),
11531
+ listRooms: (query2) => this.withCalendarKeys((c2) => listRooms(c2, query2)),
10525
11532
  freeBusy: (body) => this.withCalendarKeys((c2) => getFreeBusy(c2, body)),
10526
11533
  findTime: (body) => this.withCalendarKeys((c2) => findTime(c2, body)),
10527
11534
  /**
@@ -10690,6 +11697,223 @@ var Arbi = class {
10690
11697
  /** Fetch, decrypt and size-check one attachment. */
10691
11698
  downloadAttachment: (file) => downloadChatAttachment(this.requireClient(), file)
10692
11699
  };
11700
+ // ── Calls ─────────────────────────────────────────────────────────────
11701
+ /** My copy of a call's key K from its row (sealed to me as creator or invitee), or null. */
11702
+ async callKeyOf(call) {
11703
+ return client.openCallKeyOf(call, (await this.requireChatCrypto()).encryptionKeypair.secretKey);
11704
+ }
11705
+ /** A call's title under K, in plaintext; null when it has none or it does not open. */
11706
+ async callTitleOf(call, key) {
11707
+ if (!call.title || !key) return null;
11708
+ return client.decryptCallTitle(call.title, key);
11709
+ }
11710
+ /**
11711
+ * Calls (LiveKit): one call system for thread, chat (DM / group), contacts and scheduled calls.
11712
+ * Each call has one random key K made in the creator's process; the server and the media server
11713
+ * only ever hold it sealed to people (or in a link's fragment). `start`, `open`, `answer` and
11714
+ * `resetLink` do the key work and hand back K with the call; everything else moves ciphertext.
11715
+ */
11716
+ calls = {
11717
+ /** The deployment's calls config (`enabled`, `transcription_available`, …). */
11718
+ config: () => getCallsConfig(this.requireClient()),
11719
+ get: (callExtId) => getCall(this.requireClient(), callExtId),
11720
+ /** Create a call row as is (a scheduled call's ciphertext made by the caller). */
11721
+ create: (body) => createCall(this.requireClient(), body),
11722
+ update: (callExtId, body) => updateCall(this.requireClient(), callExtId, body),
11723
+ cancel: (callExtId) => cancelCall(this.requireClient(), callExtId),
11724
+ /**
11725
+ * Start a call: a fresh K sealed to me and to each of `invitees` (people without a key are
11726
+ * skipped), the title under K. Returns K and `sealedKeys` (K per invitee: what `ring` takes).
11727
+ * A thread call is get-or-create: when the thread already has a running call, that one comes
11728
+ * back with my copy of its key, and `sealedKeys` are sealed to its key instead.
11729
+ *
11730
+ * A scheduled call has no thread or chat; a webinar (`mode: 'webinar'`) gives each invitee
11731
+ * their `roles` entry (attendee by default).
11732
+ */
11733
+ start: async (params) => {
11734
+ const client$1 = this.requireClient();
11735
+ const me2 = await this.requireChatCrypto();
11736
+ const fresh = await client.generateCallKey();
11737
+ const sealed = await client.sealCallKeyForPeers(fresh, params.invitees, me2.userExtId);
11738
+ const roles = params.roles;
11739
+ const title = params.title?.trim();
11740
+ const call = await createCall(client$1, {
11741
+ ...params.threadExtId ? { thread_ext_id: params.threadExtId } : {},
11742
+ ...params.chatExtId ? { chat_ext_id: params.chatExtId } : {},
11743
+ mode: params.mode ?? "call",
11744
+ ...params.joinPolicy ? { join_policy: params.joinPolicy } : {},
11745
+ title: title ? await client.encryptCallTitle(title, fresh) : null,
11746
+ creator_sealed_key: await client.sealCallKey(fresh, client.bytesToBase64(me2.encryptionKeypair.publicKey)),
11747
+ invitees: Object.entries(sealed).map(([user_ext_id, sealed_key]) => ({
11748
+ user_ext_id,
11749
+ sealed_key,
11750
+ ...roles ? { role: roles[user_ext_id] ?? "attendee" } : {}
11751
+ }))
11752
+ });
11753
+ const reused = call.created === false;
11754
+ const key = reused ? await this.callKeyOf(call) : fresh;
11755
+ if (!key) throw new ArbiError("No key for the running call on this thread");
11756
+ const sealedKeys = reused ? await client.sealCallKeyForPeers(key, params.invitees, me2.userExtId) : sealed;
11757
+ return {
11758
+ call,
11759
+ key,
11760
+ title: await this.callTitleOf(call, key) ?? title ?? null,
11761
+ sealedKeys
11762
+ };
11763
+ },
11764
+ /**
11765
+ * Open a call by id (a link, the calendar, a notification): K from the link fragment when
11766
+ * given, else my sealed copy. Refuses a cancelled call and a call I hold no key for.
11767
+ */
11768
+ open: async (callExtId, linkKey) => {
11769
+ const call = await getCall(this.requireClient(), callExtId);
11770
+ if (call.cancelled)
11771
+ throw new CallApiError("This call was cancelled.", 410, "cancelled");
11772
+ const key = linkKey ?? await this.callKeyOf(call);
11773
+ if (!key) {
11774
+ throw new ArbiError("Open the full call link (it carries the key) to join this call.");
11775
+ }
11776
+ return { call, key, title: await this.callTitleOf(call, key) };
11777
+ },
11778
+ /** My copy of a call's K from its row, or null. */
11779
+ key: (call) => this.callKeyOf(call),
11780
+ /** A call's title in plaintext under K; null when it has none or it does not open. */
11781
+ title: (call, key) => this.callTitleOf(call, key),
11782
+ /** K sealed to each peer with a key (not to me): what `ring` and invitations take. */
11783
+ sealFor: async (key, peers) => client.sealCallKeyForPeers(key, peers, (await this.requireChatCrypto()).userExtId),
11784
+ /** Answer a ring: open K from its sealed blob and fetch a room token. */
11785
+ answer: async (ring) => {
11786
+ const me2 = await this.requireChatCrypto();
11787
+ const key = await client.openSealedCallKey(ring.sealed_key, me2.encryptionKeypair.secretKey);
11788
+ const token = await fetchCallToken(
11789
+ this.requireClient(),
11790
+ ring.call_ext_id,
11791
+ ring.link_version
11792
+ );
11793
+ return { key, token, title: ring.title ? await client.decryptCallTitle(ring.title, key) : null };
11794
+ },
11795
+ /**
11796
+ * A new link for a call I created: a fresh K re-sealed to me and every invitee with a key, the
11797
+ * title re-encrypted, and `link_version` bumped server-side so the old link stops working.
11798
+ */
11799
+ resetLink: async (call, title, invitees) => {
11800
+ const me2 = await this.requireChatCrypto();
11801
+ const key = await client.generateCallKey();
11802
+ const updated = await updateCall(this.requireClient(), call.external_id, {
11803
+ reset_link: true,
11804
+ creator_sealed_key: await client.sealCallKey(key, client.bytesToBase64(me2.encryptionKeypair.publicKey)),
11805
+ sealed_keys: await client.sealCallKeyForPeers(key, invitees, me2.userExtId),
11806
+ title: title ? await client.encryptCallTitle(title, key) : null
11807
+ });
11808
+ return { call: updated, key };
11809
+ },
11810
+ /**
11811
+ * Make a call's E2E meeting chat now: a fresh chat key sealed to me and to every member, and K
11812
+ * sealed to each member so they can always join. The existing chat when the call has one.
11813
+ */
11814
+ createChat: async (params) => {
11815
+ const me2 = await this.requireChatCrypto();
11816
+ const members = params.members.filter(
11817
+ (m2) => !!m2.encryption_public_key && m2.external_id !== me2.userExtId
11818
+ );
11819
+ const chatKey = await client.generateChatKey();
11820
+ try {
11821
+ const title = params.title?.trim();
11822
+ return await getOrCreateCallChat(this.requireClient(), params.callExtId, {
11823
+ title: title ? await client.encryptWithChatKey(title, chatKey) : null,
11824
+ creator_sealed_key: await client.sealChatKey(
11825
+ chatKey,
11826
+ client.bytesToBase64(me2.encryptionKeypair.publicKey)
11827
+ ),
11828
+ members: await Promise.all(
11829
+ members.map(async (m2) => ({
11830
+ user_ext_id: m2.external_id,
11831
+ sealed_key: await client.sealChatKey(chatKey, m2.encryption_public_key),
11832
+ call_sealed_key: await client.sealCallKey(params.callKey, m2.encryption_public_key)
11833
+ }))
11834
+ )
11835
+ });
11836
+ } finally {
11837
+ chatKey.fill(0);
11838
+ }
11839
+ },
11840
+ /** The call's meeting chat as is, made with `body` (an E2E chat) when it has none yet. */
11841
+ chat: (callExtId, body) => getOrCreateCallChat(this.requireClient(), callExtId, body),
11842
+ /** A room token; `inviteToken` (a personal invite link's `?i=`) admits with no lobby. */
11843
+ token: (callExtId, linkVersion, inviteToken) => fetchCallToken(this.requireClient(), callExtId, linkVersion, inviteToken),
11844
+ /** Ring users: `sealedKeys` maps each user ext id to K sealed to them (`sealFor`). */
11845
+ ring: (callExtId, sealedKeys, linkVersion) => ringCall(this.requireClient(), callExtId, sealedKeys, linkVersion),
11846
+ decline: (callExtId) => declineCall(this.requireClient(), callExtId),
11847
+ knock: (callExtId, linkVersion) => knockCall(this.requireClient(), callExtId, linkVersion),
11848
+ pollKnock: (callExtId, knockId) => pollKnock(this.requireClient(), callExtId, knockId),
11849
+ /** A host admits or turns away someone in the lobby. */
11850
+ decideKnock: (callExtId, knockId, admit) => decideKnock(this.requireClient(), callExtId, knockId, admit),
11851
+ removeParticipant: (callExtId, identity) => removeCallParticipant(this.requireClient(), callExtId, identity),
11852
+ muteParticipant: (callExtId, identity, track) => muteCallParticipant(this.requireClient(), callExtId, identity, track),
11853
+ /** Personal invite links for my unregistered contacts (register, then straight into the call). */
11854
+ inviteLinks: {
11855
+ create: (callExtId, body) => createCallInviteLink(this.requireClient(), callExtId, body),
11856
+ list: (callExtId) => listCallInviteLinks(this.requireClient(), callExtId),
11857
+ revoke: (callExtId, inviteLinkExtId) => revokeCallInviteLink(this.requireClient(), callExtId, inviteLinkExtId)
11858
+ },
11859
+ /** Live transcription: each client transcribes its own microphone; the host turns it on. */
11860
+ transcription: {
11861
+ set: (callExtId, on) => setCallTranscription(this.requireClient(), callExtId, on),
11862
+ transcribe: (callExtId, params) => transcribeCallSegment(this.requireClient(), callExtId, params),
11863
+ /** Store an (already encrypted) line in an E2E chat, idempotent per `dedupe_key`. */
11864
+ postChatLine: (chatExtId, body) => postChatTranscriptLine(this.requireClient(), chatExtId, body)
11865
+ },
11866
+ /** End-to-end encrypted recording: encrypted parts uploaded by each client, host-run. */
11867
+ recording: {
11868
+ quota: (callExtId) => getRecordingQuota(this.requireClient(), callExtId),
11869
+ start: (callExtId, mode) => startCallRecording(this.requireClient(), callExtId, mode),
11870
+ stop: (callExtId) => stopCallRecording(this.requireClient(), callExtId),
11871
+ createTrack: (callExtId, recordingExtId, body) => createRecordingTrack(this.requireClient(), callExtId, recordingExtId, body),
11872
+ presignPart: (callExtId, recordingExtId, trackExtId, body) => presignRecordingPart(
11873
+ this.requireClient(),
11874
+ callExtId,
11875
+ recordingExtId,
11876
+ trackExtId,
11877
+ body
11878
+ ),
11879
+ commitPart: (callExtId, recordingExtId, trackExtId, seq) => commitRecordingPart(
11880
+ this.requireClient(),
11881
+ callExtId,
11882
+ recordingExtId,
11883
+ trackExtId,
11884
+ seq
11885
+ ),
11886
+ list: (callExtId) => listCallRecordings(this.requireClient(), callExtId),
11887
+ get: (callExtId, recordingExtId) => getCallRecording(this.requireClient(), callExtId, recordingExtId),
11888
+ setExpiry: (callExtId, recordingExtId, expiresAt) => setRecordingExpiry(this.requireClient(), callExtId, recordingExtId, expiresAt),
11889
+ deleteMedia: (callExtId, recordingExtId) => deleteRecordingMedia(this.requireClient(), callExtId, recordingExtId),
11890
+ delete: (callExtId, recordingExtId) => deleteRecording(this.requireClient(), callExtId, recordingExtId),
11891
+ transcribe: (callExtId, recordingExtId, params) => transcribeRecordingPart(this.requireClient(), callExtId, recordingExtId, params),
11892
+ /** One part's ciphertext from its presigned GET. */
11893
+ downloadPart: (url) => downloadRecordingPart(url)
11894
+ },
11895
+ /** Webinars: a call with `mode = 'webinar'`. `linkVersion` for a link holder not yet admitted. */
11896
+ webinar: {
11897
+ get: (callExtId, linkVersion) => getWebinar(this.requireClient(), callExtId, linkVersion),
11898
+ update: (callExtId, body, linkVersion) => updateWebinar(this.requireClient(), callExtId, body, linkVersion),
11899
+ setHand: (callExtId, raised, linkVersion) => setWebinarHand(this.requireClient(), callExtId, raised, linkVersion),
11900
+ promote: (callExtId, identity, linkVersion) => promoteToStage(this.requireClient(), callExtId, identity, linkVersion),
11901
+ demote: (callExtId, identity, linkVersion) => demoteFromStage(this.requireClient(), callExtId, identity, linkVersion),
11902
+ questions: {
11903
+ list: (callExtId, linkVersion) => listQuestions(this.requireClient(), callExtId, linkVersion),
11904
+ ask: (callExtId, bodyCiphertext, linkVersion) => askQuestion(this.requireClient(), callExtId, bodyCiphertext, linkVersion),
11905
+ vote: (callExtId, questionExtId, up, linkVersion) => voteQuestion(this.requireClient(), callExtId, questionExtId, up, linkVersion),
11906
+ update: (callExtId, questionExtId, body, linkVersion) => updateQuestion(
11907
+ this.requireClient(),
11908
+ callExtId,
11909
+ questionExtId,
11910
+ body,
11911
+ linkVersion
11912
+ ),
11913
+ delete: (callExtId, questionExtId, linkVersion) => deleteQuestion(this.requireClient(), callExtId, questionExtId, linkVersion)
11914
+ }
11915
+ }
11916
+ };
10693
11917
  /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
10694
11918
  dm = {
10695
11919
  /**
@@ -10898,11 +12122,8 @@ var Arbi = class {
10898
12122
  currentId: () => client.readSessionClaims(this.client?.session.getState().accessToken)?.sessionId ?? null,
10899
12123
  /** End one of your own sessions now (not the one this device is on: that is `logout`). */
10900
12124
  terminate: (sessionId) => terminateSession(this.requireClient(), sessionId),
10901
- /** Sign out of every device on the server, then clear this instance. */
10902
- logoutAll: async () => {
10903
- await logoutAllSessions(this.requireClient());
10904
- await this.logout();
10905
- }
12125
+ /** Sign out of every device on the server, then clear this instance and this device. */
12126
+ logoutAll: () => this.logout({ everywhere: true })
10906
12127
  };
10907
12128
  // ── Internal guards ───────────────────────────────────────────────────
10908
12129
  requireClient() {
@@ -12108,11 +13329,577 @@ async function startDmListener(options) {
12108
13329
  };
12109
13330
  }
12110
13331
 
13332
+ // src/chat/output-item-reducer.ts
13333
+ function reasoningStep(arbi) {
13334
+ if (arbi?.step) return arbi.step;
13335
+ if (arbi?.model_recommendation) return "goal";
13336
+ if ((arbi?.label ?? "").startsWith("Goal check")) return "goal_progress";
13337
+ return "planning";
13338
+ }
13339
+ function isTraceItem(item) {
13340
+ if (item.type === "function_call" || item.type === "reasoning") return true;
13341
+ return item.type === "message" && (!!item.arbi?.step || !!item.arbi?.label);
13342
+ }
13343
+ function reduceOutputItem(steps, ev, assignIndex, resolveIndex) {
13344
+ const item = ev.item;
13345
+ if (!item || !isTraceItem(item)) return steps;
13346
+ if (!item.id) return steps;
13347
+ const arbi = item.arbi ?? {};
13348
+ const idx = steps.findIndex((s2) => s2._id === item.id);
13349
+ const index = assignIndex(item.id);
13350
+ const prev = idx !== -1 ? steps[idx] : void 0;
13351
+ const summaryText = item.type === "reasoning" && Array.isArray(item.summary) ? item.summary.map((c2) => c2.text).join("") : void 0;
13352
+ const isNarration = item.type === "message" && !arbi.step;
13353
+ const narrationText = isNarration && Array.isArray(item.content) ? item.content.map((c2) => c2.text).join("") : void 0;
13354
+ const next = {
13355
+ ...prev ?? {},
13356
+ type: "arbi.agent_step",
13357
+ _id: item.id,
13358
+ index,
13359
+ // First sighting wins: an item is re-emitted to attach its outcome once the
13360
+ // tool returns, and taking that later stamp would stretch the step to cover
13361
+ // its own execution and shrink the next one.
13362
+ t: prev?.t ?? ev.t ?? void 0,
13363
+ // A tool call has no lifecycle kind (it carries `detail`); everything else
13364
+ // that got this far is a declared or derived lifecycle step.
13365
+ step: item.type === "function_call" ? void 0 : reasoningStep(arbi),
13366
+ label: arbi.label ?? prev?.label,
13367
+ focus: focusUnlessRepeatsNarration(arbi.focus ?? prev?.focus, steps),
13368
+ // Reasoning items carry extended text as `summary` (a plan, a checklist);
13369
+ // function_call items (e.g. a sub-agent spawn marker) carry it as `arbi.content`
13370
+ // directly — a sub-agent's spawn task description, not a lifecycle summary.
13371
+ content: summaryText ?? narrationText ?? arbi.content ?? prev?.content,
13372
+ narration: isNarration || prev?.narration,
13373
+ reasoning: item.type === "reasoning" || prev?.reasoning,
13374
+ detail: arbi.detail ?? prev?.detail,
13375
+ outcome: arbi.outcome ?? prev?.outcome,
13376
+ guard_refused: guardRefused(arbi) || prev?.guard_refused || void 0,
13377
+ usage: arbi.usage ?? prev?.usage,
13378
+ step_tokens: arbi.step_tokens ?? prev?.step_tokens,
13379
+ step_gbp: arbi.step_gbp ?? prev?.step_gbp,
13380
+ total_tokens: arbi.total_tokens ?? prev?.total_tokens,
13381
+ context: arbi.context ?? prev?.context,
13382
+ parent_index: arbi.parent_id != null ? resolveIndex(arbi.parent_id) : prev?.parent_index,
13383
+ subagent: arbi.subagent ?? prev?.subagent,
13384
+ subagent_status: arbi.subagent_status ?? prev?.subagent_status,
13385
+ task_message_ext_id: arbi.task_message_ext_id ?? prev?.task_message_ext_id,
13386
+ model_recommendation: arbi.model_recommendation ?? prev?.model_recommendation,
13387
+ selected_model: arbi.selected_model ?? prev?.selected_model
13388
+ };
13389
+ if (idx !== -1) {
13390
+ const out = [...steps];
13391
+ out[idx] = next;
13392
+ return out;
13393
+ }
13394
+ return [...steps, next];
13395
+ }
13396
+ function guardRefused(arbi) {
13397
+ return arbi.guard_refused === true;
13398
+ }
13399
+ function focusUnlessRepeatsNarration(focus, steps) {
13400
+ const norm = (s2) => (s2 ?? "").replace(/\s+/g, " ").trim();
13401
+ const lastNarration = [...steps].reverse().find((s2) => s2.narration);
13402
+ if (!focus || !lastNarration || norm(focus) !== norm(lastNarration.content)) return focus;
13403
+ return void 0;
13404
+ }
13405
+ function createIndexAssigner(seed = []) {
13406
+ const byId3 = /* @__PURE__ */ new Map();
13407
+ let next = 0;
13408
+ for (const s2 of seed) {
13409
+ if (s2._id) {
13410
+ byId3.set(s2._id, s2.index);
13411
+ next = Math.max(next, s2.index);
13412
+ }
13413
+ }
13414
+ const assign = (id) => {
13415
+ const existing = byId3.get(id);
13416
+ if (existing != null) return existing;
13417
+ next += 1;
13418
+ byId3.set(id, next);
13419
+ return next;
13420
+ };
13421
+ const resolve2 = (id) => byId3.get(id);
13422
+ return { assign, resolve: resolve2 };
13423
+ }
13424
+
13425
+ // src/chat/agent-step-hydration.ts
13426
+ function hydrateV3(events) {
13427
+ let steps = [];
13428
+ for (const ev of events) {
13429
+ if (ev.type !== "response.output_item.done") continue;
13430
+ const { assign, resolve: resolve2 } = createIndexAssigner(steps);
13431
+ steps = reduceOutputItem(steps, ev, assign, resolve2);
13432
+ }
13433
+ return steps;
13434
+ }
13435
+ function hydrateV1(rawSteps) {
13436
+ const steps = [];
13437
+ for (const step of rawSteps) {
13438
+ if (step.step !== "tool_progress") {
13439
+ const progressIdx = steps.findIndex(
13440
+ (s2) => s2.index === step.index && s2.step === "tool_progress"
13441
+ );
13442
+ if (progressIdx !== -1) {
13443
+ steps[progressIdx] = { ...step };
13444
+ continue;
13445
+ }
13446
+ }
13447
+ const isFollowUp = step.step == null;
13448
+ if (isFollowUp) {
13449
+ const existing = steps.find((s2) => s2.index === step.index);
13450
+ if (existing) {
13451
+ for (const [key, value] of Object.entries(step)) {
13452
+ if (value != null && key !== "type" && key !== "t") {
13453
+ existing[key] = value;
13454
+ }
13455
+ }
13456
+ continue;
13457
+ }
13458
+ }
13459
+ steps.push({ ...step });
13460
+ }
13461
+ return steps;
13462
+ }
13463
+ function hydrateAgentSteps(message) {
13464
+ const tools = message.tools || message.meta?.tools;
13465
+ if (!tools) return void 0;
13466
+ const streamEvents = tools["stream_events"];
13467
+ if (!streamEvents || !("events" in streamEvents)) return void 0;
13468
+ const events = streamEvents.events;
13469
+ if (!Array.isArray(events) || events.length === 0) return void 0;
13470
+ const hasV3 = events.some(
13471
+ (e) => typeof e === "object" && e !== null && e.type === "response.output_item.done"
13472
+ );
13473
+ let steps;
13474
+ if (hasV3) {
13475
+ steps = hydrateV3(events);
13476
+ } else {
13477
+ const rawSteps = events.filter(
13478
+ (e) => typeof e === "object" && e !== null && e.type === "arbi.agent_step"
13479
+ );
13480
+ if (rawSteps.length === 0) return void 0;
13481
+ steps = hydrateV1(rawSteps);
13482
+ }
13483
+ if (steps.length === 0) return void 0;
13484
+ const completedEvent = events.find(
13485
+ (e) => typeof e === "object" && e !== null && e.type === "response.completed"
13486
+ );
13487
+ const totalElapsed = completedEvent?.t ?? null;
13488
+ const finalContext = completedEvent?.context ?? null;
13489
+ return { steps, totalElapsed, finalContext };
13490
+ }
13491
+
13492
+ // src/chat/agent-steps.ts
13493
+ function humanizeStep2(identifier) {
13494
+ const spaced = identifier.replace(/[_-]+/g, " ").trim();
13495
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
13496
+ }
13497
+ function getStepTool(step) {
13498
+ return step.detail?.[0]?.tool ?? void 0;
13499
+ }
13500
+ function resolveSummary(summary, docInfo) {
13501
+ return summary.replace(
13502
+ /\{(doc-[A-Za-z0-9]+)\}|(doc-[A-Za-z0-9]+)/g,
13503
+ (full, braced, bare) => {
13504
+ const docId = braced ?? bare ?? "";
13505
+ return docInfo[docId]?.name || (braced ? docId : full);
13506
+ }
13507
+ ).replace(/\(full\)/g, (match) => {
13508
+ const docIdMatch = summary.match(/\{(doc-[^}]+)\}/);
13509
+ if (docIdMatch) {
13510
+ const info = docInfo[docIdMatch[1]];
13511
+ if (info?.pages) return `(full \u2013 ${info.pages} pages)`;
13512
+ }
13513
+ return match;
13514
+ });
13515
+ }
13516
+ var DUPLICATE_OUTCOME = "duplicate";
13517
+ function isGuardRefused(step) {
13518
+ if (step.guard_refused === true) return true;
13519
+ return step.outcome === DUPLICATE_OUTCOME && !step.subagent;
13520
+ }
13521
+ function mergeAgentSteps(steps) {
13522
+ const byIndex = /* @__PURE__ */ new Map();
13523
+ for (const step of steps) {
13524
+ if (step.step === "tool_progress" && step.detail && step.detail.length === 1 && step.detail[0].message === "working" && !step.detail[0].label) {
13525
+ continue;
13526
+ }
13527
+ const existing = byIndex.get(step.index);
13528
+ if (!existing) {
13529
+ byIndex.set(step.index, step);
13530
+ continue;
13531
+ }
13532
+ byIndex.set(step.index, {
13533
+ ...existing,
13534
+ outcome: step.outcome ?? existing.outcome,
13535
+ guard_refused: step.guard_refused || existing.guard_refused || void 0,
13536
+ usage: step.usage ?? existing.usage,
13537
+ total_tokens: step.total_tokens ?? existing.total_tokens,
13538
+ step_tokens: step.step_tokens ?? existing.step_tokens,
13539
+ step_gbp: step.step_gbp ?? existing.step_gbp,
13540
+ context: step.context ?? existing.context,
13541
+ detail: existing.detail ?? step.detail
13542
+ });
13543
+ }
13544
+ return Array.from(byIndex.values()).filter((step) => !isGuardRefused(step)).sort((a2, b2) => a2.index - b2.index);
13545
+ }
13546
+ function topLevelAgentSteps(steps) {
13547
+ const merged = mergeAgentSteps(steps);
13548
+ const known = new Set(merged.map((s2) => s2.index));
13549
+ return merged.filter(
13550
+ (s2) => s2.parent_index == null || s2.parent_index === s2.index || !known.has(s2.parent_index)
13551
+ );
13552
+ }
13553
+ function formatTokens(n2) {
13554
+ if (n2 < 1e3) return `${n2}`;
13555
+ if (n2 < 1e4) return `${(n2 / 1e3).toFixed(1)}k`;
13556
+ return `${Math.round(n2 / 1e3)}k`;
13557
+ }
13558
+ function computeRunStats(steps) {
13559
+ const merged = mergeAgentSteps(steps);
13560
+ let toolCalls = 0;
13561
+ const running = /* @__PURE__ */ new Set();
13562
+ const terminated = /* @__PURE__ */ new Set();
13563
+ for (const s2 of merged) {
13564
+ if (s2.subagent_status === "running") running.add(s2.subagent ?? "");
13565
+ else if (s2.subagent_status === "done" || s2.subagent_status === "failed")
13566
+ terminated.add(s2.subagent ?? "");
13567
+ else if (s2.step == null && !s2.subagent_status) toolCalls += 1;
13568
+ }
13569
+ const handles = /* @__PURE__ */ new Set([...running, ...terminated]);
13570
+ return {
13571
+ toolCalls,
13572
+ subagents: handles.size,
13573
+ subagentsRunning: [...running].filter((h2) => !terminated.has(h2)).length
13574
+ };
13575
+ }
13576
+ function subagentJobLabel(task, maxLen = 42) {
13577
+ let t2 = (task || "").trim();
13578
+ if (!t2) return "Sub-agent";
13579
+ for (const stop of ["(", "\n", ". ", ": ", " \u2014 ", " - "]) {
13580
+ const i2 = t2.indexOf(stop);
13581
+ if (i2 > 8) t2 = t2.slice(0, i2).trim();
13582
+ }
13583
+ if (t2.length > maxLen) t2 = `${t2.slice(0, maxLen - 1).trimEnd()}\u2026`;
13584
+ return t2;
13585
+ }
13586
+ function extractSubagentLanes(steps) {
13587
+ const merged = mergeAgentSteps(steps);
13588
+ const order = [];
13589
+ const byHandle = /* @__PURE__ */ new Map();
13590
+ for (const s2 of merged) {
13591
+ const h2 = s2.subagent;
13592
+ if (!h2) continue;
13593
+ let e = byHandle.get(h2);
13594
+ if (!e) {
13595
+ e = { task: "", focus: "", status: "running", steps: 0 };
13596
+ byHandle.set(h2, e);
13597
+ order.push(h2);
13598
+ }
13599
+ if (s2.task_message_ext_id) e.taskMessageExtId = s2.task_message_ext_id;
13600
+ if (s2.subagent_status === "running") e.task = (s2.content || s2.focus || "").trim();
13601
+ else if (s2.subagent_status === "done") e.status = "done";
13602
+ else if (s2.subagent_status === "failed") e.status = "failed";
13603
+ else {
13604
+ e.steps += 1;
13605
+ if (s2.focus) e.focus = s2.focus.trim();
13606
+ }
13607
+ }
13608
+ return order.map((h2) => {
13609
+ const e = byHandle.get(h2);
13610
+ return {
13611
+ handle: h2,
13612
+ task: e.task,
13613
+ job: subagentJobLabel(e.task),
13614
+ focus: e.focus,
13615
+ status: e.status,
13616
+ steps: e.steps,
13617
+ taskMessageExtId: e.taskMessageExtId
13618
+ };
13619
+ });
13620
+ }
13621
+ function showFullForLabel(label) {
13622
+ const l2 = (label ?? "").trim();
13623
+ return l2.startsWith("Budget reached") || l2.startsWith("Goal") || l2.startsWith("Deep research");
13624
+ }
13625
+ function getStepDisplay(step, docInfo = {}) {
13626
+ const tool = getStepTool(step);
13627
+ if (step.narration) {
13628
+ const prose = step.content?.trim() || null;
13629
+ return {
13630
+ label: step.label || "Narration",
13631
+ summary: prose ? resolveSummary(prose, docInfo) : null,
13632
+ isMultiLine: true,
13633
+ details: []
13634
+ };
13635
+ }
13636
+ const firstDetail = step.detail?.[0];
13637
+ if (step.step) {
13638
+ if (step.step === "tool_progress") {
13639
+ const label3 = firstDetail?.label || step.label || tool && humanizeStep2(tool) || humanizeStep2(step.step);
13640
+ const message = firstDetail?.message || step.content || null;
13641
+ return {
13642
+ label: label3,
13643
+ summary: message ? resolveSummary(message, docInfo) : null,
13644
+ isMultiLine: !!message?.includes("\n"),
13645
+ details: []
13646
+ };
13647
+ }
13648
+ const label2 = step.label || humanizeStep2(step.step);
13649
+ const content2 = step.content?.trim() || null;
13650
+ const showFull = !!content2?.includes("\n") || showFullForLabel(step.label);
13651
+ return {
13652
+ label: label2,
13653
+ summary: content2 ? resolveSummary(content2, docInfo) : null,
13654
+ isMultiLine: showFull,
13655
+ details: []
13656
+ };
13657
+ }
13658
+ const label = step.label || firstDetail?.label || tool && humanizeStep2(tool) || `Step ${step.index}`;
13659
+ const summaries = (step.detail || []).map((d2) => d2.summary).filter(Boolean).map((s2) => resolveSummary(s2, docInfo));
13660
+ const focus = step.focus?.trim();
13661
+ const content = step.content?.trim() || null;
13662
+ const rest = [...summaries, ...content ? [resolveSummary(content, docInfo)] : []];
13663
+ const narrative = focus || rest.shift() || null;
13664
+ return {
13665
+ label,
13666
+ summary: narrative ? resolveSummary(narrative, docInfo) : null,
13667
+ isMultiLine: !!narrative?.includes("\n") || showFullForLabel(label),
13668
+ details: rest
13669
+ };
13670
+ }
13671
+ function getAgentStepLabel(step, docInfo = {}) {
13672
+ const { label, summary, isMultiLine } = getStepDisplay(step, docInfo);
13673
+ const narrative = summary && !isMultiLine && !step.reasoning ? summary : null;
13674
+ const text = narrative ? `${label} \u2014 ${narrative}` : label;
13675
+ return text.length > 120 ? `${text.slice(0, 119)}\u2026` : text;
13676
+ }
13677
+ function getCurrentStep(steps) {
13678
+ const merged = mergeAgentSteps(steps);
13679
+ const candidates = merged.length > 0 ? merged : steps;
13680
+ const isOwnSubstantiveStep = (s2) => {
13681
+ if (s2.subagent) return false;
13682
+ if (s2.narration) return false;
13683
+ const d2 = s2.detail?.[0];
13684
+ const isHeartbeat = s2.step === "tool_progress" && d2?.message === "working" && !d2?.label;
13685
+ return !isHeartbeat;
13686
+ };
13687
+ for (let i2 = candidates.length - 1; i2 >= 0; i2--) {
13688
+ if (isOwnSubstantiveStep(candidates[i2])) return candidates[i2];
13689
+ }
13690
+ for (let i2 = candidates.length - 1; i2 >= 0; i2--) {
13691
+ if (!candidates[i2].subagent) return candidates[i2];
13692
+ }
13693
+ return candidates[candidates.length - 1];
13694
+ }
13695
+
13696
+ // src/chat/subagent-branch.ts
13697
+ function getSubagentBranchRecord(message) {
13698
+ const entry = message.tools?.subagent;
13699
+ return entry?.record ?? null;
13700
+ }
13701
+ function findLeafForTaskMessage(threads, taskMessageExtId) {
13702
+ const thread = threads.find((t2) => t2.history.some((m2) => m2.external_id === taskMessageExtId));
13703
+ return thread?.leaf_message_ext_id ?? null;
13704
+ }
13705
+ function tailTaskMessageIndex(history) {
13706
+ const lastIndex = history.length - 1;
13707
+ if (lastIndex < 0) return -1;
13708
+ if (getSubagentBranchRecord(history[lastIndex])) return lastIndex;
13709
+ const secondLastIndex = lastIndex - 1;
13710
+ if (secondLastIndex >= 0 && getSubagentBranchRecord(history[secondLastIndex])) {
13711
+ return secondLastIndex;
13712
+ }
13713
+ return -1;
13714
+ }
13715
+ function findMainSiblingLeaf(threads, currentHistory) {
13716
+ const taskIndex = tailTaskMessageIndex(currentHistory);
13717
+ if (taskIndex <= 0) return null;
13718
+ const ancestorId = currentHistory[taskIndex - 1].external_id;
13719
+ if (!ancestorId) return null;
13720
+ const sibling = threads.find(
13721
+ (t2) => t2.history.some((m2) => m2.external_id === ancestorId) && tailTaskMessageIndex(t2.history) < 0
13722
+ );
13723
+ return sibling?.leaf_message_ext_id ?? null;
13724
+ }
13725
+ function sliceToSubagentThread(history) {
13726
+ const taskIndex = tailTaskMessageIndex(history);
13727
+ return taskIndex >= 0 ? history.slice(taskIndex) : history;
13728
+ }
13729
+ function newestThread(threads) {
13730
+ const lastAt = (t2) => Date.parse(t2.history.at(-1)?.created_at ?? "") || 0;
13731
+ return threads.reduce(
13732
+ (best, t2) => !best || lastAt(t2) > lastAt(best) ? t2 : best,
13733
+ void 0
13734
+ );
13735
+ }
13736
+ function pickMainThread(threads) {
13737
+ return newestThread(threads.filter((t2) => !t2.history.some((m2) => getSubagentBranchRecord(m2)))) ?? threads.find((t2) => tailTaskMessageIndex(t2.history) < 0) ?? threads[0];
13738
+ }
13739
+ function findSubagentRunId(threads, messageId) {
13740
+ for (const thread of threads) {
13741
+ const index = thread.history.findIndex((m2) => m2.external_id === messageId);
13742
+ if (index < 0) continue;
13743
+ const taskIndex = tailTaskMessageIndex(thread.history);
13744
+ if (taskIndex >= 0 && taskIndex <= index) {
13745
+ return getSubagentBranchRecord(thread.history[taskIndex])?.run_id ?? null;
13746
+ }
13747
+ }
13748
+ return null;
13749
+ }
13750
+
13751
+ // src/chat/reply-target.ts
13752
+ function findReplyTarget(threads, parentId) {
13753
+ if (!parentId) return null;
13754
+ const byId3 = /* @__PURE__ */ new Map();
13755
+ for (const thread of threads) {
13756
+ for (const message of thread.history) byId3.set(message.external_id, message);
13757
+ }
13758
+ let current = byId3.has(parentId) ? parentId : pickMainThread(threads)?.leaf_message_ext_id ?? null;
13759
+ while (current) {
13760
+ const message = byId3.get(current);
13761
+ if (!message) return null;
13762
+ if (message.status !== "failed") return current;
13763
+ current = message.parent_message_ext_id ?? null;
13764
+ }
13765
+ return null;
13766
+ }
13767
+
13768
+ // src/chat/stop-run.ts
13769
+ var STOP_ID_WAIT_MS = 5e3;
13770
+ var STOP_REPEAT_WINDOW_MS = 1e3;
13771
+ var RUN_ID = /^msg-[a-zA-Z0-9]{8}$/;
13772
+ function topLevelRunId(runId) {
13773
+ const root = runId.split(":")[0];
13774
+ return RUN_ID.test(root) ? root : null;
13775
+ }
13776
+ function getRunToCancel(threads, responseId) {
13777
+ const subagentRunId = findSubagentRunId(threads, responseId);
13778
+ return (subagentRunId && topLevelRunId(subagentRunId)) ?? topLevelRunId(responseId) ?? responseId;
13779
+ }
13780
+
13781
+ // src/chat/context-usage.ts
13782
+ function isNearAiUsageBudget(usage) {
13783
+ if (usage.budget_gbp == null || usage.spent_gbp == null || usage.budget_gbp <= 0) {
13784
+ return false;
13785
+ }
13786
+ return usage.spent_gbp / usage.budget_gbp >= 0.9;
13787
+ }
13788
+ function getContextUsedTokens(usage) {
13789
+ return usage.all_llm_calls?.last_input_tokens ?? usage.total_input;
13790
+ }
13791
+ function estimateDraftTokens(draftLength) {
13792
+ return Math.ceil(draftLength / 4);
13793
+ }
13794
+ function getContextUsedPercent(usage, draftLength = 0) {
13795
+ const usedTokens = getContextUsedTokens(usage) + estimateDraftTokens(draftLength);
13796
+ const usedPercent = usedTokens / usage.context_window * 100;
13797
+ return Math.min(100, Math.max(0, usedPercent));
13798
+ }
13799
+ function getContextRemainingPercent(usage, draftLength = 0) {
13800
+ return 100 - getContextUsedPercent(usage, draftLength);
13801
+ }
13802
+
13803
+ // src/chat/conversation-context.ts
13804
+ function extractDocumentIdsFromMessages(messageHistory) {
13805
+ if (!messageHistory || messageHistory.length === 0) return [];
13806
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
13807
+ const msg = messageHistory[i2];
13808
+ if (msg.role === "user" && msg.tools) {
13809
+ const documents = extractDocIdsFromTools(msg.tools);
13810
+ if (documents.length > 0) {
13811
+ return documents;
13812
+ }
13813
+ }
13814
+ }
13815
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
13816
+ const msg = messageHistory[i2];
13817
+ if (msg.role === "assistant" && msg.tools) {
13818
+ const documents = extractDocIdsFromTools(msg.tools);
13819
+ if (documents.length > 0) {
13820
+ return documents;
13821
+ }
13822
+ }
13823
+ }
13824
+ return [];
13825
+ }
13826
+ function extractFactIdsFromMessages(messageHistory) {
13827
+ if (!messageHistory || messageHistory.length === 0) return null;
13828
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
13829
+ const msg = messageHistory[i2];
13830
+ if (msg.role !== "user" || !msg.tools) continue;
13831
+ const tool = msg.tools.facts_context;
13832
+ if (tool?.name === "facts_context" && Array.isArray(tool.tool_args?.fact_ext_ids)) {
13833
+ return Array.from(new Set(tool.tool_args.fact_ext_ids));
13834
+ }
13835
+ }
13836
+ return null;
13837
+ }
13838
+ function extractDocIdsFromTools(tools) {
13839
+ const documents = [];
13840
+ try {
13841
+ const retrievalChunk = tools.retrieval_chunk;
13842
+ if (retrievalChunk && "tool_args" in retrievalChunk && "doc_ext_ids" in retrievalChunk.tool_args && retrievalChunk.tool_args.doc_ext_ids) {
13843
+ const docIds = retrievalChunk.tool_args.doc_ext_ids;
13844
+ if (Array.isArray(docIds)) {
13845
+ for (const docId of docIds) {
13846
+ documents.push({ docId, isPinned: false });
13847
+ }
13848
+ }
13849
+ }
13850
+ const retrievalFullContext = tools.retrieval_full_context;
13851
+ if (retrievalFullContext && "tool_args" in retrievalFullContext && "doc_ext_ids" in retrievalFullContext.tool_args && retrievalFullContext.tool_args.doc_ext_ids) {
13852
+ const docIds = retrievalFullContext.tool_args.doc_ext_ids;
13853
+ if (Array.isArray(docIds)) {
13854
+ for (const docId of docIds) {
13855
+ documents.push({ docId, isPinned: true });
13856
+ }
13857
+ }
13858
+ }
13859
+ if (documents.length > 0) {
13860
+ const uniqueDocuments = documents.reduce(
13861
+ (acc, doc) => {
13862
+ const existing = acc.find((d2) => d2.docId === doc.docId);
13863
+ if (existing) {
13864
+ existing.isPinned = existing.isPinned || doc.isPinned;
13865
+ } else {
13866
+ acc.push(doc);
13867
+ }
13868
+ return acc;
13869
+ },
13870
+ []
13871
+ );
13872
+ return uniqueDocuments;
13873
+ }
13874
+ } catch (error) {
13875
+ console.warn("Failed to extract document IDs from message tools:", error);
13876
+ }
13877
+ return [];
13878
+ }
13879
+
13880
+ // src/chat/run-attach.ts
13881
+ function getAttachableRunId(messages) {
13882
+ let nextQueued = null;
13883
+ for (let i2 = messages.length - 1; i2 >= 0; i2--) {
13884
+ const m2 = messages[i2];
13885
+ if (m2.role !== "assistant") continue;
13886
+ if (m2.status === "in_progress") return m2.external_id;
13887
+ if (m2.status !== "queued") break;
13888
+ nextQueued = m2.external_id;
13889
+ }
13890
+ return nextQueued;
13891
+ }
13892
+ function getRunToAttach(localGeneration, messages) {
13893
+ if (localGeneration?.isGenerating && localGeneration.abortController) return null;
13894
+ return getAttachableRunId(messages);
13895
+ }
13896
+
12111
13897
  exports.ACCOUNT_VENDOR = ACCOUNT_VENDOR;
12112
13898
  exports.Arbi = Arbi;
12113
13899
  exports.ArbiApiError = ArbiApiError;
12114
13900
  exports.ArbiError = ArbiError;
12115
13901
  exports.ArbiSessionExpiredError = ArbiSessionExpiredError;
13902
+ exports.CallApiError = CallApiError;
12116
13903
  exports.ClaudeOrchestrator = ClaudeOrchestrator;
12117
13904
  exports.DEFAULT_AI_USD_PER_GBP = DEFAULT_AI_USD_PER_GBP;
12118
13905
  exports.DOC_TERMINAL_STATUSES = DOC_TERMINAL_STATUSES;
@@ -12128,48 +13915,66 @@ exports.MAX_RETRIEVE_DOC_IDS = MAX_RETRIEVE_DOC_IDS;
12128
13915
  exports.MICROSOFT_VENDORS = MICROSOFT_VENDORS;
12129
13916
  exports.OpenClawOrchestrator = OpenClawOrchestrator;
12130
13917
  exports.PRESENCE_KINDS = PRESENCE_KINDS;
13918
+ exports.PROMPT_CONTEXT_CHARS = PROMPT_CONTEXT_CHARS;
12131
13919
  exports.PlanStepsError = PlanStepsError;
12132
13920
  exports.PublicBookingError = PublicBookingError;
12133
13921
  exports.SHAREPOINT_VENDORS = SHAREPOINT_VENDORS;
12134
13922
  exports.STEP_FIELD_OPTION_TONES = STEP_FIELD_OPTION_TONES;
13923
+ exports.STOP_ID_WAIT_MS = STOP_ID_WAIT_MS;
13924
+ exports.STOP_REPEAT_WINDOW_MS = STOP_REPEAT_WINDOW_MS;
12135
13925
  exports.TAG_KINDS = TAG_KINDS;
12136
13926
  exports.TAG_NESTING_MAX_DEPTH = TAG_NESTING_MAX_DEPTH;
12137
13927
  exports.WebSocketAuthError = WebSocketAuthError;
12138
13928
  exports.account = account_exports;
12139
13929
  exports.agentconfig = agentconfig_exports;
12140
13930
  exports.agents = agents_exports;
13931
+ exports.appendTranscriptionHints = appendTranscriptionHints;
12141
13932
  exports.assistant = assistant_exports;
12142
13933
  exports.authenticatedFetch = authenticatedFetch;
12143
13934
  exports.bookPublicSlot = bookPublicSlot;
12144
13935
  exports.buildCitationChunkData = buildCitationChunkData;
12145
13936
  exports.buildDocNameMap = buildDocNameMap;
13937
+ exports.buildDocumentTools = buildDocumentTools;
12146
13938
  exports.buildFactsContextTool = buildFactsContextTool;
12147
13939
  exports.buildRetrievalChunkTool = buildRetrievalChunkTool;
12148
13940
  exports.buildRetrievalFullContextTool = buildRetrievalFullContextTool;
12149
13941
  exports.buildRetrievalTocTool = buildRetrievalTocTool;
13942
+ exports.buildTurnRequest = buildTurnRequest;
12150
13943
  exports.calendar = calendar_exports;
13944
+ exports.calls = calls_exports;
12151
13945
  exports.canTagHaveParent = canTagHaveParent;
12152
13946
  exports.cancelPublicBooking = cancelPublicBooking;
12153
13947
  exports.chats = chats_exports;
13948
+ exports.computeRunStats = computeRunStats;
12154
13949
  exports.connectErrorMessage = connectErrorMessage;
12155
13950
  exports.connectWebSocket = connectWebSocket;
12156
13951
  exports.connectWithReconnect = connectWithReconnect;
12157
13952
  exports.connectors = connectors_exports;
12158
13953
  exports.consumeSSEStream = consumeSSEStream;
12159
13954
  exports.contacts = contacts_exports;
13955
+ exports.continuityPrompt = continuityPrompt;
12160
13956
  exports.conversations = conversations_exports;
12161
13957
  exports.countCitations = countCitations;
12162
13958
  exports.createAuthenticatedClient = createAuthenticatedClient;
12163
13959
  exports.createDocumentWaiter = createDocumentWaiter;
13960
+ exports.createIndexAssigner = createIndexAssigner;
12164
13961
  exports.defaultKindForFormat = defaultKindForFormat;
12165
13962
  exports.deviceFlow = device_flow_exports;
12166
13963
  exports.doctags = doctags_exports;
12167
13964
  exports.documents = documents_exports;
12168
13965
  exports.documentsNode = documents_node_exports;
13966
+ exports.estimateDraftTokens = estimateDraftTokens;
13967
+ exports.extractDocumentIdsFromMessages = extractDocumentIdsFromMessages;
13968
+ exports.extractFactIdsFromMessages = extractFactIdsFromMessages;
13969
+ exports.extractSubagentLanes = extractSubagentLanes;
12169
13970
  exports.facts = facts_exports;
12170
13971
  exports.files = files_exports;
12171
13972
  exports.filterDocumentTags = filterDocumentTags;
12172
13973
  exports.filterSkills = filterSkills;
13974
+ exports.findLeafForTaskMessage = findLeafForTaskMessage;
13975
+ exports.findMainSiblingLeaf = findMainSiblingLeaf;
13976
+ exports.findReplyTarget = findReplyTarget;
13977
+ exports.findSubagentRunId = findSubagentRunId;
12173
13978
  exports.firm = firm_exports;
12174
13979
  exports.flattenTagTree = flattenTagTree;
12175
13980
  exports.formatAgentStepLabel = formatAgentStepLabel;
@@ -12178,20 +13983,33 @@ exports.formatGbp = formatGbp;
12178
13983
  exports.formatGbpPerMillionTokens = formatGbpPerMillionTokens;
12179
13984
  exports.formatItemLabel = formatItemLabel;
12180
13985
  exports.formatStreamSummary = formatStreamSummary;
13986
+ exports.formatTokens = formatTokens;
12181
13987
  exports.formatUserName = formatUserName;
12182
13988
  exports.formatWorkspaceChoices = formatWorkspaceChoices;
12183
13989
  exports.formatWsMessage = formatWsMessage;
12184
13990
  exports.generateEncryptedWorkspaceKey = generateEncryptedWorkspaceKey;
12185
13991
  exports.generateNewWorkspaceKey = generateNewWorkspaceKey;
13992
+ exports.getAgentStepLabel = getAgentStepLabel;
13993
+ exports.getAttachableRunId = getAttachableRunId;
12186
13994
  exports.getChildTags = getChildTags;
13995
+ exports.getContextRemainingPercent = getContextRemainingPercent;
13996
+ exports.getContextUsedPercent = getContextUsedPercent;
13997
+ exports.getContextUsedTokens = getContextUsedTokens;
13998
+ exports.getCurrentStep = getCurrentStep;
12187
13999
  exports.getEligibleParentTags = getEligibleParentTags;
12188
14000
  exports.getErrorCode = getErrorCode;
12189
14001
  exports.getErrorMessage = getErrorMessage;
12190
14002
  exports.getPublicBookingPage = getPublicBookingPage;
12191
14003
  exports.getRawWorkspaceKey = getRawWorkspaceKey;
14004
+ exports.getRunToAttach = getRunToAttach;
14005
+ exports.getRunToCancel = getRunToCancel;
14006
+ exports.getStepDisplay = getStepDisplay;
14007
+ exports.getStepTool = getStepTool;
14008
+ exports.getSubagentBranchRecord = getSubagentBranchRecord;
12192
14009
  exports.getTagDescendantIds = getTagDescendantIds;
12193
14010
  exports.health = health_exports;
12194
14011
  exports.houseTemplates = house_template_exports;
14012
+ exports.hydrateAgentSteps = hydrateAgentSteps;
12195
14013
  exports.identityErrorCode = identityErrorCode;
12196
14014
  exports.identityVerification = identity_exports;
12197
14015
  exports.isAnnotationTag = isAnnotationTag;
@@ -12201,12 +14019,15 @@ exports.isEntityTag = isEntityTag;
12201
14019
  exports.isFlatKind = isFlatKind;
12202
14020
  exports.isLabelTag = isLabelTag;
12203
14021
  exports.isMailboxSyncVendor = isMailboxSyncVendor;
14022
+ exports.isNearAiUsageBudget = isNearAiUsageBudget;
12204
14023
  exports.isPresenceTag = isPresenceTag;
12205
14024
  exports.isSharePointVendor = isSharePointVendor;
12206
14025
  exports.isSharedSkill = isSharedSkill;
14026
+ exports.isTraceItem = isTraceItem;
12207
14027
  exports.listen = listen_exports;
12208
14028
  exports.mail = mail_exports;
12209
14029
  exports.mailNode = mail_node_exports;
14030
+ exports.mergeAgentSteps = mergeAgentSteps;
12210
14031
  exports.notifications = notifications_exports;
12211
14032
  exports.parseSSEEvents = parseSSEEvents;
12212
14033
  exports.parseSlashCommand = parseSlashCommand;
@@ -12214,30 +14035,39 @@ exports.parseSlashTokenInProgress = parseSlashTokenInProgress;
12214
14035
  exports.performPasswordLogin = performPasswordLogin;
12215
14036
  exports.performSigningKeyLogin = performSigningKeyLogin;
12216
14037
  exports.performSsoDeviceFlowLogin = performSsoDeviceFlowLogin;
14038
+ exports.pickMainThread = pickMainThread;
12217
14039
  exports.profile = profile_exports;
12218
14040
  exports.progressFetch = progressFetch;
12219
14041
  exports.projects = projects_exports;
14042
+ exports.quotaExceededFrom = quotaExceededFrom;
14043
+ exports.quotaFromStreamError = quotaFromStreamError;
14044
+ exports.reduceOutputItem = reduceOutputItem;
12220
14045
  exports.refusalReason = refusalReason;
12221
14046
  exports.requireData = requireData;
12222
14047
  exports.requireOk = requireOk;
12223
14048
  exports.resolveAuth = resolveAuth;
12224
14049
  exports.resolveCitations = resolveCitations;
14050
+ exports.resolveSummary = resolveSummary;
12225
14051
  exports.resolveWorkspace = resolveWorkspace;
12226
14052
  exports.responses = responses_exports;
12227
14053
  exports.searchChunks = searchChunks;
14054
+ exports.selectFullContextDocument = selectFullContextDocument;
12228
14055
  exports.selectWorkspace = selectWorkspace;
12229
14056
  exports.selectWorkspaceById = selectWorkspaceById;
12230
14057
  exports.sessions = sessions_exports;
12231
14058
  exports.settings = settings_exports;
12232
14059
  exports.signatureRequests = signature_requests_exports;
14060
+ exports.sliceToSubagentThread = sliceToSubagentThread;
12233
14061
  exports.startDmListener = startDmListener;
12234
14062
  exports.streamSSE = streamSSE;
12235
14063
  exports.stripCitationMarkdown = stripCitationMarkdown;
14064
+ exports.subagentJobLabel = subagentJobLabel;
12236
14065
  exports.summarizeCitations = summarizeCitations;
12237
14066
  exports.tagUseCount = tagUseCount;
12238
14067
  exports.tags = tags_exports;
12239
14068
  exports.tagsForScope = tagsForScope;
12240
14069
  exports.tagsOfGroup = tagsOfGroup;
14070
+ exports.topLevelAgentSteps = topLevelAgentSteps;
12241
14071
  exports.uploadSkill = uploadSkill;
12242
14072
  exports.usdToGbp = usdToGbp;
12243
14073
  exports.work = work_exports;