@arbidocs/sdk 0.5.61 → 0.5.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs2, { readFileSync } from 'fs';
2
2
  import path3, { dirname, resolve } from 'path';
3
3
  import os2 from 'os';
4
- import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, encryptionKeypairFromSigningKey, sealedBoxDecrypt, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, decodeSecureMailKey, openSecureMail, secureMailClaim, createSessionManager, authRequestError, changePassword, openCallKeyOf, decryptCallTitle, generateCallKey, encryptCallTitle, sealCallKeyForPeers, openSealedCallKey, readSessionClaims, isAbortError } from '@arbidocs/client';
4
+ import { createArbiClient, base64ToBytes, unwrapWorkspaceKey, sealKeyForSession, buildWebSocketUrl, createAuthMessage, parseServerMessage, isMessageType, createContentHash, encryptFile, initSodium, encryptionKeypairFromSigningKey, sealedBoxDecrypt, bytesToBase64, encryptWithChatKey, decryptWithChatKey, decryptFile, deriveDirectChatKey, openSealedChatKey, generateChatKey, sealChatKey, sealCallKey, encryptMessage, decodeSecureMailKey, openSecureMail, secureMailClaim, createSessionManager, authRequestError, isAbortError, changePassword, openCallKeyOf, decryptCallTitle, generateCallKey, encryptCallTitle, sealCallKeyForPeers, openSealedCallKey, readSessionClaims } from '@arbidocs/client';
5
5
  import { execSync, spawn } from 'child_process';
6
6
  import { createHash } from 'crypto';
7
7
  import { fileURLToPath } from 'url';
@@ -3517,6 +3517,22 @@ var ArbiWorkspaceChangedError = class extends ArbiError {
3517
3517
  }
3518
3518
  workspaceId;
3519
3519
  };
