@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/index.cjs CHANGED
@@ -3526,6 +3526,22 @@ var ArbiWorkspaceChangedError = class extends ArbiError {
3526
3526
  }
3527
3527
  workspaceId;
3528
3528
  };
3529
+ var ArbiWorkspaceUnavailableError = class extends ArbiError {
3530
+ constructor(workspaceId, cause, message = `Workspace ${workspaceId} can't be opened in this session, so nothing was sent`) {
3531
+ super(message, { code: "WORKSPACE_UNAVAILABLE", cause });
3532
+ this.workspaceId = workspaceId;
3533
+ this.name = "ArbiWorkspaceUnavailableError";
3534
+ }
3535
+ workspaceId;
3536
+ };
3537
+ function workspaceConflictOf(error) {
3538
+ const body = error instanceof ArbiApiError ? error.apiError : error instanceof Error ? void 0 : error;
3539
+ const detail = errorRecord(errorRecord(body)?.detail);
3540
+ const code = detail?.code;
3541
+ const workspaceId = detail?.workspace_ext_id;
3542
+ if (code !== "workspace_key_required" && code !== "workspace_mismatch") return null;
3543
+ return typeof workspaceId === "string" && workspaceId ? { code, workspaceId } : null;
3544
+ }
3529
3545
  function detailText(detail) {
3530
3546
  if (typeof detail === "string") return detail || void 0;
3531
3547
  if (Array.isArray(detail)) {
@@ -5165,6 +5181,228 @@ function buildChunkLookup(tools) {
5165
5181
  return lookup;
5166
5182
  }
5167
5183
 
5184
+ // src/operations/responses.ts
5185
+ var responses_exports = {};
5186
+ __export(responses_exports, {
5187
+ extractResponseText: () => extractResponseText,
5188
+ getResponse: () => getResponse,
5189
+ submitBackgroundQuery: () => submitBackgroundQuery
5190
+ });
5191
+ async function submitBackgroundQuery(options) {
5192
+ const {
5193
+ workspaceId,
5194
+ question,
5195
+ docIds,
5196
+ previousResponseId,
5197
+ model,
5198
+ text: text2,
5199
+ task,
5200
+ conversationId,
5201
+ mentions,
5202
+ activeArtifactExtId,
5203
+ fullContext = true,
5204
+ ...auth
5205
+ } = options;
5206
+ const tools = {};
5207
+ if (docIds.length > 0) {
5208
+ tools.retrieval_chunk = {
5209
+ name: "retrieval_chunk",
5210
+ description: "retrieval chunk",
5211
+ tool_args: { doc_ext_ids: docIds },
5212
+ tool_responses: {}
5213
+ };
5214
+ if (fullContext)
5215
+ tools.retrieval_full_context = {
5216
+ name: "retrieval_full_context",
5217
+ description: "retrieval full context",
5218
+ tool_args: { doc_ext_ids: docIds },
5219
+ tool_responses: {}
5220
+ };
5221
+ }
5222
+ const body = {
5223
+ input: question,
5224
+ workspace_ext_id: workspaceId,
5225
+ stream: false,
5226
+ background: true,
5227
+ store: true,
5228
+ tools,
5229
+ ...task !== void 0 ? { task } : {},
5230
+ ...conversationId ? { conversation_ext_id: conversationId } : {},
5231
+ ...mentions !== void 0 ? { mentions } : {},
5232
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5233
+ ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5234
+ ...model ? { model } : {},
5235
+ ...text2 ? { text: text2 } : {}
5236
+ };
5237
+ const res = await authenticatedFetch({
5238
+ ...auth,
5239
+ path: "/v1/responses",
5240
+ method: "POST",
5241
+ body: JSON.stringify(body),
5242
+ headers: { "Content-Type": "application/json" }
5243
+ });
5244
+ return await res.json();
5245
+ }
5246
+ async function getResponse(auth, responseId) {
5247
+ const res = await authenticatedFetch({
5248
+ ...auth,
5249
+ path: `/v1/responses/${responseId}`,
5250
+ method: "GET"
5251
+ });
5252
+ return await res.json();
5253
+ }
5254
+ function extractResponseText(response) {
5255
+ const parts = [];
5256
+ for (const msg of Array.isArray(response.output) ? response.output : []) {
5257
+ if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
5258
+ for (const item of msg.content) {
5259
+ if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
5260
+ }
5261
+ }
5262
+ return parts.join("");
5263
+ }
5264
+
5265
+ // src/responses-resource.ts
5266
+ function withOutputText(response, requestId) {
5267
+ return {
5268
+ ...response,
5269
+ output_text: extractResponseText(response),
5270
+ ...requestId ? { _request_id: requestId } : {}
5271
+ };
5272
+ }
5273
+ var ResponseStream = class {
5274
+ constructor(handle) {
5275
+ this.handle = handle;
5276
+ }
5277
+ handle;
5278
+ async *[Symbol.asyncIterator]() {
5279
+ try {
5280
+ for await (const frame of this.handle.events()) {
5281
+ const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
5282
+ yield {
5283
+ ...data,
5284
+ type: typeof data.type === "string" ? data.type : frame.event
5285
+ };
5286
+ }
5287
+ const outcome = await this.handle.outcome;
5288
+ if (outcome.status === "disconnected")
5289
+ throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
5290
+ } finally {
5291
+ this.handle.detach();
5292
+ }
5293
+ }
5294
+ };
5295
+
5296
+ // src/structured-output.ts
5297
+ var ArbiStructuredOutputError = class extends ArbiError {
5298
+ constructor(message, response, options) {
5299
+ const id = response && typeof response === "object" && "id" in response && typeof response.id === "string" ? response.id : void 0;
5300
+ super(message, { responseId: id, ...options });
5301
+ this.response = response;
5302
+ this.name = "ArbiStructuredOutputError";
5303
+ }
5304
+ response;
5305
+ };
5306
+ function localReferences(value) {
5307
+ if (Array.isArray(value)) {
5308
+ value.forEach(localReferences);
5309
+ return;
5310
+ }
5311
+ if (!value || typeof value !== "object") return;
5312
+ for (const [key, child] of Object.entries(value)) {
5313
+ if ((key === "$ref" || key === "$dynamicRef") && (typeof child !== "string" || !child.startsWith("#")))
5314
+ throw new Error("Only local schema references are supported.");
5315
+ if (!["enum", "const", "default", "examples"].includes(key)) localReferences(child);
5316
+ }
5317
+ }
5318
+ async function createStructuredParser(format) {
5319
+ let validate;
5320
+ let Constructor;
5321
+ try {
5322
+ Constructor = (await import('ajv/dist/2020.js')).default;
5323
+ } catch (cause) {
5324
+ throw new ArbiStructuredOutputError(
5325
+ "The JSON Schema validator could not be loaded.",
5326
+ void 0,
5327
+ { code: "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE", cause }
5328
+ );
5329
+ }
5330
+ try {
5331
+ 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))
5332
+ throw new Error("Invalid structured output format.");
5333
+ if (format.schema.$schema !== void 0 && format.schema.$schema !== "https://json-schema.org/draft/2020-12/schema")
5334
+ throw new Error("Expected JSON Schema draft 2020-12.");
5335
+ localReferences(format.schema);
5336
+ validate = new Constructor({
5337
+ strict: false,
5338
+ logger: false,
5339
+ validateFormats: false,
5340
+ strictNumbers: true,
5341
+ addUsedSchema: false
5342
+ }).compile(format.schema);
5343
+ } catch (cause) {
5344
+ const unavailable = cause instanceof EvalError;
5345
+ throw new ArbiStructuredOutputError(
5346
+ unavailable ? "This runtime cannot compile JSON Schema validators." : "Invalid or unsupported output schema.",
5347
+ void 0,
5348
+ {
5349
+ code: unavailable ? "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE" : "STRUCTURED_OUTPUT_SCHEMA_INVALID",
5350
+ cause
5351
+ }
5352
+ );
5353
+ }
5354
+ return (response, options = {}) => {
5355
+ const fail = (code, message, cause) => {
5356
+ throw new ArbiStructuredOutputError(message, response, { ...options, code, cause });
5357
+ };
5358
+ if (!response || typeof response !== "object")
5359
+ fail("RESPONSE_INVALID_ENVELOPE", "Expected a Responses JSON object.");
5360
+ if (response.status === "incomplete")
5361
+ fail("RESPONSE_INCOMPLETE", "The response is incomplete; no validated data is available.");
5362
+ if (response.status === "cancelled")
5363
+ fail("RESPONSE_CANCELLED", "The response was cancelled; no validated data is available.");
5364
+ if (response.status === "failed")
5365
+ fail(
5366
+ typeof response.error?.code === "string" ? response.error.code : "RESPONSE_FAILED",
5367
+ typeof response.error?.message === "string" ? response.error.message : "The response failed."
5368
+ );
5369
+ if (response.status !== "completed")
5370
+ fail(
5371
+ "RESPONSE_NOT_COMPLETED",
5372
+ "Wait for a completed response before parsing structured output."
5373
+ );
5374
+ const messages = Array.isArray(response.output) ? response.output.filter(
5375
+ (item) => item && typeof item === "object" && item.type === "message" && item.role === "assistant"
5376
+ ) : [];
5377
+ if (messages.some(
5378
+ (message) => !Array.isArray(message.content) || message.content.some((part) => !part || typeof part !== "object")
5379
+ ))
5380
+ fail("RESPONSE_INVALID_ENVELOPE", "Invalid assistant output content.");
5381
+ if (messages.some((message) => message.content.some((part) => part.type === "refusal")))
5382
+ fail("RESPONSE_REFUSED", "The model refused this response.");
5383
+ const answers = messages.map(
5384
+ (message) => message.content.filter((part) => part.type === "output_text" && typeof part.text === "string").map((part) => part.text).join("")
5385
+ ).filter((answer) => answer.length > 0);
5386
+ if (answers.length !== 1)
5387
+ fail(
5388
+ "STRUCTURED_OUTPUT_AMBIGUOUS",
5389
+ "Expected one final assistant output message; narrative and answer text are not joined."
5390
+ );
5391
+ let data;
5392
+ try {
5393
+ data = JSON.parse(answers[0]);
5394
+ } catch (cause) {
5395
+ fail("STRUCTURED_OUTPUT_INVALID_JSON", "The response is not valid JSON.", cause);
5396
+ }
5397
+ if (!validate(data))
5398
+ fail("STRUCTURED_OUTPUT_INVALID", "The response did not match the requested JSON schema.");
5399
+ return { data, response };
5400
+ };
5401
+ }
5402
+ async function parseStructuredResponse(response, format) {
5403
+ return (await createStructuredParser(format))(response);
5404
+ }
5405
+
5168
5406
  // src/response-handle.ts
