@arbidocs/sdk 0.4.167 → 0.4.169

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/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, encryptionKeypairFromSigningKey, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, sealedBoxDecrypt, decodeSecureMailKey, openSecureMail, secureMailClaim, changePassword, readSessionClaims } from '@arbidocs/client';
1
+ import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, encryptionKeypairFromSigningKey, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, sealedBoxDecrypt, decodeSecureMailKey, openSecureMail, secureMailClaim, createSessionManager, authRequestError, changePassword, openCallKeyOf, decryptCallTitle, generateCallKey, encryptCallTitle, sealCallKeyForPeers, openSealedCallKey, readSessionClaims } from '@arbidocs/client';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -3667,7 +3667,7 @@ function buildClientOptions(config, store, email) {
3667
3667
  baseUrl: config.baseUrl,
3668
3668
  deploymentDomain: config.deploymentDomain,
3669
3669
  credentials: "omit",
3670
- sessionStorage: store?.getSessionStorageProvider?.(),
3670
+ persistence: store?.getSessionPersistence?.(),
3671
3671
  userEmail: email
3672
3672
  };
3673
3673
  }
@@ -4503,14 +4503,14 @@ async function* listPaginated(arbi, options = {}) {
4503
4503
  lookahead = 1
4504
4504
  } = options;
