@arbidocs/sdk 0.5.60 → 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.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,228 @@ 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
+
4754
+ // src/structured-output.ts
4755
+ var ArbiStructuredOutputError = class extends ArbiError {
4756
+ constructor(message, response, options) {
4757
+ const id = response && typeof response === "object" && "id" in response && typeof response.id === "string" ? response.id : void 0;
4758
+ super(message, { responseId: id, ...options });
4759
+ this.response = response;
4760
+ this.name = "ArbiStructuredOutputError";
4761
+ }
4762
+ response;
4763
+ };
4764
+ function localReferences(value) {
4765
+ if (Array.isArray(value)) {
4766
+ value.forEach(localReferences);
4767
+ return;
4768
+ }
4769
+ if (!value || typeof value !== "object") return;
4770
+ for (const [key, child] of Object.entries(value)) {
4771
+ if ((key === "$ref" || key === "$dynamicRef") && (typeof child !== "string" || !child.startsWith("#")))
4772
+ throw new Error("Only local schema references are supported.");
4773
+ if (!["enum", "const", "default", "examples"].includes(key)) localReferences(child);
4774
+ }
4775
+ }
4776
+ async function createStructuredParser(format) {
4777
+ let validate;
4778
+ let Constructor;
4779
+ try {
4780
+ Constructor = (await import('ajv/dist/2020.js')).default;
4781
+ } catch (cause) {
4782
+ throw new ArbiStructuredOutputError(
4783
+ "The JSON Schema validator could not be loaded.",
4784
+ void 0,
4785
+ { code: "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE", cause }
4786
+ );
4787
+ }
4788
+ try {
4789
+ if (format.type !== "json_schema" || typeof format.name !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(format.name) || !format.schema || typeof format.schema !== "object" || Array.isArray(format.schema))
4790
+ throw new Error("Invalid structured output format.");
4791
+ if (format.schema.$schema !== void 0 && format.schema.$schema !== "https://json-schema.org/draft/2020-12/schema")
4792
+ throw new Error("Expected JSON Schema draft 2020-12.");
4793
+ localReferences(format.schema);
4794
+ validate = new Constructor({
4795
+ strict: false,
4796
+ logger: false,
4797
+ validateFormats: false,
4798
+ strictNumbers: true,
4799
+ addUsedSchema: false
4800
+ }).compile(format.schema);
4801
+ } catch (cause) {
4802
+ const unavailable = cause instanceof EvalError;
4803
+ throw new ArbiStructuredOutputError(
4804
+ unavailable ? "This runtime cannot compile JSON Schema validators." : "Invalid or unsupported output schema.",
4805
+ void 0,
4806
+ {
4807
+ code: unavailable ? "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE" : "STRUCTURED_OUTPUT_SCHEMA_INVALID",
4808
+ cause
4809
+ }
4810
+ );
4811
+ }
4812
+ return (response, options = {}) => {
4813
+ const fail = (code, message, cause) => {
4814
+ throw new ArbiStructuredOutputError(message, response, { ...options, code, cause });
4815
+ };
4816
+ if (!response || typeof response !== "object")
4817
+ fail("RESPONSE_INVALID_ENVELOPE", "Expected a Responses JSON object.");
4818
+ if (response.status === "incomplete")
4819
+ fail("RESPONSE_INCOMPLETE", "The response is incomplete; no validated data is available.");
4820
+ if (response.status === "cancelled")
4821
+ fail("RESPONSE_CANCELLED", "The response was cancelled; no validated data is available.");
4822
+ if (response.status === "failed")
4823
+ fail(
4824
+ typeof response.error?.code === "string" ? response.error.code : "RESPONSE_FAILED",
4825
+ typeof response.error?.message === "string" ? response.error.message : "The response failed."
4826
+ );
4827
+ if (response.status !== "completed")
4828
+ fail(
4829
+ "RESPONSE_NOT_COMPLETED",
4830
+ "Wait for a completed response before parsing structured output."
4831
+ );
4832
+ const messages = Array.isArray(response.output) ? response.output.filter(
4833
+ (item) => item && typeof item === "object" && item.type === "message" && item.role === "assistant"
4834
+ ) : [];
4835
+ if (messages.some(
4836
+ (message) => !Array.isArray(message.content) || message.content.some((part) => !part || typeof part !== "object")
4837
+ ))
4838
+ fail("RESPONSE_INVALID_ENVELOPE", "Invalid assistant output content.");
4839
+ if (messages.some((message) => message.content.some((part) => part.type === "refusal")))
4840
+ fail("RESPONSE_REFUSED", "The model refused this response.");
4841
+ const answers = messages.map(
4842
+ (message) => message.content.filter((part) => part.type === "output_text" && typeof part.text === "string").map((part) => part.text).join("")
4843
+ ).filter((answer) => answer.length > 0);
4844
+ if (answers.length !== 1)
4845
+ fail(
4846
+ "STRUCTURED_OUTPUT_AMBIGUOUS",
4847
+ "Expected one final assistant output message; narrative and answer text are not joined."
4848
+ );
4849
+ let data;
4850
+ try {
4851
+ data = JSON.parse(answers[0]);
4852
+ } catch (cause) {
4853
+ fail("STRUCTURED_OUTPUT_INVALID_JSON", "The response is not valid JSON.", cause);
4854
+ }
4855
+ if (!validate(data))
4856
+ fail("STRUCTURED_OUTPUT_INVALID", "The response did not match the requested JSON schema.");
4857
+ return { data, response };
4858
+ };
4859
+ }
4860
+ async function parseStructuredResponse(response, format) {
4861
+ return (await createStructuredParser(format))(response);
4862
+ }
4863
+
4613
4864
  // src/response-handle.ts
