@arbidocs/sdk 0.4.167 → 0.4.168

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