4505
4505
  const fetchPage = async (pageOffset, limit) => {
4506
- const query = {
4506
+ const query2 = {
4507
4507
  limit,
4508
4508
  offset: pageOffset,
4509
4509
  order
4510
4510
  };
4511
- if (fields) query.fields = fields;
4511
+ if (fields) query2.fields = fields;
4512
4512
  const { data, error } = await arbi.fetch.GET("/v1/document/list", {
4513
- params: { query },
4513
+ params: { query: query2 },
4514
4514
  signal
4515
4515
  });
4516
4516
  if (error) {
@@ -4616,20 +4616,20 @@ async function uploadUrl(arbi, urls, shared = false, configExtId) {
4616
4616
  );
4617
4617
  }
4618
4618
  async function uploadDocuments(arbi, files, options = {}) {
4619
- const query = {};
4620
- if (options.shared !== void 0) query.shared = options.shared;
4621
- if (options.folder) query.folder = sanitizeFolderPath(options.folder);
4622
- if (options.configExtId) query.config_ext_id = options.configExtId;
4623
- if (options.wpType) query.wp_type = options.wpType;
4624
- if (options.versionOf) query.version_of = options.versionOf;
4625
- if (options.tagExtId) query.tag_ext_id = options.tagExtId;
4626
- if (options.workspaceExtId) query.workspace_ext_id = options.workspaceExtId;
4619
+ const query2 = {};
4620
+ if (options.shared !== void 0) query2.shared = options.shared;
4621
+ if (options.folder) query2.folder = sanitizeFolderPath(options.folder);
4622
+ if (options.configExtId) query2.config_ext_id = options.configExtId;
4623
+ if (options.wpType) query2.wp_type = options.wpType;
4624
+ if (options.versionOf) query2.version_of = options.versionOf;
4625
+ if (options.tagExtId) query2.tag_ext_id = options.tagExtId;
4626
+ if (options.workspaceExtId) query2.workspace_ext_id = options.workspaceExtId;
4627
4627
  if (options.derivedFrom) {
4628
- query.derived_from = options.derivedFrom.docId;
4629
- query.derived_role = options.derivedFrom.role;
4628
+ query2.derived_from = options.derivedFrom.docId;
4629
+ query2.derived_role = options.derivedFrom.role;
4630
4630
  }
4631
4631
  const result = await arbi.fetch.POST("/v1/document/upload", {
4632
- params: { query },
4632
+ params: { query: query2 },
4633
4633
  ...options.onProgress ? { fetch: progressFetch(options.onProgress) } : {},
4634
4634
  // The schema types the files as strings; they go as multipart parts.
4635
4635
  body: { files },
@@ -5032,18 +5032,27 @@ async function listHouseTemplateCandidates(arbi) {
5032
5032
  // src/operations/workspaces.ts
5033
5033
  var workspaces_exports = {};
5034
5034
  __export(workspaces_exports, {
5035
+ EXTERNAL_ACCESS_SECONDS: () => EXTERNAL_ACCESS_SECONDS,
5035
5036
  addWorkspaceMembers: () => addWorkspaceMembers,
5037
+ addWorkspaceMembersBody: () => addWorkspaceMembersBody,
5036
5038
  addWorkspaceUsers: () => addWorkspaceUsers,
5039
+ cancelWorkspaceTransfer: () => cancelWorkspaceTransfer,
5037
5040
  copyDocuments: () => copyDocuments,
5038
5041
  createWorkspace: () => createWorkspace,
5039
5042
  deleteWorkspaces: () => deleteWorkspaces,
5043
+ exportWorkspaceData: () => exportWorkspaceData,
5040
5044
  getWorkspaceActivity: () => getWorkspaceActivity,
5045
+ getWorkspaceTransfer: () => getWorkspaceTransfer,
5041
5046
  grantTemporaryWorkspaceAccess: () => grantTemporaryWorkspaceAccess,
5047
+ listWorkspaceTransfers: () => listWorkspaceTransfers,
5042
5048
  listWorkspaceUsers: () => listWorkspaceUsers,
5043
5049
  listWorkspaces: () => listWorkspaces,
5050
+ planWorkspaceTransfer: () => planWorkspaceTransfer,
5044
5051
  primeWorkspaceKey: () => primeWorkspaceKey,
5045
5052
  removeWorkspaceUsers: () => removeWorkspaceUsers,
5053
+ resumeWorkspaceTransfer: () => resumeWorkspaceTransfer,
5046
5054
  setUserRole: () => setUserRole,
5055
+ startWorkspaceTransfer: () => startWorkspaceTransfer,
5047
5056
  updateWorkspace: () => updateWorkspace
5048
5057
  });
5049
5058
  async function listWorkspaces(arbi) {
@@ -5080,9 +5089,16 @@ async function updateWorkspace(arbi, body) {
5080
5089
  async function listWorkspaceUsers(arbi) {
5081
5090
  return requireData(await arbi.fetch.GET("/v1/workspace/users"), "Failed to fetch workspace users");
5082
5091
  }
5092
+ var EXTERNAL_ACCESS_SECONDS = 86400;
5093
+ function addWorkspaceMembersBody(request) {
5094
+ return {
5095
+ ...request,
5096
+ access_duration_seconds: request.access_duration_seconds ?? EXTERNAL_ACCESS_SECONDS
5097
+ };
5098
+ }
5083
5099
  async function addWorkspaceMembers(arbi, request) {
5084
5100
  return requireData(
5085
- await arbi.fetch.POST("/v1/workspace/users", { body: request }),
5101
+ await arbi.fetch.POST("/v1/workspace/users", { body: addWorkspaceMembersBody(request) }),
5086
5102
  "Failed to add users"
5087
5103
  );
5088
5104
  }
@@ -5090,13 +5106,15 @@ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, co
5090
5106
  const invite = confirmInvite ? { confirm_invite: true } : {};
5091
5107
  return requireData(
5092
5108
  await arbi.fetch.POST("/v1/workspace/users", {
5093
- body: target ? {
5094
- emails,
5095
- role,
5096
- workspace_ext_id: target.workspaceExtId,
5097
- workspace_key: target.workspaceKey,
5098
- ...invite
5099
- } : { emails, role, ...invite }
5109
+ body: addWorkspaceMembersBody(
5110
+ target ? {
5111
+ emails,
5112
+ role,
5113
+ workspace_ext_id: target.workspaceExtId,
5114
+ workspace_key: target.workspaceKey,
5115
+ ...invite
5116
+ } : { emails, role, ...invite }
5117
+ )
5100
5118
  }),
5101
5119
  "Failed to add users"
5102
5120
  );
@@ -5104,13 +5122,13 @@ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, co
5104
5122
  async function grantTemporaryWorkspaceAccess(arbi, params) {
5105
5123
  return requireData(
5106
5124
  await arbi.fetch.POST("/v1/workspace/users", {
5107
- body: {
5125
+ body: addWorkspaceMembersBody({
5108
5126
  emails: params.emails,
5109
5127
  role: params.role ?? "collaborator",
5110
5128
  workspace_ext_id: params.workspaceExtId,
5111
5129
  workspace_key: params.workspaceKey,
5112
5130
  session_pubkey_b64: params.sessionPubkeyB64
5113
- }
5131
+ })
5114
5132
  }),
5115
5133
  "Failed to grant temporary access"
5116
5134
  );
@@ -5166,6 +5184,63 @@ async function primeWorkspaceKey(arbi, workspaceExtId, sessionSealedKey) {
5166
5184
  "Failed to prime the workspace key"
5167
5185
  );
5168
5186
  }
5187
+ async function planWorkspaceTransfer(arbi, scope, mode) {
5188
+ return requireData(
5189
+ await arbi.fetch.POST("/v1/workspace/transfer/plan", { body: { scope, mode } }),
5190
+ "Failed to plan the transfer"
5191
+ );
5192
+ }
5193
+ async function startWorkspaceTransfer(arbi, params) {
5194
+ return requireData(
5195
+ await arbi.fetch.POST("/v1/workspace/transfer", {
5196
+ body: {
5197
+ scope: params.scope,
5198
+ mode: params.mode,
5199
+ target_workspace_ext_id: params.targetWorkspaceId,
5200
+ target_workspace_key: params.targetWorkspaceKey,
5201
+ on_conflict: params.onConflict ?? "skip"
5202
+ }
5203
+ }),
5204
+ "Failed to start the transfer"
5205
+ );
5206
+ }
5207
+ async function resumeWorkspaceTransfer(arbi, transferId, targetWorkspaceKey) {
5208
+ return requireData(
5209
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/resume", {
5210
+ params: { path: { transfer_ext_id: transferId } },
5211
+ body: { target_workspace_key: targetWorkspaceKey }
5212
+ }),
5213
+ "Failed to resume the transfer"
5214
+ );
5215
+ }
5216
+ async function cancelWorkspaceTransfer(arbi, transferId) {
5217
+ return requireData(
5218
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/cancel", {
5219
+ params: { path: { transfer_ext_id: transferId } }
5220
+ }),
5221
+ "Failed to cancel the transfer"
5222
+ );
5223
+ }
5224
+ async function getWorkspaceTransfer(arbi, transferId) {
5225
+ return requireData(
5226
+ await arbi.fetch.GET("/v1/workspace/transfer/{transfer_ext_id}", {
5227
+ params: { path: { transfer_ext_id: transferId } }
5228
+ }),
5229
+ "Failed to fetch the transfer"
5230
+ );
5231
+ }
5232
+ async function listWorkspaceTransfers(arbi) {
5233
+ return requireData(
5234
+ await arbi.fetch.GET("/v1/workspace/transfer", {}),
5235
+ "Failed to list transfers"
5236
+ );
5237
+ }
5238
+ async function exportWorkspaceData(arbi, scope) {
5239
+ return requireData(
5240
+ await arbi.fetch.POST("/v1/workspace/export", { body: { scope } }),
5241
+ "Failed to export the workspace"
5242
+ );
5243
+ }
5169
5244
 
5170
5245
  // src/operations/conversations.ts
5171
5246
  var conversations_exports = {};
@@ -5244,24 +5319,29 @@ async function updateConversationAssistantMode(arbi, conversationId, assistantMo
5244
5319
  // src/operations/assistant.ts
5245
5320
  var assistant_exports = {};
5246
5321
  __export(assistant_exports, {
5322
+ AssistantTurnRefused: () => AssistantTurnRefused,
5247
5323
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
5248
- buildFactsContextTool: () => buildFactsContextTool,
5249
- buildRetrievalChunkTool: () => buildRetrievalChunkTool,
5250
- buildRetrievalFullContextTool: () => buildRetrievalFullContextTool,
5251
- buildRetrievalTocTool: () => buildRetrievalTocTool,
5252
- cancelAssistantRun: () => cancelAssistantRun,
5324
+ SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
5325
+ cancelRun: () => cancelRun,
5253
5326
  filterSkills: () => filterSkills,
5327
+ interject: () => interject,
5254
5328
  isSharedSkill: () => isSharedSkill,
5255
5329
  listCommands: () => listCommands,
5256
5330
  listSkills: () => listSkills,
5331
+ openRunStream: () => openRunStream,
5332
+ openTurnStream: () => openTurnStream,
5257
5333
  parseSlashCommand: () => parseSlashCommand,
5258
5334
  parseSlashTokenInProgress: () => parseSlashTokenInProgress,
5259
5335
  queryAssistant: () => queryAssistant,
5260
- respondToAgent: () => respondToAgent,
5336
+ quotaExceededFrom: () => quotaExceededFrom,
5337
+ quotaFromStreamError: () => quotaFromStreamError,
5261
5338
  retrieve: () => retrieve,
5262
5339
  searchChunks: () => searchChunks,
5340
+ transcribe: () => transcribe,
5263
5341
  uploadSkill: () => uploadSkill
5264
5342
  });
5343
+
5344
+ // src/chat/turn-request.ts
5265
5345
  function buildRetrievalChunkTool(docIds, searchMode) {
5266
5346
  return {
5267
5347
  name: "retrieval_chunk",
@@ -5293,12 +5373,70 @@ function buildRetrievalTocTool(docIds) {
5293
5373
  tool_responses: {}
5294
5374
  };
5295
5375
  }
5376
+ function selectFullContextDocument(docIds, pinnedDocumentId) {
5377
+ if (pinnedDocumentId && docIds.includes(pinnedDocumentId)) {
5378
+ return {
5379
+ fullContextDocId: pinnedDocumentId,
5380
+ chunkRetrievalDocIds: docIds.filter((id) => id !== pinnedDocumentId)
5381
+ };
5382
+ }
5383
+ return { fullContextDocId: null, chunkRetrievalDocIds: [...docIds] };
5384
+ }
5385
+ function buildDocumentTools(selection) {
5386
+ return {
5387
+ retrieval_chunk: buildRetrievalChunkTool(selection.chunkRetrievalDocIds),
5388
+ retrieval_full_context: buildRetrievalFullContextTool(
5389
+ selection.fullContextDocId ? [selection.fullContextDocId] : []
5390
+ )
5391
+ };
5392
+ }
5393
+ var PA_PREFIX = "/pa ";
5394
+ function turnTools(request, activeArtifactExtId) {
5395
+ const facts = request.factIds ? { facts_context: buildFactsContextTool(request.factIds) } : {};
5396
+ if (request.tools) return { ...facts, ...request.tools };
5397
+ if (request.personalAgent) {
5398
+ return {
5399
+ personal_agent: {
5400
+ name: "personal_agent",
5401
+ description: "personal agent",
5402
+ tool_args: { task: request.question },
5403
+ tool_responses: {}
5404
+ }
5405
+ };
5406
+ }
5407
+ if (!request.docIds) return { ...facts };
5408
+ const selection = selectFullContextDocument(request.docIds, request.pinnedDocumentId);
5409
+ const documents = activeArtifactExtId && selection.fullContextDocId === activeArtifactExtId ? { ...selection, fullContextDocId: null } : selection;
5410
+ return { ...buildDocumentTools(documents), ...facts };
5411
+ }
5412
+ function buildTurnRequest(request) {
5413
+ const pa2 = request.personalAgent === true;
5414
+ const activeArtifactExtId = pa2 ? null : request.activeArtifactExtId ?? null;
5415
+ const input = pa2 && !request.question.startsWith(PA_PREFIX) ? `${PA_PREFIX}${request.question}` : request.question;
5416
+ return {
5417
+ input,
5418
+ workspace_ext_id: request.workspaceId,
5419
+ stream: true,
5420
+ background: false,
5421
+ store: true,
5422
+ tools: turnTools(request, activeArtifactExtId),
5423
+ ...request.agentId ? { agent_ext_id: request.agentId } : {},
5424
+ ...request.previousResponseId ? { previous_response_id: request.previousResponseId } : {},
5425
+ ...request.conversationId ? { conversation_ext_id: request.conversationId } : {},
5426
+ ...request.model && !pa2 ? { model: request.model } : {},
5427
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5428
+ ...request.mentions && request.mentions.length > 0 ? { mentions: request.mentions } : {},
5429
+ ...request.assistantMode ? { assistant_mode: request.assistantMode } : {}
5430
+ };
5431
+ }
5432
+
5433
+ // src/operations/assistant.ts
5296
5434
  var MAX_RETRIEVE_DOC_IDS = 5e3;
5297
5435
  async function retrieve(options) {
5298
5436
  const {
5299
5437
  arbi,
5300
5438
  workspaceId,
5301
- query,
5439
+ query: query2,
5302
5440
  docIds,
5303
5441
  searchMode,
5304
5442
  fullContextDocIds,
@@ -5316,7 +5454,7 @@ async function retrieve(options) {
5316
5454
  tools.retrieval_toc = buildRetrievalTocTool(tocDocIds);
5317
5455
  }
5318
5456
  const body = {
5319
- input: query,
5457
+ input: query2,
5320
5458
  workspace_ext_id: workspaceId,
5321
5459
  stream: false,
5322
5460
  background: false,
@@ -5369,48 +5507,120 @@ function searchChunks(result) {
5369
5507
  return Array.from(byId3.values()).sort((a2, b2) => b2.score - a2.score);
5370
5508
  }
5371
5509
  async function queryAssistant(options) {
5372
- const {
5373
- workspaceId,
5374
- question,
5375
- docIds,
5376
- previousResponseId,
5377
- conversationId,
5378
- assistantMode,
5379
- agentId,
5380
- model,
5381
- mentions,
5382
- signal,
5383
- activeArtifactExtId,
5384
- ...auth
5385
- } = options;
5386
- const body = {
5387
- input: question,
5388
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5389
- workspace_ext_id: workspaceId,
5390
- ...agentId ? { agent_ext_id: agentId } : {},
5391
- stream: true,
5392
- background: false,
5393
- store: true,
5394
- tools: agentId ? {} : {
5395
- retrieval_chunk: buildRetrievalChunkTool(docIds),
5396
- retrieval_full_context: buildRetrievalFullContextTool([])
5397
- },
5398
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5399
- ...conversationId ? { conversation_ext_id: conversationId } : {},
5400
- ...assistantMode ? { assistant_mode: assistantMode } : {},
5401
- ...model ? { model } : {},
5402
- ...mentions && mentions.length > 0 ? { mentions } : {}
5403
- };
5510
+ const { baseUrl, accessToken, signal, ...request } = options;
5404
5511
  return authenticatedFetch({
5405
- ...auth,
5512
+ baseUrl,
5513
+ accessToken,
5406
5514
  path: "/v1/assistant/query",
5407
5515
  method: "POST",
5408
- body: JSON.stringify(body),
5516
+ body: JSON.stringify(buildTurnRequest(request)),
5409
5517
  headers: { "Content-Type": "application/json" },
5410
5518
  signal
5411
5519
  });
5412
5520
  }
5413
- async function respondToAgent(arbi, assistantMessageExtId, answer) {
5521
+ var AssistantTurnRefused = class extends ArbiApiError {
5522
+ /** Set when the refusal is the project's used-up AI usage. */
5523
+ quota;
5524
+ constructor(message, status, quota = null) {
5525
+ super(message, void 0, status);
5526
+ this.name = "AssistantTurnRefused";
5527
+ this.quota = quota;
5528
+ }
5529
+ };
5530
+ var SESSION_EXPIRED_MESSAGE = "Token has expired. Please log in again.";
5531
+ function quotaExceededFrom(detail) {
5532
+ if (!detail || typeof detail !== "object") return null;
5533
+ const d2 = detail;
5534
+ if (d2.code !== "QUOTA_EXCEEDED") return null;
5535
+ return {
5536
+ spend: Number(d2.spend ?? 0),
5537
+ budget: Number(d2.budget ?? 0),
5538
+ projectExtId: d2.project_ext_id ?? null,
5539
+ ...typeof d2.message === "string" ? { message: d2.message } : {}
5540
+ };
5541
+ }
5542
+ var LITELLM_BUDGET_RE = /ExceededBudget:\s*End User=(?<project>[^\s]+)\s+over budget\.\s*Spend=(?<spend>[0-9.]+),\s*Budget=(?<budget>[0-9.]+)/;
5543
+ function quotaFromStreamError(error) {
5544
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
5545
+ if (!message.includes("ExceededBudget")) return null;
5546
+ const match = message.match(LITELLM_BUDGET_RE);
5547
+ if (!match?.groups) return null;
5548
+ const spend = usdToGbp(Number(match.groups.spend));
5549
+ const budget = usdToGbp(Number(match.groups.budget));
5550
+ if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
5551
+ return { spend, budget, projectExtId: match.groups.project ?? null };
5552
+ }
5553
+ async function readDetail(response) {
5554
+ try {
5555
+ return (await response.json())?.detail;
5556
+ } catch {
5557
+ return void 0;
5558
+ }
5559
+ }
5560
+ async function refusal(response) {
5561
+ const { status } = response;
5562
+ if (status === 409) {
5563
+ const detail2 = await readDetail(response);
5564
+ return new AssistantTurnRefused(
5565
+ detailText(detail2) || "This message has failed. Please retry from the previous message.",
5566
+ status
5567
+ );
5568
+ }
5569
+ if (status === 503) {
5570
+ return new AssistantTurnRefused(
5571
+ "The selected LLM is not responding. Please retry again in a minute or select another model.",
5572
+ status
5573
+ );
5574
+ }
5575
+ if (status === 402) {
5576
+ const detail2 = await readDetail(response);
5577
+ const quota = quotaExceededFrom(detail2);
5578
+ const message = quota?.message ?? (typeof detail2 === "string" ? detail2 : void 0) ?? detail2?.message ?? "This project's AI usage for this month is used up.";
5579
+ return new AssistantTurnRefused(
5580
+ message || "This project's AI usage for this month is used up.",
5581
+ status,
5582
+ quota
5583
+ );
5584
+ }
5585
+ const detail = await readDetail(response);
5586
+ return new AssistantTurnRefused(
5587
+ detailText(detail) || `HTTP error! status: ${status}`,
5588
+ status
5589
+ );
5590
+ }
5591
+ async function openTurnStream(auth, body, signal) {
5592
+ const response = await fetch(`${auth.baseUrl}/v1/assistant/query`, {
5593
+ method: "POST",
5594
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${auth.accessToken}` },
5595
+ body: JSON.stringify(body),
5596
+ signal,
5597
+ credentials: "include"
5598
+ });
5599
+ if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
5600
+ if (!response.ok || !response.body) throw await refusal(response);
5601
+ return response;
5602
+ }
5603
+ async function openRunStream(auth, responseId, signal) {
5604
+ const response = await fetch(
5605
+ `${auth.baseUrl}/v1/assistant/run/${encodeURIComponent(responseId)}/stream`,
5606
+ {
5607
+ method: "GET",
5608
+ headers: { Authorization: `Bearer ${auth.accessToken}` },
5609
+ signal,
5610
+ credentials: "include"
5611
+ }
5612
+ );
5613
+ if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
5614
+ if (!response.ok || !response.body) {
5615
+ throw new ArbiApiError(
5616
+ response.status === 404 ? "This run is no longer active." : `HTTP ${response.status}`,
5617
+ void 0,
5618
+ response.status
5619
+ );
5620
+ }
5621
+ return response;
5622
+ }
5623
+ async function interject(arbi, assistantMessageExtId, answer) {
5414
5624
  return requireData(
5415
5625
  await arbi.fetch.POST("/v1/assistant/interject", {
5416
5626
  body: { assistant_message_ext_id: assistantMessageExtId, answer }
@@ -5444,6 +5654,22 @@ async function listCommands(arbi) {
5444
5654
  );
5445
5655
  return result.commands;
5446
5656
  }
5657
+ async function transcribe(arbi, audio) {
5658
+ const result = requireData(
5659
+ await arbi.fetch.POST("/v1/assistant/transcribe", {
5660
+ // The generated type of a multipart binary field is `string`; the value is the Blob, sent as
5661
+ // real form data (openapi-fetch would JSON-encode a plain object).
5662
+ body: { audio },
5663
+ bodySerializer: (body) => {
5664
+ const form = new FormData();
5665
+ form.append("audio", body.audio, "voice-input.webm");
5666
+ return form;
5667
+ }
5668
+ }),
5669
+ "Failed to transcribe the recording"
5670
+ );
5671
+ return result.text;
5672
+ }
5447
5673
  function parseSlashCommand(input) {
5448
5674
  const m2 = /^\s*\/([a-zA-Z0-9_-]+)(?:\s+([\s\S]*))?$/.exec(input);
5449
5675
  if (!m2) return null;
@@ -5453,8 +5679,8 @@ function parseSlashTokenInProgress(buffer) {
5453
5679
  const m2 = /^\s*\/([a-zA-Z0-9_-]*)$/.exec(buffer);
5454
5680
  return m2 ? m2[1].toLowerCase() : null;
5455
5681
  }
5456
- function filterSkills(items, query, pinned = []) {
5457
- const q2 = query.toLowerCase();
5682
+ function filterSkills(items, query2, pinned = []) {
5683
+ const q2 = query2.toLowerCase();
5458
5684
  const pinnedSet = new Set(pinned);
5459
5685
  const key = (s2) => (s2.slug ?? s2.name).toLowerCase();
5460
5686
  const matched = q2 ? items.filter((s2) => key(s2).includes(q2)) : items.slice();
@@ -5469,7 +5695,7 @@ function filterSkills(items, query, pinned = []) {
5469
5695
  });
5470
5696
  return matched;
5471
5697
  }
5472
- async function cancelAssistantRun(auth, responseId) {
5698
+ async function cancelRun(auth, responseId) {
5473
5699
  await authenticatedFetch({
5474
5700
  ...auth,
5475
5701
  path: `/v1/assistant/run/${encodeURIComponent(responseId)}/cancel`,
@@ -5495,6 +5721,7 @@ async function submitBackgroundQuery(options) {
5495
5721
  conversationId,
5496
5722
  mentions,
5497
5723
  activeArtifactExtId,
5724
+ fullContext = true,
5498
5725
  ...auth
5499
5726
  } = options;
5500
5727
  const tools = {};
@@ -5505,12 +5732,13 @@ async function submitBackgroundQuery(options) {
5505
5732
  tool_args: { doc_ext_ids: docIds },
5506
5733
  tool_responses: {}
5507
5734
  };
5508
- tools.retrieval_full_context = {
5509
- name: "retrieval_full_context",
5510
- description: "retrieval full context",
5511
- tool_args: { doc_ext_ids: docIds },
5512
- tool_responses: {}
5513
- };
5735
+ if (fullContext)
5736
+ tools.retrieval_full_context = {
5737
+ name: "retrieval_full_context",
5738
+ description: "retrieval full context",
5739
+ tool_args: { doc_ext_ids: docIds },
5740
+ tool_responses: {}
5741
+ };
5514
5742
  }
5515
5743
  const body = {
5516
5744
  input: question,
@@ -5594,13 +5822,13 @@ var TAG_FIELD_TYPES = [
5594
5822
  "select",
5595
5823
  "person"
5596
5824
  ];
5597
- async function listTags(arbi, query = {}) {
5825
+ async function listTags(arbi, query2 = {}) {
5598
5826
  const params = {};
5599
- if (query.kind) params.kind = query.kind;
5600
- if (query.parentId) params.parent = query.parentId;
5601
- if (query.ids?.length) params.ids = query.ids;
5602
- if (query.include?.length) params.include = query.include;
5603
- if (query.linksLimit !== void 0) params.links_limit = query.linksLimit;
5827
+ if (query2.kind) params.kind = query2.kind;
5828
+ if (query2.parentId) params.parent = query2.parentId;
5829
+ if (query2.ids?.length) params.ids = query2.ids;
5830
+ if (query2.include?.length) params.include = query2.include;
5831
+ if (query2.linksLimit !== void 0) params.links_limit = query2.linksLimit;
5604
5832
  return requireData(
5605
5833
  await arbi.fetch.GET(
5606
5834
  "/v1/tag/",
@@ -6966,7 +7194,6 @@ async function getFileContent(auth, fileId) {
6966
7194
  var sessions_exports = {};
6967
7195
  __export(sessions_exports, {
6968
7196
  listSessions: () => listSessions,
6969
- logoutAllSessions: () => logoutAllSessions,
6970
7197
  terminateSession: () => terminateSession
6971
7198
  });
6972
7199
  async function listSessions(arbi) {
@@ -6981,12 +7208,6 @@ async function terminateSession(arbi, sessionId) {
6981
7208
  "Failed to end session"
6982
7209
  );
6983
7210
  }
6984
- async function logoutAllSessions(arbi) {
6985
- requireOk(
6986
- await arbi.fetch.POST("/v1/user/logout", { params: { query: { all_sessions: true } } }),
6987
- "Failed to sign out of all sessions"
6988
- );
6989
- }
6990
7211
 
6991
7212
  // src/operations/profile.ts
6992
7213
  var profile_exports = {};
@@ -7055,7 +7276,7 @@ __export(identity_exports, {
7055
7276
  remove: () => remove,
7056
7277
  startSession: () => startSession
7057
7278
  });
7058
- function refusal(apiError) {
7279
+ function refusal2(apiError) {
7059
7280
  const detail = apiError?.detail;
7060
7281
  if (typeof detail === "string") return { message: detail };
7061
7282
  if (detail && typeof detail === "object" && !Array.isArray(detail)) {
@@ -7068,12 +7289,12 @@ function refusal(apiError) {
7068
7289
  return {};
7069
7290
  }
7070
7291
  function identityErrorCode(error) {
7071
- return error instanceof ArbiApiError ? refusal(error.apiError).code : void 0;
7292
+ return error instanceof ArbiApiError ? refusal2(error.apiError).code : void 0;
7072
7293
  }
7073
7294
  function unwrap(result, fallback) {
7074
7295
  if (result.error || result.data === void 0) {
7075
7296
  throw new ArbiApiError(
7076
- refusal(result.error).message ?? fallback,
7297
+ refusal2(result.error).message ?? fallback,
7077
7298
  result.error,
7078
7299
  result.response?.status
7079
7300
  );
@@ -7143,13 +7364,13 @@ __export(projects_exports, {
7143
7364
  updateProject: () => updateProject
7144
7365
  });
7145
7366
  async function listProjects(arbi, filters = {}) {
7146
- const query = {};
7147
- if (filters.stage) query.stage = filters.stage;
7148
- if (filters.leadUser) query.lead_user = filters.leadUser;
7367
+ const query2 = {};
7368
+ if (filters.stage) query2.stage = filters.stage;
7369
+ if (filters.leadUser) query2.lead_user = filters.leadUser;
7149
7370
  return requireData(
7150
7371
  await arbi.fetch.GET(
7151
7372
  "/v1/user/projects/",
7152
- Object.keys(query).length ? { params: { query } } : void 0
7373
+ Object.keys(query2).length ? { params: { query: query2 } } : void 0
7153
7374
  ),
7154
7375
  "Failed to fetch projects"
7155
7376
  );
@@ -7163,12 +7384,12 @@ async function createProject(arbi, name, plan = "free", details = {}) {
7163
7384
  );
7164
7385
  }
7165
7386
  async function listProjectEvents(arbi, projectExtId, options = {}) {
7166
- const query = {};
7167
- if (options.kind) query.kind = options.kind;
7168
- if (options.limit !== void 0) query.limit = options.limit;
7387
+ const query2 = {};
7388
+ if (options.kind) query2.kind = options.kind;
7389
+ if (options.limit !== void 0) query2.limit = options.limit;
7169
7390
  return requireData(
7170
7391
  await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/events", {
7171
- params: { path: { project_ext_id: projectExtId }, query }
7392
+ params: { path: { project_ext_id: projectExtId }, query: query2 }
7172
7393
  }),
7173
7394
  "Failed to fetch project events"
7174
7395
  );
@@ -8930,149 +9151,857 @@ async function cancelPublicBooking(baseUrl, slug, token) {
8930
9151
  if (!res.ok) throw await bookingError(res);
8931
9152
  }
8932
9153
 
8933
- // src/arbi.ts
8934
- function tokenExpiresWithin(token, seconds) {
8935
- const expiresAt = readSessionClaims(token)?.expiresAt;
8936
- return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
9154
+ // src/operations/calls.ts
9155
+ var calls_exports = {};
9156
+ __export(calls_exports, {
9157
+ CallApiError: () => CallApiError,
9158
+ WEBINAR_MODERATORS: () => WEBINAR_MODERATORS,
9159
+ WEBINAR_TEAM: () => WEBINAR_TEAM,
9160
+ askQuestion: () => askQuestion,
9161
+ callError: () => callError,
9162
+ cancelCall: () => cancelCall,
9163
+ commitRecordingPart: () => commitRecordingPart,
9164
+ createCall: () => createCall,
9165
+ createCallInviteLink: () => createCallInviteLink,
9166
+ createRecordingTrack: () => createRecordingTrack,
9167
+ decideKnock: () => decideKnock,
9168
+ declineCall: () => declineCall,
9169
+ deleteQuestion: () => deleteQuestion,
9170
+ deleteRecording: () => deleteRecording,
9171
+ deleteRecordingMedia: () => deleteRecordingMedia,
9172
+ demoteFromStage: () => demoteFromStage,
9173
+ downloadRecordingPart: () => downloadRecordingPart,
9174
+ fetchCallToken: () => fetchCallToken,
9175
+ getCall: () => getCall,
9176
+ getCallRecording: () => getCallRecording,
9177
+ getCallsConfig: () => getCallsConfig,
9178
+ getOrCreateCallChat: () => getOrCreateCallChat,
9179
+ getRecordingQuota: () => getRecordingQuota,
9180
+ getWebinar: () => getWebinar,
9181
+ isQuotaError: () => isQuotaError,
9182
+ knockCall: () => knockCall,
9183
+ listCallInviteLinks: () => listCallInviteLinks,
9184
+ listCallRecordings: () => listCallRecordings,
9185
+ listQuestions: () => listQuestions,
9186
+ muteCallParticipant: () => muteCallParticipant,
9187
+ pollKnock: () => pollKnock,
9188
+ postChatTranscriptLine: () => postChatTranscriptLine,
9189
+ presignRecordingPart: () => presignRecordingPart,
9190
+ promoteToStage: () => promoteToStage,
9191
+ quotaNeedsWarning: () => quotaNeedsWarning,
9192
+ recordingStateFrom: () => recordingStateFrom,
9193
+ recordingStateOfCall: () => recordingStateOfCall,
9194
+ removeCallParticipant: () => removeCallParticipant,
9195
+ revokeCallInviteLink: () => revokeCallInviteLink,
9196
+ ringCall: () => ringCall,
9197
+ setCallTranscription: () => setCallTranscription,
9198
+ setRecordingExpiry: () => setRecordingExpiry,
9199
+ setWebinarHand: () => setWebinarHand,
9200
+ startCallRecording: () => startCallRecording,
9201
+ stopCallRecording: () => stopCallRecording,
9202
+ transcribeCallSegment: () => transcribeCallSegment,
9203
+ transcribeRecordingPart: () => transcribeRecordingPart,
9204
+ transcriptionStateFrom: () => transcriptionStateFrom,
9205
+ updateCall: () => updateCall,
9206
+ updateQuestion: () => updateQuestion,
9207
+ updateWebinar: () => updateWebinar,
9208
+ voteQuestion: () => voteQuestion
9209
+ });
9210
+
9211
+ // src/transcription-hints.ts
9212
+ var LANGUAGE_PATTERN = /^[a-z]{2}$/;
9213
+ var PROMPT_MAX_CHARS = 500;
9214
+ var PROMPT_CONTEXT_CHARS = 200;
9215
+ function continuityPrompt(previous) {
9216
+ const text = previous?.replace(/\s+/g, " ").trim();
9217
+ if (!text) return void 0;
9218
+ if (text.length <= PROMPT_CONTEXT_CHARS) return text;
9219
+ const tail = text.slice(-PROMPT_CONTEXT_CHARS);
9220
+ const space = tail.indexOf(" ");
9221
+ const trimmed = space >= 0 && space < tail.length - 1 ? tail.slice(space + 1) : tail;
9222
+ return trimmed || void 0;
9223
+ }
9224
+ function appendTranscriptionHints(form, hints) {
9225
+ if (hints.language && LANGUAGE_PATTERN.test(hints.language)) {
9226
+ form.append("language", hints.language);
9227
+ }
9228
+ const prompt = hints.prompt?.trim().slice(0, PROMPT_MAX_CHARS);
9229
+ if (prompt) form.append("prompt", prompt);
8937
9230
  }
8938
- var Arbi = class {
8939
- client = null;
8940
- loginResult = null;
8941
- userProfile = null;
8942
- profileListeners = /* @__PURE__ */ new Set();
8943
- currentWorkspaceId = null;
8944
- /** Wrapped workspace keys seen in the last list/create, so selecting needs no re-fetch. */
8945
- wrappedKeys = /* @__PURE__ */ new Map();
8946
- /** Workspaces whose key this server session holds (`workspaces.open`), keyed per session key. */
8947
- openedWorkspaces = /* @__PURE__ */ new Map();
8948
- openedForSessionKey = null;
8949
- chatCryptoContext = null;
8950
- /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
8951
- chatRings = /* @__PURE__ */ new Map();
8952
- sessionExpiredListeners = /* @__PURE__ */ new Set();
8953
- options;
8954
- constructor(options) {
8955
- this.options = options;
8956
- if (options.session) {
8957
- this.client = options.session.client;
8958
- this.loginResult = options.session.login;
8959
- this.userProfile = options.session.login.profile ?? null;
8960
- this.currentWorkspaceId = options.session.workspaceId ?? null;
8961
- }
8962
- }
8963
- // ── Lifecycle ───────────────────────────────────────────────────────────
8964
- /**
8965
- * The deployment domain the user's keys are derived for: `deploymentDomain` when given,
8966
- * otherwise the hostname of `url`. Signing and password changes re-derive keys with it, so a
8967
- * host that needs it (the document tools' e-signing) reads it here rather than recomputing it.
8968
- */
8969
- getDeploymentDomain() {
8970
- return this.options.deploymentDomain ?? new URL(this.options.url).hostname;
8971
- }
8972
- /** Initialize the SDK client and sodium crypto. Called automatically by login(). */
8973
- async init() {
8974
- if (this.client) return this.client;
8975
- const domain = this.getDeploymentDomain();
8976
- this.client = createArbiClient({
8977
- baseUrl: this.options.url,
8978
- deploymentDomain: domain,
8979
- credentials: this.options.credentials ?? "omit",
8980
- // A silent re-login rotates the server session key: keep ours in step, or the next
8981
- // workspace open would seal the key for a session the server no longer has.
8982
- onReloginSuccess: ({ serverSessionKey }) => {
8983
- if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
8984
- },
8985
- onSessionExpired: () => this.expireSession()
8986
- });
8987
- await this.client.crypto.initSodium();
8988
- return this.client;
8989
- }
8990
- /**
8991
- * Request a verification email for registration.
8992
- * The user will receive an email with a 3-word verification code.
8993
- */
8994
- async requestVerification(email) {
8995
- const client = await this.init();
8996
- await client.fetch.POST("/v1/user/verify-email", { body: { email } });
8997
- }
8998
- /**
8999
- * Register a new account using the verification code received by email.
9000
- */
9001
- async register(params) {
9002
- const client = await this.init();
9003
- await client.auth.register(params);
9004
- }
9005
- /**
9006
- * Log in with email and password.
9007
- * Initializes the SDK client if not already done.
9008
- */
9009
- async login(email, password) {
9010
- const client = await this.init();
9011
- this.loginResult = await client.auth.login({ email, password });
9012
- this.userProfile = this.loginResult.profile ?? null;
9013
- }
9014
- /**
9015
- * Recover a session using a stored signing private key (base64).
9016
- * Useful for session recovery without re-entering the password.
9017
- */
9018
- async loginWithKey(email, signingPrivateKeyBase64) {
9019
- const client = await this.init();
9020
- const signingPrivateKey = client.crypto.base64ToBytes(signingPrivateKeyBase64);
9021
- this.loginResult = await client.auth.loginWithKey({ email, signingPrivateKey });
9022
- this.userProfile = this.loginResult.profile ?? null;
9023
- }
9024
- /** Recover browser authentication using the encrypted signing key already in IndexedDB. */
9025
- async restoreSession(email) {
9026
- const client = await this.init();
9027
- const saved = await client.storage.getSession();
9028
- if (!saved?.signingPrivateKey) return false;
9029
- this.loginResult = await client.auth.loginWithKey({
9030
- email,
9031
- signingPrivateKey: saved.signingPrivateKey
9032
- });
9033
- this.userProfile = this.loginResult.profile ?? null;
9034
- return true;
9231
+
9232
+ // src/operations/call-errors.ts
9233
+ var CallApiError = class extends ArbiApiError {
9234
+ code;
9235
+ constructor(message, status, code, apiError) {
9236
+ super(message, apiError ?? (code ? { detail: code } : void 0), status);
9237
+ this.name = "CallApiError";
9238
+ this.code = code;
9035
9239
  }
9036
- /** Remember the wrapped keys of workspaces the server just returned. */
9037
- rememberWorkspaces(workspaces) {
9038
- for (const ws of workspaces) {
9039
- if (ws.wrapped_key) this.wrappedKeys.set(ws.external_id, ws.wrapped_key);
9040
- }
9041
- return workspaces;
9240
+ };
9241
+ var CODE_TEXT = {
9242
+ // calls
9243
+ locked: "This call is locked.",
9244
+ knock_required: "The host has to let you in.",
9245
+ invalid_invite: "This invitation is no longer valid. Ask the host for a new one.",
9246
+ stale_link: "This call link is no longer valid. Ask for a new one.",
9247
+ cancelled: "This call was cancelled.",
9248
+ not_a_contact: "You can only call people in your contacts.",
9249
+ workspace_locked: "Only members of the thread\u2019s workspace can join this call.",
9250
+ agent_not_allowed: "Agents cannot take part in calls.",
9251
+ thread_not_shared: "Calls can only be started in shared threads.",
9252
+ contact_has_no_email: "This contact has no e-mail address to send a link to.",
9253
+ contact_registered: "This contact has an ARBI account: ring them instead.",
9254
+ invalid_link: "The call link is not valid.",
9255
+ host_only: "Only the host can do that.",
9256
+ // transcription
9257
+ transcription_off: "Transcription is off.",
9258
+ speaker_mismatch: "Only the speaker (or a member, for a workspace guest) can store this line.",
9259
+ // recording
9260
+ storage_quota_exceeded: "The storage quota is full: recording stopped.",
9261
+ already_recording: "The call is already being recorded.",
9262
+ recording_stopped: "The recording has stopped.",
9263
+ recording_active: "Stop the recording first.",
9264
+ composite_needs_video: "This recording has no video.",
9265
+ not_a_member: "Only members of the meeting chat can open this recording.",
9266
+ part_committed: "That part is already stored.",
9267
+ part_not_uploaded: "The part did not reach the storage.",
9268
+ size_mismatch: "The uploaded part has the wrong size.",
9269
+ // webinars
9270
+ moderator_only: "Only the host or a co-host can do that.",
9271
+ team_only: "Only the host and panelists can do that.",
9272
+ host_not_demotable: "The host stays on stage.",
9273
+ on_stage: "You are already on stage.",
9274
+ own_question: "You cannot upvote your own question.",
9275
+ question_dismissed: "This question was dismissed.",
9276
+ question_not_open: "This question is no longer open.",
9277
+ webinar_not_live: "The webinar has not started yet.",
9278
+ not_on_stage: "Only people on stage can do that."
9279
+ };
9280
+ var TRANSCRIBE_STATUS_TEXT = {
9281
+ 413: "That audio clip is too large to transcribe.",
9282
+ 429: "Transcribing too fast \u2014 slowing down.",
9283
+ 502: "The transcriber did not answer.",
9284
+ 503: "Transcription is not available on this server."
9285
+ };
9286
+ function callError(error, status, fallback, options = {}) {
9287
+ const detail = apiErrorDetail(error);
9288
+ const quota = !!options.quota && (status === 507 || status === 402);
9289
+ const code = (detail && /^[a-z_]+$/.test(detail) ? detail : void 0) ?? (quota ? "storage_quota_exceeded" : void 0);
9290
+ const message = code && (options.texts?.[code] ?? CODE_TEXT[code]) || (status !== void 0 ? options.statusTexts?.[status] : void 0) || detail || `${fallback} (${status ?? "?"})`;
9291
+ return new CallApiError(message, status, code, error);
9292
+ }
9293
+ function isQuotaError(err) {
9294
+ if (!(err instanceof CallApiError)) return false;
9295
+ return err.code === "storage_quota_exceeded" || err.status === 507 || err.status === 402;
9296
+ }
9297
+ async function unwrapCall(result, fallback, options) {
9298
+ const { data, error, response } = await result;
9299
+ if (error !== void 0 || !response.ok) {
9300
+ throw callError(error, response.status, fallback, options);
9042
9301
  }
9043
- /**
9044
- * A workspace's wrapped key: from the cache when a list or create already returned it, else from
9045
- * a fresh workspace list (a workspace created or shared since the last list).
9046
- */
9047
- async wrappedKeyFor(workspaceId, refresh2 = false) {
9048
- const cached = refresh2 ? void 0 : this.wrappedKeys.get(workspaceId);
9049
- if (cached) return { wrappedKey: cached, fromCache: true };
9050
- this.wrappedKeys.delete(workspaceId);
9051
- this.rememberWorkspaces(await listWorkspaces(this.requireClient()));
9052
- const wrappedKey = this.wrappedKeys.get(workspaceId);
9053
- if (!wrappedKey) {
9054
- throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
9055
- }
9056
- return { wrappedKey, fromCache: false };
9302
+ return data;
9303
+ }
9304
+
9305
+ // src/operations/call-webinars.ts
9306
+ var WEBINAR_MODERATORS = /* @__PURE__ */ new Set(["host", "cohost"]);
9307
+ var WEBINAR_TEAM = /* @__PURE__ */ new Set(["host", "cohost", "panelist"]);
9308
+ var query = (linkVersion) => linkVersion == null ? void 0 : { link_version: linkVersion };
9309
+ var webinarParams = (callExtId, linkVersion) => ({
9310
+ params: { path: { call_ext_id: callExtId }, query: query(linkVersion) }
9311
+ });
9312
+ var stageParams = (callExtId, identity, linkVersion) => ({
9313
+ params: { path: { call_ext_id: callExtId, identity }, query: query(linkVersion) }
9314
+ });
9315
+ var questionParams = (callExtId, questionExtId, linkVersion) => ({
9316
+ params: {
9317
+ path: { call_ext_id: callExtId, question_ext_id: questionExtId },
9318
+ query: query(linkVersion)
9057
9319
  }
9058
- /**
9059
- * Run `withKey` with the workspace's wrapped key. A cached key that no longer works (access was
9060
- * re-granted with a new key) is dropped and the call retried once with a fresh list.
9061
- */
9062
- async withWrappedKey(workspaceId, withKey) {
9063
- const { wrappedKey, fromCache } = await this.wrappedKeyFor(workspaceId);
9064
- try {
9065
- return await withKey(wrappedKey);
9066
- } catch (error) {
9067
- if (!fromCache) throw error;
9068
- const fresh = await this.wrappedKeyFor(workspaceId, true);
9069
- return withKey(fresh.wrappedKey);
9070
- }
9320
+ });
9321
+ function getWebinar(arbi, callExtId, linkVersion) {
9322
+ return unwrapCall(
9323
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/webinar", webinarParams(callExtId, linkVersion)),
9324
+ "Could not read the webinar"
9325
+ );
9326
+ }
9327
+ function updateWebinar(arbi, callExtId, body, linkVersion) {
9328
+ return unwrapCall(
9329
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/webinar", {
9330
+ ...webinarParams(callExtId, linkVersion),
9331
+ body
9332
+ }),
9333
+ "Could not update the webinar"
9334
+ );
9335
+ }
9336
+ function setWebinarHand(arbi, callExtId, raised, linkVersion) {
9337
+ return unwrapCall(
9338
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/hand", {
9339
+ ...webinarParams(callExtId, linkVersion),
9340
+ body: { raised }
9341
+ }),
9342
+ raised ? "Could not raise your hand" : "Could not lower your hand"
9343
+ );
9344
+ }
9345
+ async function promoteToStage(arbi, callExtId, identity, linkVersion) {
9346
+ await unwrapCall(
9347
+ arbi.fetch.POST(
9348
+ "/v1/calls/{call_ext_id}/webinar/stage/{identity}",
9349
+ stageParams(callExtId, identity, linkVersion)
9350
+ ),
9351
+ "Could not bring them on stage"
9352
+ );
9353
+ }
9354
+ async function demoteFromStage(arbi, callExtId, identity, linkVersion) {
9355
+ await unwrapCall(
9356
+ arbi.fetch.DELETE(
9357
+ "/v1/calls/{call_ext_id}/webinar/stage/{identity}",
9358
+ stageParams(callExtId, identity, linkVersion)
9359
+ ),
9360
+ "Could not move them to the audience"
9361
+ );
9362
+ }
9363
+ function listQuestions(arbi, callExtId, linkVersion) {
9364
+ return unwrapCall(
9365
+ arbi.fetch.GET(
9366
+ "/v1/calls/{call_ext_id}/webinar/questions",
9367
+ webinarParams(callExtId, linkVersion)
9368
+ ),
9369
+ "Could not load the questions"
9370
+ );
9371
+ }
9372
+ function askQuestion(arbi, callExtId, bodyCiphertext, linkVersion) {
9373
+ return unwrapCall(
9374
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/questions", {
9375
+ ...webinarParams(callExtId, linkVersion),
9376
+ body: { body: bodyCiphertext }
9377
+ }),
9378
+ "Could not ask the question"
9379
+ );
9380
+ }
9381
+ function voteQuestion(arbi, callExtId, questionExtId, up, linkVersion) {
9382
+ return unwrapCall(
9383
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}/vote", {
9384
+ ...questionParams(callExtId, questionExtId, linkVersion),
9385
+ body: { up }
9386
+ }),
9387
+ "Could not vote"
9388
+ );
9389
+ }
9390
+ function updateQuestion(arbi, callExtId, questionExtId, body, linkVersion) {
9391
+ return unwrapCall(
9392
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}", {
9393
+ ...questionParams(callExtId, questionExtId, linkVersion),
9394
+ body
9395
+ }),
9396
+ "Could not update the question"
9397
+ );
9398
+ }
9399
+ async function deleteQuestion(arbi, callExtId, questionExtId, linkVersion) {
9400
+ await unwrapCall(
9401
+ arbi.fetch.DELETE(
9402
+ "/v1/calls/{call_ext_id}/webinar/questions/{question_ext_id}",
9403
+ questionParams(callExtId, questionExtId, linkVersion)
9404
+ ),
9405
+ "Could not delete the question"
9406
+ );
9407
+ }
9408
+
9409
+ // src/operations/calls.ts
9410
+ var RECORDING = { quota: true };
9411
+ var TRANSCRIBE = { statusTexts: TRANSCRIBE_STATUS_TEXT };
9412
+ var callPath = (callExtId) => ({ params: { path: { call_ext_id: callExtId } } });
9413
+ var recPath = (callExtId, recordingExtId) => ({
9414
+ params: { path: { call_ext_id: callExtId, recording_ext_id: recordingExtId } }
9415
+ });
9416
+ var trackPath = (callExtId, recordingExtId, trackExtId) => ({
9417
+ params: {
9418
+ path: { call_ext_id: callExtId, recording_ext_id: recordingExtId, track_ext_id: trackExtId }
9071
9419
  }
9072
- /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
9073
- async sealWorkspaceKey(workspaceId) {
9074
- const client = this.requireClient();
9075
- const lr2 = this.requireLogin();
9420
+ });
9421
+ function getCallsConfig(arbi) {
9422
+ return unwrapCall(arbi.fetch.GET("/v1/calls/config"), "Could not read the calls config");
9423
+ }
9424
+ function createCall(arbi, body) {
9425
+ return unwrapCall(arbi.fetch.POST("/v1/calls", { body }), "Could not create the call");
9426
+ }
9427
+ function getCall(arbi, callExtId) {
9428
+ return unwrapCall(
9429
+ arbi.fetch.GET("/v1/calls/{call_ext_id}", callPath(callExtId)),
9430
+ "Could not open the call"
9431
+ );
9432
+ }
9433
+ function updateCall(arbi, callExtId, body) {
9434
+ return unwrapCall(
9435
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}", {
9436
+ ...callPath(callExtId),
9437
+ body
9438
+ }),
9439
+ "Could not update the call"
9440
+ );
9441
+ }
9442
+ async function cancelCall(arbi, callExtId) {
9443
+ await unwrapCall(
9444
+ arbi.fetch.DELETE("/v1/calls/{call_ext_id}", callPath(callExtId)),
9445
+ "Could not cancel the call"
9446
+ );
9447
+ }
9448
+ function fetchCallToken(arbi, callExtId, linkVersion, inviteToken) {
9449
+ return unwrapCall(
9450
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/token", {
9451
+ ...callPath(callExtId),
9452
+ body: {
9453
+ link_version: linkVersion ?? null,
9454
+ ...inviteToken ? { invite_token: inviteToken } : {}
9455
+ }
9456
+ }),
9457
+ "Could not join the call"
9458
+ );
9459
+ }
9460
+ async function ringCall(arbi, callExtId, sealedKeys, linkVersion) {
9461
+ await unwrapCall(
9462
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/ring", {
9463
+ ...callPath(callExtId),
9464
+ body: { sealed_keys: sealedKeys, link_version: linkVersion ?? null }
9465
+ }),
9466
+ "Could not ring"
9467
+ );
9468
+ }
9469
+ async function declineCall(arbi, callExtId) {
9470
+ await unwrapCall(
9471
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/decline", callPath(callExtId)),
9472
+ "Could not decline"
9473
+ );
9474
+ }
9475
+ function knockCall(arbi, callExtId, linkVersion) {
9476
+ return unwrapCall(
9477
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/knock", {
9478
+ ...callPath(callExtId),
9479
+ body: { link_version: linkVersion }
9480
+ }),
9481
+ "Could not ask to join"
9482
+ );
9483
+ }
9484
+ function pollKnock(arbi, callExtId, knockId) {
9485
+ return unwrapCall(
9486
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/knock/{knock_id}", {
9487
+ params: { path: { call_ext_id: callExtId, knock_id: knockId } }
9488
+ }),
9489
+ "Could not check the request"
9490
+ );
9491
+ }
9492
+ async function decideKnock(arbi, callExtId, knockId, admit) {
9493
+ await unwrapCall(
9494
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/knock/{knock_id}", {
9495
+ params: { path: { call_ext_id: callExtId, knock_id: knockId } },
9496
+ body: { admit }
9497
+ }),
9498
+ "Could not answer the request"
9499
+ );
9500
+ }
9501
+ async function getOrCreateCallChat(arbi, callExtId, body) {
9502
+ const { data, error, response } = await arbi.fetch.POST("/v1/calls/{call_ext_id}/chat", {
9503
+ ...callPath(callExtId),
9504
+ // A thread call's meeting thread takes no body.
9505
+ ...body ? { body } : {}
9506
+ });
9507
+ if (response.status === 409) {
9508
+ throw new CallApiError(
9509
+ "Open the call's workspace to keep its meeting chat.",
9510
+ 409,
9511
+ "workspace_required",
9512
+ error
9513
+ );
9514
+ }
9515
+ if (error !== void 0 || !response.ok || !data) {
9516
+ throw callError(error, response.status, "Could not open the meeting chat");
9517
+ }
9518
+ return data;
9519
+ }
9520
+ function createCallInviteLink(arbi, callExtId, body) {
9521
+ return unwrapCall(
9522
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/invite-links", { ...callPath(callExtId), body }),
9523
+ "Could not send the invitation"
9524
+ );
9525
+ }
9526
+ function listCallInviteLinks(arbi, callExtId) {
9527
+ return unwrapCall(
9528
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/invite-links", callPath(callExtId)),
9529
+ "Could not list the invitations"
9530
+ );
9531
+ }
9532
+ async function revokeCallInviteLink(arbi, callExtId, inviteLinkExtId) {
9533
+ await unwrapCall(
9534
+ arbi.fetch.DELETE("/v1/calls/{call_ext_id}/invite-links/{invite_link_ext_id}", {
9535
+ params: { path: { call_ext_id: callExtId, invite_link_ext_id: inviteLinkExtId } }
9536
+ }),
9537
+ "Could not revoke the invitation"
9538
+ );
9539
+ }
9540
+ async function removeCallParticipant(arbi, callExtId, identity) {
9541
+ await unwrapCall(
9542
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/participants/{identity}/remove", {
9543
+ params: { path: { call_ext_id: callExtId, identity } }
9544
+ }),
9545
+ "Could not remove the participant"
9546
+ );
9547
+ }
9548
+ async function muteCallParticipant(arbi, callExtId, identity, track) {
9549
+ await unwrapCall(
9550
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/participants/{identity}/mute", {
9551
+ params: { path: { call_ext_id: callExtId, identity } },
9552
+ body: { track }
9553
+ }),
9554
+ track === "audio" ? "Could not mute the participant" : "Could not turn off the camera"
9555
+ );
9556
+ }
9557
+ function transcriptionStateFrom(value) {
9558
+ if (!value || typeof value !== "object") return null;
9559
+ const v2 = value;
9560
+ if (typeof v2.on !== "boolean") return null;
9561
+ return {
9562
+ on: v2.on,
9563
+ by_identity: typeof v2.by_identity === "string" ? v2.by_identity : null,
9564
+ by_name: typeof v2.by_name === "string" ? v2.by_name : null
9565
+ };
9566
+ }
9567
+ async function setCallTranscription(arbi, callExtId, on) {
9568
+ const data = await unwrapCall(
9569
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/transcription", {
9570
+ ...callPath(callExtId),
9571
+ body: { on }
9572
+ }),
9573
+ "Could not change transcription",
9574
+ { texts: { host_only: "Only the host can turn transcription on or off." } }
9575
+ );
9576
+ return transcriptionStateFrom(data);
9577
+ }
9578
+ function transcribeCallSegment(arbi, callExtId, params) {
9579
+ const ext = params.audio.type.includes("mp4") ? "m4a" : "webm";
9580
+ return unwrapCall(
9581
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/transcribe", {
9582
+ ...callPath(callExtId),
9583
+ // A multipart binary field is typed `string`; the runtime value is the Blob. openapi-fetch has
9584
+ // no multipart serialization, so build real FormData.
9585
+ body: {
9586
+ audio: params.audio,
9587
+ segment_id: params.segmentId,
9588
+ started_at: params.startedAt ?? null,
9589
+ link_version: params.linkVersion ?? null
9590
+ },
9591
+ bodySerializer: (body) => {
9592
+ const form = new FormData();
9593
+ form.append("audio", body.audio, `segment.${ext}`);
9594
+ form.append("segment_id", body.segment_id);
9595
+ if (body.started_at) form.append("started_at", body.started_at);
9596
+ if (body.link_version) form.append("link_version", String(body.link_version));
9597
+ appendTranscriptionHints(form, { language: params.language, prompt: params.prompt });
9598
+ return form;
9599
+ }
9600
+ }),
9601
+ "Could not transcribe",
9602
+ TRANSCRIBE
9603
+ );
9604
+ }
9605
+ function postChatTranscriptLine(arbi, chatExtId, body) {
9606
+ return unwrapCall(
9607
+ arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
9608
+ params: { path: { chat_ext_id: chatExtId } },
9609
+ body: { ...body, kind: "transcript", context_only: false }
9610
+ }),
9611
+ "Could not save the transcript",
9612
+ TRANSCRIBE
9613
+ );
9614
+ }
9615
+ function recordingStateFrom(value) {
9616
+ if (!value || typeof value !== "object") return null;
9617
+ const v2 = value;
9618
+ if (typeof v2.on !== "boolean") return null;
9619
+ const str2 = (x2) => typeof x2 === "string" && x2 ? x2 : null;
9620
+ return {
9621
+ on: v2.on,
9622
+ mode: v2.mode === "audio" || v2.mode === "audio_video" ? v2.mode : null,
9623
+ recording_ext_id: str2(v2.recording_ext_id),
9624
+ by_identity: str2(v2.by_identity),
9625
+ by_name: str2(v2.by_name),
9626
+ reason: str2(v2.reason),
9627
+ started_at: str2(v2.started_at)
9628
+ };
9629
+ }
9630
+ function recordingStateOfCall(call) {
9631
+ return recordingStateFrom(call.recording);
9632
+ }
9633
+ function quotaNeedsWarning(quota) {
9634
+ if (quota.near_limit) return true;
9635
+ return quota.remaining_mb != null && quota.remaining_mb < quota.min_start_mb;
9636
+ }
9637
+ function getRecordingQuota(arbi, callExtId) {
9638
+ return unwrapCall(
9639
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/recording/quota", callPath(callExtId)),
9640
+ "Could not read the storage quota",
9641
+ RECORDING
9642
+ );
9643
+ }
9644
+ async function startCallRecording(arbi, callExtId, mode) {
9645
+ const data = await unwrapCall(
9646
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recording", {
9647
+ ...callPath(callExtId),
9648
+ body: { mode }
9649
+ }),
9650
+ "Could not start recording",
9651
+ RECORDING
9652
+ );
9653
+ return recordingStateFrom(data);
9654
+ }
9655
+ async function stopCallRecording(arbi, callExtId) {
9656
+ const data = await unwrapCall(
9657
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recording/stop", callPath(callExtId)),
9658
+ "Could not stop recording",
9659
+ RECORDING
9660
+ );
9661
+ return recordingStateFrom(data);
9662
+ }
9663
+ function createRecordingTrack(arbi, callExtId, recordingExtId, body) {
9664
+ return unwrapCall(
9665
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks", {
9666
+ ...recPath(callExtId, recordingExtId),
9667
+ body
9668
+ }),
9669
+ "Could not start the recording track",
9670
+ RECORDING
9671
+ );
9672
+ }
9673
+ function presignRecordingPart(arbi, callExtId, recordingExtId, trackExtId, body) {
9674
+ return unwrapCall(
9675
+ arbi.fetch.POST(
9676
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks/{track_ext_id}/parts",
9677
+ { ...trackPath(callExtId, recordingExtId, trackExtId), body }
9678
+ ),
9679
+ "Could not upload a recording part",
9680
+ RECORDING
9681
+ );
9682
+ }
9683
+ async function commitRecordingPart(arbi, callExtId, recordingExtId, trackExtId, seq) {
9684
+ await unwrapCall(
9685
+ arbi.fetch.POST(
9686
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/tracks/{track_ext_id}/parts/{seq}/commit",
9687
+ {
9688
+ params: {
9689
+ path: {
9690
+ call_ext_id: callExtId,
9691
+ recording_ext_id: recordingExtId,
9692
+ track_ext_id: trackExtId,
9693
+ seq
9694
+ }
9695
+ }
9696
+ }
9697
+ ),
9698
+ "Could not commit a recording part",
9699
+ RECORDING
9700
+ );
9701
+ }
9702
+ function listCallRecordings(arbi, callExtId) {
9703
+ return unwrapCall(
9704
+ arbi.fetch.GET("/v1/calls/{call_ext_id}/recordings", callPath(callExtId)),
9705
+ "Could not list the recordings",
9706
+ RECORDING
9707
+ );
9708
+ }
9709
+ function getCallRecording(arbi, callExtId, recordingExtId) {
9710
+ return unwrapCall(
9711
+ arbi.fetch.GET(
9712
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}",
9713
+ recPath(callExtId, recordingExtId)
9714
+ ),
9715
+ "Could not open the recording",
9716
+ RECORDING
9717
+ );
9718
+ }
9719
+ function setRecordingExpiry(arbi, callExtId, recordingExtId, expiresAt) {
9720
+ return unwrapCall(
9721
+ arbi.fetch.PATCH("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}", {
9722
+ ...recPath(callExtId, recordingExtId),
9723
+ body: { expires_at: expiresAt }
9724
+ }),
9725
+ "Could not change the expiry",
9726
+ RECORDING
9727
+ );
9728
+ }
9729
+ function deleteRecordingMedia(arbi, callExtId, recordingExtId) {
9730
+ return unwrapCall(
9731
+ arbi.fetch.DELETE(
9732
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/media",
9733
+ recPath(callExtId, recordingExtId)
9734
+ ),
9735
+ "Could not delete the recording media",
9736
+ RECORDING
9737
+ );
9738
+ }
9739
+ async function deleteRecording(arbi, callExtId, recordingExtId) {
9740
+ await unwrapCall(
9741
+ arbi.fetch.DELETE(
9742
+ "/v1/calls/{call_ext_id}/recordings/{recording_ext_id}",
9743
+ recPath(callExtId, recordingExtId)
9744
+ ),
9745
+ "Could not delete the recording",
9746
+ RECORDING
9747
+ );
9748
+ }
9749
+ function transcribeRecordingPart(arbi, callExtId, recordingExtId, params) {
9750
+ const ext = params.audio.type.includes("wav") ? "wav" : params.audio.type.includes("mp4") ? "m4a" : "webm";
9751
+ const seq = params.seq ?? null;
9752
+ const segment = params.segment ?? null;
9753
+ const segmentOffsetMs = Math.max(0, Math.round(params.segmentOffsetMs ?? 0));
9754
+ return unwrapCall(
9755
+ arbi.fetch.POST("/v1/calls/{call_ext_id}/recordings/{recording_ext_id}/transcribe", {
9756
+ ...recPath(callExtId, recordingExtId),
9757
+ // A multipart binary field is typed `string`; the runtime value is the Blob. The generated
9758
+ // body types `seq` as required and lacks `language` / `prompt`: the serializer reads the real
9759
+ // values from `params`.
9760
+ body: {
9761
+ audio: params.audio,
9762
+ track_ext_id: params.trackExtId,
9763
+ seq: seq ?? 0,
9764
+ segment,
9765
+ segment_offset_ms: segmentOffsetMs
9766
+ },
9767
+ bodySerializer: (body) => {
9768
+ const form = new FormData();
9769
+ const name = seq != null ? `part-${seq}` : `piece-${segment ?? 0}`;
9770
+ form.append("audio", body.audio, `${name}.${ext}`);
9771
+ form.append("track_ext_id", body.track_ext_id);
9772
+ if (seq != null) form.append("seq", String(seq));
9773
+ if (segment != null) {
9774
+ form.append("segment", String(segment));
9775
+ form.append("segment_offset_ms", String(segmentOffsetMs));
9776
+ }
9777
+ appendTranscriptionHints(form, { language: params.language, prompt: params.prompt });
9778
+ return form;
9779
+ }
9780
+ }),
9781
+ "Could not transcribe the recording",
9782
+ { ...RECORDING, ...TRANSCRIBE }
9783
+ );
9784
+ }
9785
+ async function downloadRecordingPart(url) {
9786
+ const res = await fetch(url);
9787
+ if (!res.ok)
9788
+ throw new CallApiError(`Could not download the recording (${res.status})`, res.status);
9789
+ return new Uint8Array(await res.arrayBuffer());
9790
+ }
9791
+
9792
+ // src/arbi.ts
9793
+ function isAbort(error) {
9794
+ return error instanceof Error && error.name === "AbortError";
9795
+ }
9796
+ function tokenExpiresWithin(token, seconds) {
9797
+ const expiresAt = readSessionClaims(token)?.expiresAt;
9798
+ return expiresAt != null && expiresAt - Date.now() < seconds * 1e3;
9799
+ }
9800
+ var Arbi = class {
9801
+ client = null;
9802
+ loginResult = null;
9803
+ userProfile = null;
9804
+ profileListeners = /* @__PURE__ */ new Set();
9805
+ currentWorkspaceId = null;
9806
+ chatCryptoContext = null;
9807
+ /** The chat keys I hold, opened once per set of epochs (`chatRingSignature`). */
9808
+ chatRings = /* @__PURE__ */ new Map();
9809
+ sessionExpiredListeners = /* @__PURE__ */ new Set();
9810
+ signedInListeners = /* @__PURE__ */ new Set();
9811
+ /** The client is this instance's own (`init`), not a host's (`options.session`). */
9812
+ ownsClient = false;
9813
+ options;
9814
+ constructor(options) {
9815
+ this.options = options;
9816
+ if (options.session) {
9817
+ this.client = options.session.client;
9818
+ this.loginResult = options.session.login;
9819
+ this.userProfile = options.session.login?.profile ?? null;
9820
+ this.currentWorkspaceId = options.session.workspaceId ?? null;
9821
+ }
9822
+ }
9823
+ // ── Lifecycle ───────────────────────────────────────────────────────────
9824
+ /**
9825
+ * The deployment domain the user's keys are derived for: `deploymentDomain` when given,
9826
+ * otherwise the hostname of `url`. Signing and password changes re-derive keys with it, so a
9827
+ * host that needs it (the document tools' e-signing) reads it here rather than recomputing it.
9828
+ */
9829
+ getDeploymentDomain() {
9830
+ return this.options.deploymentDomain ?? new URL(this.options.url).hostname;
9831
+ }
9832
+ /** Initialize the SDK client and sodium crypto. Called automatically by login(). */
9833
+ async init() {
9834
+ if (this.client) return this.client;
9835
+ const domain = this.getDeploymentDomain();
9836
+ this.client = createArbiClient({
9837
+ baseUrl: this.options.url,
9838
+ deploymentDomain: domain,
9839
+ credentials: this.options.credentials ?? "omit",
9840
+ session: createSessionManager({ storage: this.options.sessionStorage }),
9841
+ // A silent re-login rotates the server session key: keep ours in step, or the next
9842
+ // workspace open would seal the key for a session the server no longer has.
9843
+ onReloginSuccess: ({ serverSessionKey }) => {
9844
+ if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
9845
+ }
9846
+ });
9847
+ this.ownsClient = true;
9848
+ this.client.auth.onSessionExpired(() => this.expireSession());
9849
+ await this.client.crypto.initSodium();
9850
+ return this.client;
9851
+ }
9852
+ /**
9853
+ * Request a verification email for registration. The user will receive an email with a link and
9854
+ * a 3-word verification code. Resolves to the server's confirmation; throws with its `detail`.
9855
+ */
9856
+ async requestVerification(email) {
9857
+ const client = await this.init();
9858
+ const { data, error, response } = await client.fetch.POST("/v1/user/verify-email", {
9859
+ body: { email }
9860
+ });
9861
+ if (error || !data) throw authRequestError("Verification", error, response.status);
9862
+ return data.detail;
9863
+ }
9864
+ /**
9865
+ * Register a new account with the verification code received by email (or, for an SSO account,
9866
+ * the provider's token as `verificationCode`). Resolves to the new identity key, for the recovery
9867
+ * key backup. Does not sign in: `login` follows.
9868
+ */
9869
+ async register(params) {
9870
+ const client = await this.init();
9871
+ return client.auth.register(params);
9872
+ }
9873
+ /**
9874
+ * Log in with email and password (and the SSO provider's token for an SSO account). Signs the
9875
+ * session in; resolves to the login, its response included. Initializes the client if needed.
9876
+ */
9877
+ async login(email, password, options = {}) {
9878
+ const client = await this.init();
9879
+ return this.signedIn(await client.auth.login({ email, password, ...options }));
9880
+ }
9881
+ /** This instance signed in (`login`, `loginWithKey`, `restore`, an SSO sign-in). */
9882
+ signedIn(login) {
9883
+ this.loginResult = login;
9884
+ this.userProfile = login.profile ?? null;
9885
+ for (const listener of [...this.signedInListeners]) listener(login);
9886
+ return login;
9887
+ }
9888
+ /**
9889
+ * Be told when this instance signs in, by whatever path (a sign-in page, a restored session).
9890
+ * Returns an unsubscribe.
9891
+ */
9892
+ onSignedIn(listener) {
9893
+ this.signedInListeners.add(listener);
9894
+ return () => this.signedInListeners.delete(listener);
9895
+ }
9896
+ /**
9897
+ * Sign in on this device while offline: the password must open the identity saved here at the
9898
+ * last login (see `ArbiClient.auth.unlock`).
9899
+ */
9900
+ async unlock(email, password) {
9901
+ const client = await this.init();
9902
+ await client.auth.unlock({ email, password });
9903
+ }
9904
+ /**
9905
+ * Single sign-on, after the provider (Auth0) signed the user in and handed over its token. The
9906
+ * account still has its own master password (the keys are derived from it); the provider's token
9907
+ * proves the identity:
9908
+ * - `status`: is there an account for this email, and how does it sign in (`new_user`,
9909
+ * `sso_exists`, `local_exists`), with the names the server knows;
9910
+ * - `register`: a new account (the token stands in for the verification code); resolves with the
9911
+ * identity key, for its backup; `login` follows (with the provider's name and picture);
9912
+ * - `login`: an SSO account signs in; `link`: a password account signs in with the token and is
9913
+ * linked to SSO from then on;
9914
+ * - `resendVerification`: the provider's verification email again (its user id).
9915
+ */
9916
+ sso = {
9917
+ status: async (params) => {
9918
+ const client = await this.init();
9919
+ const { data, error, response } = await client.fetch.POST("/v1/user/sso-status", {
9920
+ body: { sso_token: params.token, email: params.email, picture: params.picture }
9921
+ });
9922
+ if (error || !data) throw authRequestError("SSO status", error, response.status);
9923
+ return data;
9924
+ },
9925
+ register: (params) => this.register({
9926
+ email: params.email,
9927
+ password: params.password,
9928
+ verificationCode: params.token,
9929
+ firstName: params.firstName,
9930
+ lastName: params.lastName,
9931
+ picture: params.picture ?? void 0
9932
+ }),
9933
+ login: (params) => this.login(params.email, params.password, {
9934
+ ssoToken: params.token,
9935
+ profile: params.profile
9936
+ }),
9937
+ link: (params) => this.login(params.email, params.password, { ssoToken: params.token }),
9938
+ resendVerification: async (providerUserId) => {
9939
+ const client = await this.init();
9940
+ const { data, error, response } = await client.fetch.POST(
9941
+ "/v1/user/sso-send-verification-email",
9942
+ { body: { auth0_id: providerUserId } }
9943
+ );
9944
+ if (error || !data) throw authRequestError("Verification email", error, response.status);
9945
+ return data.detail ?? "";
9946
+ }
9947
+ };
9948
+ /**
9949
+ * Sign in with the account's identity key itself (a recovery key, a stored key; bytes or base64)
9950
+ * instead of the password. Resolves to the login, its response included.
9951
+ */
9952
+ async loginWithKey(email, signingPrivateKey, options = {}) {
9953
+ const client = await this.init();
9954
+ return this.signedIn(
9955
+ await client.auth.loginWithKey({
9956
+ email,
9957
+ signingPrivateKey: typeof signingPrivateKey === "string" ? client.crypto.base64ToBytes(signingPrivateKey) : signingPrivateKey,
9958
+ ...options
9959
+ })
9960
+ );
9961
+ }
9962
+ /**
9963
+ * Sign in again from the session kept on this device (`sessionStorage`): the account signed in
9964
+ * last, with its identity key from the encrypted store. False, and the kept session dropped,
9965
+ * when there is none to restore.
9966
+ */
9967
+ async restore() {
9968
+ const client = await this.init();
9969
+ const { signedIn, userEmail } = client.session.getState();
9970
+ if (!signedIn || !userEmail) return false;
9971
+ const saved = await client.storage.getSession().catch(() => null);
9972
+ if (!saved?.signingPrivateKey) {
9973
+ client.session.clear();
9974
+ return false;
9975
+ }
9976
+ await this.loginWithKey(userEmail, saved.signingPrivateKey);
9977
+ return true;
9978
+ }
9979
+ /**
9980
+ * Run `withKey` with the workspace's wrapped key (the client's, from the lists it has seen). A
9981
+ * remembered key that no longer works (access was re-granted with a new key) is read again and
9982
+ * the call retried once. Throws for a public workspace the user holds no key for.
9983
+ */
9984
+ async withWrappedKey(workspaceId, withKey) {
9985
+ const keys = this.requireClient().workspaceKeys;
9986
+ const required = (key) => {
9987
+ if (!key) throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
9988
+ return key;
9989
+ };
9990
+ const { wrappedKey, fromCache } = await keys.wrappedKey(workspaceId).catch((error) => {
9991
+ throw new ArbiError(error instanceof Error ? error.message : String(error));
9992
+ });
9993
+ try {
9994
+ return await withKey(required(wrappedKey));
9995
+ } catch (error) {
9996
+ if (!fromCache) throw error;
9997
+ const fresh = await keys.wrappedKey(workspaceId, { refresh: true });
9998
+ return withKey(required(fresh.wrappedKey));
9999
+ }
10000
+ }
10001
+ /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
10002
+ async sealWorkspaceKey(workspaceId) {
10003
+ const client = this.requireClient();
10004
+ const lr2 = this.requireLogin();
9076
10005
  return this.withWrappedKey(
9077
10006
  workspaceId,
9078
10007
  (wrappedKey) => generateEncryptedWorkspaceKey(
@@ -9085,28 +10014,13 @@ var Arbi = class {
9085
10014
  }
9086
10015
  /**
9087
10016
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
9088
- * the server or here): its key, sealed to this server session, is deposited with `/prime-key`.
9089
- * Idempotent: cached per server session (a re-login rotates it), concurrent calls share one
9090
- * request, and the current workspace is already open.
10017
+ * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
10018
+ * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
9091
10019
  */
9092
10020
  openWorkspace(workspaceId) {
9093
10021
  if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
9094
- const lr2 = this.requireLogin();
9095
- if (this.openedForSessionKey !== lr2.serverSessionKey) {
9096
- this.openedWorkspaces.clear();
9097
- this.openedForSessionKey = lr2.serverSessionKey;
9098
- }
9099
- const cached = this.openedWorkspaces.get(workspaceId);
9100
- if (cached) return cached;
9101
- const opening = this.sealWorkspaceKey(workspaceId).then(
9102
- (sealedKey) => primeWorkspaceKey(this.requireClient(), workspaceId, sealedKey)
9103
- );
9104
- this.openedWorkspaces.set(workspaceId, opening);
9105
- opening.catch(() => {
9106
- if (this.openedWorkspaces.get(workspaceId) === opening)
9107
- this.openedWorkspaces.delete(workspaceId);
9108
- });
9109
- return opening;
10022
+ this.requireLogin();
10023
+ return this.requireClient().workspaceKeys.prime(workspaceId);
9110
10024
  }
9111
10025
  /** The workspace a call names, opened for this session; `undefined` for the current one. */
9112
10026
  async targetWorkspace(workspaceId) {
@@ -9117,35 +10031,50 @@ var Arbi = class {
9117
10031
  /**
9118
10032
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
9119
10033
  * session's active workspace) and record it in the session. This is navigation: only the host's
9120
- * workspace switch calls it. Package code that needs another workspace calls
9121
- * `workspaces.open(id)` and passes the workspace to the request instead.
10034
+ * workspace switch (`useSwitchWorkspace` in `@arbidocs/react`) calls it. Package code that needs
10035
+ * another workspace calls `workspaces.open(id)` and passes the workspace to the request instead.
10036
+ *
10037
+ * Returns what the server opened: the workspace with its conversations and tags (not its
10038
+ * documents, which are listed page by page). A public workspace has no key and opens without one.
9122
10039
  */
9123
10040
  async selectWorkspace(workspaceId) {
9124
10041
  const client = this.requireClient();
9125
10042
  const lr2 = this.requireLogin();
9126
- const signingPrivateKeyBase64 = client.crypto.bytesToBase64(lr2.signingPrivateKey);
9127
- await this.withWrappedKey(workspaceId, async (wrappedKey) => {
9128
- const sealedKey = await selectWorkspace(
9129
- client,
9130
- workspaceId,
9131
- wrappedKey,
9132
- lr2.serverSessionKey,
9133
- signingPrivateKeyBase64
9134
- );
10043
+ const open = async (workspaceKey) => requireData(
9135
10044
  await client.fetch.POST("/v1/workspace/{workspace_ext_id}/open", {
9136
- params: { path: { workspace_ext_id: workspaceId } },
9137
- body: { workspace_key: sealedKey }
9138
- });
10045
+ params: { path: { workspace_ext_id: workspaceId }, query: { include_documents: false } },
10046
+ body: { workspace_key: workspaceKey }
10047
+ }),
10048
+ `Failed to open workspace ${workspaceId}`
10049
+ );
10050
+ const listed = await client.workspaceKeys.wrappedKey(workspaceId).catch((error) => {
10051
+ throw new ArbiError(error instanceof Error ? error.message : String(error));
9139
10052
  });
10053
+ const opened = !listed.wrappedKey ? await open("") : await this.withWrappedKey(
10054
+ workspaceId,
10055
+ async (wrappedKey) => open(
10056
+ await selectWorkspace(
10057
+ client,
10058
+ workspaceId,
10059
+ wrappedKey,
10060
+ lr2.serverSessionKey,
10061
+ client.crypto.bytesToBase64(lr2.signingPrivateKey)
10062
+ )
10063
+ )
10064
+ );
10065
+ client.session.setSelectedWorkspace(workspaceId);
9140
10066
  this.currentWorkspaceId = workspaceId;
10067
+ return opened;
9141
10068
  }
9142
10069
  /**
9143
10070
  * Subscribe to "the session cannot be recovered". Fires when a request failed with 401 or
9144
10071
  * "No active workspace" and neither a workspace re-open nor a silent re-login was possible
9145
10072
  * (the server refused; an unreachable server does not fire). The local session is already
9146
10073
  * cleared when it fires: show "Your session expired, sign in again". Returns an unsubscribe.
10074
+ * On a host's session it is the host client's expiry.
9147
10075
  */
9148
10076
  onSessionExpired(listener) {
10077
+ if (this.client && !this.ownsClient) return this.client.auth.onSessionExpired(listener);
9149
10078
  this.sessionExpiredListeners.add(listener);
9150
10079
  return () => this.sessionExpiredListeners.delete(listener);
9151
10080
  }
@@ -9157,16 +10086,15 @@ var Arbi = class {
9157
10086
  this.loginResult = null;
9158
10087
  this.userProfile = null;
9159
10088
  this.currentWorkspaceId = null;
9160
- this.wrappedKeys.clear();
9161
10089
  this.chatCryptoContext = null;
9162
10090
  this.chatRings.clear();
9163
- this.client?.session.clear();
9164
10091
  for (const listener of [...this.sessionExpiredListeners]) listener();
9165
10092
  }
9166
10093
  /**
9167
10094
  * Run a raw-fetch operation (streaming, multipart: no middleware) and, when it fails because
9168
10095
  * the token expired or the server lost the open workspace, recover once and run it again.
9169
- * `run` must read the auth headers itself so the retry carries the fresh token.
10096
+ * `run` must read the auth headers itself so the retry carries the fresh token. The client's
10097
+ * re-login is the one recovery: a refused one has already ended the session (`onSessionExpired`).
9170
10098
  */
9171
10099
  async recovering(run) {
9172
10100
  if (this.client && tokenExpiresWithin(this.client.session.getState().accessToken, 30)) {
@@ -9181,10 +10109,7 @@ var Arbi = class {
9181
10109
  if (!(error instanceof ArbiApiError) || !(noWorkspace || unauthorised)) throw error;
9182
10110
  const client = this.requireClient();
9183
10111
  const recovered = noWorkspace && await client.auth.reopenWorkspace() || await client.auth.relogin() !== null;
9184
- if (!recovered) {
9185
- this.expireSession();
9186
- throw new ArbiSessionExpiredError();
9187
- }
10112
+ if (!recovered) throw new ArbiSessionExpiredError();
9188
10113
  return run();
9189
10114
  }
9190
10115
  }
@@ -9192,10 +10117,14 @@ var Arbi = class {
9192
10117
  this.userProfile = profile;
9193
10118
  for (const listener of [...this.profileListeners]) listener(profile);
9194
10119
  }
9195
- /** Log out and clear internal state. */
9196
- async logout() {
10120
+ /**
10121
+ * Sign out: the server session ends (every session of the user with `everywhere`), the session
10122
+ * state is cleared and, with `everywhere`, so are the keys kept on this device (a single sign-out
10123
+ * keeps them for an offline unlock). Then this instance's own state is cleared.
10124
+ */
10125
+ async logout(options = {}) {
9197
10126
  if (this.client) {
9198
- await this.client.auth.logout();
10127
+ await this.client.auth.logout(options);
9199
10128
  }
9200
10129
  if (this.loginResult) {
9201
10130
  this.loginResult.signingPrivateKey.fill(0);
@@ -9204,11 +10133,17 @@ var Arbi = class {
9204
10133
  this.loginResult = null;
9205
10134
  this.userProfile = null;
9206
10135
  this.currentWorkspaceId = null;
9207
- this.wrappedKeys.clear();
9208
10136
  this.chatCryptoContext = null;
9209
10137
  this.chatRings.clear();
9210
10138
  }
9211
10139
  // ── Accessors ─────────────────────────────────────────────────────────
10140
+ /**
10141
+ * The session state this instance runs on (token, user, SSO mode, signed in), to read and
10142
+ * subscribe to; `null` before a client exists.
10143
+ */
10144
+ get session() {
10145
+ return this.client?.session ?? null;
10146
+ }
9212
10147
  /** Get the underlying ArbiClient (throws if not initialized). */
9213
10148
  getClient() {
9214
10149
  return this.requireClient();
@@ -9436,9 +10371,26 @@ var Arbi = class {
9436
10371
  * Idempotent and cached per server session. Navigation uses `selectWorkspace`.
9437
10372
  */
9438
10373
  open: (workspaceId) => this.openWorkspace(workspaceId),
10374
+ /**
10375
+ * A workspace's key sealed to this server session: what `POST /workspace/users` takes to give
10376
+ * someone (an agent) access, and what `/prime-key` deposits. Throws when the user holds no key
10377
+ * for it (a public workspace, or one they can see but never joined).
10378
+ */
10379
+ sealKey: (workspaceId) => this.sealWorkspaceKey(workspaceId),
10380
+ /**
10381
+ * A workspace's raw key, unwrapped with my identity (for content I encrypt under it myself,
10382
+ * such as a thread call's recording). Never sent anywhere.
10383
+ */
10384
+ key: (workspaceId) => this.withWrappedKey(
10385
+ workspaceId,
10386
+ async (wrappedKey) => unwrapWorkspaceKey(wrappedKey, this.requireLogin().signingPrivateKey)
10387
+ ),
9439
10388
  /** Hand this server session a workspace's key (sealed to the session) without opening it. */
9440
10389
  primeKey: (workspaceExtId, sessionSealedKey) => primeWorkspaceKey(this.requireClient(), workspaceExtId, sessionSealedKey),
9441
- list: async () => this.rememberWorkspaces(await listWorkspaces(this.requireClient())),
10390
+ list: async () => {
10391
+ const client = this.requireClient();
10392
+ return client.workspaceKeys.remember(await listWorkspaces(client));
10393
+ },
9442
10394
  create: async (name, projectExtId, description, isPublic) => {
9443
10395
  const client = this.requireClient();
9444
10396
  const lr2 = this.requireLogin();
@@ -9455,12 +10407,12 @@ var Arbi = class {
9455
10407
  description,
9456
10408
  isPublic
9457
10409
  );
9458
- this.rememberWorkspaces([created]);
10410
+ client.workspaceKeys.remember([created]);
9459
10411
  return created;
9460
10412
  },
9461
10413
  delete: async (workspaceIds) => {
9462
10414
  await deleteWorkspaces(this.requireClient(), workspaceIds);
9463
- for (const id of workspaceIds) this.wrappedKeys.delete(id);
10415
+ this.requireClient().workspaceKeys.forget(workspaceIds);
9464
10416
  },
9465
10417
  update: (body) => updateWorkspace(this.requireClient(), body),
9466
10418
  listUsers: () => listWorkspaceUsers(this.requireClient()),
@@ -9534,7 +10486,28 @@ var Arbi = class {
9534
10486
  targetWorkspaceId,
9535
10487
  docIds,
9536
10488
  targetWorkspaceKey
9537
- )
10489
+ ),
10490
+ /**
10491
+ * Download, copy or move a scope of the current workspace (`/v1/workspace/transfer*`): plan it,
10492
+ * run a copy or move into another workspace as a background job (its key is sealed here), follow,
10493
+ * resume or cancel the job, or export the scope's data for a download.
10494
+ */
10495
+ transfer: {
10496
+ plan: (scope, mode) => planWorkspaceTransfer(this.requireClient(), scope, mode),
10497
+ start: async (params) => startWorkspaceTransfer(this.requireClient(), {
10498
+ ...params,
10499
+ targetWorkspaceKey: await this.sealWorkspaceKey(params.targetWorkspaceId)
10500
+ }),
10501
+ resume: async (transferId, targetWorkspaceId) => resumeWorkspaceTransfer(
10502
+ this.requireClient(),
10503
+ transferId,
10504
+ await this.sealWorkspaceKey(targetWorkspaceId)
10505
+ ),
10506
+ cancel: (transferId) => cancelWorkspaceTransfer(this.requireClient(), transferId),
10507
+ get: (transferId) => getWorkspaceTransfer(this.requireClient(), transferId),
10508
+ list: () => listWorkspaceTransfers(this.requireClient()),
10509
+ exportData: (scope) => exportWorkspaceData(this.requireClient(), scope)
10510
+ }
9538
10511
  };
9539
10512
  // ── Documents ─────────────────────────────────────────────────────────
9540
10513
  documents = {
@@ -9653,7 +10626,10 @@ var Arbi = class {
9653
10626
  },
9654
10627
  getMessage: (messageId) => getMessage(this.requireClient(), messageId),
9655
10628
  deleteMessage: (messageId) => deleteMessage(this.requireClient(), messageId),
9656
- /** Post a human comment (no assistant run) — see `postConversationMessage`. */
10629
+ /**
10630
+ * Post a human comment (no assistant run) — see `postConversationMessage`. A thread in another
10631
+ * workspace than the current one works too: its key is handed to the session on demand.
10632
+ */
9657
10633
  postMessage: (body) => postConversationMessage(this.requireClient(), body),
9658
10634
  setAssistantMode: (conversationId, assistantMode) => updateConversationAssistantMode(
9659
10635
  this.requireClient(),
@@ -9737,7 +10713,79 @@ var Arbi = class {
9737
10713
  };
9738
10714
  // ── Assistant ─────────────────────────────────────────────────────────
9739
10715
  assistant = {
9740
- cancelRun: (responseId) => this.recovering(() => cancelAssistantRun(this.getAuthHeaders(), responseId)),
10716
+ /**
10717
+ * Ask the assistant: send one turn (the body is `buildTurnRequest`) and stream it into
10718
+ * `handlers`. Resolves with the accumulated result when the stream ends.
10719
+ *
10720
+ * The token is renewed before a long stream starts and once on a 401. A refusal (402 quota,
10721
+ * 409, 503, …) reaches `onError` as the server's words, a 402 quota also `onQuotaExceeded`,
10722
+ * and `ask` rejects with it; a dropped connection reaches `onError` as the `Error` and rejects
10723
+ * with it; an abort just rejects.
10724
+ */
10725
+ ask: async (request, handlers = {}) => {
10726
+ const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
10727
+ const body = buildTurnRequest({
10728
+ ...request,
10729
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
10730
+ });
10731
+ const refuse = (message, error = new Error(message)) => {
10732
+ onError?.(message);
10733
+ throw error;
10734
+ };
10735
+ let response;
10736
+ try {
10737
+ response = await this.recovering(
10738
+ () => openTurnStream(this.getAuthHeaders(), body, signal)
10739
+ );
10740
+ } catch (error) {
10741
+ if (isAbort(error)) throw error;
10742
+ if (error instanceof AssistantTurnRefused) {
10743
+ if (error.quota) onQuotaExceeded?.(error.quota);
10744
+ return refuse(error.message);
10745
+ }
10746
+ if (error instanceof ArbiSessionExpiredError || error instanceof ArbiApiError && error.status === 401) {
10747
+ const message = SESSION_EXPIRED_MESSAGE;
10748
+ return refuse(message, new ArbiSessionExpiredError(message));
10749
+ }
10750
+ onError?.(error);
10751
+ throw error;
10752
+ }
10753
+ try {
10754
+ return await streamSSE(response, {
10755
+ ...callbacks,
10756
+ onError: (message) => onError?.(message),
10757
+ onArbiError: (event) => {
10758
+ const quota = quotaExceededFrom(event);
10759
+ if (quota) onQuotaExceeded?.(quota);
10760
+ }
10761
+ });
10762
+ } catch (error) {
10763
+ if (!isAbort(error)) onError?.(error);
10764
+ throw error;
10765
+ }
10766
+ },
10767
+ /**
10768
+ * Attach to a running turn by its response id: replays its frames so far, then tails the live
10769
+ * ones until it ends. Rejects when the run is no longer active ("This run is no longer active.").
10770
+ */
10771
+ attachRun: async (responseId, handlers = {}) => {
10772
+ const { signal, ...callbacks } = handlers;
10773
+ const response = await this.recovering(
10774
+ () => openRunStream(this.getAuthHeaders(), responseId, signal)
10775
+ );
10776
+ return streamSSE(response, callbacks);
10777
+ },
10778
+ /**
10779
+ * Interject into a running turn: answer its question, steer it, or send a run-control command
10780
+ * (`/pause`, `/resume`, `/report`).
10781
+ */
10782
+ interject: (assistantMessageExtId, answer) => interject(this.requireClient(), assistantMessageExtId, answer),
10783
+ /** Stop a run on the server (closing its stream alone leaves it running). */
10784
+ cancel: (responseId) => this.recovering(() => cancelRun(this.getAuthHeaders(), responseId)),
10785
+ /** The backend's built-in slash commands (`/compact`, `/goal`, …), for a slash menu. */
10786
+ commands: () => listCommands(this.requireClient()),
10787
+ /** Transcribe a voice recording to text (empty when no speech was found). */
10788
+ transcribe: (audio) => transcribe(this.requireClient(), audio),
9741
10789
  /** Start a durable background turn; task options make its thread a work item. */
9742
10790
  submit: (question, options) => {
9743
10791
  const workspaceId = this.requireWorkspace();
@@ -9752,47 +10800,6 @@ var Arbi = class {
9752
10800
  },
9753
10801
  /** Read the status of a background turn. */
9754
10802
  getResponse: (id) => this.recovering(() => getResponse(this.getAuthHeaders(), id)),
9755
- /**
9756
- * Send a question to the RAG assistant with streaming support.
9757
- * Returns the accumulated result after the stream completes.
9758
- */
9759
- query: async (question, options) => {
9760
- const workspaceId = options.workspaceId ?? this.requireWorkspace();
9761
- const response = await this.recovering(
9762
- () => queryAssistant({
9763
- ...this.getAuthHeaders(),
9764
- workspaceId,
9765
- question,
9766
- agentId: options.agentId,
9767
- docIds: options.docIds,
9768
- previousResponseId: options.previousResponseId,
9769
- conversationId: options.conversationId,
9770
- assistantMode: options.assistantMode,
9771
- mentions: options.mentions,
9772
- model: options.model,
9773
- activeArtifactExtId: options.activeArtifactExtId,
9774
- signal: options.signal
9775
- })
9776
- );
9777
- const callbacks = {
9778
- onToken: options.onToken,
9779
- onStreamStart: options.onStreamStart,
9780
- onOutputItemDone: options.onOutputItemDone,
9781
- onError: options.onError,
9782
- onUserMessage: options.onUserMessage,
9783
- onMetadata: options.onMetadata,
9784
- onUserInputRequest: options.onUserInputRequest,
9785
- onArtifact: options.onArtifact,
9786
- onMailDraft: options.onMailDraft,
9787
- onElapsedTime: options.onElapsedTime,
9788
- onComplete: options.onComplete
9789
- };
9790
- return streamSSE(response, callbacks);
9791
- },
9792
- /**
9793
- * Respond to an agent's question during a human-in-the-loop workflow.
9794
- */
9795
- respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
9796
10803
  /** The skills the caller can run (own + shared marketplace), metadata only. */
9797
10804
  listSkills: (options) => listSkills(this.requireClient(), options),
9798
10805
  /**
@@ -9809,10 +10816,10 @@ var Arbi = class {
9809
10816
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
9810
10817
  * workspace; `searchChunks(result)` ranks the passages found.
9811
10818
  */
9812
- retrieve: (query, docIds, options) => retrieve({
10819
+ retrieve: (query2, docIds, options) => retrieve({
9813
10820
  arbi: this.requireClient(),
9814
10821
  workspaceId: this.requireWorkspace(),
9815
- query,
10822
+ query: query2,
9816
10823
  docIds,
9817
10824
  ...options
9818
10825
  })
@@ -9824,7 +10831,7 @@ var Arbi = class {
9824
10831
  * each tag's documents, facts and threads: `list({ kind: 'issue', include: ['links'] })` is the
9825
10832
  * issue table's rows (its columns: `tagKinds.get('issue')`).
9826
10833
  */
9827
- list: (query) => listTags(this.requireClient(), query),
10834
+ list: (query2) => listTags(this.requireClient(), query2),
9828
10835
  create: (options) => createTag(this.requireClient(), {
9829
10836
  ...options,
9830
10837
  workspaceId: options.workspaceId ?? this.requireWorkspace()
@@ -9920,7 +10927,7 @@ var Arbi = class {
9920
10927
  listHolidayCountries: () => this.withCalendarKeys((c2) => listHolidayCountries(c2)),
9921
10928
  addHolidays: (body) => this.withCalendarKeys((c2) => addHolidayCalendar(c2, body)),
9922
10929
  createRoom: (body) => this.withCalendarKeys((c2) => createRoom(c2, body)),
9923
- listRooms: (query) => this.withCalendarKeys((c2) => listRooms(c2, query)),
10930
+ listRooms: (query2) => this.withCalendarKeys((c2) => listRooms(c2, query2)),
9924
10931
  freeBusy: (body) => this.withCalendarKeys((c2) => getFreeBusy(c2, body)),
9925
10932
  findTime: (body) => this.withCalendarKeys((c2) => findTime(c2, body)),
9926
10933
  /**
@@ -10089,6 +11096,223 @@ var Arbi = class {
10089
11096
  /** Fetch, decrypt and size-check one attachment. */
10090
11097
  downloadAttachment: (file) => downloadChatAttachment(this.requireClient(), file)
10091
11098
  };
11099
+ // ── Calls ─────────────────────────────────────────────────────────────
11100
+ /** My copy of a call's key K from its row (sealed to me as creator or invitee), or null. */
11101
+ async callKeyOf(call) {
11102
+ return openCallKeyOf(call, (await this.requireChatCrypto()).encryptionKeypair.secretKey);
11103
+ }
11104
+ /** A call's title under K, in plaintext; null when it has none or it does not open. */
11105
+ async callTitleOf(call, key) {
11106
+ if (!call.title || !key) return null;
11107
+ return decryptCallTitle(call.title, key);
11108
+ }
11109
+ /**
11110
+ * Calls (LiveKit): one call system for thread, chat (DM / group), contacts and scheduled calls.
11111
+ * Each call has one random key K made in the creator's process; the server and the media server
11112
+ * only ever hold it sealed to people (or in a link's fragment). `start`, `open`, `answer` and
11113
+ * `resetLink` do the key work and hand back K with the call; everything else moves ciphertext.
11114
+ */
11115
+ calls = {
11116
+ /** The deployment's calls config (`enabled`, `transcription_available`, …). */
11117
+ config: () => getCallsConfig(this.requireClient()),
11118
+ get: (callExtId) => getCall(this.requireClient(), callExtId),
11119
+ /** Create a call row as is (a scheduled call's ciphertext made by the caller). */
11120
+ create: (body) => createCall(this.requireClient(), body),
11121
+ update: (callExtId, body) => updateCall(this.requireClient(), callExtId, body),
11122
+ cancel: (callExtId) => cancelCall(this.requireClient(), callExtId),
11123
+ /**
11124
+ * Start a call: a fresh K sealed to me and to each of `invitees` (people without a key are
11125
+ * skipped), the title under K. Returns K and `sealedKeys` (K per invitee: what `ring` takes).
11126
+ * A thread call is get-or-create: when the thread already has a running call, that one comes
11127
+ * back with my copy of its key, and `sealedKeys` are sealed to its key instead.
11128
+ *
11129
+ * A scheduled call has no thread or chat; a webinar (`mode: 'webinar'`) gives each invitee
11130
+ * their `roles` entry (attendee by default).
11131
+ */
11132
+ start: async (params) => {
11133
+ const client = this.requireClient();
11134
+ const me2 = await this.requireChatCrypto();
11135
+ const fresh = await generateCallKey();
11136
+ const sealed = await sealCallKeyForPeers(fresh, params.invitees, me2.userExtId);
11137
+ const roles = params.roles;
11138
+ const title = params.title?.trim();
11139
+ const call = await createCall(client, {
11140
+ ...params.threadExtId ? { thread_ext_id: params.threadExtId } : {},
11141
+ ...params.chatExtId ? { chat_ext_id: params.chatExtId } : {},
11142
+ mode: params.mode ?? "call",
11143
+ ...params.joinPolicy ? { join_policy: params.joinPolicy } : {},
11144
+ title: title ? await encryptCallTitle(title, fresh) : null,
11145
+ creator_sealed_key: await sealCallKey(fresh, bytesToBase64(me2.encryptionKeypair.publicKey)),
11146
+ invitees: Object.entries(sealed).map(([user_ext_id, sealed_key]) => ({
11147
+ user_ext_id,
11148
+ sealed_key,
11149
+ ...roles ? { role: roles[user_ext_id] ?? "attendee" } : {}
11150
+ }))
11151
+ });
11152
+ const reused = call.created === false;
11153
+ const key = reused ? await this.callKeyOf(call) : fresh;
11154
+ if (!key) throw new ArbiError("No key for the running call on this thread");
11155
+ const sealedKeys = reused ? await sealCallKeyForPeers(key, params.invitees, me2.userExtId) : sealed;
11156
+ return {
11157
+ call,
11158
+ key,
11159
+ title: await this.callTitleOf(call, key) ?? title ?? null,
11160
+ sealedKeys
11161
+ };
11162
+ },
11163
+ /**
11164
+ * Open a call by id (a link, the calendar, a notification): K from the link fragment when
11165
+ * given, else my sealed copy. Refuses a cancelled call and a call I hold no key for.
11166
+ */
11167
+ open: async (callExtId, linkKey) => {
11168
+ const call = await getCall(this.requireClient(), callExtId);
11169
+ if (call.cancelled)
11170
+ throw new CallApiError("This call was cancelled.", 410, "cancelled");
11171
+ const key = linkKey ?? await this.callKeyOf(call);
11172
+ if (!key) {
11173
+ throw new ArbiError("Open the full call link (it carries the key) to join this call.");
11174
+ }
11175
+ return { call, key, title: await this.callTitleOf(call, key) };
11176
+ },
11177
+ /** My copy of a call's K from its row, or null. */
11178
+ key: (call) => this.callKeyOf(call),
11179
+ /** A call's title in plaintext under K; null when it has none or it does not open. */
11180
+ title: (call, key) => this.callTitleOf(call, key),
11181
+ /** K sealed to each peer with a key (not to me): what `ring` and invitations take. */
11182
+ sealFor: async (key, peers) => sealCallKeyForPeers(key, peers, (await this.requireChatCrypto()).userExtId),
11183
+ /** Answer a ring: open K from its sealed blob and fetch a room token. */
11184
+ answer: async (ring) => {
11185
+ const me2 = await this.requireChatCrypto();
11186
+ const key = await openSealedCallKey(ring.sealed_key, me2.encryptionKeypair.secretKey);
11187
+ const token = await fetchCallToken(
11188
+ this.requireClient(),
11189
+ ring.call_ext_id,
11190
+ ring.link_version
11191
+ );
11192
+ return { key, token, title: ring.title ? await decryptCallTitle(ring.title, key) : null };
11193
+ },
11194
+ /**
11195
+ * A new link for a call I created: a fresh K re-sealed to me and every invitee with a key, the
11196
+ * title re-encrypted, and `link_version` bumped server-side so the old link stops working.
11197
+ */
11198
+ resetLink: async (call, title, invitees) => {
11199
+ const me2 = await this.requireChatCrypto();
11200
+ const key = await generateCallKey();
11201
+ const updated = await updateCall(this.requireClient(), call.external_id, {
11202
+ reset_link: true,
11203
+ creator_sealed_key: await sealCallKey(key, bytesToBase64(me2.encryptionKeypair.publicKey)),
11204
+ sealed_keys: await sealCallKeyForPeers(key, invitees, me2.userExtId),
11205
+ title: title ? await encryptCallTitle(title, key) : null
11206
+ });
11207
+ return { call: updated, key };
11208
+ },
11209
+ /**
11210
+ * Make a call's E2E meeting chat now: a fresh chat key sealed to me and to every member, and K
11211
+ * sealed to each member so they can always join. The existing chat when the call has one.
11212
+ */
11213
+ createChat: async (params) => {
11214
+ const me2 = await this.requireChatCrypto();
11215
+ const members = params.members.filter(
11216
+ (m2) => !!m2.encryption_public_key && m2.external_id !== me2.userExtId
11217
+ );
11218
+ const chatKey = await generateChatKey();
11219
+ try {
11220
+ const title = params.title?.trim();
11221
+ return await getOrCreateCallChat(this.requireClient(), params.callExtId, {
11222
+ title: title ? await encryptWithChatKey(title, chatKey) : null,
11223
+ creator_sealed_key: await sealChatKey(
11224
+ chatKey,
11225
+ bytesToBase64(me2.encryptionKeypair.publicKey)
11226
+ ),
11227
+ members: await Promise.all(
11228
+ members.map(async (m2) => ({
11229
+ user_ext_id: m2.external_id,
11230
+ sealed_key: await sealChatKey(chatKey, m2.encryption_public_key),
11231
+ call_sealed_key: await sealCallKey(params.callKey, m2.encryption_public_key)
11232
+ }))
11233
+ )
11234
+ });
11235
+ } finally {
11236
+ chatKey.fill(0);
11237
+ }
11238
+ },
11239
+ /** The call's meeting chat as is, made with `body` (an E2E chat) when it has none yet. */
11240
+ chat: (callExtId, body) => getOrCreateCallChat(this.requireClient(), callExtId, body),
11241
+ /** A room token; `inviteToken` (a personal invite link's `?i=`) admits with no lobby. */
11242
+ token: (callExtId, linkVersion, inviteToken) => fetchCallToken(this.requireClient(), callExtId, linkVersion, inviteToken),
11243
+ /** Ring users: `sealedKeys` maps each user ext id to K sealed to them (`sealFor`). */
11244
+ ring: (callExtId, sealedKeys, linkVersion) => ringCall(this.requireClient(), callExtId, sealedKeys, linkVersion),
11245
+ decline: (callExtId) => declineCall(this.requireClient(), callExtId),
11246
+ knock: (callExtId, linkVersion) => knockCall(this.requireClient(), callExtId, linkVersion),
11247
+ pollKnock: (callExtId, knockId) => pollKnock(this.requireClient(), callExtId, knockId),
11248
+ /** A host admits or turns away someone in the lobby. */
11249
+ decideKnock: (callExtId, knockId, admit) => decideKnock(this.requireClient(), callExtId, knockId, admit),
11250
+ removeParticipant: (callExtId, identity) => removeCallParticipant(this.requireClient(), callExtId, identity),
11251
+ muteParticipant: (callExtId, identity, track) => muteCallParticipant(this.requireClient(), callExtId, identity, track),
11252
+ /** Personal invite links for my unregistered contacts (register, then straight into the call). */
11253
+ inviteLinks: {
11254
+ create: (callExtId, body) => createCallInviteLink(this.requireClient(), callExtId, body),
11255
+ list: (callExtId) => listCallInviteLinks(this.requireClient(), callExtId),
11256
+ revoke: (callExtId, inviteLinkExtId) => revokeCallInviteLink(this.requireClient(), callExtId, inviteLinkExtId)
11257
+ },
11258
+ /** Live transcription: each client transcribes its own microphone; the host turns it on. */
11259
+ transcription: {
11260
+ set: (callExtId, on) => setCallTranscription(this.requireClient(), callExtId, on),
11261
+ transcribe: (callExtId, params) => transcribeCallSegment(this.requireClient(), callExtId, params),
11262
+ /** Store an (already encrypted) line in an E2E chat, idempotent per `dedupe_key`. */
11263
+ postChatLine: (chatExtId, body) => postChatTranscriptLine(this.requireClient(), chatExtId, body)
11264
+ },
11265
+ /** End-to-end encrypted recording: encrypted parts uploaded by each client, host-run. */
11266
+ recording: {
11267
+ quota: (callExtId) => getRecordingQuota(this.requireClient(), callExtId),
11268
+ start: (callExtId, mode) => startCallRecording(this.requireClient(), callExtId, mode),
11269
+ stop: (callExtId) => stopCallRecording(this.requireClient(), callExtId),
11270
+ createTrack: (callExtId, recordingExtId, body) => createRecordingTrack(this.requireClient(), callExtId, recordingExtId, body),
11271
+ presignPart: (callExtId, recordingExtId, trackExtId, body) => presignRecordingPart(
11272
+ this.requireClient(),
11273
+ callExtId,
11274
+ recordingExtId,
11275
+ trackExtId,
11276
+ body
11277
+ ),
11278
+ commitPart: (callExtId, recordingExtId, trackExtId, seq) => commitRecordingPart(
11279
+ this.requireClient(),
11280
+ callExtId,
11281
+ recordingExtId,
11282
+ trackExtId,
11283
+ seq
11284
+ ),
11285
+ list: (callExtId) => listCallRecordings(this.requireClient(), callExtId),
11286
+ get: (callExtId, recordingExtId) => getCallRecording(this.requireClient(), callExtId, recordingExtId),
11287
+ setExpiry: (callExtId, recordingExtId, expiresAt) => setRecordingExpiry(this.requireClient(), callExtId, recordingExtId, expiresAt),
11288
+ deleteMedia: (callExtId, recordingExtId) => deleteRecordingMedia(this.requireClient(), callExtId, recordingExtId),
11289
+ delete: (callExtId, recordingExtId) => deleteRecording(this.requireClient(), callExtId, recordingExtId),
11290
+ transcribe: (callExtId, recordingExtId, params) => transcribeRecordingPart(this.requireClient(), callExtId, recordingExtId, params),
11291
+ /** One part's ciphertext from its presigned GET. */
11292
+ downloadPart: (url) => downloadRecordingPart(url)
11293
+ },
11294
+ /** Webinars: a call with `mode = 'webinar'`. `linkVersion` for a link holder not yet admitted. */
11295
+ webinar: {
11296
+ get: (callExtId, linkVersion) => getWebinar(this.requireClient(), callExtId, linkVersion),
11297
+ update: (callExtId, body, linkVersion) => updateWebinar(this.requireClient(), callExtId, body, linkVersion),
11298
+ setHand: (callExtId, raised, linkVersion) => setWebinarHand(this.requireClient(), callExtId, raised, linkVersion),
11299
+ promote: (callExtId, identity, linkVersion) => promoteToStage(this.requireClient(), callExtId, identity, linkVersion),
11300
+ demote: (callExtId, identity, linkVersion) => demoteFromStage(this.requireClient(), callExtId, identity, linkVersion),
11301
+ questions: {
11302
+ list: (callExtId, linkVersion) => listQuestions(this.requireClient(), callExtId, linkVersion),
11303
+ ask: (callExtId, bodyCiphertext, linkVersion) => askQuestion(this.requireClient(), callExtId, bodyCiphertext, linkVersion),
11304
+ vote: (callExtId, questionExtId, up, linkVersion) => voteQuestion(this.requireClient(), callExtId, questionExtId, up, linkVersion),
11305
+ update: (callExtId, questionExtId, body, linkVersion) => updateQuestion(
11306
+ this.requireClient(),
11307
+ callExtId,
11308
+ questionExtId,
11309
+ body,
11310
+ linkVersion
11311
+ ),
11312
+ delete: (callExtId, questionExtId, linkVersion) => deleteQuestion(this.requireClient(), callExtId, questionExtId, linkVersion)
11313
+ }
11314
+ }
11315
+ };
10092
11316
  /** Direct-chat conveniences addressed by peer (email or `usr-`/`agt-` id). */
10093
11317
  dm = {
10094
11318
  /**
@@ -10297,11 +11521,8 @@ var Arbi = class {
10297
11521
  currentId: () => readSessionClaims(this.client?.session.getState().accessToken)?.sessionId ?? null,
10298
11522
  /** End one of your own sessions now (not the one this device is on: that is `logout`). */
10299
11523
  terminate: (sessionId) => terminateSession(this.requireClient(), sessionId),
10300
- /** Sign out of every device on the server, then clear this instance. */
10301
- logoutAll: async () => {
10302
- await logoutAllSessions(this.requireClient());
10303
- await this.logout();
10304
- }
11524
+ /** Sign out of every device on the server, then clear this instance and this device. */
11525
+ logoutAll: () => this.logout({ everywhere: true })
10305
11526
  };
10306
11527
  // ── Internal guards ───────────────────────────────────────────────────
10307
11528
  requireClient() {
@@ -10434,6 +11655,571 @@ function canTagHaveParent(tags, tagId) {
10434
11655
  return getChildTags(tags, tagId).length === 0;
10435
11656
  }
10436
11657
 
10437
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PRESENCE_KINDS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, calendar_exports as calendar, canTagHaveParent, cancelPublicBooking, chats_exports as chats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, defaultKindForFormat, doctags_exports as doctags, documents_exports as documents, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatUserName, formatWorkspaceChoices, getChildTags, getEligibleParentTags, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isPresenceTag, isSharePointVendor, isSharedSkill, mail_exports as mail, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, profile_exports as profile, progressFetch, projects_exports as projects, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, searchChunks, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, streamSSE, stripCitationMarkdown, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
11658
+ // src/chat/output-item-reducer.ts
11659
+ function reasoningStep(arbi) {
11660
+ if (arbi?.step) return arbi.step;
11661
+ if (arbi?.model_recommendation) return "goal";
11662
+ if ((arbi?.label ?? "").startsWith("Goal check")) return "goal_progress";
11663
+ return "planning";
11664
+ }
11665
+ function isTraceItem(item) {
11666
+ if (item.type === "function_call" || item.type === "reasoning") return true;
11667
+ return item.type === "message" && (!!item.arbi?.step || !!item.arbi?.label);
11668
+ }
11669
+ function reduceOutputItem(steps, ev, assignIndex, resolveIndex) {
11670
+ const item = ev.item;
11671
+ if (!item || !isTraceItem(item)) return steps;
11672
+ if (!item.id) return steps;
11673
+ const arbi = item.arbi ?? {};
11674
+ const idx = steps.findIndex((s2) => s2._id === item.id);
11675
+ const index = assignIndex(item.id);
11676
+ const prev = idx !== -1 ? steps[idx] : void 0;
11677
+ const summaryText = item.type === "reasoning" && Array.isArray(item.summary) ? item.summary.map((c2) => c2.text).join("") : void 0;
11678
+ const isNarration = item.type === "message" && !arbi.step;
11679
+ const narrationText = isNarration && Array.isArray(item.content) ? item.content.map((c2) => c2.text).join("") : void 0;
11680
+ const next = {
11681
+ ...prev ?? {},
11682
+ type: "arbi.agent_step",
11683
+ _id: item.id,
11684
+ index,
11685
+ // First sighting wins: an item is re-emitted to attach its outcome once the
11686
+ // tool returns, and taking that later stamp would stretch the step to cover
11687
+ // its own execution and shrink the next one.
11688
+ t: prev?.t ?? ev.t ?? void 0,
11689
+ // A tool call has no lifecycle kind (it carries `detail`); everything else
11690
+ // that got this far is a declared or derived lifecycle step.
11691
+ step: item.type === "function_call" ? void 0 : reasoningStep(arbi),
11692
+ label: arbi.label ?? prev?.label,
11693
+ focus: focusUnlessRepeatsNarration(arbi.focus ?? prev?.focus, steps),
11694
+ // Reasoning items carry extended text as `summary` (a plan, a checklist);
11695
+ // function_call items (e.g. a sub-agent spawn marker) carry it as `arbi.content`
11696
+ // directly — a sub-agent's spawn task description, not a lifecycle summary.
11697
+ content: summaryText ?? narrationText ?? arbi.content ?? prev?.content,
11698
+ narration: isNarration || prev?.narration,
11699
+ reasoning: item.type === "reasoning" || prev?.reasoning,
11700
+ detail: arbi.detail ?? prev?.detail,
11701
+ outcome: arbi.outcome ?? prev?.outcome,
11702
+ guard_refused: guardRefused(arbi) || prev?.guard_refused || void 0,
11703
+ usage: arbi.usage ?? prev?.usage,
11704
+ step_tokens: arbi.step_tokens ?? prev?.step_tokens,
11705
+ step_gbp: arbi.step_gbp ?? prev?.step_gbp,
11706
+ total_tokens: arbi.total_tokens ?? prev?.total_tokens,
11707
+ context: arbi.context ?? prev?.context,
11708
+ parent_index: arbi.parent_id != null ? resolveIndex(arbi.parent_id) : prev?.parent_index,
11709
+ subagent: arbi.subagent ?? prev?.subagent,
11710
+ subagent_status: arbi.subagent_status ?? prev?.subagent_status,
11711
+ task_message_ext_id: arbi.task_message_ext_id ?? prev?.task_message_ext_id,
11712
+ model_recommendation: arbi.model_recommendation ?? prev?.model_recommendation,
11713
+ selected_model: arbi.selected_model ?? prev?.selected_model
11714
+ };
11715
+ if (idx !== -1) {
11716
+ const out = [...steps];
11717
+ out[idx] = next;
11718
+ return out;
11719
+ }
11720
+ return [...steps, next];
11721
+ }
11722
+ function guardRefused(arbi) {
11723
+ return arbi.guard_refused === true;
11724
+ }
11725
+ function focusUnlessRepeatsNarration(focus, steps) {
11726
+ const norm = (s2) => (s2 ?? "").replace(/\s+/g, " ").trim();
11727
+ const lastNarration = [...steps].reverse().find((s2) => s2.narration);
11728
+ if (!focus || !lastNarration || norm(focus) !== norm(lastNarration.content)) return focus;
11729
+ return void 0;
11730
+ }
11731
+ function createIndexAssigner(seed = []) {
11732
+ const byId3 = /* @__PURE__ */ new Map();
11733
+ let next = 0;
11734
+ for (const s2 of seed) {
11735
+ if (s2._id) {
11736
+ byId3.set(s2._id, s2.index);
11737
+ next = Math.max(next, s2.index);
11738
+ }
11739
+ }
11740
+ const assign = (id) => {
11741
+ const existing = byId3.get(id);
11742
+ if (existing != null) return existing;
11743
+ next += 1;
11744
+ byId3.set(id, next);
11745
+ return next;
11746
+ };
11747
+ const resolve = (id) => byId3.get(id);
11748
+ return { assign, resolve };
11749
+ }
11750
+
11751
+ // src/chat/agent-step-hydration.ts
11752
+ function hydrateV3(events) {
11753
+ let steps = [];
11754
+ for (const ev of events) {
11755
+ if (ev.type !== "response.output_item.done") continue;
11756
+ const { assign, resolve } = createIndexAssigner(steps);
11757
+ steps = reduceOutputItem(steps, ev, assign, resolve);
11758
+ }
11759
+ return steps;
11760
+ }
11761
+ function hydrateV1(rawSteps) {
11762
+ const steps = [];
11763
+ for (const step of rawSteps) {
11764
+ if (step.step !== "tool_progress") {
11765
+ const progressIdx = steps.findIndex(
11766
+ (s2) => s2.index === step.index && s2.step === "tool_progress"
11767
+ );
11768
+ if (progressIdx !== -1) {
11769
+ steps[progressIdx] = { ...step };
11770
+ continue;
11771
+ }
11772
+ }
11773
+ const isFollowUp = step.step == null;
11774
+ if (isFollowUp) {
11775
+ const existing = steps.find((s2) => s2.index === step.index);
11776
+ if (existing) {
11777
+ for (const [key, value] of Object.entries(step)) {
11778
+ if (value != null && key !== "type" && key !== "t") {
11779
+ existing[key] = value;
11780
+ }
11781
+ }
11782
+ continue;
11783
+ }
11784
+ }
11785
+ steps.push({ ...step });
11786
+ }
11787
+ return steps;
11788
+ }
11789
+ function hydrateAgentSteps(message) {
11790
+ const tools = message.tools || message.meta?.tools;
11791
+ if (!tools) return void 0;
11792
+ const streamEvents = tools["stream_events"];
11793
+ if (!streamEvents || !("events" in streamEvents)) return void 0;
11794
+ const events = streamEvents.events;
11795
+ if (!Array.isArray(events) || events.length === 0) return void 0;
11796
+ const hasV3 = events.some(
11797
+ (e) => typeof e === "object" && e !== null && e.type === "response.output_item.done"
11798
+ );
11799
+ let steps;
11800
+ if (hasV3) {
11801
+ steps = hydrateV3(events);
11802
+ } else {
11803
+ const rawSteps = events.filter(
11804
+ (e) => typeof e === "object" && e !== null && e.type === "arbi.agent_step"
11805
+ );
11806
+ if (rawSteps.length === 0) return void 0;
11807
+ steps = hydrateV1(rawSteps);
11808
+ }
11809
+ if (steps.length === 0) return void 0;
11810
+ const completedEvent = events.find(
11811
+ (e) => typeof e === "object" && e !== null && e.type === "response.completed"
11812
+ );
11813
+ const totalElapsed = completedEvent?.t ?? null;
11814
+ const finalContext = completedEvent?.context ?? null;
11815
+ return { steps, totalElapsed, finalContext };
11816
+ }
11817
+
11818
+ // src/chat/agent-steps.ts
11819
+ function humanizeStep2(identifier) {
11820
+ const spaced = identifier.replace(/[_-]+/g, " ").trim();
11821
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
11822
+ }
11823
+ function getStepTool(step) {
11824
+ return step.detail?.[0]?.tool ?? void 0;
11825
+ }
11826
+ function resolveSummary(summary, docInfo) {
11827
+ return summary.replace(
11828
+ /\{(doc-[A-Za-z0-9]+)\}|(doc-[A-Za-z0-9]+)/g,
11829
+ (full, braced, bare) => {
11830
+ const docId = braced ?? bare ?? "";
11831
+ return docInfo[docId]?.name || (braced ? docId : full);
11832
+ }
11833
+ ).replace(/\(full\)/g, (match) => {
11834
+ const docIdMatch = summary.match(/\{(doc-[^}]+)\}/);
11835
+ if (docIdMatch) {
11836
+ const info = docInfo[docIdMatch[1]];
11837
+ if (info?.pages) return `(full \u2013 ${info.pages} pages)`;
11838
+ }
11839
+ return match;
11840
+ });
11841
+ }
11842
+ var DUPLICATE_OUTCOME = "duplicate";
11843
+ function isGuardRefused(step) {
11844
+ if (step.guard_refused === true) return true;
11845
+ return step.outcome === DUPLICATE_OUTCOME && !step.subagent;
11846
+ }
11847
+ function mergeAgentSteps(steps) {
11848
+ const byIndex = /* @__PURE__ */ new Map();
11849
+ for (const step of steps) {
11850
+ if (step.step === "tool_progress" && step.detail && step.detail.length === 1 && step.detail[0].message === "working" && !step.detail[0].label) {
11851
+ continue;
11852
+ }
11853
+ const existing = byIndex.get(step.index);
11854
+ if (!existing) {
11855
+ byIndex.set(step.index, step);
11856
+ continue;
11857
+ }
11858
+ byIndex.set(step.index, {
11859
+ ...existing,
11860
+ outcome: step.outcome ?? existing.outcome,
11861
+ guard_refused: step.guard_refused || existing.guard_refused || void 0,
11862
+ usage: step.usage ?? existing.usage,
11863
+ total_tokens: step.total_tokens ?? existing.total_tokens,
11864
+ step_tokens: step.step_tokens ?? existing.step_tokens,
11865
+ step_gbp: step.step_gbp ?? existing.step_gbp,
11866
+ context: step.context ?? existing.context,
11867
+ detail: existing.detail ?? step.detail
11868
+ });
11869
+ }
11870
+ return Array.from(byIndex.values()).filter((step) => !isGuardRefused(step)).sort((a2, b2) => a2.index - b2.index);
11871
+ }
11872
+ function topLevelAgentSteps(steps) {
11873
+ const merged = mergeAgentSteps(steps);
11874
+ const known = new Set(merged.map((s2) => s2.index));
11875
+ return merged.filter(
11876
+ (s2) => s2.parent_index == null || s2.parent_index === s2.index || !known.has(s2.parent_index)
11877
+ );
11878
+ }
11879
+ function formatTokens(n2) {
11880
+ if (n2 < 1e3) return `${n2}`;
11881
+ if (n2 < 1e4) return `${(n2 / 1e3).toFixed(1)}k`;
11882
+ return `${Math.round(n2 / 1e3)}k`;
11883
+ }
11884
+ function computeRunStats(steps) {
11885
+ const merged = mergeAgentSteps(steps);
11886
+ let toolCalls = 0;
11887
+ const running = /* @__PURE__ */ new Set();
11888
+ const terminated = /* @__PURE__ */ new Set();
11889
+ for (const s2 of merged) {
11890
+ if (s2.subagent_status === "running") running.add(s2.subagent ?? "");
11891
+ else if (s2.subagent_status === "done" || s2.subagent_status === "failed")
11892
+ terminated.add(s2.subagent ?? "");
11893
+ else if (s2.step == null && !s2.subagent_status) toolCalls += 1;
11894
+ }
11895
+ const handles = /* @__PURE__ */ new Set([...running, ...terminated]);
11896
+ return {
11897
+ toolCalls,
11898
+ subagents: handles.size,
11899
+ subagentsRunning: [...running].filter((h2) => !terminated.has(h2)).length
11900
+ };
11901
+ }
11902
+ function subagentJobLabel(task, maxLen = 42) {
11903
+ let t2 = (task || "").trim();
11904
+ if (!t2) return "Sub-agent";
11905
+ for (const stop of ["(", "\n", ". ", ": ", " \u2014 ", " - "]) {
11906
+ const i2 = t2.indexOf(stop);
11907
+ if (i2 > 8) t2 = t2.slice(0, i2).trim();
11908
+ }
11909
+ if (t2.length > maxLen) t2 = `${t2.slice(0, maxLen - 1).trimEnd()}\u2026`;
11910
+ return t2;
11911
+ }
11912
+ function extractSubagentLanes(steps) {
11913
+ const merged = mergeAgentSteps(steps);
11914
+ const order = [];
11915
+ const byHandle = /* @__PURE__ */ new Map();
11916
+ for (const s2 of merged) {
11917
+ const h2 = s2.subagent;
11918
+ if (!h2) continue;
11919
+ let e = byHandle.get(h2);
11920
+ if (!e) {
11921
+ e = { task: "", focus: "", status: "running", steps: 0 };
11922
+ byHandle.set(h2, e);
11923
+ order.push(h2);
11924
+ }
11925
+ if (s2.task_message_ext_id) e.taskMessageExtId = s2.task_message_ext_id;
11926
+ if (s2.subagent_status === "running") e.task = (s2.content || s2.focus || "").trim();
11927
+ else if (s2.subagent_status === "done") e.status = "done";
11928
+ else if (s2.subagent_status === "failed") e.status = "failed";
11929
+ else {
11930
+ e.steps += 1;
11931
+ if (s2.focus) e.focus = s2.focus.trim();
11932
+ }
11933
+ }
11934
+ return order.map((h2) => {
11935
+ const e = byHandle.get(h2);
11936
+ return {
11937
+ handle: h2,
11938
+ task: e.task,
11939
+ job: subagentJobLabel(e.task),
11940
+ focus: e.focus,
11941
+ status: e.status,
11942
+ steps: e.steps,
11943
+ taskMessageExtId: e.taskMessageExtId
11944
+ };
11945
+ });
11946
+ }
11947
+ function showFullForLabel(label) {
11948
+ const l2 = (label ?? "").trim();
11949
+ return l2.startsWith("Budget reached") || l2.startsWith("Goal") || l2.startsWith("Deep research");
11950
+ }
11951
+ function getStepDisplay(step, docInfo = {}) {
11952
+ const tool = getStepTool(step);
11953
+ if (step.narration) {
11954
+ const prose = step.content?.trim() || null;
11955
+ return {
11956
+ label: step.label || "Narration",
11957
+ summary: prose ? resolveSummary(prose, docInfo) : null,
11958
+ isMultiLine: true,
11959
+ details: []
11960
+ };
11961
+ }
11962
+ const firstDetail = step.detail?.[0];
11963
+ if (step.step) {
11964
+ if (step.step === "tool_progress") {
11965
+ const label3 = firstDetail?.label || step.label || tool && humanizeStep2(tool) || humanizeStep2(step.step);
11966
+ const message = firstDetail?.message || step.content || null;
11967
+ return {
11968
+ label: label3,
11969
+ summary: message ? resolveSummary(message, docInfo) : null,
11970
+ isMultiLine: !!message?.includes("\n"),
11971
+ details: []
11972
+ };
11973
+ }
11974
+ const label2 = step.label || humanizeStep2(step.step);
11975
+ const content2 = step.content?.trim() || null;
11976
+ const showFull = !!content2?.includes("\n") || showFullForLabel(step.label);
11977
+ return {
11978
+ label: label2,
11979
+ summary: content2 ? resolveSummary(content2, docInfo) : null,
11980
+ isMultiLine: showFull,
11981
+ details: []
11982
+ };
11983
+ }
11984
+ const label = step.label || firstDetail?.label || tool && humanizeStep2(tool) || `Step ${step.index}`;
11985
+ const summaries = (step.detail || []).map((d2) => d2.summary).filter(Boolean).map((s2) => resolveSummary(s2, docInfo));
11986
+ const focus = step.focus?.trim();
11987
+ const content = step.content?.trim() || null;
11988
+ const rest = [...summaries, ...content ? [resolveSummary(content, docInfo)] : []];
11989
+ const narrative = focus || rest.shift() || null;
11990
+ return {
11991
+ label,
11992
+ summary: narrative ? resolveSummary(narrative, docInfo) : null,
11993
+ isMultiLine: !!narrative?.includes("\n") || showFullForLabel(label),
11994
+ details: rest
11995
+ };
11996
+ }
11997
+ function getAgentStepLabel(step, docInfo = {}) {
11998
+ const { label, summary, isMultiLine } = getStepDisplay(step, docInfo);
11999
+ const narrative = summary && !isMultiLine && !step.reasoning ? summary : null;
12000
+ const text = narrative ? `${label} \u2014 ${narrative}` : label;
12001
+ return text.length > 120 ? `${text.slice(0, 119)}\u2026` : text;
12002
+ }
12003
+ function getCurrentStep(steps) {
12004
+ const merged = mergeAgentSteps(steps);
12005
+ const candidates = merged.length > 0 ? merged : steps;
12006
+ const isOwnSubstantiveStep = (s2) => {
12007
+ if (s2.subagent) return false;
12008
+ if (s2.narration) return false;
12009
+ const d2 = s2.detail?.[0];
12010
+ const isHeartbeat = s2.step === "tool_progress" && d2?.message === "working" && !d2?.label;
12011
+ return !isHeartbeat;
12012
+ };
12013
+ for (let i2 = candidates.length - 1; i2 >= 0; i2--) {
12014
+ if (isOwnSubstantiveStep(candidates[i2])) return candidates[i2];
12015
+ }
12016
+ for (let i2 = candidates.length - 1; i2 >= 0; i2--) {
12017
+ if (!candidates[i2].subagent) return candidates[i2];
12018
+ }
12019
+ return candidates[candidates.length - 1];
12020
+ }
12021
+
12022
+ // src/chat/subagent-branch.ts
12023
+ function getSubagentBranchRecord(message) {
12024
+ const entry = message.tools?.subagent;
12025
+ return entry?.record ?? null;
12026
+ }
12027
+ function findLeafForTaskMessage(threads, taskMessageExtId) {
12028
+ const thread = threads.find((t2) => t2.history.some((m2) => m2.external_id === taskMessageExtId));
12029
+ return thread?.leaf_message_ext_id ?? null;
12030
+ }
12031
+ function tailTaskMessageIndex(history) {
12032
+ const lastIndex = history.length - 1;
12033
+ if (lastIndex < 0) return -1;
12034
+ if (getSubagentBranchRecord(history[lastIndex])) return lastIndex;
12035
+ const secondLastIndex = lastIndex - 1;
12036
+ if (secondLastIndex >= 0 && getSubagentBranchRecord(history[secondLastIndex])) {
12037
+ return secondLastIndex;
12038
+ }
12039
+ return -1;
12040
+ }
12041
+ function findMainSiblingLeaf(threads, currentHistory) {
12042
+ const taskIndex = tailTaskMessageIndex(currentHistory);
12043
+ if (taskIndex <= 0) return null;
12044
+ const ancestorId = currentHistory[taskIndex - 1].external_id;
12045
+ if (!ancestorId) return null;
12046
+ const sibling = threads.find(
12047
+ (t2) => t2.history.some((m2) => m2.external_id === ancestorId) && tailTaskMessageIndex(t2.history) < 0
12048
+ );
12049
+ return sibling?.leaf_message_ext_id ?? null;
12050
+ }
12051
+ function sliceToSubagentThread(history) {
12052
+ const taskIndex = tailTaskMessageIndex(history);
12053
+ return taskIndex >= 0 ? history.slice(taskIndex) : history;
12054
+ }
12055
+ function newestThread(threads) {
12056
+ const lastAt = (t2) => Date.parse(t2.history.at(-1)?.created_at ?? "") || 0;
12057
+ return threads.reduce(
12058
+ (best, t2) => !best || lastAt(t2) > lastAt(best) ? t2 : best,
12059
+ void 0
12060
+ );
12061
+ }
12062
+ function pickMainThread(threads) {
12063
+ return newestThread(threads.filter((t2) => !t2.history.some((m2) => getSubagentBranchRecord(m2)))) ?? threads.find((t2) => tailTaskMessageIndex(t2.history) < 0) ?? threads[0];
12064
+ }
12065
+ function findSubagentRunId(threads, messageId) {
12066
+ for (const thread of threads) {
12067
+ const index = thread.history.findIndex((m2) => m2.external_id === messageId);
12068
+ if (index < 0) continue;
12069
+ const taskIndex = tailTaskMessageIndex(thread.history);
12070
+ if (taskIndex >= 0 && taskIndex <= index) {
12071
+ return getSubagentBranchRecord(thread.history[taskIndex])?.run_id ?? null;
12072
+ }
12073
+ }
12074
+ return null;
12075
+ }
12076
+
12077
+ // src/chat/reply-target.ts
12078
+ function findReplyTarget(threads, parentId) {
12079
+ if (!parentId) return null;
12080
+ const byId3 = /* @__PURE__ */ new Map();
12081
+ for (const thread of threads) {
12082
+ for (const message of thread.history) byId3.set(message.external_id, message);
12083
+ }
12084
+ let current = byId3.has(parentId) ? parentId : pickMainThread(threads)?.leaf_message_ext_id ?? null;
12085
+ while (current) {
12086
+ const message = byId3.get(current);
12087
+ if (!message) return null;
12088
+ if (message.status !== "failed") return current;
12089
+ current = message.parent_message_ext_id ?? null;
12090
+ }
12091
+ return null;
12092
+ }
12093
+
12094
+ // src/chat/stop-run.ts
12095
+ var STOP_ID_WAIT_MS = 5e3;
12096
+ var STOP_REPEAT_WINDOW_MS = 1e3;
12097
+ var RUN_ID = /^msg-[a-zA-Z0-9]{8}$/;
12098
+ function topLevelRunId(runId) {
12099
+ const root = runId.split(":")[0];
12100
+ return RUN_ID.test(root) ? root : null;
12101
+ }
12102
+ function getRunToCancel(threads, responseId) {
12103
+ const subagentRunId = findSubagentRunId(threads, responseId);
12104
+ return (subagentRunId && topLevelRunId(subagentRunId)) ?? topLevelRunId(responseId) ?? responseId;
12105
+ }
12106
+
12107
+ // src/chat/context-usage.ts
12108
+ function isNearAiUsageBudget(usage) {
12109
+ if (usage.budget_gbp == null || usage.spent_gbp == null || usage.budget_gbp <= 0) {
12110
+ return false;
12111
+ }
12112
+ return usage.spent_gbp / usage.budget_gbp >= 0.9;
12113
+ }
12114
+ function getContextUsedTokens(usage) {
12115
+ return usage.all_llm_calls?.last_input_tokens ?? usage.total_input;
12116
+ }
12117
+ function estimateDraftTokens(draftLength) {
12118
+ return Math.ceil(draftLength / 4);
12119
+ }
12120
+ function getContextUsedPercent(usage, draftLength = 0) {
12121
+ const usedTokens = getContextUsedTokens(usage) + estimateDraftTokens(draftLength);
12122
+ const usedPercent = usedTokens / usage.context_window * 100;
12123
+ return Math.min(100, Math.max(0, usedPercent));
12124
+ }
12125
+ function getContextRemainingPercent(usage, draftLength = 0) {
12126
+ return 100 - getContextUsedPercent(usage, draftLength);
12127
+ }
12128
+
12129
+ // src/chat/conversation-context.ts
12130
+ function extractDocumentIdsFromMessages(messageHistory) {
12131
+ if (!messageHistory || messageHistory.length === 0) return [];
12132
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
12133
+ const msg = messageHistory[i2];
12134
+ if (msg.role === "user" && msg.tools) {
12135
+ const documents = extractDocIdsFromTools(msg.tools);
12136
+ if (documents.length > 0) {
12137
+ return documents;
12138
+ }
12139
+ }
12140
+ }
12141
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
12142
+ const msg = messageHistory[i2];
12143
+ if (msg.role === "assistant" && msg.tools) {
12144
+ const documents = extractDocIdsFromTools(msg.tools);
12145
+ if (documents.length > 0) {
12146
+ return documents;
12147
+ }
12148
+ }
12149
+ }
12150
+ return [];
12151
+ }
12152
+ function extractFactIdsFromMessages(messageHistory) {
12153
+ if (!messageHistory || messageHistory.length === 0) return null;
12154
+ for (let i2 = messageHistory.length - 1; i2 >= 0; i2--) {
12155
+ const msg = messageHistory[i2];
12156
+ if (msg.role !== "user" || !msg.tools) continue;
12157
+ const tool = msg.tools.facts_context;
12158
+ if (tool?.name === "facts_context" && Array.isArray(tool.tool_args?.fact_ext_ids)) {
12159
+ return Array.from(new Set(tool.tool_args.fact_ext_ids));
12160
+ }
12161
+ }
12162
+ return null;
12163
+ }
12164
+ function extractDocIdsFromTools(tools) {
12165
+ const documents = [];
12166
+ try {
12167
+ const retrievalChunk = tools.retrieval_chunk;
12168
+ if (retrievalChunk && "tool_args" in retrievalChunk && "doc_ext_ids" in retrievalChunk.tool_args && retrievalChunk.tool_args.doc_ext_ids) {
12169
+ const docIds = retrievalChunk.tool_args.doc_ext_ids;
12170
+ if (Array.isArray(docIds)) {
12171
+ for (const docId of docIds) {
12172
+ documents.push({ docId, isPinned: false });
12173
+ }
12174
+ }
12175
+ }
12176
+ const retrievalFullContext = tools.retrieval_full_context;
12177
+ if (retrievalFullContext && "tool_args" in retrievalFullContext && "doc_ext_ids" in retrievalFullContext.tool_args && retrievalFullContext.tool_args.doc_ext_ids) {
12178
+ const docIds = retrievalFullContext.tool_args.doc_ext_ids;
12179
+ if (Array.isArray(docIds)) {
12180
+ for (const docId of docIds) {
12181
+ documents.push({ docId, isPinned: true });
12182
+ }
12183
+ }
12184
+ }
12185
+ if (documents.length > 0) {
12186
+ const uniqueDocuments = documents.reduce(
12187
+ (acc, doc) => {
12188
+ const existing = acc.find((d2) => d2.docId === doc.docId);
12189
+ if (existing) {
12190
+ existing.isPinned = existing.isPinned || doc.isPinned;
12191
+ } else {
12192
+ acc.push(doc);
12193
+ }
12194
+ return acc;
12195
+ },
12196
+ []
12197
+ );
12198
+ return uniqueDocuments;
12199
+ }
12200
+ } catch (error) {
12201
+ console.warn("Failed to extract document IDs from message tools:", error);
12202
+ }
12203
+ return [];
12204
+ }
12205
+
12206
+ // src/chat/run-attach.ts
12207
+ function getAttachableRunId(messages) {
12208
+ let nextQueued = null;
12209
+ for (let i2 = messages.length - 1; i2 >= 0; i2--) {
12210
+ const m2 = messages[i2];
12211
+ if (m2.role !== "assistant") continue;
12212
+ if (m2.status === "in_progress") return m2.external_id;
12213
+ if (m2.status !== "queued") break;
12214
+ nextQueued = m2.external_id;
12215
+ }
12216
+ return nextQueued;
12217
+ }
12218
+ function getRunToAttach(localGeneration, messages) {
12219
+ if (localGeneration?.isGenerating && localGeneration.abortController) return null;
12220
+ return getAttachableRunId(messages);
12221
+ }
12222
+
12223
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, CallApiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, chats_exports as chats, computeRunStats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, consumeSSEStream, contacts_exports as contacts, continuityPrompt, conversations_exports as conversations, countCitations, createAuthenticatedClient, createIndexAssigner, defaultKindForFormat, doctags_exports as doctags, documents_exports as documents, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatTokens, formatUserName, formatWorkspaceChoices, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, mail_exports as mail, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, sliceToSubagentThread, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
10438
12224
  //# sourceMappingURL=browser.js.map
10439
12225
  //# sourceMappingURL=browser.js.map