@arbidocs/sdk 0.5.61 → 0.5.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3526,6 +3526,22 @@ var ArbiWorkspaceChangedError = class extends ArbiError {
3526
3526
  }
3527
3527
  workspaceId;
3528
3528
  };
3529
+ var ArbiWorkspaceUnavailableError = class extends ArbiError {
3530
+ constructor(workspaceId, cause, message = `Workspace ${workspaceId} can't be opened in this session, so nothing was sent`) {
3531
+ super(message, { code: "WORKSPACE_UNAVAILABLE", cause });
3532
+ this.workspaceId = workspaceId;
3533
+ this.name = "ArbiWorkspaceUnavailableError";
3534
+ }
3535
+ workspaceId;
3536
+ };
3537
+ function workspaceConflictOf(error) {
3538
+ const body = error instanceof ArbiApiError ? error.apiError : error instanceof Error ? void 0 : error;
3539
+ const detail = errorRecord(errorRecord(body)?.detail);
3540
+ const code = detail?.code;
3541
+ const workspaceId = detail?.workspace_ext_id;
3542
+ if (code !== "workspace_key_required" && code !== "workspace_mismatch") return null;
3543
+ return typeof workspaceId === "string" && workspaceId ? { code, workspaceId } : null;
3544
+ }
3529
3545
  function detailText(detail) {
3530
3546
  if (typeof detail === "string") return detail || void 0;
3531
3547
  if (Array.isArray(detail)) {
@@ -5165,6 +5181,118 @@ function buildChunkLookup(tools) {
5165
5181
  return lookup;
5166
5182
  }
5167
5183
 
5184
+ // src/operations/responses.ts
5185
+ var responses_exports = {};
5186
+ __export(responses_exports, {
5187
+ extractResponseText: () => extractResponseText,
5188
+ getResponse: () => getResponse,
5189
+ submitBackgroundQuery: () => submitBackgroundQuery
5190
+ });
5191
+ async function submitBackgroundQuery(options) {
5192
+ const {
5193
+ workspaceId,
5194
+ question,
5195
+ docIds,
5196
+ previousResponseId,
5197
+ model,
5198
+ text: text2,
5199
+ task,
5200
+ conversationId,
5201
+ mentions,
5202
+ activeArtifactExtId,
5203
+ fullContext = true,
5204
+ ...auth
5205
+ } = options;
5206
+ const tools = {};
5207
+ if (docIds.length > 0) {
5208
+ tools.retrieval_chunk = {
5209
+ name: "retrieval_chunk",
5210
+ description: "retrieval chunk",
5211
+ tool_args: { doc_ext_ids: docIds },
5212
+ tool_responses: {}
5213
+ };
5214
+ if (fullContext)
5215
+ tools.retrieval_full_context = {
5216
+ name: "retrieval_full_context",
5217
+ description: "retrieval full context",
5218
+ tool_args: { doc_ext_ids: docIds },
5219
+ tool_responses: {}
5220
+ };
5221
+ }
5222
+ const body = {
5223
+ input: question,
5224
+ workspace_ext_id: workspaceId,
5225
+ stream: false,
5226
+ background: true,
5227
+ store: true,
5228
+ tools,
5229
+ ...task !== void 0 ? { task } : {},
5230
+ ...conversationId ? { conversation_ext_id: conversationId } : {},
5231
+ ...mentions !== void 0 ? { mentions } : {},
5232
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5233
+ ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5234
+ ...model ? { model } : {},
5235
+ ...text2 ? { text: text2 } : {}
5236
+ };
5237
+ const res = await authenticatedFetch({
5238
+ ...auth,
5239
+ path: "/v1/responses",
5240
+ method: "POST",
5241
+ body: JSON.stringify(body),
5242
+ headers: { "Content-Type": "application/json" }
5243
+ });
5244
+ return await res.json();
5245
+ }
5246
+ async function getResponse(auth, responseId) {
5247
+ const res = await authenticatedFetch({
5248
+ ...auth,
5249
+ path: `/v1/responses/${responseId}`,
5250
+ method: "GET"
5251
+ });
5252
+ return await res.json();
5253
+ }
5254
+ function extractResponseText(response) {
5255
+ const parts = [];
5256
+ for (const msg of Array.isArray(response.output) ? response.output : []) {
5257
+ if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
5258
+ for (const item of msg.content) {
5259
+ if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
5260
+ }
5261
+ }
5262
+ return parts.join("");
5263
+ }
5264
+
5265
+ // src/responses-resource.ts
5266
+ function withOutputText(response, requestId) {
5267
+ return {
5268
+ ...response,
5269
+ output_text: extractResponseText(response),
5270
+ ...requestId ? { _request_id: requestId } : {}
5271
+ };
5272
+ }
5273
+ var ResponseStream = class {
5274
+ constructor(handle) {
5275
+ this.handle = handle;
5276
+ }
5277
+ handle;
5278
+ async *[Symbol.asyncIterator]() {
5279
+ try {
5280
+ for await (const frame of this.handle.events()) {
5281
+ const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
5282
+ yield {
5283
+ ...data,
5284
+ type: typeof data.type === "string" ? data.type : frame.event
5285
+ };
5286
+ }
5287
+ const outcome = await this.handle.outcome;
5288
+ if (outcome.status === "disconnected")
5289
+ throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
5290
+ } finally {
5291
+ this.handle.detach();
5292
+ }
5293
+ }
5294
+ };
5295
+
5168
5296
  // src/structured-output.ts
5169
5297
  var ArbiStructuredOutputError = class extends ArbiError {
5170
5298
  constructor(message, response, options) {
@@ -5371,12 +5499,17 @@ function consumeResponse(response, controller, cancel, options = {}) {
5371
5499
  let acknowledgement;
5372
5500
  const listeners = /* @__PURE__ */ new Set();
5373
5501
  const queue = [];
5502
+ let capacityAvailable;
5503
+ const releaseCapacity = () => {
5504
+ capacityAvailable?.();
5505
+ capacityAvailable = void 0;
5506
+ };
5374
5507
  let claimed = false;
5375
5508
  let iteratorClosed = false;
5376
5509
  let iteratorError;
5377
5510
  let pending;
5378
5511
  const emit = (event) => {
5379
- if (!claimed || iteratorClosed) return;
5512
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
5380
5513
  if (pending) {
5381
5514
  pending.resolve({ value: immutable(event), done: false });
5382
5515
  pending = void 0;
@@ -5405,6 +5538,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
5405
5538
  const finish = (value, detached = false) => {
5406
5539
  if (finished) return;
5407
5540
  finished = true;
5541
+ releaseCapacity();
5408
5542
  controller.signal.removeEventListener("abort", abort);
5409
5543
  options.cleanup?.();
5410
5544
  update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
@@ -5452,6 +5586,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
5452
5586
  const close = () => {
5453
5587
  iteratorClosed = true;
5454
5588
  queue.length = 0;
5589
+ releaseCapacity();
5455
5590
  if (pending) {
5456
5591
  pending.resolve({ value: void 0, done: true });
5457
5592
  pending = void 0;
@@ -5463,7 +5598,11 @@ function consumeResponse(response, controller, cancel, options = {}) {
5463
5598
  },
5464
5599
  next() {
5465
5600
  if (iteratorError) return Promise.reject(iteratorError);
5466
- if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5601
+ if (queue.length) {
5602
+ const value = queue.shift();
5603
+ releaseCapacity();
5604
+ return Promise.resolve({ value, done: false });
5605
+ }
5467
5606
  if (finished || iteratorClosed)
5468
5607
  return Promise.resolve({ value: void 0, done: true });
5469
5608
  if (pending)
@@ -5624,8 +5763,13 @@ function consumeResponse(response, controller, cancel, options = {}) {
5624
5763
  try {
5625
5764
  while (!finished) {
5626
5765
  const { value, done } = await reader.read();
5627
- for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5766
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5628
5767
  process2(frame);
5768
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5769
+ await new Promise((resolve2) => {
5770
+ capacityAvailable = resolve2;
5771
+ });
5772
+ }
5629
5773
  if (done) break;
5630
5774
  }
5631
5775
  if (!finished) {
@@ -6089,9 +6233,12 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6089
6233
  folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
6090
6234
  presign_expires_in: options?.presignExpiresIn ?? 3600
6091
6235
  };
6092
- const initResult = requireData(
6093
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6094
- "Failed to initialize direct upload"
6236
+ const guarded = options?.inWorkspace ?? ((send) => send());
6237
+ const initResult = await guarded(
6238
+ async () => requireData(
6239
+ await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6240
+ "Failed to initialize direct upload"
6241
+ )
6095
6242
  );
6096
6243
  const items = initResult.items ?? [];
6097
6244
  const bytesByName = /* @__PURE__ */ new Map();
@@ -6148,14 +6295,16 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6148
6295
  if (toCommit.length === 0) {
6149
6296
  return { doc_ext_ids: [], skipped };
6150
6297
  }
6151
- const commitResult = requireData(
6152
- await arbi.fetch.POST("/v1/document/upload-commit", {
6153
- body: {
6154
- doc_ext_ids: toCommit,
6155
- tag_ext_id: options?.tagExtId ?? null
6156
- }
6157
- }),
6158
- "Failed to commit direct upload"
6298
+ const commitResult = await guarded(
6299
+ async () => requireData(
6300
+ await arbi.fetch.POST("/v1/document/upload-commit", {
6301
+ body: {
6302
+ doc_ext_ids: toCommit,
6303
+ tag_ext_id: options?.tagExtId ?? null
6304
+ }
6305
+ }),
6306
+ "Failed to commit direct upload"
6307
+ )
6159
6308
  );
6160
6309
  return {
6161
6310
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6673,6 +6822,7 @@ __export(assistant_exports, {
6673
6822
  AssistantTurnRefused: () => AssistantTurnRefused,
6674
6823
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
6675
6824
  SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
6825
+ WORKSPACE_CONFLICT_MESSAGES: () => WORKSPACE_CONFLICT_MESSAGES,
6676
6826
  cancelRun: () => cancelRun,
6677
6827
  filterSkills: () => filterSkills,
6678
6828
  interject: () => interject,
@@ -6906,11 +7056,29 @@ function quotaFromStreamError(error) {
6906
7056
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6907
7057
  return { spend, budget, projectExtId: match.groups.project ?? null };
6908
7058
  }
7059
+ var WORKSPACE_CONFLICT_MESSAGES = {
7060
+ workspace_mismatch: "This conversation belongs to another workspace, so the reply was not sent. Open that workspace to continue it.",
7061
+ 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."
7062
+ };
6909
7063
  async function refusal(response) {
6910
7064
  const { status } = response;
6911
7065
  const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6912
7066
  const detail = parsed.apiError?.detail;
6913
7067
  const quota = status === 402 ? quotaExceededFrom(detail) : null;
7068
+ const conflict = status === 409 ? workspaceConflictOf(parsed.apiError) : null;
7069
+ if (conflict) {
7070
+ return new AssistantTurnRefused(
7071
+ WORKSPACE_CONFLICT_MESSAGES[conflict.code],
7072
+ status,
7073
+ null,
7074
+ parsed.apiError,
7075
+ {
7076
+ code: conflict.code,
7077
+ requestId: parsed.requestId,
7078
+ responseId: parsed.responseId
7079
+ }
7080
+ );
7081
+ }
6914
7082
  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;
6915
7083
  return new AssistantTurnRefused(
6916
7084
  quota?.message || parsed.detail || fallback,
@@ -7049,88 +7217,6 @@ async function cancelRun(auth, responseId) {
7049
7217
  });
7050
7218
  }
7051
7219
 
7052
- // src/operations/responses.ts
7053
- var responses_exports = {};
7054
- __export(responses_exports, {
7055
- extractResponseText: () => extractResponseText,
7056
- getResponse: () => getResponse,
7057
- submitBackgroundQuery: () => submitBackgroundQuery
7058
- });
7059
- async function submitBackgroundQuery(options) {
7060
- const {
7061
- workspaceId,
7062
- question,
7063
- docIds,
7064
- previousResponseId,
7065
- model,
7066
- text: text2,
7067
- task,
7068
- conversationId,
7069
- mentions,
7070
- activeArtifactExtId,
7071
- fullContext = true,
7072
- ...auth
7073
- } = options;
7074
- const tools = {};
7075
- if (docIds.length > 0) {
7076
- tools.retrieval_chunk = {
7077
- name: "retrieval_chunk",
7078
- description: "retrieval chunk",
7079
- tool_args: { doc_ext_ids: docIds },
7080
- tool_responses: {}
7081
- };
7082
- if (fullContext)
7083
- tools.retrieval_full_context = {
7084
- name: "retrieval_full_context",
7085
- description: "retrieval full context",
7086
- tool_args: { doc_ext_ids: docIds },
7087
- tool_responses: {}
7088
- };
7089
- }
7090
- const body = {
7091
- input: question,
7092
- workspace_ext_id: workspaceId,
7093
- stream: false,
7094
- background: true,
7095
- store: true,
7096
- tools,
7097
- ...task !== void 0 ? { task } : {},
7098
- ...conversationId ? { conversation_ext_id: conversationId } : {},
7099
- ...mentions !== void 0 ? { mentions } : {},
7100
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
7101
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
7102
- ...model ? { model } : {},
7103
- ...text2 ? { text: text2 } : {}
7104
- };
7105
- const res = await authenticatedFetch({
7106
- ...auth,
7107
- path: "/v1/responses",
7108
- method: "POST",
7109
- body: JSON.stringify(body),
7110
- headers: { "Content-Type": "application/json" }
7111
- });
7112
- return await res.json();
7113
- }
7114
- async function getResponse(auth, responseId) {
7115
- const res = await authenticatedFetch({
7116
- ...auth,
7117
- path: `/v1/responses/${responseId}`,
7118
- method: "GET"
7119
- });
7120
- return await res.json();
7121
- }
7122
- function extractResponseText(response) {
7123
- const parts = [];
7124
- for (const msg of response.output) {
7125
- for (const item of msg.content) {
7126
- if ("type" in item && item.type === "output_text" && "text" in item) {
7127
- parts.push(item.text);
7128
- }
7129
- }
7130
- }
7131
- return parts.join("");
7132
- }
7133
-
7134
7220
  // src/operations/tags.ts
7135
7221
  var tags_exports = {};
7136
7222
  __export(tags_exports, {
@@ -11567,11 +11653,57 @@ var Arbi = class {
11567
11653
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
11568
11654
  * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
11569
11655
  * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
11656
+ * A workspace the user holds no key for (a public one, or a temporary grant whose key the server
11657
+ * session already holds) has nothing to deposit: the server answers for it as it is.
11570
11658
  */
11571
- openWorkspace(workspaceId) {
11572
- if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
11659
+ async openWorkspace(workspaceId) {
11660
+ if (workspaceId === this.currentWorkspaceId) return;
11573
11661
  this.requireLogin();
11574
- return this.requireClient().workspaceKeys.prime(workspaceId);
11662
+ const keys = this.requireClient().workspaceKeys;
11663
+ const { wrappedKey } = await keys.wrappedKey(workspaceId).catch(keyLookupFailed);
11664
+ if (!wrappedKey) return;
11665
+ return keys.prime(workspaceId);
11666
+ }
11667
+ /**
11668
+ * {@link openWorkspace} (or, with `force`, deposit the key again even for the current workspace:
11669
+ * the server said it lacks it), failing with {@link ArbiWorkspaceUnavailableError} when the key
11670
+ * cannot be deposited. Then nothing is sent, so nothing can land in another workspace.
11671
+ */
11672
+ async primeOrFail(workspaceId, options = {}) {
11673
+ try {
11674
+ if (options.force) {
11675
+ this.requireLogin();
11676
+ await this.requireClient().workspaceKeys.prime(workspaceId, { force: true });
11677
+ } else await this.openWorkspace(workspaceId);
11678
+ } catch (error) {
11679
+ if (client.isAbortError(error) || error instanceof ArbiSessionExpiredError) throw error;
11680
+ throw new ArbiWorkspaceUnavailableError(workspaceId, error);
11681
+ }
11682
+ }
11683
+ /**
11684
+ * Open a chat turn's stream in `workspaceId` (captured by the caller when the turn started): the
11685
+ * workspace is opened for this session first if it is not the current one, and the body names
11686
+ * it, so a switch meanwhile cannot move the turn. A follow-up refused with 409
11687
+ * `workspace_mismatch` (its thread is in another workspace: nothing was written) is sent once
11688
+ * more in the thread's workspace, which is where the server stores a follow-up anyway.
11689
+ * `onWorkspace` hears the workspace the turn was accepted in.
11690
+ */
11691
+ async openTurn(request, workspaceId, open, onWorkspace) {
11692
+ let target = workspaceId;
11693
+ for (let attempt = 0; ; attempt++) {
11694
+ await this.primeOrFail(target);
11695
+ const body = buildTurnRequest({ ...request, workspaceId: target });
11696
+ try {
11697
+ const response = await this.recovering(() => open(body));
11698
+ onWorkspace?.(target);
11699
+ return response;
11700
+ } catch (error) {
11701
+ const conflict = workspaceConflictOf(error);
11702
+ const retryInThread = attempt === 0 && !!request.previousResponseId && conflict?.code === "workspace_mismatch" && conflict.workspaceId !== target;
11703
+ if (!retryInThread) throw error;
11704
+ target = conflict.workspaceId;
11705
+ }
11706
+ }
11575
11707
  }
11576
11708
  /**
11577
11709
  * Create a tag in `workspaceId`, named on the request: a switch while it is sent cannot move it to the workspace
@@ -11728,6 +11860,11 @@ var Arbi = class {
11728
11860
  try {
11729
11861
  return await run();
11730
11862
  } catch (error) {
11863
+ const conflict = workspaceConflictOf(error);
11864
+ if (conflict?.code === "workspace_key_required") {
11865
+ await this.primeOrFail(conflict.workspaceId, { force: true });
11866
+ return run();
11867
+ }
11731
11868
  const message = error instanceof Error ? error.message : "";
11732
11869
  const noWorkspace = /no active workspace/i.test(message);
11733
11870
  const unauthorised = /\b401\b|token has expired/i.test(message);
@@ -12235,6 +12372,23 @@ var Arbi = class {
12235
12372
  });
12236
12373
  });
12237
12374
  },
12375
+ /**
12376
+ * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
12377
+ * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
12378
+ * name no workspace yet (they act on the session's open one), so each runs under
12379
+ * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
12380
+ * it is sent and still when it returns. A switch refuses the upload
12381
+ * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
12382
+ * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
12383
+ */
12384
+ uploadDirect: (workspaceId, workspaceKey, files, options) => {
12385
+ if (this.currentWorkspaceId !== workspaceId)
12386
+ return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
12387
+ return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
12388
+ ...options,
12389
+ inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
12390
+ });
12391
+ },
12238
12392
  /** Download a document's original file — its current version, or `version`. */
12239
12393
  download: (docId, version) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId, version)),
12240
12394
  getParsedContent: (docId, stage, version) => this.recovering(
@@ -12290,8 +12444,13 @@ var Arbi = class {
12290
12444
  const first = await runConversation(client, conversationId);
12291
12445
  if (!first.pending_auth_request_id) return first;
12292
12446
  const pending = await getPendingAuth(client, conversationId);
12447
+ if (!pending.workspace_ext_id)
12448
+ throw new ArbiError(
12449
+ "The run is waiting for access, but the server did not say to which workspace",
12450
+ { code: "PENDING_AUTH_WITHOUT_WORKSPACE" }
12451
+ );
12293
12452
  await this.workspaces.grantTemporaryAccess({
12294
- workspaceId: pending.workspace_ext_id ?? this.getWorkspaceId(),
12453
+ workspaceId: pending.workspace_ext_id,
12295
12454
  emails: [pending.agent_email],
12296
12455
  sessionPubkeyB64: pending.session_pubkey
12297
12456
  });
@@ -12384,7 +12543,7 @@ var Arbi = class {
12384
12543
  });
12385
12544
  }
12386
12545
  };
12387
- async openResponseHandle(open, options, id) {
12546
+ async openResponseHandle(open, options, id, bufferEvents = false) {
12388
12547
  const controller = new AbortController();
12389
12548
  const abort = () => controller.abort();
12390
12549
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -12396,7 +12555,7 @@ var Arbi = class {
12396
12555
  response,
12397
12556
  controller,
12398
12557
  (responseId) => this.assistant.cancel(responseId),
12399
- { id, cleanup }
12558
+ { id, cleanup, bufferEvents }
12400
12559
  );
12401
12560
  } catch (error) {
12402
12561
  cleanup();
@@ -12407,18 +12566,41 @@ var Arbi = class {
12407
12566
  /** Canonical Responses-shaped requests; existing assistant convenience helpers remain supported. */
12408
12567
  responses = {
12409
12568
  create: async (request, options = {}) => {
12569
+ if (request.stream) {
12570
+ if (request.background)
12571
+ throw new ArbiError(
12572
+ "Streaming background creation is not supported yet. Create in background mode, then attach to the returned response.",
12573
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12574
+ );
12575
+ const body2 = {
12576
+ ...request,
12577
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12578
+ stream: true,
12579
+ background: false,
12580
+ store: request.store ?? true
12581
+ };
12582
+ const started = await this.openResponseHandle(
12583
+ (signal) => openTurnStream(this.getAuthHeaders(), body2, signal),
12584
+ options,
12585
+ void 0,
12586
+ true
12587
+ );
12588
+ if (started.kind !== "response")
12589
+ throw new ArbiError("The control command was acknowledged without creating a response.", {
12590
+ code: "RESPONSE_CONTROL_ACKNOWLEDGED",
12591
+ cause: started.acknowledgement
12592
+ });
12593
+ return new ResponseStream(started.handle);
12594
+ }
12595
+ const requestBody = {
12596
+ ...request,
12597
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12598
+ stream: false,
12599
+ background: request.background ?? false,
12600
+ store: request.store ?? true
12601
+ };
12410
12602
  const response = await this.recovering(
12411
- () => openTurnStream(
12412
- this.getAuthHeaders(),
12413
- {
12414
- ...request,
12415
- workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12416
- stream: false,
12417
- background: request.background ?? false,
12418
- store: request.store ?? true
12419
- },
12420
- options.signal
12421
- )
12603
+ () => openTurnStream(this.getAuthHeaders(), requestBody, options.signal)
12422
12604
  );
12423
12605
  let body;
12424
12606
  try {
@@ -12427,7 +12609,10 @@ var Arbi = class {
12427
12609
  throw transportError(cause);
12428
12610
  }
12429
12611
  try {
12430
- return JSON.parse(body);
12612
+ return withOutputText(
12613
+ JSON.parse(body),
12614
+ response.headers.get("x-request-id") ?? void 0
12615
+ );
12431
12616
  } catch (cause) {
12432
12617
  throw new ArbiError("Expected a Responses JSON object.", {
12433
12618
  code: "RESPONSE_INVALID_ENVELOPE",
@@ -12436,6 +12621,23 @@ var Arbi = class {
12436
12621
  });
12437
12622
  }
12438
12623
  },
12624
+ parse: async (request, options = {}) => {
12625
+ if (request.stream || request.background)
12626
+ throw new ArbiError(
12627
+ "Parse a synchronous response, or validate a completed stored response separately.",
12628
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12629
+ );
12630
+ const workspaceId = request.workspace_ext_id ?? this.requireWorkspace();
12631
+ const parse = await createStructuredParser(request.text.format);
12632
+ const response = await this.responses.create(
12633
+ { ...request, workspace_ext_id: workspaceId, stream: false, background: false },
12634
+ options
12635
+ );
12636
+ return {
12637
+ ...response,
12638
+ output_parsed: parse(response, { requestId: response._request_id }).data
12639
+ };
12640
+ },
12439
12641
  stream: (request, options = {}) => this.openResponseHandle(
12440
12642
  (signal) => openTurnStream(
12441
12643
  this.getAuthHeaders(),
@@ -12450,7 +12652,7 @@ var Arbi = class {
12450
12652
  ),
12451
12653
  options
12452
12654
  ),
12453
- retrieve: (id) => this.assistant.getResponse(id),
12655
+ retrieve: async (id) => withOutputText(await this.assistant.getResponse(id)),
12454
12656
  cancel: (id) => this.assistant.cancel(id),
12455
12657
  attach: (id, options = {}) => this.assistant.attachResponse(id, options)
12456
12658
  };
@@ -12490,12 +12692,14 @@ var Arbi = class {
12490
12692
  },
12491
12693
  /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
12492
12694
  startResponse: async (request, options = {}) => {
12493
- const body = buildTurnRequest({
12494
- ...request,
12495
- workspaceId: request.workspaceId ?? this.requireWorkspace()
12496
- });
12695
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
12497
12696
  return this.openResponseHandle(
12498
- (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12697
+ (signal) => this.openTurn(
12698
+ request,
12699
+ workspaceId,
12700
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12701
+ options.onWorkspace
12702
+ ),
12499
12703
  options
12500
12704
  );
12501
12705
  },
@@ -12523,22 +12727,29 @@ var Arbi = class {
12523
12727
  * with it; an abort just rejects.
12524
12728
  */
12525
12729
  ask: async (request, handlers = {}) => {
12526
- const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
12527
- const body = buildTurnRequest({
12528
- ...request,
12529
- workspaceId: request.workspaceId ?? this.requireWorkspace()
12530
- });
12730
+ const { signal, onError, onQuotaExceeded, onWorkspace, ...callbacks } = handlers;
12731
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
12531
12732
  const refuse = (message, error = new Error(message)) => {
12532
12733
  onError?.(message);
12533
12734
  throw error;
12534
12735
  };
12535
12736
  let response;
12536
12737
  try {
12537
- response = await this.recovering(
12538
- () => openTurnStream(this.getAuthHeaders(), body, signal)
12738
+ response = await this.openTurn(
12739
+ request,
12740
+ workspaceId,
12741
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12742
+ onWorkspace
12539
12743
  );
12540
12744
  } catch (error) {
12541
12745
  if (isAbort(error)) throw error;
12746
+ if (error instanceof ArbiWorkspaceUnavailableError) {
12747
+ callbacks.onErrorDetails?.(error);
12748
+ return refuse(
12749
+ "This chat's workspace can't be opened in this session, so the message was not sent.",
12750
+ error
12751
+ );
12752
+ }
12542
12753
  if (error instanceof AssistantTurnRefused) {
12543
12754
  if (error.quota) onQuotaExceeded?.(error.quota);
12544
12755
  callbacks.onErrorDetails?.(error);
@@ -12596,14 +12807,16 @@ var Arbi = class {
12596
12807
  transcribe: (audio) => transcribe(this.requireClient(), audio),
12597
12808
  /** Start a durable background turn; task options make its thread a work item. */
12598
12809
  submit: (question, options) => {
12599
- const workspaceId = this.requireWorkspace();
12600
- return this.recovering(
12601
- () => submitBackgroundQuery({
12602
- ...this.getAuthHeaders(),
12603
- ...options,
12604
- workspaceId,
12605
- question
12606
- })
12810
+ const workspaceId = options.workspaceId ?? this.requireWorkspace();
12811
+ return this.primeOrFail(workspaceId).then(
12812
+ () => this.recovering(
12813
+ () => submitBackgroundQuery({
12814
+ ...this.getAuthHeaders(),
12815
+ ...options,
12816
+ workspaceId,
12817
+ question
12818
+ })
12819
+ )
12607
12820
  );
12608
12821
  },
12609
12822
  /** Read the status of a background turn. */
@@ -12624,13 +12837,19 @@ var Arbi = class {
12624
12837
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
12625
12838
  * workspace; `searchChunks(result)` ranks the passages found.
12626
12839
  */
12627
- retrieve: (query2, docIds, options) => retrieve({
12628
- arbi: this.requireClient(),
12629
- workspaceId: this.requireWorkspace(),
12630
- query: query2,
12631
- docIds,
12632
- ...options
12633
- })
12840
+ retrieve: (query2, docIds, options) => {
12841
+ const { workspaceId: named, ...rest } = options ?? {};
12842
+ const workspaceId = named ?? this.requireWorkspace();
12843
+ return this.primeOrFail(workspaceId).then(
12844
+ () => retrieve({
12845
+ arbi: this.requireClient(),
12846
+ workspaceId,
12847
+ query: query2,
12848
+ docIds,
12849
+ ...rest
12850
+ })
12851
+ );
12852
+ }
12634
12853
  };
12635
12854
  // ── Tags ──────────────────────────────────────────────────────────────
12636
12855
  tags = {
@@ -15183,6 +15402,7 @@ exports.ArbiStructuredOutputError = ArbiStructuredOutputError;
15183
15402
  exports.ArbiTransportError = ArbiTransportError;
15184
15403
  exports.ArbiWorkspaceChangedError = ArbiWorkspaceChangedError;
15185
15404
  exports.ArbiWorkspaceSupersededError = ArbiWorkspaceSupersededError;
15405
+ exports.ArbiWorkspaceUnavailableError = ArbiWorkspaceUnavailableError;
15186
15406
  exports.CallApiError = CallApiError;
15187
15407
  exports.ClaudeOrchestrator = ClaudeOrchestrator;
15188
15408
  exports.DEFAULT_AI_USD_PER_GBP = DEFAULT_AI_USD_PER_GBP;
@@ -15202,6 +15422,7 @@ exports.PRESENCE_KINDS = PRESENCE_KINDS;
15202
15422
  exports.PROMPT_CONTEXT_CHARS = PROMPT_CONTEXT_CHARS;
15203
15423
  exports.PlanStepsError = PlanStepsError;
15204
15424
  exports.PublicBookingError = PublicBookingError;
15425
+ exports.ResponseStream = ResponseStream;
15205
15426
  exports.SHAREPOINT_VENDORS = SHAREPOINT_VENDORS;
15206
15427
  exports.STEP_FIELD_OPTION_TONES = STEP_FIELD_OPTION_TONES;
15207
15428
  exports.STOP_ID_WAIT_MS = STOP_ID_WAIT_MS;
@@ -15364,6 +15585,7 @@ exports.usdToGbp = usdToGbp;
15364
15585
  exports.work = work_exports;
15365
15586
  exports.workflowSteps = workflow_steps_exports;
15366
15587
  exports.workflows = workflows_exports;
15588
+ exports.workspaceConflictOf = workspaceConflictOf;
15367
15589
  exports.workspaces = workspaces_exports;
15368
15590
  exports.wouldCreateTagCycle = wouldCreateTagCycle;
15369
15591
  //# sourceMappingURL=index.cjs.map