5169
5407
  var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5170
5408
  var text = (value) => typeof value === "string" ? value : void 0;
@@ -5261,12 +5499,17 @@ function consumeResponse(response, controller, cancel, options = {}) {
5261
5499
  let acknowledgement;
5262
5500
  const listeners = /* @__PURE__ */ new Set();
5263
5501
  const queue = [];
5502
+ let capacityAvailable;
5503
+ const releaseCapacity = () => {
5504
+ capacityAvailable?.();
5505
+ capacityAvailable = void 0;
5506
+ };
5264
5507
  let claimed = false;
5265
5508
  let iteratorClosed = false;
5266
5509
  let iteratorError;
5267
5510
  let pending;
5268
5511
  const emit = (event) => {
5269
- if (!claimed || iteratorClosed) return;
5512
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
5270
5513
  if (pending) {
5271
5514
  pending.resolve({ value: immutable(event), done: false });
5272
5515
  pending = void 0;
@@ -5295,6 +5538,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
5295
5538
  const finish = (value, detached = false) => {
5296
5539
  if (finished) return;
5297
5540
  finished = true;
5541
+ releaseCapacity();
5298
5542
  controller.signal.removeEventListener("abort", abort);
5299
5543
  options.cleanup?.();
5300
5544
  update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
@@ -5342,6 +5586,7 @@ function consumeResponse(response, controller, cancel, options = {}) {
5342
5586
  const close = () => {
5343
5587
  iteratorClosed = true;
5344
5588
  queue.length = 0;
5589
+ releaseCapacity();
5345
5590
  if (pending) {
5346
5591
  pending.resolve({ value: void 0, done: true });
5347
5592
  pending = void 0;
@@ -5353,7 +5598,11 @@ function consumeResponse(response, controller, cancel, options = {}) {
5353
5598
  },
5354
5599
  next() {
5355
5600
  if (iteratorError) return Promise.reject(iteratorError);
5356
- if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5601
+ if (queue.length) {
5602
+ const value = queue.shift();
5603
+ releaseCapacity();
5604
+ return Promise.resolve({ value, done: false });
5605
+ }
5357
5606
  if (finished || iteratorClosed)
5358
5607
  return Promise.resolve({ value: void 0, done: true });
5359
5608
  if (pending)
@@ -5514,8 +5763,13 @@ function consumeResponse(response, controller, cancel, options = {}) {
5514
5763
  try {
5515
5764
  while (!finished) {
5516
5765
  const { value, done } = await reader.read();
5517
- for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5766
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5518
5767
  process2(frame);
5768
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5769
+ await new Promise((resolve2) => {
5770
+ capacityAvailable = resolve2;
5771
+ });
5772
+ }
5519
5773
  if (done) break;
5520
5774
  }
5521
5775
  if (!finished) {
@@ -5979,9 +6233,12 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5979
6233
  folder: options?.folder ? sanitizeFolderPath(options.folder) : null,
5980
6234
  presign_expires_in: options?.presignExpiresIn ?? 3600
5981
6235
  };
5982
- const initResult = requireData(
5983
- await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
5984
- "Failed to initialize direct upload"
6236
+ const guarded = options?.inWorkspace ?? ((send) => send());
6237
+ const initResult = await guarded(
6238
+ async () => requireData(
6239
+ await arbi.fetch.POST("/v1/document/upload-init", { body: initBody }),
6240
+ "Failed to initialize direct upload"
6241
+ )
5985
6242
  );
5986
6243
  const items = initResult.items ?? [];
5987
6244
  const bytesByName = /* @__PURE__ */ new Map();
@@ -6038,14 +6295,16 @@ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6038
6295
  if (toCommit.length === 0) {
6039
6296
  return { doc_ext_ids: [], skipped };
6040
6297
  }
6041
- const commitResult = requireData(
6042
- await arbi.fetch.POST("/v1/document/upload-commit", {
6043
- body: {
6044
- doc_ext_ids: toCommit,
6045
- tag_ext_id: options?.tagExtId ?? null
6046
- }
6047
- }),
6048
- "Failed to commit direct upload"
6298
+ const commitResult = await guarded(
6299
+ async () => requireData(
6300
+ await arbi.fetch.POST("/v1/document/upload-commit", {
6301
+ body: {
6302
+ doc_ext_ids: toCommit,
6303
+ tag_ext_id: options?.tagExtId ?? null
6304
+ }
6305
+ }),
6306
+ "Failed to commit direct upload"
6307
+ )
6049
6308
  );
6050
6309
  return {
6051
6310
  doc_ext_ids: commitResult.doc_ext_ids ?? [],
@@ -6563,6 +6822,7 @@ __export(assistant_exports, {
6563
6822
  AssistantTurnRefused: () => AssistantTurnRefused,
6564
6823
  MAX_RETRIEVE_DOC_IDS: () => MAX_RETRIEVE_DOC_IDS,
6565
6824
  SESSION_EXPIRED_MESSAGE: () => SESSION_EXPIRED_MESSAGE,
6825
+ WORKSPACE_CONFLICT_MESSAGES: () => WORKSPACE_CONFLICT_MESSAGES,
6566
6826
  cancelRun: () => cancelRun,
6567
6827
  filterSkills: () => filterSkills,
6568
6828
  interject: () => interject,
@@ -6665,6 +6925,7 @@ function buildTurnRequest(request) {
6665
6925
  ...request.previousResponseId ? { previous_response_id: request.previousResponseId } : {},
6666
6926
  ...request.conversationId ? { conversation_ext_id: request.conversationId } : {},
6667
6927
  ...request.model && !pa2 ? { model: request.model } : {},
6928
+ ...request.text ? { text: request.text } : {},
6668
6929
  ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6669
6930
  ...request.bindDocumentId && !request.previousResponseId && !pa2 ? { bound_document_ext_id: request.bindDocumentId } : {},
6670
6931
  ...request.mentions && request.mentions.length > 0 ? { mentions: request.mentions } : {},
@@ -6795,11 +7056,29 @@ function quotaFromStreamError(error) {
6795
7056
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6796
7057
  return { spend, budget, projectExtId: match.groups.project ?? null };
6797
7058
  }
7059
+ var WORKSPACE_CONFLICT_MESSAGES = {
7060
+ workspace_mismatch: "This conversation belongs to another workspace, so the reply was not sent. Open that workspace to continue it.",
7061
+ workspace_key_required: "This chat's workspace isn't open in this session, so the message was not sent. Open the workspace and try again."
7062
+ };
6798
7063
  async function refusal(response) {
6799
7064
  const { status } = response;
6800
7065
  const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6801
7066
  const detail = parsed.apiError?.detail;
6802
7067
  const quota = status === 402 ? quotaExceededFrom(detail) : null;
7068
+ const conflict = status === 409 ? workspaceConflictOf(parsed.apiError) : null;
7069
+ if (conflict) {
7070
+ return new AssistantTurnRefused(
7071
+ WORKSPACE_CONFLICT_MESSAGES[conflict.code],
7072
+ status,
7073
+ null,
7074
+ parsed.apiError,
7075
+ {
7076
+ code: conflict.code,
7077
+ requestId: parsed.requestId,
7078
+ responseId: parsed.responseId
7079
+ }
7080
+ );
7081
+ }
6803
7082
  const fallback = status === 409 ? "This message has failed. Please retry from the previous message." : status === 503 ? "The selected LLM is not responding. Please retry again in a minute or select another model." : status === 402 ? "This project's AI usage for this month is used up." : parsed.message;
6804
7083
  return new AssistantTurnRefused(
6805
7084
  quota?.message || parsed.detail || fallback,
@@ -6938,86 +7217,6 @@ async function cancelRun(auth, responseId) {
6938
7217
  });
6939
7218
  }
6940
7219
 
6941
- // src/operations/responses.ts
6942
- var responses_exports = {};
6943
- __export(responses_exports, {
6944
- extractResponseText: () => extractResponseText,
6945
- getResponse: () => getResponse,
6946
- submitBackgroundQuery: () => submitBackgroundQuery
6947
- });
6948
- async function submitBackgroundQuery(options) {
6949
- const {
6950
- workspaceId,
6951
- question,
6952
- docIds,
6953
- previousResponseId,
6954
- model,
6955
- task,
6956
- conversationId,
6957
- mentions,
6958
- activeArtifactExtId,
6959
- fullContext = true,
6960
- ...auth
6961
- } = options;
6962
- const tools = {};
6963
- if (docIds.length > 0) {
6964
- tools.retrieval_chunk = {
6965
- name: "retrieval_chunk",
6966
- description: "retrieval chunk",
6967
- tool_args: { doc_ext_ids: docIds },
6968
- tool_responses: {}
6969
- };
6970
- if (fullContext)
6971
- tools.retrieval_full_context = {
6972
- name: "retrieval_full_context",
6973
- description: "retrieval full context",
6974
- tool_args: { doc_ext_ids: docIds },
6975
- tool_responses: {}
6976
- };
6977
- }
6978
- const body = {
6979
- input: question,
6980
- workspace_ext_id: workspaceId,
6981
- stream: false,
6982
- background: true,
6983
- store: true,
6984
- tools,
6985
- ...task !== void 0 ? { task } : {},
6986
- ...conversationId ? { conversation_ext_id: conversationId } : {},
6987
- ...mentions !== void 0 ? { mentions } : {},
6988
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
6989
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
6990
- ...model ? { model } : {}
6991
- };
6992
- const res = await authenticatedFetch({
6993
- ...auth,
6994
- path: "/v1/responses",
6995
- method: "POST",
6996
- body: JSON.stringify(body),
6997
- headers: { "Content-Type": "application/json" }
6998
- });
6999
- return await res.json();
7000
- }
7001
- async function getResponse(auth, responseId) {
7002
- const res = await authenticatedFetch({
7003
- ...auth,
7004
- path: `/v1/responses/${responseId}`,
7005
- method: "GET"
7006
- });
7007
- return await res.json();
7008
- }
7009
- function extractResponseText(response) {
7010
- const parts = [];
7011
- for (const msg of response.output) {
7012
- for (const item of msg.content) {
7013
- if ("type" in item && item.type === "output_text" && "text" in item) {
7014
- parts.push(item.text);
7015
- }
7016
- }
7017
- }
7018
- return parts.join("");
7019
- }
7020
-
7021
7220
  // src/operations/tags.ts
7022
7221
  var tags_exports = {};
7023
7222
  __export(tags_exports, {
@@ -11454,11 +11653,57 @@ var Arbi = class {
11454
11653
  * Make a workspace usable for requests that name it, WITHOUT changing the current workspace (on
11455
11654
  * the server or here): its key, sealed to this server session, is deposited with `/prime-key`
11456
11655
  * (the client's `workspaceKeys.prime`: once per server session). The current workspace is open.
11656
+ * A workspace the user holds no key for (a public one, or a temporary grant whose key the server
11657
+ * session already holds) has nothing to deposit: the server answers for it as it is.
11457
11658
  */
11458
- openWorkspace(workspaceId) {
11459
- if (workspaceId === this.currentWorkspaceId) return Promise.resolve();
11659
+ async openWorkspace(workspaceId) {
11660
+ if (workspaceId === this.currentWorkspaceId) return;
11460
11661
  this.requireLogin();
11461
- return this.requireClient().workspaceKeys.prime(workspaceId);
11662
+ const keys = this.requireClient().workspaceKeys;
11663
+ const { wrappedKey } = await keys.wrappedKey(workspaceId).catch(keyLookupFailed);
11664
+ if (!wrappedKey) return;
11665
+ return keys.prime(workspaceId);
11666
+ }
11667
+ /**
11668
+ * {@link openWorkspace} (or, with `force`, deposit the key again even for the current workspace:
11669
+ * the server said it lacks it), failing with {@link ArbiWorkspaceUnavailableError} when the key
11670
+ * cannot be deposited. Then nothing is sent, so nothing can land in another workspace.
11671
+ */
11672
+ async primeOrFail(workspaceId, options = {}) {
11673
+ try {
11674
+ if (options.force) {
11675
+ this.requireLogin();
11676
+ await this.requireClient().workspaceKeys.prime(workspaceId, { force: true });
11677
+ } else await this.openWorkspace(workspaceId);
11678
+ } catch (error) {
11679
+ if (client.isAbortError(error) || error instanceof ArbiSessionExpiredError) throw error;
11680
+ throw new ArbiWorkspaceUnavailableError(workspaceId, error);
11681
+ }
11682
+ }
11683
+ /**
11684
+ * Open a chat turn's stream in `workspaceId` (captured by the caller when the turn started): the
11685
+ * workspace is opened for this session first if it is not the current one, and the body names
11686
+ * it, so a switch meanwhile cannot move the turn. A follow-up refused with 409
11687
+ * `workspace_mismatch` (its thread is in another workspace: nothing was written) is sent once
11688
+ * more in the thread's workspace, which is where the server stores a follow-up anyway.
11689
+ * `onWorkspace` hears the workspace the turn was accepted in.
11690
+ */
11691
+ async openTurn(request, workspaceId, open, onWorkspace) {
11692
+ let target = workspaceId;
11693
+ for (let attempt = 0; ; attempt++) {
11694
+ await this.primeOrFail(target);
11695
+ const body = buildTurnRequest({ ...request, workspaceId: target });
11696
+ try {
11697
+ const response = await this.recovering(() => open(body));
11698
+ onWorkspace?.(target);
11699
+ return response;
11700
+ } catch (error) {
11701
+ const conflict = workspaceConflictOf(error);
11702
+ const retryInThread = attempt === 0 && !!request.previousResponseId && conflict?.code === "workspace_mismatch" && conflict.workspaceId !== target;
11703
+ if (!retryInThread) throw error;
11704
+ target = conflict.workspaceId;
11705
+ }
11706
+ }
11462
11707
  }
11463
11708
  /**
11464
11709
  * Create a tag in `workspaceId`, named on the request: a switch while it is sent cannot move it to the workspace
@@ -11615,6 +11860,11 @@ var Arbi = class {
11615
11860
  try {
11616
11861
  return await run();
11617
11862
  } catch (error) {
11863
+ const conflict = workspaceConflictOf(error);
11864
+ if (conflict?.code === "workspace_key_required") {
11865
+ await this.primeOrFail(conflict.workspaceId, { force: true });
11866
+ return run();
11867
+ }
11618
11868
  const message = error instanceof Error ? error.message : "";
11619
11869
  const noWorkspace = /no active workspace/i.test(message);
11620
11870
  const unauthorised = /\b401\b|token has expired/i.test(message);
@@ -12122,6 +12372,23 @@ var Arbi = class {
12122
12372
  });
12123
12373
  });
12124
12374
  },
12375
+ /**
12376
+ * Upload files straight to storage, encrypted here with `workspaceKey` (`uploadDocumentsDirect`),
12377
+ * into `workspaceId`, which must be the workspace open NOW. `upload-init` and `upload-commit`
12378
+ * name no workspace yet (they act on the session's open one), so each runs under
12379
+ * `readInWorkspace`: it is not sent, or its answer not kept, unless `workspaceId` is open when
12380
+ * it is sent and still when it returns. A switch refuses the upload
12381
+ * (`ArbiWorkspaceChangedError`) instead of storing files encrypted with one workspace's key in
12382
+ * another. For any other workspace use `upload` with `workspaceExtId`, which names it.
12383
+ */
12384
+ uploadDirect: (workspaceId, workspaceKey, files, options) => {
12385
+ if (this.currentWorkspaceId !== workspaceId)
12386
+ return Promise.reject(new ArbiWorkspaceChangedError(workspaceId, "uploading to"));
12387
+ return uploadDocumentsDirect(this.requireClient(), workspaceKey, files, {
12388
+ ...options,
12389
+ inWorkspace: (send) => this.readInWorkspace(workspaceId, send)
12390
+ });
12391
+ },
12125
12392
  /** Download a document's original file — its current version, or `version`. */
12126
12393
  download: (docId, version) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId, version)),
12127
12394
  getParsedContent: (docId, stage, version) => this.recovering(
@@ -12177,8 +12444,13 @@ var Arbi = class {
12177
12444
  const first = await runConversation(client, conversationId);
12178
12445
  if (!first.pending_auth_request_id) return first;
12179
12446
  const pending = await getPendingAuth(client, conversationId);
12447
+ if (!pending.workspace_ext_id)
12448
+ throw new ArbiError(
12449
+ "The run is waiting for access, but the server did not say to which workspace",
12450
+ { code: "PENDING_AUTH_WITHOUT_WORKSPACE" }
12451
+ );
12180
12452
  await this.workspaces.grantTemporaryAccess({
12181
- workspaceId: pending.workspace_ext_id ?? this.getWorkspaceId(),
12453
+ workspaceId: pending.workspace_ext_id,
12182
12454
  emails: [pending.agent_email],
12183
12455
  sessionPubkeyB64: pending.session_pubkey
12184
12456
  });
@@ -12271,7 +12543,7 @@ var Arbi = class {
12271
12543
  });
12272
12544
  }
12273
12545
  };
12274
- async openResponseHandle(open, options, id) {
12546
+ async openResponseHandle(open, options, id, bufferEvents = false) {
12275
12547
  const controller = new AbortController();
12276
12548
  const abort = () => controller.abort();
12277
12549
  options.signal?.addEventListener("abort", abort, { once: true });
@@ -12283,7 +12555,7 @@ var Arbi = class {
12283
12555
  response,
12284
12556
  controller,
12285
12557
  (responseId) => this.assistant.cancel(responseId),
12286
- { id, cleanup }
12558
+ { id, cleanup, bufferEvents }
12287
12559
  );
12288
12560
  } catch (error) {
12289
12561
  cleanup();
@@ -12291,16 +12563,143 @@ var Arbi = class {
12291
12563
  throw error;
12292
12564
  }
12293
12565
  }
12566
+ /** Canonical Responses-shaped requests; existing assistant convenience helpers remain supported. */
12567
+ responses = {
12568
+ create: async (request, options = {}) => {
12569
+ if (request.stream) {
12570
+ if (request.background)
12571
+ throw new ArbiError(
12572
+ "Streaming background creation is not supported yet. Create in background mode, then attach to the returned response.",
12573
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12574
+ );
12575
+ const body2 = {
12576
+ ...request,
12577
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12578
+ stream: true,
12579
+ background: false,
12580
+ store: request.store ?? true
12581
+ };
12582
+ const started = await this.openResponseHandle(
12583
+ (signal) => openTurnStream(this.getAuthHeaders(), body2, signal),
12584
+ options,
12585
+ void 0,
12586
+ true
12587
+ );
12588
+ if (started.kind !== "response")
12589
+ throw new ArbiError("The control command was acknowledged without creating a response.", {
12590
+ code: "RESPONSE_CONTROL_ACKNOWLEDGED",
12591
+ cause: started.acknowledgement
12592
+ });
12593
+ return new ResponseStream(started.handle);
12594
+ }
12595
+ const requestBody = {
12596
+ ...request,
12597
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12598
+ stream: false,
12599
+ background: request.background ?? false,
12600
+ store: request.store ?? true
12601
+ };
12602
+ const response = await this.recovering(
12603
+ () => openTurnStream(this.getAuthHeaders(), requestBody, options.signal)
12604
+ );
12605
+ let body;
12606
+ try {
12607
+ body = await response.text();
12608
+ } catch (cause) {
12609
+ throw transportError(cause);
12610
+ }
12611
+ try {
12612
+ return withOutputText(
12613
+ JSON.parse(body),
12614
+ response.headers.get("x-request-id") ?? void 0
12615
+ );
12616
+ } catch (cause) {
12617
+ throw new ArbiError("Expected a Responses JSON object.", {
12618
+ code: "RESPONSE_INVALID_ENVELOPE",
12619
+ cause,
12620
+ requestId: response.headers.get("x-request-id") ?? void 0
12621
+ });
12622
+ }
12623
+ },
12624
+ parse: async (request, options = {}) => {
12625
+ if (request.stream || request.background)
12626
+ throw new ArbiError(
12627
+ "Parse a synchronous response, or validate a completed stored response separately.",
12628
+ { code: "RESPONSES_UNSUPPORTED_OPTION" }
12629
+ );
12630
+ const workspaceId = request.workspace_ext_id ?? this.requireWorkspace();
12631
+ const parse = await createStructuredParser(request.text.format);
12632
+ const response = await this.responses.create(
12633
+ { ...request, workspace_ext_id: workspaceId, stream: false, background: false },
12634
+ options
12635
+ );
12636
+ return {
12637
+ ...response,
12638
+ output_parsed: parse(response, { requestId: response._request_id }).data
12639
+ };
12640
+ },
12641
+ stream: (request, options = {}) => this.openResponseHandle(
12642
+ (signal) => openTurnStream(
12643
+ this.getAuthHeaders(),
12644
+ {
12645
+ ...request,
12646
+ workspace_ext_id: request.workspace_ext_id ?? this.requireWorkspace(),
12647
+ stream: true,
12648
+ background: false,
12649
+ store: request.store ?? true
12650
+ },
12651
+ signal
12652
+ ),
12653
+ options
12654
+ ),
12655
+ retrieve: async (id) => withOutputText(await this.assistant.getResponse(id)),
12656
+ cancel: (id) => this.assistant.cancel(id),
12657
+ attach: (id, options = {}) => this.assistant.attachResponse(id, options)
12658
+ };
12294
12659
  // ── Assistant ─────────────────────────────────────────────────────────
12295
12660
  assistant = {
12661
+ /** Create one synchronous Responses result and return validated JSON alongside the raw response. */
12662
+ parseResponse: async (request, options = {}) => {
12663
+ const parse = await createStructuredParser(request.text.format);
12664
+ const body = {
12665
+ ...buildTurnRequest({
12666
+ ...request,
12667
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
12668
+ }),
12669
+ stream: false,
12670
+ background: false
12671
+ };
12672
+ const response = await this.recovering(
12673
+ () => openTurnStream(this.getAuthHeaders(), body, options.signal)
12674
+ );
12675
+ let rawText;
12676
+ try {
12677
+ rawText = await response.text();
12678
+ } catch (cause) {
12679
+ throw transportError(cause);
12680
+ }
12681
+ let raw;
12682
+ try {
12683
+ raw = JSON.parse(rawText);
12684
+ } catch (cause) {
12685
+ throw new ArbiStructuredOutputError("Expected a Responses JSON object.", rawText, {
12686
+ code: "RESPONSE_INVALID_ENVELOPE",
12687
+ cause,
12688
+ requestId: response.headers.get("x-request-id") ?? void 0
12689
+ });
12690
+ }
12691
+ return parse(raw, { requestId: response.headers.get("x-request-id") ?? void 0 });
12692
+ },
12296
12693
  /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
12297
12694
  startResponse: async (request, options = {}) => {
12298
- const body = buildTurnRequest({
12299
- ...request,
12300
- workspaceId: request.workspaceId ?? this.requireWorkspace()
12301
- });
12695
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
12302
12696
  return this.openResponseHandle(
12303
- (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12697
+ (signal) => this.openTurn(
12698
+ request,
12699
+ workspaceId,
12700
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12701
+ options.onWorkspace
12702
+ ),
12304
12703
  options
12305
12704
  );
12306
12705
  },
@@ -12328,22 +12727,29 @@ var Arbi = class {
12328
12727
  * with it; an abort just rejects.
12329
12728
  */
12330
12729
  ask: async (request, handlers = {}) => {
12331
- const { signal, onError, onQuotaExceeded, ...callbacks } = handlers;
12332
- const body = buildTurnRequest({
12333
- ...request,
12334
- workspaceId: request.workspaceId ?? this.requireWorkspace()
12335
- });
12730
+ const { signal, onError, onQuotaExceeded, onWorkspace, ...callbacks } = handlers;
12731
+ const workspaceId = request.workspaceId ?? this.requireWorkspace();
12336
12732
  const refuse = (message, error = new Error(message)) => {
12337
12733
  onError?.(message);
12338
12734
  throw error;
12339
12735
  };
12340
12736
  let response;
12341
12737
  try {
12342
- response = await this.recovering(
12343
- () => openTurnStream(this.getAuthHeaders(), body, signal)
12738
+ response = await this.openTurn(
12739
+ request,
12740
+ workspaceId,
12741
+ (body) => openTurnStream(this.getAuthHeaders(), body, signal),
12742
+ onWorkspace
12344
12743
  );
12345
12744
  } catch (error) {
12346
12745
  if (isAbort(error)) throw error;
12746
+ if (error instanceof ArbiWorkspaceUnavailableError) {
12747
+ callbacks.onErrorDetails?.(error);
12748
+ return refuse(
12749
+ "This chat's workspace can't be opened in this session, so the message was not sent.",
12750
+ error
12751
+ );
12752
+ }
12347
12753
  if (error instanceof AssistantTurnRefused) {
12348
12754
  if (error.quota) onQuotaExceeded?.(error.quota);
12349
12755
  callbacks.onErrorDetails?.(error);
@@ -12401,14 +12807,16 @@ var Arbi = class {
12401
12807
  transcribe: (audio) => transcribe(this.requireClient(), audio),
12402
12808
  /** Start a durable background turn; task options make its thread a work item. */
12403
12809
  submit: (question, options) => {
12404
- const workspaceId = this.requireWorkspace();
12405
- return this.recovering(
12406
- () => submitBackgroundQuery({
12407
- ...this.getAuthHeaders(),
12408
- ...options,
12409
- workspaceId,
12410
- question
12411
- })
12810
+ const workspaceId = options.workspaceId ?? this.requireWorkspace();
12811
+ return this.primeOrFail(workspaceId).then(
12812
+ () => this.recovering(
12813
+ () => submitBackgroundQuery({
12814
+ ...this.getAuthHeaders(),
12815
+ ...options,
12816
+ workspaceId,
12817
+ question
12818
+ })
12819
+ )
12412
12820
  );
12413
12821
  },
12414
12822
  /** Read the status of a background turn. */
@@ -12429,13 +12837,19 @@ var Arbi = class {
12429
12837
  * Search documents without LLM generation (retrieval only). No `docIds` searches the whole
12430
12838
  * workspace; `searchChunks(result)` ranks the passages found.
12431
12839
  */
12432
- retrieve: (query2, docIds, options) => retrieve({
12433
- arbi: this.requireClient(),
12434
- workspaceId: this.requireWorkspace(),
12435
- query: query2,
12436
- docIds,
12437
- ...options
12438
- })
12840
+ retrieve: (query2, docIds, options) => {
12841
+ const { workspaceId: named, ...rest } = options ?? {};
12842
+ const workspaceId = named ?? this.requireWorkspace();
12843
+ return this.primeOrFail(workspaceId).then(
12844
+ () => retrieve({
12845
+ arbi: this.requireClient(),
12846
+ workspaceId,
12847
+ query: query2,
12848
+ docIds,
12849
+ ...rest
12850
+ })
12851
+ );
12852
+ }
12439
12853
  };
12440
12854
  // ── Tags ──────────────────────────────────────────────────────────────
12441
12855
  tags = {
@@ -14930,14 +15344,65 @@ function getRunToAttach(localGeneration, messages) {
14930
15344
  return getAttachableRunId(messages);
14931
15345
  }
14932
15346
 
15347
+ // src/configuration.ts
15348
+ function composeConfiguration(base, ...patches) {
15349
+ const result = structuredClone(base);
15350
+ for (const patch of patches) {
15351
+ for (const [key, value] of Object.entries(patch)) {
15352
+ if (value === void 0) continue;
15353
+ result[key] = value && typeof value === "object" && !Array.isArray(value) ? { ...result[key] ?? {}, ...structuredClone(value) } : structuredClone(value);
15354
+ }
15355
+ }
15356
+ return result;
15357
+ }
15358
+ function instructions(text2) {
15359
+ return { QueryLLM: { SYSTEM_INSTRUCTION: text2 }, Agents: { PERSONA: text2 } };
15360
+ }
15361
+ function capabilities(options) {
15362
+ const flags = {
15363
+ webSearch: "WEB_SEARCH_ENABLED",
15364
+ codeExecution: "RUN_CODE_ENABLED",
15365
+ planning: "PLANNING_ENABLED",
15366
+ deepResearch: "DEEP_RESEARCH_ENABLED",
15367
+ subagents: "SUBAGENTS_ENABLED",
15368
+ humanInput: "HUMAN_IN_THE_LOOP"
15369
+ };
15370
+ const Agents = {};
15371
+ for (const key of Object.keys(flags)) {
15372
+ if (options[key] !== void 0) Agents[flags[key]] = options[key];
15373
+ }
15374
+ return { Agents };
15375
+ }
15376
+ function mcpTools(base, names, mode) {
15377
+ return {
15378
+ Agents: {
15379
+ MCP_TOOLS: [
15380
+ .../* @__PURE__ */ new Set([...mode === "add" ? base.Agents?.MCP_TOOLS ?? [] : [], ...names])
15381
+ ]
15382
+ }
15383
+ };
15384
+ }
15385
+ function documentTools(options) {
15386
+ return {
15387
+ ...options.search ? { retrieval_chunk: buildRetrievalChunkTool([...options.search]) } : {},
15388
+ ...options.fullContext ? { retrieval_full_context: buildRetrievalFullContextTool([...options.fullContext]) } : {},
15389
+ ...options.tableOfContents ? { retrieval_toc: buildRetrievalTocTool([...options.tableOfContents]) } : {}
15390
+ };
15391
+ }
15392
+ function composeTools(base, next, mode) {
15393
+ return structuredClone(mode === "add" ? { ...base, ...next } : next);
15394
+ }
15395
+
14933
15396
  exports.ACCOUNT_VENDOR = ACCOUNT_VENDOR;
14934
15397
  exports.Arbi = Arbi;
14935
15398
  exports.ArbiApiError = ArbiApiError;
14936
15399
  exports.ArbiError = ArbiError;
14937
15400
  exports.ArbiSessionExpiredError = ArbiSessionExpiredError;
15401
+ exports.ArbiStructuredOutputError = ArbiStructuredOutputError;
14938
15402
  exports.ArbiTransportError = ArbiTransportError;
14939
15403
  exports.ArbiWorkspaceChangedError = ArbiWorkspaceChangedError;
14940
15404
  exports.ArbiWorkspaceSupersededError = ArbiWorkspaceSupersededError;
15405
+ exports.ArbiWorkspaceUnavailableError = ArbiWorkspaceUnavailableError;
14941
15406
  exports.CallApiError = CallApiError;
14942
15407
  exports.ClaudeOrchestrator = ClaudeOrchestrator;
14943
15408
  exports.DEFAULT_AI_USD_PER_GBP = DEFAULT_AI_USD_PER_GBP;
@@ -14957,6 +15422,7 @@ exports.PRESENCE_KINDS = PRESENCE_KINDS;
14957
15422
  exports.PROMPT_CONTEXT_CHARS = PROMPT_CONTEXT_CHARS;
14958
15423
  exports.PlanStepsError = PlanStepsError;
14959
15424
  exports.PublicBookingError = PublicBookingError;
15425
+ exports.ResponseStream = ResponseStream;
14960
15426
  exports.SHAREPOINT_VENDORS = SHAREPOINT_VENDORS;
14961
15427
  exports.STEP_FIELD_OPTION_TONES = STEP_FIELD_OPTION_TONES;
14962
15428
  exports.STOP_ID_WAIT_MS = STOP_ID_WAIT_MS;
@@ -14983,7 +15449,10 @@ exports.calendar = calendar_exports;
14983
15449
  exports.calls = calls_exports;
14984
15450
  exports.canTagHaveParent = canTagHaveParent;
14985
15451
  exports.cancelPublicBooking = cancelPublicBooking;
15452
+ exports.capabilities = capabilities;
14986
15453
  exports.chats = chats_exports;
15454
+ exports.composeConfiguration = composeConfiguration;
15455
+ exports.composeTools = composeTools;
14987
15456
  exports.computeRunStats = computeRunStats;
14988
15457
  exports.connectErrorMessage = connectErrorMessage;
14989
15458
  exports.connectWebSocket = connectWebSocket;
@@ -15000,6 +15469,7 @@ exports.databases = databases_exports;
15000
15469
  exports.defaultKindForFormat = defaultKindForFormat;
15001
15470
  exports.deviceFlow = device_flow_exports;
15002
15471
  exports.doctags = doctags_exports;
15472
+ exports.documentTools = documentTools;
15003
15473
  exports.documents = documents_exports;
15004
15474
  exports.documentsNode = documents_node_exports;
15005
15475
  exports.estimateDraftTokens = estimateDraftTokens;
@@ -15051,6 +15521,7 @@ exports.houseTemplates = house_template_exports;
15051
15521
  exports.hydrateAgentSteps = hydrateAgentSteps;
15052
15522
  exports.identityErrorCode = identityErrorCode;
15053
15523
  exports.identityVerification = identity_exports;
15524
+ exports.instructions = instructions;
15054
15525
  exports.isAnnotationTag = isAnnotationTag;
15055
15526
  exports.isConnectorVendorVisible = isConnectorVendorVisible;
15056
15527
  exports.isDriveSyncVendor = isDriveSyncVendor;
@@ -15066,11 +15537,13 @@ exports.isTraceItem = isTraceItem;
15066
15537
  exports.listen = listen_exports;
15067
15538
  exports.mail = mail_exports;
15068
15539
  exports.mailNode = mail_node_exports;
15540
+ exports.mcpTools = mcpTools;
15069
15541
  exports.mergeAgentSteps = mergeAgentSteps;
15070
15542
  exports.notifications = notifications_exports;
15071
15543
  exports.parseSSEEvents = parseSSEEvents;
15072
15544
  exports.parseSlashCommand = parseSlashCommand;
15073
15545
  exports.parseSlashTokenInProgress = parseSlashTokenInProgress;
15546
+ exports.parseStructuredResponse = parseStructuredResponse;
15074
15547
  exports.performPasswordLogin = performPasswordLogin;
15075
15548
  exports.performSigningKeyLogin = performSigningKeyLogin;
15076
15549
  exports.performSsoDeviceFlowLogin = performSsoDeviceFlowLogin;
@@ -15112,6 +15585,7 @@ exports.usdToGbp = usdToGbp;
15112
15585
  exports.work = work_exports;
15113
15586
  exports.workflowSteps = workflow_steps_exports;
15114
15587
  exports.workflows = workflows_exports;
15588
+ exports.workspaceConflictOf = workspaceConflictOf;
15115
15589
  exports.workspaces = workspaces_exports;
15116
15590
  exports.wouldCreateTagCycle = wouldCreateTagCycle;
15117
15591
  //# sourceMappingURL=index.cjs.map