4614
4865
  var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4615
4866
  var text = (value) => typeof value === "string" ? value : void 0;
@@ -4706,12 +4957,17 @@ function consumeResponse(response, controller, cancel, options = {}) {
4706
4957
  let acknowledgement;
4707
4958
  const listeners = /* @__PURE__ */ new Set();
4708
4959
  const queue = [];
4960
+ let capacityAvailable;
4961
+ const releaseCapacity = () => {
4962
+ capacityAvailable?.();
4963
+ capacityAvailable = void 0;
4964
+ };
4709
4965
  let claimed = false;
4710
4966
  let iteratorClosed = false;
4711
4967
  let iteratorError;
4712
4968
  let pending;
4713
4969
  const emit = (event) => {
4714
- if (!claimed || iteratorClosed) return;
4970
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
4715
4971
  if (pending) {
4716
4972
  pending.resolve({ value: immutable(event), done: false });
4717
4973
  pending = void 0;
@@ -4740,6 +4996,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
4740
4996
  const finish = (value, detached = false) => {
4741
4997
  if (finished) return;
4742
4998
  finished = true;
4999
+ releaseCapacity();
4743
5000
  controller.signal.removeEventListener("abort", abort);
4744
5001
  options.cleanup?.();
4745
5002
  update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
@@ -4787,6 +5044,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
4787
5044
  const close = () => {
4788
5045
  iteratorClosed = true;
4789
5046
  queue.length = 0;
5047
+ releaseCapacity();
4790
5048
  if (pending) {
4791
5049
  pending.resolve({ value: void 0, done: true });
4792
5050
  pending = void 0;
@@ -4798,7 +5056,11 @@ function consumeResponse(response, controller, cancel, options = {}) {
4798
5056
  },
4799
5057
  next() {
4800
5058
  if (iteratorError) return Promise.reject(iteratorError);
4801
- 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
+ }
4802
5064
  if (finished || iteratorClosed)
4803
5065
  return Promise.resolve({ value: void 0, done: true });
4804
5066
  if (pending)
@@ -4959,8 +5221,13 @@ function consumeResponse(response, controller, cancel, options = {}) {
4959
5221
  try {
4960
5222
  while (!finished) {
4961
5223
  const { value, done } = await reader.read();
4962
- 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)) {
4963
5225
  process(frame);
5226
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5227
+ await new Promise((resolve) => {
5228
+ capacityAvailable = resolve;
5229
+ });
5230
+ }
4964
5231
  if (done) break;
4965
5232
  }
4966
5233
  if (!finished) {
@@ -5424,9 +5691,12 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5424
5691
  folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
5425
5692
  presign_expires_in: options?.presignExpiresIn ?? 3600
5426
5693
  };
5427
- const initResult = requireData(
5428
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5429
- "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
+ )
5430
5700
  );
5431
5701
  const items = initResult.items ?? [];
5432
5702
  const bytesByName = /* @__PURE__ */ new Map();
@@ -5483,14 +5753,16 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5483
5753
  if (toCommit.length === 0) {
5484
5754
  return { doc_ext_ids: [], skipped };
5485
5755
  }
5486
- const commitResult = requireData(
5487
- await arbi.fetch.POST("/v1/document/upload-commit", {
5488
- body: {
5489
- doc_ext_ids: toCommit,
5490
- tag_ext_id: options?.tagExtId ?? null
5491
- }
5492
- }),
5493
- "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
+ )
5494
5766
  );
5495
5767
  return {
5496
5768
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -5985,6 +6257,7 @@ __export(assistant_exports, {
5985
6257
  AssistantTurnRefused: () => AssistantTurnRefused,
5986
6258
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
5987
6259
  SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
6260
+ WORKSPACE_CONFLICT_MESSAGES: () => WORKSPACE_CONFLICT_MESSAGES,
5988
6261
  cancelRun: () => cancelRun,
5989
6262
  filterSkills: () => filterSkills,
5990
6263
  interject: () => interject,
@@ -6087,6 +6360,7 @@ function buildTurnRequest(request) {
6087
6360
  ...request.previousResponseId ? { previous_response_id: request.previousResponseId } : {},
6088
6361
  ...request.conversationId ? { conversation_ext_id: request.conversationId } : {},
6089
6362
  ...request.model && !pa2 ? { model: request.model } : {},
6363
+ ...request.text ? { text: request.text } : {},
6090
6364
  ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6091
6365
  ...request.bindDocumentId && !request.previousResponseId && !pa2 ? { bound_document_ext_id: request.bindDocumentId } : {},
6092
6366
  ...request.mentions && request.mentions.length > 0 ? { mentions: request.mentions } : {},
@@ -6217,11 +6491,29 @@ function quotaFromStreamError(error) {
6217
6491
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6218
6492
  return { spend, budget, projectExtId: match.groups.project ?? null };
6219
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
+ };
6220
6498
  async function refusal(response) {
6221
6499
  const { status } = response;
6222
6500
  const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6223
6501
  const detail = parsed.apiError?.detail;
6224
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
+ }
6225
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;
6226
6518
  return new AssistantTurnRefused(
6227
6519
  quota?.message || parsed.detail || fallback,
@@ -6360,86 +6652,6 @@ async function cancelRun(auth, responseId) {
6360
6652
  });
6361
6653
  }
6362
6654
 
6363
- // src/operations/responses.ts
6364
- var responses_exports = {};
6365
- __export(responses_exports, {
6366
- extractResponseText: () => extractResponseText,
6367
- getResponse: () => getResponse,
6368
- submitBackgroundQuery: () => submitBackgroundQuery
6369
- });
6370
- async function submitBackgroundQuery(options) {
6371
- const {
6372
- workspaceId,
6373
- question,
6374
- docIds,
6375
- previousResponseId,
6376
- model,
6377
- task,
6378
- conversationId,
6379
- mentions,
6380
- activeArtifactExtId,
6381
- fullContext = true,
6382
- ...auth
6383
- } = options;
6384
- const tools = {};
6385
- if (docIds.length > 0) {
6386
- tools.retrieval_chunk = {
6387
- name: "retrieval_chunk",
6388
- description: "retrieval chunk",
6389
- tool_args: { doc_ext_ids: docIds },
6390
- tool_responses: {}
6391
- };
6392
- if (fullContext)
6393
- tools.retrieval_full_context = {
6394
- name: "retrieval_full_context",
6395
- description: "retrieval full context",
6396
- tool_args: { doc_ext_ids: docIds },
6397
- tool_responses: {}
6398
- };
6399
- }
6400
- const body = {
6401
- input: question,
6402
- workspace_ext_id: workspaceId,
6403
- stream: false,
6404
- background: true,
6405
- store: true,
6406
- tools,
6407
- ...task !== void 0 ? { task } : {},
6408
- ...conversationId ? { conversation_ext_id: conversationId } : {},
6409
- ...mentions !== void 0 ? { mentions } : {},
6410
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6411
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
6412
- ...model ? { model } : {}
6413
- };
6414
- const res = await authenticatedFetch({
6415
- ...auth,
6416
- path: "/v1/responses",
6417
- method: "POST",
6418
- body: JSON.stringify(body),
6419
- headers: { "Content-Type": "application/json" }
6420
- });
6421
- return await res.json();
6422
- }
6423
- async function getResponse(auth, responseId) {
6424
- const res = await authenticatedFetch({
6425
- ...auth,
6426
- path: `/v1/responses/${responseId}`,
6427
- method: "GET"
6428
- });
6429
- return await res.json();
6430
- }
6431
- function extractResponseText(response) {
6432
- const parts = [];
6433
- for (const msg of response.output) {
6434
- for (const item of msg.content) {
6435
- if ("type" in item && item.type === "output_text" && "text" in item) {
6436
- parts.push(item.text);
6437
- }
6438
- }
6439
- }
6440
- return parts.join("");
6441
- }
6442
-
6443
6655
  // src/operations/tags.ts
6444
6656
  var tags_exports = {};
6445
6657
  __export(tags_exports, {
@@ -10855,11 +11067,57 @@ var Arbi = class {
10855
11067
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
10856
11068
  * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
10857
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.
10858
11072
  */
10859
- openWorkspace(workspaceId) {
10860
- if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
11073
+ async openWorkspace(workspaceId) {
11074
+ if (workspaceId === this.currentWorkspaceId) return;
10861
11075
  this.requireLogin();
10862
- 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
+ }
10863
11121
  }
10864
11122
  /**
10865
11123
  * Create a tag in `workspaceId`, named on the request: a switch while it is sent cannot move it to the workspace
@@ -11016,6 +11274,11 @@ var Arbi = class {
11016
11274
  try {
11017
11275
  return await run();
11018
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
+ }
11019
11282
  const message = error instanceof Error ? error.message : "";
11020
11283
  const noWorkspace = /no active workspace/i.test(message);
11021
11284
  const unauthorised = /\b401\b|token has expired/i.test(message);
@@ -11523,6 +11786,23 @@ var Arbi = class {
11523
11786
  });
11524
11787
  });
11525
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
+ },
11526
11806
  /** Download a document's original file — its current version, or `version`. */
11527
11807
  download: (docId, version) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId, version)),
11528
11808
  getParsedContent: (docId, stage, version) => this.recovering(
@@ -11578,8 +11858,13 @@ var Arbi = class {
11578
11858
  const first = await runConversation(client, conversationId);
11579
11859
  if (!first.pending_auth_request_id) return first;
11580
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
+ );
11581
11866
  await this.workspaces.grantTemporaryAccess({
11582
- workspaceId: pending.workspace_ext_id ?? this.getWorkspaceId(),
11867
+ workspaceId: pending.workspace_ext_id,
11583
11868
  emails: [pending.agent_email],
11584
11869
  sessionPubkeyB64: pending.session_pubkey
11585
11870
  });
@@ -11672,7 +11957,7 @@ var Arbi = class {
11672
11957
  });
11673
11958
  }
11674
11959
  };
11675
- async openResponseHandle(open, options, id) {
11960
+ async openResponseHandle(open, options, id, bufferEvents = false) {
11676
11961
  const controller = new AbortController();
11677
11962
  const abort = () => controller.abort();
11678
11963
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -11684,7 +11969,7 @@ var Arbi = class {
11684
11969
  response,
11685
11970
  controller,
11686
11971
  (responseId) => this.assistant.cancel(responseId),
11687
- { id, cleanup }
11972
+ { id, cleanup, bufferEvents }
11688
11973
  );
11689
11974
  } catch (error) {
11690
11975
  cleanup();
@@ -11692,16 +11977,143 @@ var Arbi = class {
11692
11977
  throw error;
11693
11978
  }
11694
11979
  }
11980
+ /** Canonical Responses-shaped requests; existing assistant convenience helpers remain supported. */
11981
+ responses = {
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
+ };
12016
+ const response = await this.recovering(
12017
+ () => openTurnStream(this.getAuthHeaders(), requestBody, options.signal)
12018
+ );
12019
+ let body;
12020
+ try {
12021
+ body = await response.text();
12022
+ } catch (cause) {
12023
+ throw transportError(cause);
12024
+ }
12025
+ try {
12026
+ return withOutputText(
12027
+ JSON.parse(body),
12028
+ response.headers.get("x-request-id") ?? void 0
12029
+ );
12030
+ } catch (cause) {
12031
+ throw new ArbiError("Expected a Responses JSON object.", {
12032
+ code: "RESPONSE_INVALID_ENVELOPE",
12033
+ cause,
12034
+ requestId: response.headers.get("x-request-id") ?? void 0
12035
+ });
12036
+ }
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
+ },
12055
+ stream: (request, options = {}) => this.openResponseHandle(
12056
+ (signal) => openTurnStream(
12057
+ this.getAuthHeaders(),
12058
+ {
12059
+ ...request,
12060
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12061
+ stream: true,
12062
+ background: false,
12063
+ store: request.store ?? true
12064
+ },
12065
+ signal
12066
+ ),
12067
+ options
12068
+ ),
12069
+ retrieve: async (id) => withOutputText(await this.assistant.getResponse(id)),
12070
+ cancel: (id) => this.assistant.cancel(id),
12071
+ attach: (id, options = {}) => this.assistant.attachResponse(id, options)
12072
+ };
11695
12073
  // ── Assistant ─────────────────────────────────────────────────────────
11696
12074
  assistant = {
12075
+ /** Create one synchronous Responses result and return validated JSON alongside the raw response. */
12076
+ parseResponse: async (request, options = {}) => {
12077
+ const parse = await createStructuredParser(request.text.format);
12078
+ const body = {
12079
+ ...buildTurnRequest({
12080
+ ...request,
12081
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
12082
+ }),
12083
+ stream: false,
12084
+ background: false
12085
+ };
12086
+ const response = await this.recovering(
12087
+ () => openTurnStream(this.getAuthHeaders(), body, options.signal)
12088
+ );
12089
+ let rawText;
12090
+ try {
12091
+ rawText = await response.text();
12092
+ } catch (cause) {
12093
+ throw transportError(cause);
12094
+ }
12095
+ let raw;
12096
+ try {
12097
+ raw = JSON.parse(rawText);
12098
+ } catch (cause) {
12099
+ throw new ArbiStructuredOutputError("Expected a Responses JSON object.", rawText, {
12100
+ code: "RESPONSE_INVALID_ENVELOPE",
12101
+ cause,
12102
+ requestId: response.headers.get("x-request-id") ?? void 0
12103
+ });
12104
+ }
12105
+ return parse(raw, { requestId: response.headers.get("x-request-id") ?? void 0 });
12106
+ },
11697
12107
  /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
11698
12108
  startResponse: async (request, options = {}) => {
11699
- const body = buildTurnRequest({
11700
- ...request,
11701
- workspaceId: request.workspaceId ?? this.requireWorkspace()
11702
- });
12109
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
11703
12110
  return this.openResponseHandle(
11704
- (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
+ ),
11705
12117
  options
11706
12118
  );
11707
12119
  },
@@ -11729,22 +12141,29 @@ var Arbi = class {
11729
12141
  * with it; an abort just rejects.
11730
12142
  */
11731
12143
  ask: async (request, handlers = {}) => {
11732
- const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
11733
- const body = buildTurnRequest({
11734
- ...request,
11735
- workspaceId: request.workspaceId ?? this.requireWorkspace()
11736
- });
12144
+ const { signal, onError, onQuotaExceeded, onWorkspace, ...callbacks } = handlers;
12145
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
11737
12146
  const refuse = (message, error = new Error(message)) => {
11738
12147
  onError?.(message);
11739
12148
  throw error;
11740
12149
  };
11741
12150
  let response;
11742
12151
  try {
11743
- response = await this.recovering(
11744
- () => openTurnStream(this.getAuthHeaders(), body, signal)
12152
+ response = await this.openTurn(
12153
+ request,
12154
+ workspaceId,
12155
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12156
+ onWorkspace
11745
12157
  );
11746
12158
  } catch (error) {
11747
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
+ }
11748
12167
  if (error instanceof AssistantTurnRefused) {
11749
12168
  if (error.quota) onQuotaExceeded?.(error.quota);
11750
12169
  callbacks.onErrorDetails?.(error);
@@ -11802,14 +12221,16 @@ var Arbi = class {
11802
12221
  transcribe: (audio) => transcribe(this.requireClient(), audio),
11803
12222
  /** Start a durable background turn; task options make its thread a work item. */
11804
12223
  submit: (question, options) => {
11805
- const workspaceId = this.requireWorkspace();
11806
- return this.recovering(
11807
- () => submitBackgroundQuery({
11808
- ...this.getAuthHeaders(),
11809
- ...options,
11810
- workspaceId,
11811
- question
11812
- })
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
+ )
11813
12234
  );
11814
12235
  },
11815
12236
  /** Read the status of a background turn. */
@@ -11830,13 +12251,19 @@ var Arbi = class {
11830
12251
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
11831
12252
  * workspace; `searchChunks(result)` ranks the passages found.
11832
12253
  */
11833
- retrieve: (query2, docIds, options) => retrieve({
11834
- arbi: this.requireClient(),
11835
- workspaceId: this.requireWorkspace(),
11836
- query: query2,
11837
- docIds,
11838
- ...options
11839
- })
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
+ }
11840
12267
  };
11841
12268
  // ── Tags ──────────────────────────────────────────────────────────────
11842
12269
  tags = {
@@ -13258,13 +13685,65 @@ function getRunToAttach(localGeneration, messages) {
13258
13685
  return getAttachableRunId(messages);
13259
13686
  }
13260
13687
 
13688
+ // src/configuration.ts
13689
+ function composeConfiguration(base, ...patches) {
13690
+ const result = structuredClone(base);
13691
+ for (const patch of patches) {
13692
+ for (const [key, value] of Object.entries(patch)) {
13693
+ if (value === void 0) continue;
13694
+ result[key] = value && typeof value === "object" && !Array.isArray(value) ? { ...result[key] ?? {}, ...structuredClone(value) } : structuredClone(value);
13695
+ }
13696
+ }
13697
+ return result;
13698
+ }
13699
+ function instructions(text2) {
13700
+ return { QueryLLM: { SYSTEM_INSTRUCTION: text2 }, Agents: { PERSONA: text2 } };
13701
+ }
13702
+ function capabilities(options) {
13703
+ const flags = {
13704
+ webSearch: "WEB_SEARCH_ENABLED",
13705
+ codeExecution: "RUN_CODE_ENABLED",
13706
+ planning: "PLANNING_ENABLED",
13707
+ deepResearch: "DEEP_RESEARCH_ENABLED",
13708
+ subagents: "SUBAGENTS_ENABLED",
13709
+ humanInput: "HUMAN_IN_THE_LOOP"
13710
+ };
13711
+ const Agents = {};
13712
+ for (const key of Object.keys(flags)) {
13713
+ if (options[key] !== void 0) Agents[flags[key]] = options[key];
13714
+ }
13715
+ return { Agents };
13716
+ }
13717
+ function mcpTools(base, names, mode) {
13718
+ return {
13719
+ Agents: {
13720
+ MCP_TOOLS: [
13721
+ .../* @__PURE__ */ new Set([...mode === "add" ? base.Agents?.MCP_TOOLS ?? [] : [], ...names])
13722
+ ]
13723
+ }
13724
+ };
13725
+ }
13726
+ function documentTools(options) {
13727
+ return {
13728
+ ...options.search ? { retrieval_chunk: buildRetrievalChunkTool([...options.search]) } : {},
13729
+ ...options.fullContext ? { retrieval_full_context: buildRetrievalFullContextTool([...options.fullContext]) } : {},
13730
+ ...options.tableOfContents ? { retrieval_toc: buildRetrievalTocTool([...options.tableOfContents]) } : {}
13731
+ };
13732
+ }
13733
+ function composeTools(base, next, mode) {
13734
+ return structuredClone(mode === "add" ? { ...base, ...next } : next);
13735
+ }
13736
+
13261
13737
  exports.ACCOUNT_VENDOR = ACCOUNT_VENDOR;
13262
13738
  exports.Arbi = Arbi;
13263
13739
  exports.ArbiApiError = ArbiApiError;
13264
13740
  exports.ArbiError = ArbiError;
13741
+ exports.ArbiSessionExpiredError = ArbiSessionExpiredError;
13742
+ exports.ArbiStructuredOutputError = ArbiStructuredOutputError;
13265
13743
  exports.ArbiTransportError = ArbiTransportError;
13266
13744
  exports.ArbiWorkspaceChangedError = ArbiWorkspaceChangedError;
13267
13745
  exports.ArbiWorkspaceSupersededError = ArbiWorkspaceSupersededError;
13746
+ exports.ArbiWorkspaceUnavailableError = ArbiWorkspaceUnavailableError;
13268
13747
  exports.CallApiError = CallApiError;
13269
13748
  exports.DEFAULT_AI_USD_PER_GBP = DEFAULT_AI_USD_PER_GBP;
13270
13749
  exports.DRIVE_SYNC_VENDORS = DRIVE_SYNC_VENDORS;
@@ -13280,6 +13759,7 @@ exports.PRESENCE_KINDS = PRESENCE_KINDS;
13280
13759
  exports.PROMPT_CONTEXT_CHARS = PROMPT_CONTEXT_CHARS;
13281
13760
  exports.PlanStepsError = PlanStepsError;
13282
13761
  exports.PublicBookingError = PublicBookingError;
13762
+ exports.ResponseStream = ResponseStream;
13283
13763
  exports.SHAREPOINT_VENDORS = SHAREPOINT_VENDORS;
13284
13764
  exports.STOP_ID_WAIT_MS = STOP_ID_WAIT_MS;
13285
13765
  exports.STOP_REPEAT_WINDOW_MS = STOP_REPEAT_WINDOW_MS;
@@ -13303,7 +13783,10 @@ exports.calendar = calendar_exports;
13303
13783
  exports.calls = calls_exports;
13304
13784
  exports.canTagHaveParent = canTagHaveParent;
13305
13785
  exports.cancelPublicBooking = cancelPublicBooking;
13786
+ exports.capabilities = capabilities;
13306
13787
  exports.chats = chats_exports;
13788
+ exports.composeConfiguration = composeConfiguration;
13789
+ exports.composeTools = composeTools;
13307
13790
  exports.computeRunStats = computeRunStats;
13308
13791
  exports.connectErrorMessage = connectErrorMessage;
13309
13792
  exports.connectWebSocket = connectWebSocket;
@@ -13318,6 +13801,7 @@ exports.createIndexAssigner = createIndexAssigner;
13318
13801
  exports.databases = databases_exports;
13319
13802
  exports.defaultKindForFormat = defaultKindForFormat;
13320
13803
  exports.doctags = doctags_exports;
13804
+ exports.documentTools = documentTools;
13321
13805
  exports.documents = documents_exports;
13322
13806
  exports.estimateDraftTokens = estimateDraftTokens;
13323
13807
  exports.extractDocumentIdsFromMessages = extractDocumentIdsFromMessages;
@@ -13348,6 +13832,7 @@ exports.getContextUsedPercent = getContextUsedPercent;
13348
13832
  exports.getContextUsedTokens = getContextUsedTokens;
13349
13833
  exports.getCurrentStep = getCurrentStep;
13350
13834
  exports.getEligibleParentTags = getEligibleParentTags;
13835
+ exports.getErrorCode = getErrorCode;
13351
13836
  exports.getErrorMessage = getErrorMessage;
13352
13837
  exports.getPublicBookingPage = getPublicBookingPage;
13353
13838
  exports.getRawWorkspaceKey = getRawWorkspaceKey;
@@ -13362,6 +13847,7 @@ exports.houseTemplates = house_template_exports;
13362
13847
  exports.hydrateAgentSteps = hydrateAgentSteps;
13363
13848
  exports.identityErrorCode = identityErrorCode;
13364
13849
  exports.identityVerification = identity_exports;
13850
+ exports.instructions = instructions;
13365
13851
  exports.isAnnotationTag = isAnnotationTag;
13366
13852
  exports.isConnectorVendorVisible = isConnectorVendorVisible;
13367
13853
  exports.isDriveSyncVendor = isDriveSyncVendor;
@@ -13375,11 +13861,13 @@ exports.isSharePointVendor = isSharePointVendor;
13375
13861
  exports.isSharedSkill = isSharedSkill;
13376
13862
  exports.isTraceItem = isTraceItem;
13377
13863
  exports.mail = mail_exports;
13864
+ exports.mcpTools = mcpTools;
13378
13865
  exports.mergeAgentSteps = mergeAgentSteps;
13379
13866
  exports.notifications = notifications_exports;
13380
13867
  exports.parseSSEEvents = parseSSEEvents;
13381
13868
  exports.parseSlashCommand = parseSlashCommand;
13382
13869
  exports.parseSlashTokenInProgress = parseSlashTokenInProgress;
13870
+ exports.parseStructuredResponse = parseStructuredResponse;
13383
13871
  exports.performPasswordLogin = performPasswordLogin;
13384
13872
  exports.pickMainThread = pickMainThread;
13385
13873
  exports.profile = profile_exports;
@@ -13416,6 +13904,7 @@ exports.usdToGbp = usdToGbp;
13416
13904
  exports.work = work_exports;
13417
13905
  exports.workflowSteps = workflow_steps_exports;
13418
13906
  exports.workflows = workflows_exports;
13907
+ exports.workspaceConflictOf = workspaceConflictOf;
13419
13908
  exports.workspaces = workspaces_exports;
13420
13909
  exports.wouldCreateTagCycle = wouldCreateTagCycle;
13421
13910
  //# sourceMappingURL=browser.cjs.map