@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/browser.cjs CHANGED
@@ -3514,6 +3514,22 @@ var ArbiWorkspaceChangedError = class extends ArbiError {
3514
3514
  }
3515
3515
  workspaceId;
3516
3516
  };
3517
+ var ArbiWorkspaceUnavailableError = class extends ArbiError {
3518
+ constructor(workspaceId, cause, message = `Workspace ${workspaceId} can't be opened in this session, so nothing was sent`) {
3519
+ super(message, { code: "WORKSPACE_UNAVAILABLE", cause });
3520
+ this.workspaceId = workspaceId;
3521
+ this.name = "ArbiWorkspaceUnavailableError";
3522
+ }
3523
+ workspaceId;
3524
+ };
3525
+ function workspaceConflictOf(error) {
3526
+ const body = error instanceof ArbiApiError ? error.apiError : error instanceof Error ? void 0 : error;
3527
+ const detail = errorRecord(errorRecord(body)?.detail);
3528
+ const code = detail?.code;
3529
+ const workspaceId = detail?.workspace_ext_id;
3530
+ if (code !== "workspace_key_required" && code !== "workspace_mismatch") return null;
3531
+ return typeof workspaceId === "string" && workspaceId ? { code, workspaceId } : null;
3532
+ }
3517
3533
  function detailText(detail) {
3518
3534
  if (typeof detail === "string") return detail || void 0;
3519
3535
  if (Array.isArray(detail)) {
@@ -3651,6 +3667,19 @@ function getDeepestCause(err) {
3651
3667
  }
3652
3668
  return current;
3653
3669
  }
3670
+ function getErrorCode(err) {
3671
+ if (!(err instanceof Error)) return void 0;
3672
+ let current = err;
3673
+ const seen = /* @__PURE__ */ new Set();
3674
+ while (current && !seen.has(current)) {
3675
+ seen.add(current);
3676
+ const code = current.code;
3677
+ if (typeof code === "string" && !(current instanceof ArbiTransportError && current.cause instanceof Error))
3678
+ return code;
3679
+ current = current.cause instanceof Error ? current.cause : void 0;
3680
+ }
3681
+ return void 0;
3682
+ }
3654
3683
 
3655
3684
  // src/fetch.ts
3656
3685
  var STATUS_FALLBACKS = {
@@ -4610,6 +4639,118 @@ function buildChunkLookup(tools) {
4610
4639
  return lookup;
4611
4640
  }
4612
4641
 
4642
+ // src/operations/responses.ts
4643
+ var responses_exports = {};
4644
+ __export(responses_exports, {
4645
+ extractResponseText: () => extractResponseText,
4646
+ getResponse: () => getResponse,
4647
+ submitBackgroundQuery: () => submitBackgroundQuery
4648
+ });
4649
+ async function submitBackgroundQuery(options) {
4650
+ const {
4651
+ workspaceId,
4652
+ question,
4653
+ docIds,
4654
+ previousResponseId,
4655
+ model,
4656
+ text: text2,
4657
+ task,
4658
+ conversationId,
4659
+ mentions,
4660
+ activeArtifactExtId,
4661
+ fullContext = true,
4662
+ ...auth
4663
+ } = options;
4664
+ const tools = {};
4665
+ if (docIds.length > 0) {
4666
+ tools.retrieval_chunk = {
4667
+ name: "retrieval_chunk",
4668
+ description: "retrieval chunk",
4669
+ tool_args: { doc_ext_ids: docIds },
4670
+ tool_responses: {}
4671
+ };
4672
+ if (fullContext)
4673
+ tools.retrieval_full_context = {
4674
+ name: "retrieval_full_context",
4675
+ description: "retrieval full context",
4676
+ tool_args: { doc_ext_ids: docIds },
4677
+ tool_responses: {}
4678
+ };
4679
+ }
4680
+ const body = {
4681
+ input: question,
4682
+ workspace_ext_id: workspaceId,
4683
+ stream: false,
4684
+ background: true,
4685
+ store: true,
4686
+ tools,
4687
+ ...task !== void 0 ? { task } : {},
4688
+ ...conversationId ? { conversation_ext_id: conversationId } : {},
4689
+ ...mentions !== void 0 ? { mentions } : {},
4690
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
4691
+ ...previousResponseId ? { previous_response_id: previousResponseId } : {},
4692
+ ...model ? { model } : {},
4693
+ ...text2 ? { text: text2 } : {}
4694
+ };
4695
+ const res = await authenticatedFetch({
4696
+ ...auth,
4697
+ path: "/v1/responses",
4698
+ method: "POST",
4699
+ body: JSON.stringify(body),
4700
+ headers: { "Content-Type": "application/json" }
4701
+ });
4702
+ return await res.json();
4703
+ }
4704
+ async function getResponse(auth, responseId) {
4705
+ const res = await authenticatedFetch({
4706
+ ...auth,
4707
+ path: `/v1/responses/${responseId}`,
4708
+ method: "GET"
4709
+ });
4710
+ return await res.json();
4711
+ }
4712
+ function extractResponseText(response) {
4713
+ const parts = [];
4714
+ for (const msg of Array.isArray(response.output) ? response.output : []) {
4715
+ if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
4716
+ for (const item of msg.content) {
4717
+ if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
4718
+ }
4719
+ }
4720
+ return parts.join("");
4721
+ }
4722
+
4723
+ // src/responses-resource.ts
4724
+ function withOutputText(response, requestId) {
4725
+ return {
4726
+ ...response,
4727
+ output_text: extractResponseText(response),
4728
+ ...requestId ? { _request_id: requestId } : {}
4729
+ };
4730
+ }
4731
+ var ResponseStream = class {
4732
+ constructor(handle) {
4733
+ this.handle = handle;
4734
+ }
4735
+ handle;
4736
+ async *[Symbol.asyncIterator]() {
4737
+ try {
4738
+ for await (const frame of this.handle.events()) {
4739
+ const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
4740
+ yield {
4741
+ ...data,
4742
+ type: typeof data.type === "string" ? data.type : frame.event
4743
+ };
4744
+ }
4745
+ const outcome = await this.handle.outcome;
4746
+ if (outcome.status === "disconnected")
4747
+ throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
4748
+ } finally {
4749
+ this.handle.detach();
4750
+ }
4751
+ }
4752
+ };
4753
+
4613
4754
  // src/structured-output.ts
4614
4755
  var ArbiStructuredOutputError = class extends ArbiError {
4615
4756
  constructor(message, response, options) {
@@ -4816,12 +4957,17 @@ function consumeResponse(response, controller, cancel, options = {}) {
4816
4957
  let acknowledgement;
4817
4958
  const listeners = /* @__PURE__ */ new Set();
4818
4959
  const queue = [];
4960
+ let capacityAvailable;
4961
+ const releaseCapacity = () => {
4962
+ capacityAvailable?.();
4963
+ capacityAvailable = void 0;
4964
+ };
4819
4965
  let claimed = false;
4820
4966
  let iteratorClosed = false;
4821
4967
  let iteratorError;
4822
4968
  let pending;
4823
4969
  const emit = (event) => {
4824
- if (!claimed || iteratorClosed) return;
4970
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
4825
4971
  if (pending) {
4826
4972
  pending.resolve({ value: immutable(event), done: false });
4827
4973
  pending = void 0;
@@ -4850,6 +4996,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
4850
4996
  const finish = (value, detached = false) => {
4851
4997
  if (finished) return;
4852
4998
  finished = true;
4999
+ releaseCapacity();
4853
5000
  controller.signal.removeEventListener("abort", abort);
4854
5001
  options.cleanup?.();
4855
5002
  update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
@@ -4897,6 +5044,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
4897
5044
  const close = () => {
4898
5045
  iteratorClosed = true;
4899
5046
  queue.length = 0;
5047
+ releaseCapacity();
4900
5048
  if (pending) {
4901
5049
  pending.resolve({ value: void 0, done: true });
4902
5050
  pending = void 0;
@@ -4908,7 +5056,11 @@ function consumeResponse(response, controller, cancel, options = {}) {
4908
5056
  },
4909
5057
  next() {
4910
5058
  if (iteratorError) return Promise.reject(iteratorError);
4911
- if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5059
+ if (queue.length) {
5060
+ const value = queue.shift();
5061
+ releaseCapacity();
5062
+ return Promise.resolve({ value, done: false });
5063
+ }
4912
5064
  if (finished || iteratorClosed)
4913
5065
  return Promise.resolve({ value: void 0, done: true });
4914
5066
  if (pending)
@@ -5069,8 +5221,13 @@ function consumeResponse(response, controller, cancel, options = {}) {
5069
5221
  try {
5070
5222
  while (!finished) {
5071
5223
  const { value, done } = await reader.read();
5072
- for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5224
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5073
5225
  process(frame);
5226
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5227
+ await new Promise((resolve) => {
5228
+ capacityAvailable = resolve;
5229
+ });
5230
+ }
5074
5231
  if (done) break;
5075
5232
  }
5076
5233
  if (!finished) {
@@ -5534,9 +5691,12 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5534
5691
  folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
5535
5692
  presign_expires_in: options?.presignExpiresIn ?? 3600
5536
5693
  };
5537
- const initResult = requireData(
5538
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5539
- "Failed to initialize direct upload"
5694
+ const guarded = options?.inWorkspace ?? ((send) => send());
5695
+ const initResult = await guarded(
5696
+ async () => requireData(
5697
+ await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5698
+ "Failed to initialize direct upload"
5699
+ )
5540
5700
  );
5541
5701
  const items = initResult.items ?? [];
5542
5702
  const bytesByName = /* @__PURE__ */ new Map();
@@ -5593,14 +5753,16 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5593
5753
  if (toCommit.length === 0) {
5594
5754
  return { doc_ext_ids: [], skipped };
5595
5755
  }
5596
- const commitResult = requireData(
5597
- await arbi.fetch.POST("/v1/document/upload-commit", {
5598
- body: {
5599
- doc_ext_ids: toCommit,
5600
- tag_ext_id: options?.tagExtId ?? null
5601
- }
5602
- }),
5603
- "Failed to commit direct upload"
5756
+ const commitResult = await guarded(
5757
+ async () => requireData(
5758
+ await arbi.fetch.POST("/v1/document/upload-commit", {
5759
+ body: {
5760
+ doc_ext_ids: toCommit,
5761
+ tag_ext_id: options?.tagExtId ?? null
5762
+ }
5763
+ }),
5764
+ "Failed to commit direct upload"
5765
+ )
5604
5766
  );
5605
5767
  return {
5606
5768
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6095,6 +6257,7 @@ __export(assistant_exports, {
6095
6257
  AssistantTurnRefused: () => AssistantTurnRefused,
6096
6258
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
6097
6259
  SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
6260
+ WORKSPACE_CONFLICT_MESSAGES: () => WORKSPACE_CONFLICT_MESSAGES,
6098
6261
  cancelRun: () => cancelRun,
6099
6262
  filterSkills: () => filterSkills,
6100
6263
  interject: () => interject,
@@ -6328,11 +6491,29 @@ function quotaFromStreamError(error) {
6328
6491
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6329
6492
  return { spend, budget, projectExtId: match.groups.project ?? null };
6330
6493
  }
6494
+ var WORKSPACE_CONFLICT_MESSAGES = {
6495
+ workspace_mismatch: "This conversation belongs to another workspace, so the reply was not sent. Open that workspace to continue it.",
6496
+ 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."
6497
+ };
6331
6498
  async function refusal(response) {
6332
6499
  const { status } = response;
6333
6500
  const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6334
6501
  const detail = parsed.apiError?.detail;
6335
6502
  const quota = status === 402 ? quotaExceededFrom(detail) : null;
6503
+ const conflict = status === 409 ? workspaceConflictOf(parsed.apiError) : null;
6504
+ if (conflict) {
6505
+ return new AssistantTurnRefused(
6506
+ WORKSPACE_CONFLICT_MESSAGES[conflict.code],
6507
+ status,
6508
+ null,
6509
+ parsed.apiError,
6510
+ {
6511
+ code: conflict.code,
6512
+ requestId: parsed.requestId,
6513
+ responseId: parsed.responseId
6514
+ }
6515
+ );
6516
+ }
6336
6517
  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;
6337
6518
  return new AssistantTurnRefused(
6338
6519
  quota?.message || parsed.detail || fallback,
@@ -6471,88 +6652,6 @@ async function cancelRun(auth, responseId) {
6471
6652
  });
6472
6653
  }
6473
6654
 
6474
- // src/operations/responses.ts
6475
- var responses_exports = {};
6476
- __export(responses_exports, {
6477
- extractResponseText: () => extractResponseText,
6478
- getResponse: () => getResponse,
6479
- submitBackgroundQuery: () => submitBackgroundQuery
6480
- });
6481
- async function submitBackgroundQuery(options) {
6482
- const {
6483
- workspaceId,
6484
- question,
6485
- docIds,
6486
- previousResponseId,
6487
- model,
6488
- text: text2,
6489
- task,
6490
- conversationId,
6491
- mentions,
6492
- activeArtifactExtId,
6493
- fullContext = true,
6494
- ...auth
6495
- } = options;
6496
- const tools = {};
6497
- if (docIds.length > 0) {
6498
- tools.retrieval_chunk = {
6499
- name: "retrieval_chunk",
6500
- description: "retrieval chunk",
6501
- tool_args: { doc_ext_ids: docIds },
6502
- tool_responses: {}
6503
- };
6504
- if (fullContext)
6505
- tools.retrieval_full_context = {
6506
- name: "retrieval_full_context",
6507
- description: "retrieval full context",
6508
- tool_args: { doc_ext_ids: docIds },
6509
- tool_responses: {}
6510
- };
6511
- }
6512
- const body = {
6513
- input: question,
6514
- workspace_ext_id: workspaceId,
6515
- stream: false,
6516
- background: true,
6517
- store: true,
6518
- tools,
6519
- ...task !== void 0 ? { task } : {},
6520
- ...conversationId ? { conversation_ext_id: conversationId } : {},
6521
- ...mentions !== void 0 ? { mentions } : {},
6522
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6523
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
6524
- ...model ? { model } : {},
6525
- ...text2 ? { text: text2 } : {}
6526
- };
6527
- const res = await authenticatedFetch({
6528
- ...auth,
6529
- path: "/v1/responses",
6530
- method: "POST",
6531
- body: JSON.stringify(body),
6532
- headers: { "Content-Type": "application/json" }
6533
- });
6534
- return await res.json();
6535
- }
6536
- async function getResponse(auth, responseId) {
6537
- const res = await authenticatedFetch({
6538
- ...auth,
6539
- path: `/v1/responses/${responseId}`,
6540
- method: "GET"
6541
- });
6542
- return await res.json();
6543
- }
6544
- function extractResponseText(response) {
6545
- const parts = [];
6546
- for (const msg of response.output) {
6547
- for (const item of msg.content) {
6548
- if ("type" in item && item.type === "output_text" && "text" in item) {
6549
- parts.push(item.text);
6550
- }
6551
- }
6552
- }
6553
- return parts.join("");
6554
- }
6555
-
6556
6655
  // src/operations/tags.ts
6557
6656
  var tags_exports = {};
6558
6657
  __export(tags_exports, {
@@ -10968,11 +11067,57 @@ var Arbi = class {
10968
11067
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
10969
11068
  * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
10970
11069
  * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
11070
+ * A workspace the user holds no key for (a public one, or a temporary grant whose key the server
11071
+ * session already holds) has nothing to deposit: the server answers for it as it is.
10971
11072
  */
10972
- openWorkspace(workspaceId) {
10973
- if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
11073
+ async openWorkspace(workspaceId) {
11074
+ if (workspaceId === this.currentWorkspaceId) return;
10974
11075
  this.requireLogin();
10975
- return this.requireClient().workspaceKeys.prime(workspaceId);
11076
+ const keys = this.requireClient().workspaceKeys;
11077
+ const { wrappedKey } = await keys.wrappedKey(workspaceId).catch(keyLookupFailed);
11078
+ if (!wrappedKey) return;
11079
+ return keys.prime(workspaceId);
11080
+ }
11081
+ /**
11082
+ * {@link openWorkspace} (or, with `force`, deposit the key again even for the current workspace:
11083
+ * the server said it lacks it), failing with {@link ArbiWorkspaceUnavailableError} when the key
11084
+ * cannot be deposited. Then nothing is sent, so nothing can land in another workspace.
11085
+ */
11086
+ async primeOrFail(workspaceId, options = {}) {
11087
+ try {
11088
+ if (options.force) {
11089
+ this.requireLogin();
11090
+ await this.requireClient().workspaceKeys.prime(workspaceId, { force: true });
11091
+ } else await this.openWorkspace(workspaceId);
11092
+ } catch (error) {
11093
+ if (client.isAbortError(error) || error instanceof ArbiSessionExpiredError) throw error;
11094
+ throw new ArbiWorkspaceUnavailableError(workspaceId, error);
11095
+ }
11096
+ }
11097
+ /**
11098
+ * Open a chat turn's stream in `workspaceId` (captured by the caller when the turn started): the
11099
+ * workspace is opened for this session first if it is not the current one, and the body names
11100
+ * it, so a switch meanwhile cannot move the turn. A follow-up refused with 409
11101
+ * `workspace_mismatch` (its thread is in another workspace: nothing was written) is sent once
11102
+ * more in the thread's workspace, which is where the server stores a follow-up anyway.
11103
+ * `onWorkspace` hears the workspace the turn was accepted in.
11104
+ */
11105
+ async openTurn(request, workspaceId, open, onWorkspace) {
11106
+ let target = workspaceId;
11107
+ for (let attempt = 0; ; attempt++) {
11108
+ await this.primeOrFail(target);
11109
+ const body = buildTurnRequest({ ...request, workspaceId: target });
11110
+ try {
11111
+ const response = await this.recovering(() => open(body));
11112
+ onWorkspace?.(target);
11113
+ return response;
11114
+ } catch (error) {
11115
+ const conflict = workspaceConflictOf(error);
11116
+ const retryInThread = attempt === 0 && !!request.previousResponseId && conflict?.code === "workspace_mismatch" && conflict.workspaceId !== target;
11117
+ if (!retryInThread) throw error;
11118
+ target = conflict.workspaceId;
11119
+ }
11120
+ }
10976
11121
  }
10977
11122
  /**
10978
11123
  * Create a tag in `workspaceId`, named on the request: a switch while it is sent cannot move it to the workspace
@@ -11129,6 +11274,11 @@ var Arbi = class {
11129
11274
  try {
11130
11275
  return await run();
11131
11276
  } catch (error) {
11277
+ const conflict = workspaceConflictOf(error);
11278
+ if (conflict?.code === "workspace_key_required") {
11279
+ await this.primeOrFail(conflict.workspaceId, { force: true });
11280
+ return run();
11281
+ }
11132
11282
  const message = error instanceof Error ? error.message : "";
11133
11283
  const noWorkspace = /no active workspace/i.test(message);
11134
11284
  const unauthorised = /\b401\b|token has expired/i.test(message);
@@ -11636,6 +11786,23 @@ var Arbi = class {
11636
11786
  });
11637
11787
  });
11638
11788
  },
11789
+ /**
11790
+ * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
11791
+ * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
11792
+ * name no workspace yet (they act on the session's open one), so each runs under
11793
+ * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
11794
+ * it is sent and still when it returns. A switch refuses the upload
11795
+ * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
11796
+ * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
11797
+ */
11798
+ uploadDirect: (workspaceId, workspaceKey, files, options) => {
11799
+ if (this.currentWorkspaceId !== workspaceId)
11800
+ return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
11801
+ return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
11802
+ ...options,
11803
+ inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
11804
+ });
11805
+ },
11639
11806
  /** Download a document's original file — its current version, or `version`. */
11640
11807
  download: (docId, version) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId, version)),
11641
11808
  getParsedContent: (docId, stage, version) => this.recovering(
@@ -11691,8 +11858,13 @@ var Arbi = class {
11691
11858
  const first = await runConversation(client, conversationId);
11692
11859
  if (!first.pending_auth_request_id) return first;
11693
11860
  const pending = await getPendingAuth(client, conversationId);
11861
+ if (!pending.workspace_ext_id)
11862
+ throw new ArbiError(
11863
+ "The run is waiting for access, but the server did not say to which workspace",
11864
+ { code: "PENDING_AUTH_WITHOUT_WORKSPACE" }
11865
+ );
11694
11866
  await this.workspaces.grantTemporaryAccess({
11695
- workspaceId: pending.workspace_ext_id ?? this.getWorkspaceId(),
11867
+ workspaceId: pending.workspace_ext_id,
11696
11868
  emails: [pending.agent_email],
11697
11869
  sessionPubkeyB64: pending.session_pubkey
11698
11870
  });
@@ -11785,7 +11957,7 @@ var Arbi = class {
11785
11957
  });
11786
11958
  }
11787
11959
  };
11788
- async openResponseHandle(open, options, id) {
11960
+ async openResponseHandle(open, options, id, bufferEvents = false) {
11789
11961
  const controller = new AbortController();
11790
11962
  const abort = () => controller.abort();
11791
11963
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -11797,7 +11969,7 @@ var Arbi = class {
11797
11969
  response,
11798
11970
  controller,
11799
11971
  (responseId) => this.assistant.cancel(responseId),
11800
- { id, cleanup }
11972
+ { id, cleanup, bufferEvents }
11801
11973
  );
11802
11974
  } catch (error) {
11803
11975
  cleanup();
@@ -11808,18 +11980,41 @@ var Arbi = class {
11808
11980
  /** Canonical Responses-shaped requests; existing assistant convenience helpers remain supported. */
11809
11981
  responses = {
11810
11982
  create: async (request, options = {}) => {
11983
+ if (request.stream) {
11984
+ if (request.background)
11985
+ throw new ArbiError(
11986
+ "Streaming background creation is not supported yet. Create in background mode, then attach to the returned response.",
11987
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
11988
+ );
11989
+ const body2 = {
11990
+ ...request,
11991
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
11992
+ stream: true,
11993
+ background: false,
11994
+ store: request.store ?? true
11995
+ };
11996
+ const started = await this.openResponseHandle(
11997
+ (signal) => openTurnStream(this.getAuthHeaders(), body2, signal),
11998
+ options,
11999
+ void 0,
12000
+ true
12001
+ );
12002
+ if (started.kind !== "response")
12003
+ throw new ArbiError("The control command was acknowledged without creating a response.", {
12004
+ code: "RESPONSE_CONTROL_ACKNOWLEDGED",
12005
+ cause: started.acknowledgement
12006
+ });
12007
+ return new ResponseStream(started.handle);
12008
+ }
12009
+ const requestBody = {
12010
+ ...request,
12011
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12012
+ stream: false,
12013
+ background: request.background ?? false,
12014
+ store: request.store ?? true
12015
+ };
11811
12016
  const response = await this.recovering(
11812
- () => openTurnStream(
11813
- this.getAuthHeaders(),
11814
- {
11815
- ...request,
11816
- workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
11817
- stream: false,
11818
- background: request.background ?? false,
11819
- store: request.store ?? true
11820
- },
11821
- options.signal
11822
- )
12017
+ () => openTurnStream(this.getAuthHeaders(), requestBody, options.signal)
11823
12018
  );
11824
12019
  let body;
11825
12020
  try {
@@ -11828,7 +12023,10 @@ var Arbi = class {
11828
12023
  throw transportError(cause);
11829
12024
  }
11830
12025
  try {
11831
- return JSON.parse(body);
12026
+ return withOutputText(
12027
+ JSON.parse(body),
12028
+ response.headers.get("x-request-id") ?? void 0
12029
+ );
11832
12030
  } catch (cause) {
11833
12031
  throw new ArbiError("Expected a Responses JSON object.", {
11834
12032
  code: "RESPONSE_INVALID_ENVELOPE",
@@ -11837,6 +12035,23 @@ var Arbi = class {
11837
12035
  });
11838
12036
  }
11839
12037
  },
12038
+ parse: async (request, options = {}) => {
12039
+ if (request.stream || request.background)
12040
+ throw new ArbiError(
12041
+ "Parse a synchronous response, or validate a completed stored response separately.",
12042
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12043
+ );
12044
+ const workspaceId = request.workspace_ext_id ?? this.requireWorkspace();
12045
+ const parse = await createStructuredParser(request.text.format);
12046
+ const response = await this.responses.create(
12047
+ { ...request, workspace_ext_id: workspaceId, stream: false, background: false },
12048
+ options
12049
+ );
12050
+ return {
12051
+ ...response,
12052
+ output_parsed: parse(response, { requestId: response._request_id }).data
12053
+ };
12054
+ },
11840
12055
  stream: (request, options = {}) => this.openResponseHandle(
11841
12056
  (signal) => openTurnStream(
11842
12057
  this.getAuthHeaders(),
@@ -11851,7 +12066,7 @@ var Arbi = class {
11851
12066
  ),
11852
12067
  options
11853
12068
  ),
11854
- retrieve: (id) => this.assistant.getResponse(id),
12069
+ retrieve: async (id) => withOutputText(await this.assistant.getResponse(id)),
11855
12070
  cancel: (id) => this.assistant.cancel(id),
11856
12071
  attach: (id, options = {}) => this.assistant.attachResponse(id, options)
11857
12072
  };
@@ -11891,12 +12106,14 @@ var Arbi = class {
11891
12106
  },
11892
12107
  /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
11893
12108
  startResponse: async (request, options = {}) => {
11894
- const body = buildTurnRequest({
11895
- ...request,
11896
- workspaceId: request.workspaceId ?? this.requireWorkspace()
11897
- });
12109
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
11898
12110
  return this.openResponseHandle(
11899
- (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12111
+ (signal) => this.openTurn(
12112
+ request,
12113
+ workspaceId,
12114
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12115
+ options.onWorkspace
12116
+ ),
11900
12117
  options
11901
12118
  );
11902
12119
  },
@@ -11924,22 +12141,29 @@ var Arbi = class {
11924
12141
  * with it; an abort just rejects.
11925
12142
  */
11926
12143
  ask: async (request, handlers = {}) => {
11927
- const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
11928
- const body = buildTurnRequest({
11929
- ...request,
11930
- workspaceId: request.workspaceId ?? this.requireWorkspace()
11931
- });
12144
+ const { signal, onError, onQuotaExceeded, onWorkspace, ...callbacks } = handlers;
12145
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
11932
12146
  const refuse = (message, error = new Error(message)) => {
11933
12147
  onError?.(message);
11934
12148
  throw error;
11935
12149
  };
11936
12150
  let response;
11937
12151
  try {
11938
- response = await this.recovering(
11939
- () => openTurnStream(this.getAuthHeaders(), body, signal)
12152
+ response = await this.openTurn(
12153
+ request,
12154
+ workspaceId,
12155
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12156
+ onWorkspace
11940
12157
  );
11941
12158
  } catch (error) {
11942
12159
  if (isAbort(error)) throw error;
12160
+ if (error instanceof ArbiWorkspaceUnavailableError) {
12161
+ callbacks.onErrorDetails?.(error);
12162
+ return refuse(
12163
+ "This chat's workspace can't be opened in this session, so the message was not sent.",
12164
+ error
12165
+ );
12166
+ }
11943
12167
  if (error instanceof AssistantTurnRefused) {
11944
12168
  if (error.quota) onQuotaExceeded?.(error.quota);
11945
12169
  callbacks.onErrorDetails?.(error);
@@ -11997,14 +12221,16 @@ var Arbi = class {
11997
12221
  transcribe: (audio) => transcribe(this.requireClient(), audio),
11998
12222
  /** Start a durable background turn; task options make its thread a work item. */
11999
12223
  submit: (question, options) => {
12000
- const workspaceId = this.requireWorkspace();
12001
- return this.recovering(
12002
- () => submitBackgroundQuery({
12003
- ...this.getAuthHeaders(),
12004
- ...options,
12005
- workspaceId,
12006
- question
12007
- })
12224
+ const workspaceId = options.workspaceId ?? this.requireWorkspace();
12225
+ return this.primeOrFail(workspaceId).then(
12226
+ () => this.recovering(
12227
+ () => submitBackgroundQuery({
12228
+ ...this.getAuthHeaders(),
12229
+ ...options,
12230
+ workspaceId,
12231
+ question
12232
+ })
12233
+ )
12008
12234
  );
12009
12235
  },
12010
12236
  /** Read the status of a background turn. */
@@ -12025,13 +12251,19 @@ var Arbi = class {
12025
12251
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
12026
12252
  * workspace; `searchChunks(result)` ranks the passages found.
12027
12253
  */
12028
- retrieve: (query2, docIds, options) => retrieve({
12029
- arbi: this.requireClient(),
12030
- workspaceId: this.requireWorkspace(),
12031
- query: query2,
12032
- docIds,
12033
- ...options
12034
- })
12254
+ retrieve: (query2, docIds, options) => {
12255
+ const { workspaceId: named, ...rest } = options ?? {};
12256
+ const workspaceId = named ?? this.requireWorkspace();
12257
+ return this.primeOrFail(workspaceId).then(
12258
+ () => retrieve({
12259
+ arbi: this.requireClient(),
12260
+ workspaceId,
12261
+ query: query2,
12262
+ docIds,
12263
+ ...rest
12264
+ })
12265
+ );
12266
+ }
12035
12267
  };
12036
12268
  // ── Tags ──────────────────────────────────────────────────────────────
12037
12269
  tags = {
@@ -13506,10 +13738,12 @@ exports.ACCOUNT_VENDOR = ACCOUNT_VENDOR;
13506
13738
  exports.Arbi = Arbi;
13507
13739
  exports.ArbiApiError = ArbiApiError;
13508
13740
  exports.ArbiError = ArbiError;
13741
+ exports.ArbiSessionExpiredError = ArbiSessionExpiredError;
13509
13742
  exports.ArbiStructuredOutputError = ArbiStructuredOutputError;
13510
13743
  exports.ArbiTransportError = ArbiTransportError;
13511
13744
  exports.ArbiWorkspaceChangedError = ArbiWorkspaceChangedError;
13512
13745
  exports.ArbiWorkspaceSupersededError = ArbiWorkspaceSupersededError;
13746
+ exports.ArbiWorkspaceUnavailableError = ArbiWorkspaceUnavailableError;
13513
13747
  exports.CallApiError = CallApiError;
13514
13748
  exports.DEFAULT_AI_USD_PER_GBP = DEFAULT_AI_USD_PER_GBP;
13515
13749
  exports.DRIVE_SYNC_VENDORS = DRIVE_SYNC_VENDORS;
@@ -13525,6 +13759,7 @@ exports.PRESENCE_KINDS = PRESENCE_KINDS;
13525
13759
  exports.PROMPT_CONTEXT_CHARS = PROMPT_CONTEXT_CHARS;
13526
13760
  exports.PlanStepsError = PlanStepsError;
13527
13761
  exports.PublicBookingError = PublicBookingError;
13762
+ exports.ResponseStream = ResponseStream;
13528
13763
  exports.SHAREPOINT_VENDORS = SHAREPOINT_VENDORS;
13529
13764
  exports.STOP_ID_WAIT_MS = STOP_ID_WAIT_MS;
13530
13765
  exports.STOP_REPEAT_WINDOW_MS = STOP_REPEAT_WINDOW_MS;
@@ -13597,6 +13832,7 @@ exports.getContextUsedPercent = getContextUsedPercent;
13597
13832
  exports.getContextUsedTokens = getContextUsedTokens;
13598
13833
  exports.getCurrentStep = getCurrentStep;
13599
13834
  exports.getEligibleParentTags = getEligibleParentTags;
13835
+ exports.getErrorCode = getErrorCode;
13600
13836
  exports.getErrorMessage = getErrorMessage;
13601
13837
  exports.getPublicBookingPage = getPublicBookingPage;
13602
13838
  exports.getRawWorkspaceKey = getRawWorkspaceKey;
@@ -13668,6 +13904,7 @@ exports.usdToGbp = usdToGbp;
13668
13904
  exports.work = work_exports;
13669
13905
  exports.workflowSteps = workflow_steps_exports;
13670
13906
  exports.workflows = workflows_exports;
13907
+ exports.workspaceConflictOf = workspaceConflictOf;
13671
13908
  exports.workspaces = workspaces_exports;
13672
13909
  exports.wouldCreateTagCycle = wouldCreateTagCycle;
13673
13910
  //# sourceMappingURL=browser.cjs.map