3520
+ var ArbiWorkspaceUnavailableError = class extends ArbiError {
3521
+ constructor(workspaceId, cause, message = `Workspace ${workspaceId} can't be opened in this session, so nothing was sent`) {
3522
+ super(message, { code: "WORKSPACE_UNAVAILABLE", cause });
3523
+ this.workspaceId = workspaceId;
3524
+ this.name = "ArbiWorkspaceUnavailableError";
3525
+ }
3526
+ workspaceId;
3527
+ };
3528
+ function workspaceConflictOf(error) {
3529
+ const body = error instanceof ArbiApiError ? error.apiError : error instanceof Error ? void 0 : error;
3530
+ const detail = errorRecord(errorRecord(body)?.detail);
3531
+ const code = detail?.code;
3532
+ const workspaceId = detail?.workspace_ext_id;
3533
+ if (code !== "workspace_key_required" && code !== "workspace_mismatch") return null;
3534
+ return typeof workspaceId === "string" && workspaceId ? { code, workspaceId } : null;
3535
+ }
3520
3536
  function detailText(detail) {
3521
3537
  if (typeof detail === "string") return detail || void 0;
3522
3538
  if (Array.isArray(detail)) {
@@ -5156,6 +5172,118 @@ function buildChunkLookup(tools) {
5156
5172
  return lookup;
5157
5173
  }
5158
5174
 
5175
+ // src/operations/responses.ts
5176
+ var responses_exports = {};
5177
+ __export(responses_exports, {
5178
+ extractResponseText: () => extractResponseText,
5179
+ getResponse: () => getResponse,
5180
+ submitBackgroundQuery: () => submitBackgroundQuery
5181
+ });
5182
+ async function submitBackgroundQuery(options) {
5183
+ const {
5184
+ workspaceId,
5185
+ question,
5186
+ docIds,
5187
+ previousResponseId,
5188
+ model,
5189
+ text: text2,
5190
+ task,
5191
+ conversationId,
5192
+ mentions,
5193
+ activeArtifactExtId,
5194
+ fullContext = true,
5195
+ ...auth
5196
+ } = options;
5197
+ const tools = {};
5198
+ if (docIds.length > 0) {
5199
+ tools.retrieval_chunk = {
5200
+ name: "retrieval_chunk",
5201
+ description: "retrieval chunk",
5202
+ tool_args: { doc_ext_ids: docIds },
5203
+ tool_responses: {}
5204
+ };
5205
+ if (fullContext)
5206
+ tools.retrieval_full_context = {
5207
+ name: "retrieval_full_context",
5208
+ description: "retrieval full context",
5209
+ tool_args: { doc_ext_ids: docIds },
5210
+ tool_responses: {}
5211
+ };
5212
+ }
5213
+ const body = {
5214
+ input: question,
5215
+ workspace_ext_id: workspaceId,
5216
+ stream: false,
5217
+ background: true,
5218
+ store: true,
5219
+ tools,
5220
+ ...task !== void 0 ? { task } : {},
5221
+ ...conversationId ? { conversation_ext_id: conversationId } : {},
5222
+ ...mentions !== void 0 ? { mentions } : {},
5223
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5224
+ ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5225
+ ...model ? { model } : {},
5226
+ ...text2 ? { text: text2 } : {}
5227
+ };
5228
+ const res = await authenticatedFetch({
5229
+ ...auth,
5230
+ path: "/v1/responses",
5231
+ method: "POST",
5232
+ body: JSON.stringify(body),
5233
+ headers: { "Content-Type": "application/json" }
5234
+ });
5235
+ return await res.json();
5236
+ }
5237
+ async function getResponse(auth, responseId) {
5238
+ const res = await authenticatedFetch({
5239
+ ...auth,
5240
+ path: `/v1/responses/${responseId}`,
5241
+ method: "GET"
5242
+ });
5243
+ return await res.json();
5244
+ }
5245
+ function extractResponseText(response) {
5246
+ const parts = [];
5247
+ for (const msg of Array.isArray(response.output) ? response.output : []) {
5248
+ if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
5249
+ for (const item of msg.content) {
5250
+ if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
5251
+ }
5252
+ }
5253
+ return parts.join("");
5254
+ }
5255
+
5256
+ // src/responses-resource.ts
5257
+ function withOutputText(response, requestId) {
5258
+ return {
5259
+ ...response,
5260
+ output_text: extractResponseText(response),
5261
+ ...requestId ? { _request_id: requestId } : {}
5262
+ };
5263
+ }
5264
+ var ResponseStream = class {
5265
+ constructor(handle) {
5266
+ this.handle = handle;
5267
+ }
5268
+ handle;
5269
+ async *[Symbol.asyncIterator]() {
5270
+ try {
5271
+ for await (const frame of this.handle.events()) {
5272
+ const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
5273
+ yield {
5274
+ ...data,
5275
+ type: typeof data.type === "string" ? data.type : frame.event
5276
+ };
5277
+ }
5278
+ const outcome = await this.handle.outcome;
5279
+ if (outcome.status === "disconnected")
5280
+ throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
5281
+ } finally {
5282
+ this.handle.detach();
5283
+ }
5284
+ }
5285
+ };
5286
+
5159
5287
  // src/structured-output.ts
5160
5288
  var ArbiStructuredOutputError = class extends ArbiError {
5161
5289
  constructor(message, response, options) {
@@ -5362,12 +5490,17 @@ function consumeResponse(response, controller, cancel, options = {}) {
5362
5490
  let acknowledgement;
5363
5491
  const listeners = /* @__PURE__ */ new Set();
5364
5492
  const queue = [];
5493
+ let capacityAvailable;
5494
+ const releaseCapacity = () => {
5495
+ capacityAvailable?.();
5496
+ capacityAvailable = void 0;
5497
+ };
5365
5498
  let claimed = false;
5366
5499
  let iteratorClosed = false;
5367
5500
  let iteratorError;
5368
5501
  let pending;
5369
5502
  const emit = (event) => {
5370
- if (!claimed || iteratorClosed) return;
5503
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
5371
5504
  if (pending) {
5372
5505
  pending.resolve({ value: immutable(event), done: false });
5373
5506
  pending = void 0;
@@ -5396,6 +5529,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
5396
5529
  const finish = (value, detached = false) => {
5397
5530
  if (finished) return;
5398
5531
  finished = true;
5532
+ releaseCapacity();
5399
5533
  controller.signal.removeEventListener("abort", abort);
5400
5534
  options.cleanup?.();
5401
5535
  update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
@@ -5443,6 +5577,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
5443
5577
  const close = () => {
5444
5578
  iteratorClosed = true;
5445
5579
  queue.length = 0;
5580
+ releaseCapacity();
5446
5581
  if (pending) {
5447
5582
  pending.resolve({ value: void 0, done: true });
5448
5583
  pending = void 0;
@@ -5454,7 +5589,11 @@ function consumeResponse(response, controller, cancel, options = {}) {
5454
5589
  },
5455
5590
  next() {
5456
5591
  if (iteratorError) return Promise.reject(iteratorError);
5457
- if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5592
+ if (queue.length) {
5593
+ const value = queue.shift();
5594
+ releaseCapacity();
5595
+ return Promise.resolve({ value, done: false });
5596
+ }
5458
5597
  if (finished || iteratorClosed)
5459
5598
  return Promise.resolve({ value: void 0, done: true });
5460
5599
  if (pending)
@@ -5615,8 +5754,13 @@ function consumeResponse(response, controller, cancel, options = {}) {
5615
5754
  try {
5616
5755
  while (!finished) {
5617
5756
  const { value, done } = await reader.read();
5618
- for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5757
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5619
5758
  process2(frame);
5759
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5760
+ await new Promise((resolve2) => {
5761
+ capacityAvailable = resolve2;
5762
+ });
5763
+ }
5620
5764
  if (done) break;
5621
5765
  }
5622
5766
  if (!finished) {
@@ -6080,9 +6224,12 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6080
6224
  folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
6081
6225
  presign_expires_in: options?.presignExpiresIn ?? 3600
6082
6226
  };
6083
- const initResult = requireData(
6084
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6085
- "Failed to initialize direct upload"
6227
+ const guarded = options?.inWorkspace ?? ((send) => send());
6228
+ const initResult = await guarded(
6229
+ async () => requireData(
6230
+ await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6231
+ "Failed to initialize direct upload"
6232
+ )
6086
6233
  );
6087
6234
  const items = initResult.items ?? [];
6088
6235
  const bytesByName = /* @__PURE__ */ new Map();
@@ -6139,14 +6286,16 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6139
6286
  if (toCommit.length === 0) {
6140
6287
  return { doc_ext_ids: [], skipped };
6141
6288
  }
6142
- const commitResult = requireData(
6143
- await arbi.fetch.POST("/v1/document/upload-commit", {
6144
- body: {
6145
- doc_ext_ids: toCommit,
6146
- tag_ext_id: options?.tagExtId ?? null
6147
- }
6148
- }),
6149
- "Failed to commit direct upload"
6289
+ const commitResult = await guarded(
6290
+ async () => requireData(
6291
+ await arbi.fetch.POST("/v1/document/upload-commit", {
6292
+ body: {
6293
+ doc_ext_ids: toCommit,
6294
+ tag_ext_id: options?.tagExtId ?? null
6295
+ }
6296
+ }),
6297
+ "Failed to commit direct upload"
6298
+ )
6150
6299
  );
6151
6300
  return {
6152
6301
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6664,6 +6813,7 @@ __export(assistant_exports, {
6664
6813
  AssistantTurnRefused: () => AssistantTurnRefused,
6665
6814
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
6666
6815
  SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
6816
+ WORKSPACE_CONFLICT_MESSAGES: () => WORKSPACE_CONFLICT_MESSAGES,
6667
6817
  cancelRun: () => cancelRun,
6668
6818
  filterSkills: () => filterSkills,
6669
6819
  interject: () => interject,
@@ -6897,11 +7047,29 @@ function quotaFromStreamError(error) {
6897
7047
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6898
7048
  return { spend, budget, projectExtId: match.groups.project ?? null };
6899
7049
  }
7050
+ var WORKSPACE_CONFLICT_MESSAGES = {
7051
+ workspace_mismatch: "This conversation belongs to another workspace, so the reply was not sent. Open that workspace to continue it.",
7052
+ workspace_key_required: "This chat's workspace isn't open in this session, so the message was not sent. Open the workspace and try again."
7053
+ };
6900
7054
  async function refusal(response) {
6901
7055
  const { status } = response;
6902
7056
  const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6903
7057
  const detail = parsed.apiError?.detail;
6904
7058
  const quota = status === 402 ? quotaExceededFrom(detail) : null;
7059
+ const conflict = status === 409 ? workspaceConflictOf(parsed.apiError) : null;
7060
+ if (conflict) {
7061
+ return new AssistantTurnRefused(
7062
+ WORKSPACE_CONFLICT_MESSAGES[conflict.code],
7063
+ status,
7064
+ null,
7065
+ parsed.apiError,
7066
+ {
7067
+ code: conflict.code,
7068
+ requestId: parsed.requestId,
7069
+ responseId: parsed.responseId
7070
+ }
7071
+ );
7072
+ }
6905
7073
  const fallback = status === 409 ? "This message has failed. Please retry from the previous message." : status === 503 ? "The selected LLM is not responding. Please retry again in a minute or select another model." : status === 402 ? "This project's AI usage for this month is used up." : parsed.message;
6906
7074
  return new AssistantTurnRefused(
6907
7075
  quota?.message || parsed.detail || fallback,
@@ -7040,88 +7208,6 @@ async function cancelRun(auth, responseId) {
7040
7208
  });
7041
7209
  }
7042
7210
 
7043
- // src/operations/responses.ts
7044
- var responses_exports = {};
7045
- __export(responses_exports, {
7046
- extractResponseText: () => extractResponseText,
7047
- getResponse: () => getResponse,
7048
- submitBackgroundQuery: () => submitBackgroundQuery
7049
- });
7050
- async function submitBackgroundQuery(options) {
7051
- const {
7052
- workspaceId,
7053
- question,
7054
- docIds,
7055
- previousResponseId,
7056
- model,
7057
- text: text2,
7058
- task,
7059
- conversationId,
7060
- mentions,
7061
- activeArtifactExtId,
7062
- fullContext = true,
7063
- ...auth
7064
- } = options;
7065
- const tools = {};
7066
- if (docIds.length > 0) {
7067
- tools.retrieval_chunk = {
7068
- name: "retrieval_chunk",
7069
- description: "retrieval chunk",
7070
- tool_args: { doc_ext_ids: docIds },
7071
- tool_responses: {}
7072
- };
7073
- if (fullContext)
7074
- tools.retrieval_full_context = {
7075
- name: "retrieval_full_context",
7076
- description: "retrieval full context",
7077
- tool_args: { doc_ext_ids: docIds },
7078
- tool_responses: {}
7079
- };
7080
- }
7081
- const body = {
7082
- input: question,
7083
- workspace_ext_id: workspaceId,
7084
- stream: false,
7085
- background: true,
7086
- store: true,
7087
- tools,
7088
- ...task !== void 0 ? { task } : {},
7089
- ...conversationId ? { conversation_ext_id: conversationId } : {},
7090
- ...mentions !== void 0 ? { mentions } : {},
7091
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
7092
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
7093
- ...model ? { model } : {},
7094
- ...text2 ? { text: text2 } : {}
7095
- };
7096
- const res = await authenticatedFetch({
7097
- ...auth,
7098
- path: "/v1/responses",
7099
- method: "POST",
7100
- body: JSON.stringify(body),
7101
- headers: { "Content-Type": "application/json" }
7102
- });
7103
- return await res.json();
7104
- }
7105
- async function getResponse(auth, responseId) {
7106
- const res = await authenticatedFetch({
7107
- ...auth,
7108
- path: `/v1/responses/${responseId}`,
7109
- method: "GET"
7110
- });
7111
- return await res.json();
7112
- }
7113
- function extractResponseText(response) {
7114
- const parts = [];
7115
- for (const msg of response.output) {
7116
- for (const item of msg.content) {
7117
- if ("type" in item && item.type === "output_text" && "text" in item) {
7118
- parts.push(item.text);
7119
- }
7120
- }
7121
- }
7122
- return parts.join("");
7123
- }
7124
-
7125
7211
  // src/operations/tags.ts
7126
7212
  var tags_exports = {};
7127
7213
  __export(tags_exports, {
@@ -11558,11 +11644,57 @@ var Arbi = class {
11558
11644
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
11559
11645
  * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
11560
11646
  * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
11647
+ * A workspace the user holds no key for (a public one, or a temporary grant whose key the server
11648
+ * session already holds) has nothing to deposit: the server answers for it as it is.
11561
11649
  */
11562
- openWorkspace(workspaceId) {
11563
- if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
11650
+ async openWorkspace(workspaceId) {
11651
+ if (workspaceId === this.currentWorkspaceId) return;
11564
11652
  this.requireLogin();
11565
- return this.requireClient().workspaceKeys.prime(workspaceId);
11653
+ const keys = this.requireClient().workspaceKeys;
11654
+ const { wrappedKey } = await keys.wrappedKey(workspaceId).catch(keyLookupFailed);
11655
+ if (!wrappedKey) return;
11656
+ return keys.prime(workspaceId);
11657
+ }
11658
+ /**
11659
+ * {@link openWorkspace} (or, with `force`, deposit the key again even for the current workspace:
11660
+ * the server said it lacks it), failing with {@link ArbiWorkspaceUnavailableError} when the key
11661
+ * cannot be deposited. Then nothing is sent, so nothing can land in another workspace.
11662
+ */
11663
+ async primeOrFail(workspaceId, options = {}) {
11664
+ try {
11665
+ if (options.force) {
11666
+ this.requireLogin();
11667
+ await this.requireClient().workspaceKeys.prime(workspaceId, { force: true });
11668
+ } else await this.openWorkspace(workspaceId);
11669
+ } catch (error) {
11670
+ if (isAbortError(error) || error instanceof ArbiSessionExpiredError) throw error;
11671
+ throw new ArbiWorkspaceUnavailableError(workspaceId, error);
11672
+ }
11673
+ }
11674
+ /**
11675
+ * Open a chat turn's stream in `workspaceId` (captured by the caller when the turn started): the
11676
+ * workspace is opened for this session first if it is not the current one, and the body names
11677
+ * it, so a switch meanwhile cannot move the turn. A follow-up refused with 409
11678
+ * `workspace_mismatch` (its thread is in another workspace: nothing was written) is sent once
11679
+ * more in the thread's workspace, which is where the server stores a follow-up anyway.
11680
+ * `onWorkspace` hears the workspace the turn was accepted in.
11681
+ */
11682
+ async openTurn(request, workspaceId, open, onWorkspace) {
11683
+ let target = workspaceId;
11684
+ for (let attempt = 0; ; attempt++) {
11685
+ await this.primeOrFail(target);
11686
+ const body = buildTurnRequest({ ...request, workspaceId: target });
11687
+ try {
11688
+ const response = await this.recovering(() => open(body));
11689
+ onWorkspace?.(target);
11690
+ return response;
11691
+ } catch (error) {
11692
+ const conflict = workspaceConflictOf(error);
11693
+ const retryInThread = attempt === 0 && !!request.previousResponseId && conflict?.code === "workspace_mismatch" && conflict.workspaceId !== target;
11694
+ if (!retryInThread) throw error;
11695
+ target = conflict.workspaceId;
11696
+ }
11697
+ }
11566
11698
  }
11567
11699
  /**
11568
11700
  * Create a tag in `workspaceId`, named on the request: a switch while it is sent cannot move it to the workspace
@@ -11719,6 +11851,11 @@ var Arbi = class {
11719
11851
  try {
11720
11852
  return await run();
11721
11853
  } catch (error) {
11854
+ const conflict = workspaceConflictOf(error);
11855
+ if (conflict?.code === "workspace_key_required") {
11856
+ await this.primeOrFail(conflict.workspaceId, { force: true });
11857
+ return run();
11858
+ }
11722
11859
  const message = error instanceof Error ? error.message : "";
11723
11860
  const noWorkspace = /no active workspace/i.test(message);
11724
11861
  const unauthorised = /\b401\b|token has expired/i.test(message);
@@ -12226,6 +12363,23 @@ var Arbi = class {
12226
12363
  });
12227
12364
  });
12228
12365
  },
12366
+ /**
12367
+ * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
12368
+ * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
12369
+ * name no workspace yet (they act on the session's open one), so each runs under
12370
+ * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
12371
+ * it is sent and still when it returns. A switch refuses the upload
12372
+ * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
12373
+ * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
12374
+ */
12375
+ uploadDirect: (workspaceId, workspaceKey, files, options) => {
12376
+ if (this.currentWorkspaceId !== workspaceId)
12377
+ return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
12378
+ return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
12379
+ ...options,
12380
+ inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
12381
+ });
12382
+ },
12229
12383
  /** Download a document's original file — its current version, or `version`. */
12230
12384
  download: (docId, version) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId, version)),
12231
12385
  getParsedContent: (docId, stage, version) => this.recovering(
@@ -12281,8 +12435,13 @@ var Arbi = class {
12281
12435
  const first = await runConversation(client, conversationId);
12282
12436
  if (!first.pending_auth_request_id) return first;
12283
12437
  const pending = await getPendingAuth(client, conversationId);
12438
+ if (!pending.workspace_ext_id)
12439
+ throw new ArbiError(
12440
+ "The run is waiting for access, but the server did not say to which workspace",
12441
+ { code: "PENDING_AUTH_WITHOUT_WORKSPACE" }
12442
+ );
12284
12443
  await this.workspaces.grantTemporaryAccess({
12285
- workspaceId: pending.workspace_ext_id ?? this.getWorkspaceId(),
12444
+ workspaceId: pending.workspace_ext_id,
12286
12445
  emails: [pending.agent_email],
12287
12446
  sessionPubkeyB64: pending.session_pubkey
12288
12447
  });
@@ -12375,7 +12534,7 @@ var Arbi = class {
12375
12534
  });
12376
12535
  }
12377
12536
  };
12378
- async openResponseHandle(open, options, id) {
12537
+ async openResponseHandle(open, options, id, bufferEvents = false) {
12379
12538
  const controller = new AbortController();
12380
12539
  const abort = () => controller.abort();
12381
12540
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -12387,7 +12546,7 @@ var Arbi = class {
12387
12546
  response,
12388
12547
  controller,
12389
12548
  (responseId) => this.assistant.cancel(responseId),
12390
- { id, cleanup }
12549
+ { id, cleanup, bufferEvents }
12391
12550
  );
12392
12551
  } catch (error) {
12393
12552
  cleanup();
@@ -12398,18 +12557,41 @@ var Arbi = class {
12398
12557
  /** Canonical Responses-shaped requests; existing assistant convenience helpers remain supported. */
12399
12558
  responses = {
12400
12559
  create: async (request, options = {}) => {
12560
+ if (request.stream) {
12561
+ if (request.background)
12562
+ throw new ArbiError(
12563
+ "Streaming background creation is not supported yet. Create in background mode, then attach to the returned response.",
12564
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12565
+ );
12566
+ const body2 = {
12567
+ ...request,
12568
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12569
+ stream: true,
12570
+ background: false,
12571
+ store: request.store ?? true
12572
+ };
12573
+ const started = await this.openResponseHandle(
12574
+ (signal) => openTurnStream(this.getAuthHeaders(), body2, signal),
12575
+ options,
12576
+ void 0,
12577
+ true
12578
+ );
12579
+ if (started.kind !== "response")
12580
+ throw new ArbiError("The control command was acknowledged without creating a response.", {
12581
+ code: "RESPONSE_CONTROL_ACKNOWLEDGED",
12582
+ cause: started.acknowledgement
12583
+ });
12584
+ return new ResponseStream(started.handle);
12585
+ }
12586
+ const requestBody = {
12587
+ ...request,
12588
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12589
+ stream: false,
12590
+ background: request.background ?? false,
12591
+ store: request.store ?? true
12592
+ };
12401
12593
  const response = await this.recovering(
12402
- () => openTurnStream(
12403
- this.getAuthHeaders(),
12404
- {
12405
- ...request,
12406
- workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12407
- stream: false,
12408
- background: request.background ?? false,
12409
- store: request.store ?? true
12410
- },
12411
- options.signal
12412
- )
12594
+ () => openTurnStream(this.getAuthHeaders(), requestBody, options.signal)
12413
12595
  );
12414
12596
  let body;
12415
12597
  try {
@@ -12418,7 +12600,10 @@ var Arbi = class {
12418
12600
  throw transportError(cause);
12419
12601
  }
12420
12602
  try {
12421
- return JSON.parse(body);
12603
+ return withOutputText(
12604
+ JSON.parse(body),
12605
+ response.headers.get("x-request-id") ?? void 0
12606
+ );
12422
12607
  } catch (cause) {
12423
12608
  throw new ArbiError("Expected a Responses JSON object.", {
12424
12609
  code: "RESPONSE_INVALID_ENVELOPE",
@@ -12427,6 +12612,23 @@ var Arbi = class {
12427
12612
  });
12428
12613
  }
12429
12614
  },
12615
+ parse: async (request, options = {}) => {
12616
+ if (request.stream || request.background)
12617
+ throw new ArbiError(
12618
+ "Parse a synchronous response, or validate a completed stored response separately.",
12619
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12620
+ );
12621
+ const workspaceId = request.workspace_ext_id ?? this.requireWorkspace();
12622
+ const parse = await createStructuredParser(request.text.format);
12623
+ const response = await this.responses.create(
12624
+ { ...request, workspace_ext_id: workspaceId, stream: false, background: false },
12625
+ options
12626
+ );
12627
+ return {
12628
+ ...response,
12629
+ output_parsed: parse(response, { requestId: response._request_id }).data
12630
+ };
12631
+ },
12430
12632
  stream: (request, options = {}) => this.openResponseHandle(
12431
12633
  (signal) => openTurnStream(
12432
12634
  this.getAuthHeaders(),
@@ -12441,7 +12643,7 @@ var Arbi = class {
12441
12643
  ),
12442
12644
  options
12443
12645
  ),
12444
- retrieve: (id) => this.assistant.getResponse(id),
12646
+ retrieve: async (id) => withOutputText(await this.assistant.getResponse(id)),
12445
12647
  cancel: (id) => this.assistant.cancel(id),
12446
12648
  attach: (id, options = {}) => this.assistant.attachResponse(id, options)
12447
12649
  };
@@ -12481,12 +12683,14 @@ var Arbi = class {
12481
12683
  },
12482
12684
  /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
12483
12685
  startResponse: async (request, options = {}) => {
12484
- const body = buildTurnRequest({
12485
- ...request,
12486
- workspaceId: request.workspaceId ?? this.requireWorkspace()
12487
- });
12686
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
12488
12687
  return this.openResponseHandle(
12489
- (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12688
+ (signal) => this.openTurn(
12689
+ request,
12690
+ workspaceId,
12691
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12692
+ options.onWorkspace
12693
+ ),
12490
12694
  options
12491
12695
  );
12492
12696
  },
@@ -12514,22 +12718,29 @@ var Arbi = class {
12514
12718
  * with it; an abort just rejects.
12515
12719
  */
12516
12720
  ask: async (request, handlers = {}) => {
12517
- const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
12518
- const body = buildTurnRequest({
12519
- ...request,
12520
- workspaceId: request.workspaceId ?? this.requireWorkspace()
12521
- });
12721
+ const { signal, onError, onQuotaExceeded, onWorkspace, ...callbacks } = handlers;
12722
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
12522
12723
  const refuse = (message, error = new Error(message)) => {
12523
12724
  onError?.(message);
12524
12725
  throw error;
12525
12726
  };
12526
12727
  let response;
12527
12728
  try {
12528
- response = await this.recovering(
12529
- () => openTurnStream(this.getAuthHeaders(), body, signal)
12729
+ response = await this.openTurn(
12730
+ request,
12731
+ workspaceId,
12732
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12733
+ onWorkspace
12530
12734
  );
12531
12735
  } catch (error) {
12532
12736
  if (isAbort(error)) throw error;
12737
+ if (error instanceof ArbiWorkspaceUnavailableError) {
12738
+ callbacks.onErrorDetails?.(error);
12739
+ return refuse(
12740
+ "This chat's workspace can't be opened in this session, so the message was not sent.",
12741
+ error
12742
+ );
12743
+ }
12533
12744
  if (error instanceof AssistantTurnRefused) {
12534
12745
  if (error.quota) onQuotaExceeded?.(error.quota);
12535
12746
  callbacks.onErrorDetails?.(error);
@@ -12587,14 +12798,16 @@ var Arbi = class {
12587
12798
  transcribe: (audio) => transcribe(this.requireClient(), audio),
12588
12799
  /** Start a durable background turn; task options make its thread a work item. */
12589
12800
  submit: (question, options) => {
12590
- const workspaceId = this.requireWorkspace();
12591
- return this.recovering(
12592
- () => submitBackgroundQuery({
12593
- ...this.getAuthHeaders(),
12594
- ...options,
12595
- workspaceId,
12596
- question
12597
- })
12801
+ const workspaceId = options.workspaceId ?? this.requireWorkspace();
12802
+ return this.primeOrFail(workspaceId).then(
12803
+ () => this.recovering(
12804
+ () => submitBackgroundQuery({
12805
+ ...this.getAuthHeaders(),
12806
+ ...options,
12807
+ workspaceId,
12808
+ question
12809
+ })
12810
+ )
12598
12811
  );
12599
12812
  },
12600
12813
  /** Read the status of a background turn. */
@@ -12615,13 +12828,19 @@ var Arbi = class {
12615
12828
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
12616
12829
  * workspace; `searchChunks(result)` ranks the passages found.
12617
12830
  */
12618
- retrieve: (query2, docIds, options) => retrieve({
12619
- arbi: this.requireClient(),
12620
- workspaceId: this.requireWorkspace(),
12621
- query: query2,
12622
- docIds,
12623
- ...options
12624
- })
12831
+ retrieve: (query2, docIds, options) => {
12832
+ const { workspaceId: named, ...rest } = options ?? {};
12833
+ const workspaceId = named ?? this.requireWorkspace();
12834
+ return this.primeOrFail(workspaceId).then(
12835
+ () => retrieve({
12836
+ arbi: this.requireClient(),
12837
+ workspaceId,
12838
+ query: query2,
12839
+ docIds,
12840
+ ...rest
12841
+ })
12842
+ );
12843
+ }
12625
12844
  };
12626
12845
  // ── Tags ──────────────────────────────────────────────────────────────
12627
12846
  tags = {
@@ -15165,6 +15384,6 @@ function composeTools(base, next, mode) {
15165
15384
  return structuredClone(mode === "add" ? { ...base, ...next } : next);
15166
15385
  }
15167
15386
 
15168
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiStructuredOutputError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, CallApiError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, capabilities, chats_exports as chats, composeConfiguration, composeTools, computeRunStats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, contacts_exports as contacts, continuityPrompt, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, createIndexAssigner, databases_exports as databases, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documentTools, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, instructions, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mcpTools, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, parseStructuredResponse, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
15387
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiStructuredOutputError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, ArbiWorkspaceUnavailableError, CallApiError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, ResponseStream, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, capabilities, chats_exports as chats, composeConfiguration, composeTools, computeRunStats, connectErrorMessage, connectWebSocket, connectWithReconnect, connectors_exports as connectors, contacts_exports as contacts, continuityPrompt, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, createIndexAssigner, databases_exports as databases, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documentTools, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, instructions, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mcpTools, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, parseStructuredResponse, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaceConflictOf, workspaces_exports as workspaces, wouldCreateTagCycle };
15169
15388
  //# sourceMappingURL=index.js.map
15170
15389
  //# sourceMappingURL=index.js.map