@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/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- 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';
1
+ 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';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -3511,6 +3511,22 @@ var ArbiWorkspaceChangedError = class extends ArbiError {
3511
3511
  }
3512
3512
  workspaceId;
3513
3513
  };
3514
+ var ArbiWorkspaceUnavailableError = class extends ArbiError {
3515
+ constructor(workspaceId, cause, message = `Workspace ${workspaceId} can't be opened in this session, so nothing was sent`) {
3516
+ super(message, { code: "WORKSPACE_UNAVAILABLE", cause });
3517
+ this.workspaceId = workspaceId;
3518
+ this.name = "ArbiWorkspaceUnavailableError";
3519
+ }
3520
+ workspaceId;
3521
+ };
3522
+ function workspaceConflictOf(error) {
3523
+ const body = error instanceof ArbiApiError ? error.apiError : error instanceof Error ? void 0 : error;
3524
+ const detail = errorRecord(errorRecord(body)?.detail);
3525
+ const code = detail?.code;
3526
+ const workspaceId = detail?.workspace_ext_id;
3527
+ if (code !== "workspace_key_required" && code !== "workspace_mismatch") return null;
3528
+ return typeof workspaceId === "string" && workspaceId ? { code, workspaceId } : null;
3529
+ }
3514
3530
  function detailText(detail) {
3515
3531
  if (typeof detail === "string") return detail || void 0;
3516
3532
  if (Array.isArray(detail)) {
@@ -3648,6 +3664,19 @@ function getDeepestCause(err) {
3648
3664
  }
3649
3665
  return current;
3650
3666
  }
3667
+ function getErrorCode(err) {
3668
+ if (!(err instanceof Error)) return void 0;
3669
+ let current = err;
3670
+ const seen = /* @__PURE__ */ new Set();
3671
+ while (current && !seen.has(current)) {
3672
+ seen.add(current);
3673
+ const code = current.code;
3674
+ if (typeof code === "string" && !(current instanceof ArbiTransportError && current.cause instanceof Error))
3675
+ return code;
3676
+ current = current.cause instanceof Error ? current.cause : void 0;
3677
+ }
3678
+ return void 0;
3679
+ }
3651
3680
 
3652
3681
  // src/fetch.ts
3653
3682
  var STATUS_FALLBACKS = {
@@ -4607,6 +4636,118 @@ function buildChunkLookup(tools) {
4607
4636
  return lookup;
4608
4637
  }
4609
4638
 
4639
+ // src/operations/responses.ts
4640
+ var responses_exports = {};
4641
+ __export(responses_exports, {
4642
+ extractResponseText: () => extractResponseText,
4643
+ getResponse: () => getResponse,
4644
+ submitBackgroundQuery: () => submitBackgroundQuery
4645
+ });
4646
+ async function submitBackgroundQuery(options) {
4647
+ const {
4648
+ workspaceId,
4649
+ question,
4650
+ docIds,
4651
+ previousResponseId,
4652
+ model,
4653
+ text: text2,
4654
+ task,
4655
+ conversationId,
4656
+ mentions,
4657
+ activeArtifactExtId,
4658
+ fullContext = true,
4659
+ ...auth
4660
+ } = options;
4661
+ const tools = {};
4662
+ if (docIds.length > 0) {
4663
+ tools.retrieval_chunk = {
4664
+ name: "retrieval_chunk",
4665
+ description: "retrieval chunk",
4666
+ tool_args: { doc_ext_ids: docIds },
4667
+ tool_responses: {}
4668
+ };
4669
+ if (fullContext)
4670
+ tools.retrieval_full_context = {
4671
+ name: "retrieval_full_context",
4672
+ description: "retrieval full context",
4673
+ tool_args: { doc_ext_ids: docIds },
4674
+ tool_responses: {}
4675
+ };
4676
+ }
4677
+ const body = {
4678
+ input: question,
4679
+ workspace_ext_id: workspaceId,
4680
+ stream: false,
4681
+ background: true,
4682
+ store: true,
4683
+ tools,
4684
+ ...task !== void 0 ? { task } : {},
4685
+ ...conversationId ? { conversation_ext_id: conversationId } : {},
4686
+ ...mentions !== void 0 ? { mentions } : {},
4687
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
4688
+ ...previousResponseId ? { previous_response_id: previousResponseId } : {},
4689
+ ...model ? { model } : {},
4690
+ ...text2 ? { text: text2 } : {}
4691
+ };
4692
+ const res = await authenticatedFetch({
4693
+ ...auth,
4694
+ path: "/v1/responses",
4695
+ method: "POST",
4696
+ body: JSON.stringify(body),
4697
+ headers: { "Content-Type": "application/json" }
4698
+ });
4699
+ return await res.json();
4700
+ }
4701
+ async function getResponse(auth, responseId) {
4702
+ const res = await authenticatedFetch({
4703
+ ...auth,
4704
+ path: `/v1/responses/${responseId}`,
4705
+ method: "GET"
4706
+ });
4707
+ return await res.json();
4708
+ }
4709
+ function extractResponseText(response) {
4710
+ const parts = [];
4711
+ for (const msg of Array.isArray(response.output) ? response.output : []) {
4712
+ if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
4713
+ for (const item of msg.content) {
4714
+ if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
4715
+ }
4716
+ }
4717
+ return parts.join("");
4718
+ }
4719
+
4720
+ // src/responses-resource.ts
4721
+ function withOutputText(response, requestId) {
4722
+ return {
4723
+ ...response,
4724
+ output_text: extractResponseText(response),
4725
+ ...requestId ? { _request_id: requestId } : {}
4726
+ };
4727
+ }
4728
+ var ResponseStream = class {
4729
+ constructor(handle) {
4730
+ this.handle = handle;
4731
+ }
4732
+ handle;
4733
+ async *[Symbol.asyncIterator]() {
4734
+ try {
4735
+ for await (const frame of this.handle.events()) {
4736
+ const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
4737
+ yield {
4738
+ ...data,
4739
+ type: typeof data.type === "string" ? data.type : frame.event
4740
+ };
4741
+ }
4742
+ const outcome = await this.handle.outcome;
4743
+ if (outcome.status === "disconnected")
4744
+ throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
4745
+ } finally {
4746
+ this.handle.detach();
4747
+ }
4748
+ }
4749
+ };
4750
+
4610
4751
  // src/structured-output.ts
4611
4752
  var ArbiStructuredOutputError = class extends ArbiError {
4612
4753
  constructor(message, response, options) {
@@ -4813,12 +4954,17 @@ function consumeResponse(response, controller, cancel, options = {}) {
4813
4954
  let acknowledgement;
4814
4955
  const listeners = /* @__PURE__ */ new Set();
4815
4956
  const queue = [];
4957
+ let capacityAvailable;
4958
+ const releaseCapacity = () => {
4959
+ capacityAvailable?.();
4960
+ capacityAvailable = void 0;
4961
+ };
4816
4962
  let claimed = false;
4817
4963
  let iteratorClosed = false;
4818
4964
  let iteratorError;
4819
4965
  let pending;
4820
4966
  const emit = (event) => {
4821
- if (!claimed || iteratorClosed) return;
4967
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
4822
4968
  if (pending) {
4823
4969
  pending.resolve({ value: immutable(event), done: false });
4824
4970
  pending = void 0;
@@ -4847,6 +4993,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
4847
4993
  const finish = (value, detached = false) => {
4848
4994
  if (finished) return;
4849
4995
  finished = true;
4996
+ releaseCapacity();
4850
4997
  controller.signal.removeEventListener("abort", abort);
4851
4998
  options.cleanup?.();
4852
4999
  update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
@@ -4894,6 +5041,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
4894
5041
  const close = () => {
4895
5042
  iteratorClosed = true;
4896
5043
  queue.length = 0;
5044
+ releaseCapacity();
4897
5045
  if (pending) {
4898
5046
  pending.resolve({ value: void 0, done: true });
4899
5047
  pending = void 0;
@@ -4905,7 +5053,11 @@ function consumeResponse(response, controller, cancel, options = {}) {
4905
5053
  },
4906
5054
  next() {
4907
5055
  if (iteratorError) return Promise.reject(iteratorError);
4908
- if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5056
+ if (queue.length) {
5057
+ const value = queue.shift();
5058
+ releaseCapacity();
5059
+ return Promise.resolve({ value, done: false });
5060
+ }
4909
5061
  if (finished || iteratorClosed)
4910
5062
  return Promise.resolve({ value: void 0, done: true });
4911
5063
  if (pending)
@@ -5066,8 +5218,13 @@ function consumeResponse(response, controller, cancel, options = {}) {
5066
5218
  try {
5067
5219
  while (!finished) {
5068
5220
  const { value, done } = await reader.read();
5069
- for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5221
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5070
5222
  process(frame);
5223
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5224
+ await new Promise((resolve) => {
5225
+ capacityAvailable = resolve;
5226
+ });
5227
+ }
5071
5228
  if (done) break;
5072
5229
  }
5073
5230
  if (!finished) {
@@ -5531,9 +5688,12 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5531
5688
  folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
5532
5689
  presign_expires_in: options?.presignExpiresIn ?? 3600
5533
5690
  };
5534
- const initResult = requireData(
5535
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5536
- "Failed to initialize direct upload"
5691
+ const guarded = options?.inWorkspace ?? ((send) => send());
5692
+ const initResult = await guarded(
5693
+ async () => requireData(
5694
+ await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5695
+ "Failed to initialize direct upload"
5696
+ )
5537
5697
  );
5538
5698
  const items = initResult.items ?? [];
5539
5699
  const bytesByName = /* @__PURE__ */ new Map();
@@ -5590,14 +5750,16 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5590
5750
  if (toCommit.length === 0) {
5591
5751
  return { doc_ext_ids: [], skipped };
5592
5752
  }
5593
- const commitResult = requireData(
5594
- await arbi.fetch.POST("/v1/document/upload-commit", {
5595
- body: {
5596
- doc_ext_ids: toCommit,
5597
- tag_ext_id: options?.tagExtId ?? null
5598
- }
5599
- }),
5600
- "Failed to commit direct upload"
5753
+ const commitResult = await guarded(
5754
+ async () => requireData(
5755
+ await arbi.fetch.POST("/v1/document/upload-commit", {
5756
+ body: {
5757
+ doc_ext_ids: toCommit,
5758
+ tag_ext_id: options?.tagExtId ?? null
5759
+ }
5760
+ }),
5761
+ "Failed to commit direct upload"
5762
+ )
5601
5763
  );
5602
5764
  return {
5603
5765
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6092,6 +6254,7 @@ __export(assistant_exports, {
6092
6254
  AssistantTurnRefused: () => AssistantTurnRefused,
6093
6255
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
6094
6256
  SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
6257
+ WORKSPACE_CONFLICT_MESSAGES: () => WORKSPACE_CONFLICT_MESSAGES,
6095
6258
  cancelRun: () => cancelRun,
6096
6259
  filterSkills: () => filterSkills,
6097
6260
  interject: () => interject,
@@ -6325,11 +6488,29 @@ function quotaFromStreamError(error) {
6325
6488
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6326
6489
  return { spend, budget, projectExtId: match.groups.project ?? null };
6327
6490
  }
6491
+ var WORKSPACE_CONFLICT_MESSAGES = {
6492
+ workspace_mismatch: "This conversation belongs to another workspace, so the reply was not sent. Open that workspace to continue it.",
6493
+ 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."
6494
+ };
6328
6495
  async function refusal(response) {
6329
6496
  const { status } = response;
6330
6497
  const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6331
6498
  const detail = parsed.apiError?.detail;
6332
6499
  const quota = status === 402 ? quotaExceededFrom(detail) : null;
6500
+ const conflict = status === 409 ? workspaceConflictOf(parsed.apiError) : null;
6501
+ if (conflict) {
6502
+ return new AssistantTurnRefused(
6503
+ WORKSPACE_CONFLICT_MESSAGES[conflict.code],
6504
+ status,
6505
+ null,
6506
+ parsed.apiError,
6507
+ {
6508
+ code: conflict.code,
6509
+ requestId: parsed.requestId,
6510
+ responseId: parsed.responseId
6511
+ }
6512
+ );
6513
+ }
6333
6514
  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;
6334
6515
  return new AssistantTurnRefused(
6335
6516
  quota?.message || parsed.detail || fallback,
@@ -6468,88 +6649,6 @@ async function cancelRun(auth, responseId) {
6468
6649
  });
6469
6650
  }
6470
6651
 
6471
- // src/operations/responses.ts
6472
- var responses_exports = {};
6473
- __export(responses_exports, {
6474
- extractResponseText: () => extractResponseText,
6475
- getResponse: () => getResponse,
6476
- submitBackgroundQuery: () => submitBackgroundQuery
6477
- });
6478
- async function submitBackgroundQuery(options) {
6479
- const {
6480
- workspaceId,
6481
- question,
6482
- docIds,
6483
- previousResponseId,
6484
- model,
6485
- text: text2,
6486
- task,
6487
- conversationId,
6488
- mentions,
6489
- activeArtifactExtId,
6490
- fullContext = true,
6491
- ...auth
6492
- } = options;
6493
- const tools = {};
6494
- if (docIds.length > 0) {
6495
- tools.retrieval_chunk = {
6496
- name: "retrieval_chunk",
6497
- description: "retrieval chunk",
6498
- tool_args: { doc_ext_ids: docIds },
6499
- tool_responses: {}
6500
- };
6501
- if (fullContext)
6502
- tools.retrieval_full_context = {
6503
- name: "retrieval_full_context",
6504
- description: "retrieval full context",
6505
- tool_args: { doc_ext_ids: docIds },
6506
- tool_responses: {}
6507
- };
6508
- }
6509
- const body = {
6510
- input: question,
6511
- workspace_ext_id: workspaceId,
6512
- stream: false,
6513
- background: true,
6514
- store: true,
6515
- tools,
6516
- ...task !== void 0 ? { task } : {},
6517
- ...conversationId ? { conversation_ext_id: conversationId } : {},
6518
- ...mentions !== void 0 ? { mentions } : {},
6519
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6520
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
6521
- ...model ? { model } : {},
6522
- ...text2 ? { text: text2 } : {}
6523
- };
6524
- const res = await authenticatedFetch({
6525
- ...auth,
6526
- path: "/v1/responses",
6527
- method: "POST",
6528
- body: JSON.stringify(body),
6529
- headers: { "Content-Type": "application/json" }
6530
- });
6531
- return await res.json();
6532
- }
6533
- async function getResponse(auth, responseId) {
6534
- const res = await authenticatedFetch({
6535
- ...auth,
6536
- path: `/v1/responses/${responseId}`,
6537
- method: "GET"
6538
- });
6539
- return await res.json();
6540
- }
6541
- function extractResponseText(response) {
6542
- const parts = [];
6543
- for (const msg of response.output) {
6544
- for (const item of msg.content) {
6545
- if ("type" in item && item.type === "output_text" && "text" in item) {
6546
- parts.push(item.text);
6547
- }
6548
- }
6549
- }
6550
- return parts.join("");
6551
- }
6552
-
6553
6652
  // src/operations/tags.ts
6554
6653
  var tags_exports = {};
6555
6654
  __export(tags_exports, {
@@ -10965,11 +11064,57 @@ var Arbi = class {
10965
11064
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
10966
11065
  * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
10967
11066
  * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
11067
+ * A workspace the user holds no key for (a public one, or a temporary grant whose key the server
11068
+ * session already holds) has nothing to deposit: the server answers for it as it is.
10968
11069
  */
10969
- openWorkspace(workspaceId) {
10970
- if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
11070
+ async openWorkspace(workspaceId) {
11071
+ if (workspaceId === this.currentWorkspaceId) return;
10971
11072
  this.requireLogin();
10972
- return this.requireClient().workspaceKeys.prime(workspaceId);
11073
+ const keys = this.requireClient().workspaceKeys;
11074
+ const { wrappedKey } = await keys.wrappedKey(workspaceId).catch(keyLookupFailed);
11075
+ if (!wrappedKey) return;
11076
+ return keys.prime(workspaceId);
11077
+ }
11078
+ /**
11079
+ * {@link openWorkspace} (or, with `force`, deposit the key again even for the current workspace:
11080
+ * the server said it lacks it), failing with {@link ArbiWorkspaceUnavailableError} when the key
11081
+ * cannot be deposited. Then nothing is sent, so nothing can land in another workspace.
11082
+ */
11083
+ async primeOrFail(workspaceId, options = {}) {
11084
+ try {
11085
+ if (options.force) {
11086
+ this.requireLogin();
11087
+ await this.requireClient().workspaceKeys.prime(workspaceId, { force: true });
11088
+ } else await this.openWorkspace(workspaceId);
11089
+ } catch (error) {
11090
+ if (isAbortError(error) || error instanceof ArbiSessionExpiredError) throw error;
11091
+ throw new ArbiWorkspaceUnavailableError(workspaceId, error);
11092
+ }
11093
+ }
11094
+ /**
11095
+ * Open a chat turn's stream in `workspaceId` (captured by the caller when the turn started): the
11096
+ * workspace is opened for this session first if it is not the current one, and the body names
11097
+ * it, so a switch meanwhile cannot move the turn. A follow-up refused with 409
11098
+ * `workspace_mismatch` (its thread is in another workspace: nothing was written) is sent once
11099
+ * more in the thread's workspace, which is where the server stores a follow-up anyway.
11100
+ * `onWorkspace` hears the workspace the turn was accepted in.
11101
+ */
11102
+ async openTurn(request, workspaceId, open, onWorkspace) {
11103
+ let target = workspaceId;
11104
+ for (let attempt = 0; ; attempt++) {
11105
+ await this.primeOrFail(target);
11106
+ const body = buildTurnRequest({ ...request, workspaceId: target });
11107
+ try {
11108
+ const response = await this.recovering(() => open(body));
11109
+ onWorkspace?.(target);
11110
+ return response;
11111
+ } catch (error) {
11112
+ const conflict = workspaceConflictOf(error);
11113
+ const retryInThread = attempt === 0 && !!request.previousResponseId && conflict?.code === "workspace_mismatch" && conflict.workspaceId !== target;
11114
+ if (!retryInThread) throw error;
11115
+ target = conflict.workspaceId;
11116
+ }
11117
+ }
10973
11118
  }
10974
11119
  /**
10975
11120
  * Create a tag in `workspaceId`, named on the request: a switch while it is sent cannot move it to the workspace
@@ -11126,6 +11271,11 @@ var Arbi = class {
11126
11271
  try {
11127
11272
  return await run();
11128
11273
  } catch (error) {
11274
+ const conflict = workspaceConflictOf(error);
11275
+ if (conflict?.code === "workspace_key_required") {
11276
+ await this.primeOrFail(conflict.workspaceId, { force: true });
11277
+ return run();
11278
+ }
11129
11279
  const message = error instanceof Error ? error.message : "";
11130
11280
  const noWorkspace = /no active workspace/i.test(message);
11131
11281
  const unauthorised = /\b401\b|token has expired/i.test(message);
@@ -11633,6 +11783,23 @@ var Arbi = class {
11633
11783
  });
11634
11784
  });
11635
11785
  },
11786
+ /**
11787
+ * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
11788
+ * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
11789
+ * name no workspace yet (they act on the session's open one), so each runs under
11790
+ * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
11791
+ * it is sent and still when it returns. A switch refuses the upload
11792
+ * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
11793
+ * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
11794
+ */
11795
+ uploadDirect: (workspaceId, workspaceKey, files, options) => {
11796
+ if (this.currentWorkspaceId !== workspaceId)
11797
+ return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
11798
+ return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
11799
+ ...options,
11800
+ inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
11801
+ });
11802
+ },
11636
11803
  /** Download a document's original file — its current version, or `version`. */
11637
11804
  download: (docId, version) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId, version)),
11638
11805
  getParsedContent: (docId, stage, version) => this.recovering(
@@ -11688,8 +11855,13 @@ var Arbi = class {
11688
11855
  const first = await runConversation(client, conversationId);
11689
11856
  if (!first.pending_auth_request_id) return first;
11690
11857
  const pending = await getPendingAuth(client, conversationId);
11858
+ if (!pending.workspace_ext_id)
11859
+ throw new ArbiError(
11860
+ "The run is waiting for access, but the server did not say to which workspace",
11861
+ { code: "PENDING_AUTH_WITHOUT_WORKSPACE" }
11862
+ );
11691
11863
  await this.workspaces.grantTemporaryAccess({
11692
- workspaceId: pending.workspace_ext_id ?? this.getWorkspaceId(),
11864
+ workspaceId: pending.workspace_ext_id,
11693
11865
  emails: [pending.agent_email],
11694
11866
  sessionPubkeyB64: pending.session_pubkey
11695
11867
  });
@@ -11782,7 +11954,7 @@ var Arbi = class {
11782
11954
  });
11783
11955
  }
11784
11956
  };
11785
- async openResponseHandle(open, options, id) {
11957
+ async openResponseHandle(open, options, id, bufferEvents = false) {
11786
11958
  const controller = new AbortController();
11787
11959
  const abort = () => controller.abort();
11788
11960
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -11794,7 +11966,7 @@ var Arbi = class {
11794
11966
  response,
11795
11967
  controller,
11796
11968
  (responseId) => this.assistant.cancel(responseId),
11797
- { id, cleanup }
11969
+ { id, cleanup, bufferEvents }
11798
11970
  );
11799
11971
  } catch (error) {
11800
11972
  cleanup();
@@ -11805,18 +11977,41 @@ var Arbi = class {
11805
11977
  /** Canonical Responses-shaped requests; existing assistant convenience helpers remain supported. */
11806
11978
  responses = {
11807
11979
  create: async (request, options = {}) => {
11980
+ if (request.stream) {
11981
+ if (request.background)
11982
+ throw new ArbiError(
11983
+ "Streaming background creation is not supported yet. Create in background mode, then attach to the returned response.",
11984
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
11985
+ );
11986
+ const body2 = {
11987
+ ...request,
11988
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
11989
+ stream: true,
11990
+ background: false,
11991
+ store: request.store ?? true
11992
+ };
11993
+ const started = await this.openResponseHandle(
11994
+ (signal) => openTurnStream(this.getAuthHeaders(), body2, signal),
11995
+ options,
11996
+ void 0,
11997
+ true
11998
+ );
11999
+ if (started.kind !== "response")
12000
+ throw new ArbiError("The control command was acknowledged without creating a response.", {
12001
+ code: "RESPONSE_CONTROL_ACKNOWLEDGED",
12002
+ cause: started.acknowledgement
12003
+ });
12004
+ return new ResponseStream(started.handle);
12005
+ }
12006
+ const requestBody = {
12007
+ ...request,
12008
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12009
+ stream: false,
12010
+ background: request.background ?? false,
12011
+ store: request.store ?? true
12012
+ };
11808
12013
  const response = await this.recovering(
11809
- () => openTurnStream(
11810
- this.getAuthHeaders(),
11811
- {
11812
- ...request,
11813
- workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
11814
- stream: false,
11815
- background: request.background ?? false,
11816
- store: request.store ?? true
11817
- },
11818
- options.signal
11819
- )
12014
+ () => openTurnStream(this.getAuthHeaders(), requestBody, options.signal)
11820
12015
  );
11821
12016
  let body;
11822
12017
  try {
@@ -11825,7 +12020,10 @@ var Arbi = class {
11825
12020
  throw transportError(cause);
11826
12021
  }
11827
12022
  try {
11828
- return JSON.parse(body);
12023
+ return withOutputText(
12024
+ JSON.parse(body),
12025
+ response.headers.get("x-request-id") ?? void 0
12026
+ );
11829
12027
  } catch (cause) {
11830
12028
  throw new ArbiError("Expected a Responses JSON object.", {
11831
12029
  code: "RESPONSE_INVALID_ENVELOPE",
@@ -11834,6 +12032,23 @@ var Arbi = class {
11834
12032
  });
11835
12033
  }
11836
12034
  },
12035
+ parse: async (request, options = {}) => {
12036
+ if (request.stream || request.background)
12037
+ throw new ArbiError(
12038
+ "Parse a synchronous response, or validate a completed stored response separately.",
12039
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12040
+ );
12041
+ const workspaceId = request.workspace_ext_id ?? this.requireWorkspace();
12042
+ const parse = await createStructuredParser(request.text.format);
12043
+ const response = await this.responses.create(
12044
+ { ...request, workspace_ext_id: workspaceId, stream: false, background: false },
12045
+ options
12046
+ );
12047
+ return {
12048
+ ...response,
12049
+ output_parsed: parse(response, { requestId: response._request_id }).data
12050
+ };
12051
+ },
11837
12052
  stream: (request, options = {}) => this.openResponseHandle(
11838
12053
  (signal) => openTurnStream(
11839
12054
  this.getAuthHeaders(),
@@ -11848,7 +12063,7 @@ var Arbi = class {
11848
12063
  ),
11849
12064
  options
11850
12065
  ),
11851
- retrieve: (id) => this.assistant.getResponse(id),
12066
+ retrieve: async (id) => withOutputText(await this.assistant.getResponse(id)),
11852
12067
  cancel: (id) => this.assistant.cancel(id),
11853
12068
  attach: (id, options = {}) => this.assistant.attachResponse(id, options)
11854
12069
  };
@@ -11888,12 +12103,14 @@ var Arbi = class {
11888
12103
  },
11889
12104
  /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
11890
12105
  startResponse: async (request, options = {}) => {
11891
- const body = buildTurnRequest({
11892
- ...request,
11893
- workspaceId: request.workspaceId ?? this.requireWorkspace()
11894
- });
12106
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
11895
12107
  return this.openResponseHandle(
11896
- (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12108
+ (signal) => this.openTurn(
12109
+ request,
12110
+ workspaceId,
12111
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12112
+ options.onWorkspace
12113
+ ),
11897
12114
  options
11898
12115
  );
11899
12116
  },
@@ -11921,22 +12138,29 @@ var Arbi = class {
11921
12138
  * with it; an abort just rejects.
11922
12139
  */
11923
12140
  ask: async (request, handlers = {}) => {
11924
- const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
11925
- const body = buildTurnRequest({
11926
- ...request,
11927
- workspaceId: request.workspaceId ?? this.requireWorkspace()
11928
- });
12141
+ const { signal, onError, onQuotaExceeded, onWorkspace, ...callbacks } = handlers;
12142
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
11929
12143
  const refuse = (message, error = new Error(message)) => {
11930
12144
  onError?.(message);
11931
12145
  throw error;
11932
12146
  };
11933
12147
  let response;
11934
12148
  try {
11935
- response = await this.recovering(
11936
- () => openTurnStream(this.getAuthHeaders(), body, signal)
12149
+ response = await this.openTurn(
12150
+ request,
12151
+ workspaceId,
12152
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12153
+ onWorkspace
11937
12154
  );
11938
12155
  } catch (error) {
11939
12156
  if (isAbort(error)) throw error;
12157
+ if (error instanceof ArbiWorkspaceUnavailableError) {
12158
+ callbacks.onErrorDetails?.(error);
12159
+ return refuse(
12160
+ "This chat's workspace can't be opened in this session, so the message was not sent.",
12161
+ error
12162
+ );
12163
+ }
11940
12164
  if (error instanceof AssistantTurnRefused) {
11941
12165
  if (error.quota) onQuotaExceeded?.(error.quota);
11942
12166
  callbacks.onErrorDetails?.(error);
@@ -11994,14 +12218,16 @@ var Arbi = class {
11994
12218
  transcribe: (audio) => transcribe(this.requireClient(), audio),
11995
12219
  /** Start a durable background turn; task options make its thread a work item. */
11996
12220
  submit: (question, options) => {
11997
- const workspaceId = this.requireWorkspace();
11998
- return this.recovering(
11999
- () => submitBackgroundQuery({
12000
- ...this.getAuthHeaders(),
12001
- ...options,
12002
- workspaceId,
12003
- question
12004
- })
12221
+ const workspaceId = options.workspaceId ?? this.requireWorkspace();
12222
+ return this.primeOrFail(workspaceId).then(
12223
+ () => this.recovering(
12224
+ () => submitBackgroundQuery({
12225
+ ...this.getAuthHeaders(),
12226
+ ...options,
12227
+ workspaceId,
12228
+ question
12229
+ })
12230
+ )
12005
12231
  );
12006
12232
  },
12007
12233
  /** Read the status of a background turn. */
@@ -12022,13 +12248,19 @@ var Arbi = class {
12022
12248
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
12023
12249
  * workspace; `searchChunks(result)` ranks the passages found.
12024
12250
  */
12025
- retrieve: (query2, docIds, options) => retrieve({
12026
- arbi: this.requireClient(),
12027
- workspaceId: this.requireWorkspace(),
12028
- query: query2,
12029
- docIds,
12030
- ...options
12031
- })
12251
+ retrieve: (query2, docIds, options) => {
12252
+ const { workspaceId: named, ...rest } = options ?? {};
12253
+ const workspaceId = named ?? this.requireWorkspace();
12254
+ return this.primeOrFail(workspaceId).then(
12255
+ () => retrieve({
12256
+ arbi: this.requireClient(),
12257
+ workspaceId,
12258
+ query: query2,
12259
+ docIds,
12260
+ ...rest
12261
+ })
12262
+ );
12263
+ }
12032
12264
  };
12033
12265
  // ── Tags ──────────────────────────────────────────────────────────────
12034
12266
  tags = {
@@ -13499,6 +13731,6 @@ function composeTools(base, next, mode) {
13499
13731
  return structuredClone(mode === "add" ? { ...base, ...next } : next);
13500
13732
  }
13501
13733
 
13502
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiStructuredOutputError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, CallApiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, 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, createIndexAssigner, databases_exports as databases, defaultKindForFormat, doctags_exports as doctags, documentTools, documents_exports as documents, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatTokens, formatUserName, formatWorkspaceChoices, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, instructions, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, mail_exports as mail, mcpTools, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, parseStructuredResponse, performPasswordLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, sliceToSubagentThread, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
13734
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiStructuredOutputError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, ArbiWorkspaceUnavailableError, CallApiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, ResponseStream, SHAREPOINT_VENDORS, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocumentTools, buildFactsContextTool, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, buildTurnRequest, calendar_exports as calendar, calls_exports as calls, canTagHaveParent, cancelPublicBooking, 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, createIndexAssigner, databases_exports as databases, defaultKindForFormat, doctags_exports as doctags, documentTools, documents_exports as documents, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatTokens, formatUserName, formatWorkspaceChoices, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, 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, mail_exports as mail, mcpTools, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, parseStructuredResponse, performPasswordLogin, pickMainThread, profile_exports as profile, progressFetch, projects_exports as projects, quotaExceededFrom, quotaFromStreamError, reduceOutputItem, refusalReason, requireData, requireOk, resolveAuth, resolveCitations, resolveSummary, resolveWorkspace, responses_exports as responses, searchChunks, selectFullContextDocument, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, sliceToSubagentThread, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaceConflictOf, workspaces_exports as workspaces, wouldCreateTagCycle };
13503
13735
  //# sourceMappingURL=browser.js.map
13504
13736
  //# sourceMappingURL=browser.js.map