@arbidocs/sdk 0.5.55 → 0.5.57

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
@@ -3476,14 +3476,20 @@ var init_libsodium_wrappers = __esm({
3476
3476
 
3477
3477
  // src/errors.ts
3478
3478
  var ArbiError = class extends Error {
3479
- constructor(message) {
3480
- super(message);
3479
+ code;
3480
+ requestId;
3481
+ responseId;
3482
+ constructor(message, options = {}) {
3483
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
3484
+ this.code = options.code;
3485
+ this.requestId = options.requestId;
3486
+ this.responseId = options.responseId;
3481
3487
  this.name = "ArbiError";
3482
3488
  }
3483
3489
  };
3484
3490
  var ArbiSessionExpiredError = class extends ArbiError {
3485
- constructor(message = "Your session expired. Sign in again.") {
3486
- super(message);
3491
+ constructor(message = "Your session expired. Sign in again.", options = {}) {
3492
+ super(message, { ...options, code: "SESSION_EXPIRED" });
3487
3493
  this.name = "ArbiSessionExpiredError";
3488
3494
  }
3489
3495
  };
@@ -3512,7 +3518,7 @@ function detailText(detail) {
3512
3518
  return messages.length ? messages.join("; ") : void 0;
3513
3519
  }
3514
3520
  if (!detail || typeof detail !== "object") return void 0;
3515
- const message = typeof detail.message === "string" ? detail.message : void 0;
3521
+ const message = typeof detail.message === "string" ? detail.message : typeof detail.hint === "string" ? detail.hint : void 0;
3516
3522
  const fields = detail.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields) ? Object.entries(detail.fields).map(([name, problem]) => `${name}: ${String(problem)}`).join("; ") : "";
3517
3523
  if (message) return fields ? `${message} (${fields})` : message;
3518
3524
  return fields || void 0;
@@ -3521,21 +3527,80 @@ function apiErrorDetail(apiError) {
3521
3527
  if (typeof apiError === "string") return apiError || void 0;
3522
3528
  if (!apiError || typeof apiError !== "object") return void 0;
3523
3529
  const body = apiError;
3524
- return detailText(body.detail) || (typeof body.message === "string" ? body.message : void 0);
3530
+ return detailText(body.detail) || (typeof body.message === "string" ? body.message : void 0) || (typeof body.error === "string" ? body.error : detailText(errorRecord(body.error)));
3525
3531
  }
3526
3532
  var ArbiApiError = class extends ArbiError {
3527
3533
  status;
3528
3534
  apiError;
3529
3535
  /** Why the server refused, in its words (e.g. "run_at must be in the future"), when it said. */
3530
3536
  detail;
3531
- constructor(message, apiError, status) {
3532
- super(message);
3537
+ constructor(message, apiError, status, options = {}) {
3538
+ super(message, {
3539
+ ...apiErrorMetadata(apiError, status),
3540
+ ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0))
3541
+ });
3533
3542
  this.name = "ArbiApiError";
3534
3543
  this.apiError = apiError;
3535
3544
  this.status = status;
3536
3545
  this.detail = apiErrorDetail(apiError);
3537
3546
  }
3538
3547
  };
3548
+ function errorRecord(value) {
3549
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3550
+ }
3551
+ function firstString(...values) {
3552
+ return values.find((value) => typeof value === "string" && value.length > 0);
3553
+ }
3554
+ function apiErrorMetadata(apiError, status) {
3555
+ const body = errorRecord(apiError);
3556
+ const response = errorRecord(body?.response);
3557
+ const detail = errorRecord(body?.detail);
3558
+ const error = errorRecord(response?.error) ?? errorRecord(body?.error);
3559
+ return {
3560
+ code: firstString(error?.code, detail?.code, body?.code) ?? (status !== void 0 ? `HTTP_${status}` : void 0),
3561
+ requestId: firstString(body?.request_id, detail?.request_id, error?.request_id),
3562
+ responseId: firstString(
3563
+ response?.id,
3564
+ body?.response_id,
3565
+ typeof body?.status === "string" ? body?.id : void 0,
3566
+ detail?.response_id,
3567
+ error?.response_id
3568
+ )
3569
+ };
3570
+ }
3571
+ async function apiErrorFromResponse(response, fallback, options = {}) {
3572
+ let body;
3573
+ try {
3574
+ const text2 = await response.text();
3575
+ if (text2) {
3576
+ try {
3577
+ body = JSON.parse(text2);
3578
+ } catch {
3579
+ body = text2.length < 200 ? text2 : void 0;
3580
+ }
3581
+ }
3582
+ } catch {
3583
+ }
3584
+ return new ArbiApiError(fallback, body, response.status, {
3585
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? void 0,
3586
+ ...options
3587
+ });
3588
+ }
3589
+ var ArbiTransportError = class extends ArbiError {
3590
+ constructor(cause, responseId) {
3591
+ super(cause instanceof Error ? cause.message : String(cause), {
3592
+ code: "TRANSPORT_ERROR",
3593
+ cause,
3594
+ responseId
3595
+ });
3596
+ this.name = "ArbiTransportError";
3597
+ }
3598
+ };
3599
+ function transportError(error, responseId) {
3600
+ if (error instanceof ArbiError || error instanceof Error && error.name === "AbortError")
3601
+ return error;
3602
+ return new ArbiTransportError(error, responseId);
3603
+ }
3539
3604
  var DuplicateContactError = class extends ArbiApiError {
3540
3605
  contactId;
3541
3606
  constructor(message, contactId, apiError) {
@@ -3550,13 +3615,17 @@ function refusalReason(err, fallback) {
3550
3615
  }
3551
3616
  function requireData(result, message) {
3552
3617
  if (result.error || !result.data) {
3553
- throw new ArbiApiError(message, result.error, result.response?.status);
3618
+ throw new ArbiApiError(message, result.error, result.response?.status, {
3619
+ requestId: result.response?.headers?.get("x-request-id") ?? void 0
3620
+ });
3554
3621
  }
3555
3622
  return result.data;
3556
3623
  }
3557
3624
  function requireOk(result, message) {
3558
3625
  if (result.error) {
3559
- throw new ArbiApiError(message, result.error, result.response?.status);
3626
+ throw new ArbiApiError(message, result.error, result.response?.status, {
3627
+ requestId: result.response?.headers?.get("x-request-id") ?? void 0
3628
+ });
3560
3629
  }
3561
3630
  }
3562
3631
  function getErrorMessage(err) {
@@ -3587,39 +3656,30 @@ var STATUS_FALLBACKS = {
3587
3656
  404: "Resource not found.",
3588
3657
  503: "The selected LLM is not responding. Please retry or select another model."
3589
3658
  };
3590
- async function extractErrorMessage(res) {
3591
- let bodyDetail;
3592
- try {
3593
- const text = await res.text();
3594
- if (text) {
3595
- try {
3596
- const json2 = JSON.parse(text);
3597
- bodyDetail = detailText(json2.detail) || json2.message || json2.error || void 0;
3598
- } catch {
3599
- if (text.length < 200) bodyDetail = text;
3600
- }
3601
- }
3602
- } catch {
3603
- }
3604
- if (bodyDetail) return `Request failed (${res.status}): ${bodyDetail}`;
3605
- const fallback = STATUS_FALLBACKS[res.status];
3606
- if (fallback) return fallback;
3607
- return `Request failed: ${res.status} ${res.statusText}`;
3608
- }
3609
3659
  async function authenticatedFetch(options) {
3610
3660
  const { baseUrl, accessToken, path: path2, method, body, headers, signal } = options;
3611
- const res = await fetch(`${baseUrl}${path2}`, {
3612
- method: method ?? (body ? "POST" : "GET"),
3613
- headers: {
3614
- Authorization: `Bearer ${accessToken}`,
3615
- ...headers
3616
- },
3617
- body,
3618
- signal
3619
- });
3661
+ let res;
3662
+ try {
3663
+ res = await fetch(`${baseUrl}${path2}`, {
3664
+ method: method ?? (body ? "POST" : "GET"),
3665
+ headers: {
3666
+ Authorization: `Bearer ${accessToken}`,
3667
+ ...headers
3668
+ },
3669
+ body,
3670
+ signal
3671
+ });
3672
+ } catch (error) {
3673
+ throw transportError(error);
3674
+ }
3620
3675
  if (!res.ok) {
3621
- const message = await extractErrorMessage(res);
3622
- throw new ArbiApiError(message, { status: res.status, statusText: res.statusText }, res.status);
3676
+ const error = await apiErrorFromResponse(
3677
+ res,
3678
+ STATUS_FALLBACKS[res.status] ?? `Request failed: ${res.status} ${res.statusText}`
3679
+ );
3680
+ const detail = error.detail || (typeof error.apiError === "string" ? error.apiError : void 0);
3681
+ if (detail) error.message = `Request failed (${res.status}): ${detail}`;
3682
+ throw error;
3623
3683
  }
3624
3684
  return res;
3625
3685
  }
@@ -3932,9 +3992,9 @@ function humanizeStep(identifier) {
3932
3992
  const spaced = identifier.replace(/[_-]+/g, " ").trim();
3933
3993
  return spaced.charAt(0).toUpperCase() + spaced.slice(1);
3934
3994
  }
3935
- function resolveDocRefs(text, docNames) {
3936
- if (!docNames) return text;
3937
- return text.replace(/\{(doc-[^}]+)\}/g, (_match, id) => docNames[id] ?? id);
3995
+ function resolveDocRefs(text2, docNames) {
3996
+ if (!docNames) return text2;
3997
+ return text2.replace(/\{(doc-[^}]+)\}/g, (_match, id) => docNames[id] ?? id);
3938
3998
  }
3939
3999
  function resolveStepDocName(step, docNames) {
3940
4000
  if (!docNames) return void 0;
@@ -4013,13 +4073,16 @@ function parseSSEEvents(chunk, buffer) {
4013
4073
  return { events, remaining };
4014
4074
  }
4015
4075
  async function streamSSE(response, callbacks = {}) {
4076
+ if (!response.ok) throw await apiErrorFromResponse(response, `HTTP ${response.status}`);
4016
4077
  if (!response.body) {
4017
- throw new Error("No response body");
4078
+ throw new ArbiApiError("No response body", void 0, response.status, {
4079
+ code: "MISSING_RESPONSE_BODY"
4080
+ });
4018
4081
  }
4019
4082
  const reader = response.body.getReader();
4020
4083
  const decoder = new TextDecoder("utf-8");
4021
4084
  let sseBuffer = "";
4022
- let text = "";
4085
+ let text2 = "";
4023
4086
  let assistantMessageExtId = null;
4024
4087
  const agentSteps = [];
4025
4088
  let toolCallCount = 0;
@@ -4030,6 +4093,35 @@ async function streamSSE(response, callbacks = {}) {
4030
4093
  let usage = null;
4031
4094
  let context = null;
4032
4095
  let completed = false;
4096
+ let terminal = false;
4097
+ let outcome;
4098
+ let acknowledged = false;
4099
+ const errorDetails = [];
4100
+ const reportError = (error) => {
4101
+ errorDetails.push(error);
4102
+ errors.push(error.message);
4103
+ callbacks.onErrorDetails?.(error);
4104
+ callbacks.onError?.(error.message);
4105
+ };
4106
+ const settle = (payload, fallback) => {
4107
+ const status = payload?.status;
4108
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : fallback;
4109
+ const id = typeof payload?.id === "string" && payload.id ? payload.id : assistantMessageExtId;
4110
+ assistantMessageExtId = id;
4111
+ const rawError = payload?.error;
4112
+ let error;
4113
+ if (resolved === "failed" || rawError) {
4114
+ const body = { response: payload };
4115
+ const message = rawError && typeof rawError === "object" && "message" in rawError && typeof rawError.message === "string" ? rawError.message : "Unknown streaming error";
4116
+ error = new ArbiApiError(message, body, void 0, {
4117
+ code: apiErrorMetadata(body).code ?? "RESPONSE_FAILED",
4118
+ responseId: id ?? void 0
4119
+ });
4120
+ reportError(error);
4121
+ }
4122
+ outcome = { status: resolved, responseId: id, response: payload, ...error ? { error } : {} };
4123
+ terminal = true;
4124
+ };
4033
4125
  const eventHandlers = {
4034
4126
  // OpenAI Responses API events (dot-separated names from server)
4035
4127
  "response.created": (raw) => {
@@ -4050,7 +4142,7 @@ async function streamSSE(response, callbacks = {}) {
4050
4142
  "response.output_text.delta": (raw) => {
4051
4143
  const data = JSON.parse(raw);
4052
4144
  if (data.delta) {
4053
- text += data.delta;
4145
+ text2 += data.delta;
4054
4146
  if (callbacks.onOutputTextDelta) {
4055
4147
  callbacks.onOutputTextDelta({ item_id: data.item_id ?? "", delta: data.delta });
4056
4148
  } else {
@@ -4060,7 +4152,7 @@ async function streamSSE(response, callbacks = {}) {
4060
4152
  },
4061
4153
  "response.output_text.done": (raw) => {
4062
4154
  const data = JSON.parse(raw);
4063
- text = data.text;
4155
+ text2 = data.text;
4064
4156
  callbacks.onTextDone?.(data.text);
4065
4157
  },
4066
4158
  "response.function_call_arguments.delta": (raw) => {
@@ -4081,6 +4173,7 @@ async function streamSSE(response, callbacks = {}) {
4081
4173
  "response.completed": (raw) => {
4082
4174
  const data = JSON.parse(raw);
4083
4175
  completed = true;
4176
+ settle(data.response, "completed");
4084
4177
  if (data.response?.usage) {
4085
4178
  usage = data.response.usage;
4086
4179
  callbacks.onUsage?.(data.response.usage);
@@ -4092,7 +4185,7 @@ async function streamSSE(response, callbacks = {}) {
4092
4185
  }
4093
4186
  const finalText = data.response?.metadata?.content;
4094
4187
  if (finalText) {
4095
- text = finalText;
4188
+ text2 = finalText;
4096
4189
  callbacks.onTextDone?.(finalText);
4097
4190
  }
4098
4191
  if (data.context) {
@@ -4104,12 +4197,17 @@ async function streamSSE(response, callbacks = {}) {
4104
4197
  },
4105
4198
  "response.failed": (raw) => {
4106
4199
  const data = JSON.parse(raw);
4107
- const message = data.response?.error?.message || "Unknown streaming error";
4108
- errors.push(message);
4109
- callbacks.onError?.(message);
4200
+ settle(data.response, "failed");
4201
+ },
4202
+ "response.cancelled": (raw) => {
4203
+ settle(JSON.parse(raw).response, "cancelled");
4204
+ },
4205
+ "response.incomplete": (raw) => {
4206
+ settle(JSON.parse(raw).response, "incomplete");
4110
4207
  },
4111
4208
  // ARBI-specific events (dot-prefixed from server)
4112
4209
  "arbi.message_queued": (raw) => {
4210
+ acknowledged = true;
4113
4211
  const data = JSON.parse(raw);
4114
4212
  if (data.user_message) {
4115
4213
  userMessage = data.user_message;
@@ -4132,6 +4230,7 @@ async function streamSSE(response, callbacks = {}) {
4132
4230
  callbacks.onUserInputRequest?.(data);
4133
4231
  },
4134
4232
  "arbi.probe_answer": (raw) => {
4233
+ acknowledged = true;
4135
4234
  const data = JSON.parse(raw);
4136
4235
  callbacks.onProbeAnswer?.(data);
4137
4236
  },
@@ -4140,6 +4239,7 @@ async function streamSSE(response, callbacks = {}) {
4140
4239
  callbacks.onDeferredInterjection?.(data);
4141
4240
  },
4142
4241
  "arbi.agent_control_state": (raw) => {
4242
+ acknowledged = true;
4143
4243
  const data = JSON.parse(raw);
4144
4244
  callbacks.onAgentControlState?.(data);
4145
4245
  },
@@ -4155,47 +4255,81 @@ async function streamSSE(response, callbacks = {}) {
4155
4255
  "arbi.error": (raw) => {
4156
4256
  const data = JSON.parse(raw);
4157
4257
  const message = typeof data?.message === "string" && data.message.length > 0 ? data.message : data.code;
4258
+ const error = new ArbiApiError(message, data, void 0, {
4259
+ responseId: assistantMessageExtId ?? void 0
4260
+ });
4261
+ errorDetails.push(error);
4158
4262
  errors.push(message);
4263
+ callbacks.onErrorDetails?.(error);
4264
+ outcome = { status: "failed", responseId: assistantMessageExtId, error };
4159
4265
  callbacks.onArbiError?.(data);
4160
4266
  callbacks.onError?.(message);
4161
4267
  }
4162
4268
  };
4163
4269
  const processEvents = (events) => {
4164
4270
  for (const { event, data } of events) {
4271
+ if (terminal) break;
4272
+ if (event === "reasoning") {
4273
+ callbacks.onReasoningDelta?.(data);
4274
+ continue;
4275
+ }
4276
+ const handler = eventHandlers[event];
4277
+ if (!handler) {
4278
+ console.warn(`[arbi-sse] unhandled SSE event: ${event}`);
4279
+ continue;
4280
+ }
4165
4281
  try {
4166
- if (event === "reasoning") {
4167
- callbacks.onReasoningDelta?.(data);
4168
- continue;
4169
- }
4170
- const handler = eventHandlers[event];
4171
- if (handler) {
4172
- handler(data);
4173
- } else {
4174
- console.warn(`[arbi-sse] unhandled SSE event: ${event}`);
4175
- }
4282
+ JSON.parse(data);
4176
4283
  } catch {
4284
+ continue;
4177
4285
  }
4286
+ handler(data);
4178
4287
  }
4179
4288
  };
4180
- while (true) {
4181
- const { done, value } = await reader.read();
4182
- if (done) break;
4183
- const { events, remaining } = parseSSEEvents(decoder.decode(value, { stream: true }), sseBuffer);
4184
- sseBuffer = remaining;
4185
- processEvents(events);
4186
- if (completed) {
4187
- sseBuffer = "";
4188
- void reader.cancel().catch(() => {
4189
- });
4190
- break;
4289
+ try {
4290
+ while (true) {
4291
+ let chunk;
4292
+ try {
4293
+ chunk = await reader.read();
4294
+ } catch (cause) {
4295
+ const error = transportError(cause, assistantMessageExtId ?? void 0);
4296
+ const aborted = error.name === "AbortError";
4297
+ const disconnected = {
4298
+ status: "disconnected",
4299
+ responseId: assistantMessageExtId,
4300
+ reason: aborted ? "aborted" : "connection_error",
4301
+ ...error instanceof ArbiError ? { error } : {}
4302
+ };
4303
+ if (error instanceof ArbiError) callbacks.onErrorDetails?.(error);
4304
+ callbacks.onOutcome?.(disconnected);
4305
+ throw error;
4306
+ }
4307
+ const { done, value } = chunk;
4308
+ if (done) break;
4309
+ const { events, remaining } = parseSSEEvents(
4310
+ decoder.decode(value, { stream: true }),
4311
+ sseBuffer
4312
+ );
4313
+ sseBuffer = remaining;
4314
+ processEvents(events);
4315
+ if (terminal) {
4316
+ sseBuffer = "";
4317
+ void reader.cancel().catch(() => {
4318
+ });
4319
+ break;
4320
+ }
4191
4321
  }
4322
+ if (sseBuffer.trim()) {
4323
+ const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
4324
+ processEvents(events);
4325
+ }
4326
+ } finally {
4327
+ reader.releaseLock();
4192
4328
  }
4193
- if (sseBuffer.trim()) {
4194
- const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
4195
- processEvents(events);
4196
- }
4329
+ outcome ??= acknowledged && !assistantMessageExtId ? { status: "acknowledged", responseId: null } : { status: "disconnected", responseId: assistantMessageExtId, reason: "connection_closed" };
4330
+ callbacks.onOutcome?.(outcome);
4197
4331
  return {
4198
- text,
4332
+ text: text2,
4199
4333
  assistantMessageExtId,
4200
4334
  agentSteps,
4201
4335
  toolCallCount,
@@ -4205,7 +4339,9 @@ async function streamSSE(response, callbacks = {}) {
4205
4339
  artifacts,
4206
4340
  usage,
4207
4341
  context,
4208
- completed
4342
+ completed,
4343
+ outcome,
4344
+ errorDetails
4209
4345
  };
4210
4346
  }
4211
4347
  var AUTH_TIMEOUT_MS = 1e4;
@@ -4401,8 +4537,8 @@ function countCitations(metadata) {
4401
4537
  const responses = modelCitations?.tool_responses;
4402
4538
  return responses ? Object.keys(responses).length : 0;
4403
4539
  }
4404
- function stripCitationMarkdown(text) {
4405
- return text.replace(/\[([^\]]+)\]\(#cite-(\d+)\)/g, "$1[$2]");
4540
+ function stripCitationMarkdown(text2) {
4541
+ return text2.replace(/\[([^\]]+)\]\(#cite-(\d+)\)/g, "$1[$2]");
4406
4542
  }
4407
4543
  function buildCitationChunkData(message) {
4408
4544
  const merged = {};
@@ -4441,6 +4577,403 @@ function buildChunkLookup(tools) {
4441
4577
  return lookup;
4442
4578
  }
4443
4579
 
4580
+ // src/response-handle.ts
4581
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4582
+ var text = (value) => typeof value === "string" ? value : void 0;
4583
+ var messageId = (value) => typeof value === "string" && /^msg-[\w-]+$/.test(value);
4584
+ function immutable(value) {
4585
+ if (value && typeof value === "object" && !(value instanceof Error) && !Object.isFrozen(value)) {
4586
+ Object.freeze(value);
4587
+ for (const child of Object.values(value)) immutable(child);
4588
+ }
4589
+ return value;
4590
+ }
4591
+ function reportObserverError(error) {
4592
+ queueMicrotask(() => {
4593
+ throw error;
4594
+ });
4595
+ }
4596
+ var ResponseEventDecoder = class {
4597
+ buffer = "";
4598
+ event = "";
4599
+ data = [];
4600
+ id;
4601
+ push(chunk, final = false) {
4602
+ this.buffer += chunk;
4603
+ const frames = [];
4604
+ const dispatch = () => {
4605
+ if (this.data.length)
4606
+ frames.push({
4607
+ event: this.event || "message",
4608
+ data: this.data.join("\n"),
4609
+ ...this.id !== void 0 ? { id: this.id } : {}
4610
+ });
4611
+ this.event = "";
4612
+ this.data = [];
4613
+ this.id = void 0;
4614
+ };
4615
+ const line = (value) => {
4616
+ if (!value) {
4617
+ dispatch();
4618
+ return;
4619
+ }
4620
+ if (value.startsWith(":")) return;
4621
+ const colon = value.indexOf(":");
4622
+ const field = colon < 0 ? value : value.slice(0, colon);
4623
+ let content = colon < 0 ? "" : value.slice(colon + 1);
4624
+ if (content.startsWith(" ")) content = content.slice(1);
4625
+ if (field === "event") this.event = content;
4626
+ if (field === "data") this.data.push(content);
4627
+ if (field === "id" && !content.includes("\0")) this.id = content;
4628
+ };
4629
+ while (true) {
4630
+ const index = this.buffer.search(/[\r\n]/);
4631
+ if (index < 0 || !final && index === this.buffer.length - 1 && this.buffer[index] === "\r")
4632
+ break;
4633
+ const width = this.buffer[index] === "\r" && this.buffer[index + 1] === "\n" ? 2 : 1;
4634
+ line(this.buffer.slice(0, index));
4635
+ this.buffer = this.buffer.slice(index + width);
4636
+ }
4637
+ if (final) {
4638
+ if (this.buffer) line(this.buffer);
4639
+ this.buffer = "";
4640
+ dispatch();
4641
+ }
4642
+ return frames;
4643
+ }
4644
+ };
4645
+ function consumeResponse(response, controller, cancel, options = {}) {
4646
+ if (!response.body)
4647
+ return Promise.reject(
4648
+ new ArbiApiError("Response has no stream body.", void 0, response.status, {
4649
+ code: "MISSING_RESPONSE_BODY"
4650
+ })
4651
+ );
4652
+ const reader = response.body.getReader();
4653
+ let resolveStart;
4654
+ let rejectStart;
4655
+ const start = new Promise((resolve, reject) => {
4656
+ resolveStart = resolve;
4657
+ rejectStart = reject;
4658
+ });
4659
+ let resolveOutcome;
4660
+ const outcome = new Promise((resolve) => {
4661
+ resolveOutcome = resolve;
4662
+ });
4663
+ let state = immutable({
4664
+ id: options.id ?? "",
4665
+ conversationId: null,
4666
+ connection: "connecting",
4667
+ responseStatus: null,
4668
+ output: [],
4669
+ displayText: ""
4670
+ });
4671
+ let bound = false;
4672
+ let finished = false;
4673
+ let acknowledgement;
4674
+ const listeners = /* @__PURE__ */ new Set();
4675
+ const queue = [];
4676
+ let claimed = false;
4677
+ let iteratorClosed = false;
4678
+ let iteratorError;
4679
+ let pending;
4680
+ const emit = (event) => {
4681
+ if (!claimed || iteratorClosed) return;
4682
+ if (pending) {
4683
+ pending.resolve({ value: immutable(event), done: false });
4684
+ pending = void 0;
4685
+ } else if (queue.length < 256) queue.push(immutable(event));
4686
+ else {
4687
+ iteratorError = new ArbiError("Raw response event consumer fell behind.", {
4688
+ code: "RESPONSE_EVENT_OVERFLOW"
4689
+ });
4690
+ queue.length = 0;
4691
+ iteratorClosed = true;
4692
+ }
4693
+ };
4694
+ const notify = () => {
4695
+ for (const listener of [...listeners]) {
4696
+ try {
4697
+ listener(state);
4698
+ } catch (error) {
4699
+ reportObserverError(error);
4700
+ }
4701
+ }
4702
+ };
4703
+ const update = (patch) => {
4704
+ state = immutable({ ...state, ...patch });
4705
+ notify();
4706
+ };
4707
+ const finish = (value, detached = false) => {
4708
+ if (finished) return;
4709
+ finished = true;
4710
+ controller.signal.removeEventListener("abort", abort);
4711
+ options.cleanup?.();
4712
+ update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
4713
+ listeners.clear();
4714
+ resolveOutcome(state.outcome);
4715
+ if (pending) {
4716
+ pending.resolve({ value: void 0, done: true });
4717
+ pending = void 0;
4718
+ }
4719
+ void reader.cancel().catch(() => {
4720
+ });
4721
+ };
4722
+ const abort = () => {
4723
+ if (!bound) rejectStart(new DOMException("The operation was aborted.", "AbortError"));
4724
+ finish({ status: "disconnected", responseId: bound ? state.id : null, reason: "aborted" }, true);
4725
+ queue.length = 0;
4726
+ };
4727
+ const handle = {
4728
+ get id() {
4729
+ return state.id;
4730
+ },
4731
+ snapshot: () => state,
4732
+ subscribe(listener) {
4733
+ if (!finished) listeners.add(listener);
4734
+ try {
4735
+ listener(state);
4736
+ } catch (error) {
4737
+ reportObserverError(error);
4738
+ }
4739
+ return () => {
4740
+ listeners.delete(listener);
4741
+ };
4742
+ },
4743
+ outcome,
4744
+ detach: () => {
4745
+ if (!finished) controller.abort();
4746
+ },
4747
+ cancel: () => cancel(state.id),
4748
+ events() {
4749
+ if (claimed)
4750
+ throw new ArbiError("A response handle supports one raw event iterator.", {
4751
+ code: "RESPONSE_EVENTS_ALREADY_CLAIMED"
4752
+ });
4753
+ claimed = true;
4754
+ const close = () => {
4755
+ iteratorClosed = true;
4756
+ queue.length = 0;
4757
+ if (pending) {
4758
+ pending.resolve({ value: void 0, done: true });
4759
+ pending = void 0;
4760
+ }
4761
+ };
4762
+ return {
4763
+ [Symbol.asyncIterator]() {
4764
+ return this;
4765
+ },
4766
+ next() {
4767
+ if (iteratorError) return Promise.reject(iteratorError);
4768
+ if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
4769
+ if (finished || iteratorClosed)
4770
+ return Promise.resolve({ value: void 0, done: true });
4771
+ if (pending)
4772
+ return Promise.reject(
4773
+ new ArbiError("Concurrent iterator reads are unsupported.", {
4774
+ code: "RESPONSE_EVENTS_CONCURRENT_READ"
4775
+ })
4776
+ );
4777
+ return new Promise((resolve, reject) => {
4778
+ pending = { resolve, reject };
4779
+ });
4780
+ },
4781
+ async return() {
4782
+ close();
4783
+ return { value: void 0, done: true };
4784
+ },
4785
+ async throw(error) {
4786
+ close();
4787
+ throw error;
4788
+ }
4789
+ };
4790
+ }
4791
+ };
4792
+ const bind = (id) => {
4793
+ if (bound) return;
4794
+ bound = true;
4795
+ state = immutable({ ...state, id, connection: "streaming" });
4796
+ resolveStart({ kind: "response", handle });
4797
+ };
4798
+ const diagnostic = (code, frame) => emit({ event: "arbi.sdk.protocol_error", data: { code, frame } });
4799
+ const process = (frame) => {
4800
+ if (finished) return;
4801
+ let data;
4802
+ if (frame.event === "reasoning") {
4803
+ emit({
4804
+ event: frame.event,
4805
+ data: frame.data,
4806
+ ...frame.id !== void 0 ? { id: frame.id } : {}
4807
+ });
4808
+ return;
4809
+ }
4810
+ try {
4811
+ data = JSON.parse(frame.data);
4812
+ } catch {
4813
+ diagnostic("MALFORMED_JSON", frame);
4814
+ return;
4815
+ }
4816
+ const payload = object(data);
4817
+ const raw = object(payload?.response);
4818
+ const id = raw?.id;
4819
+ if (bound && typeof id === "string" && id !== state.id) {
4820
+ diagnostic("CONFLICTING_RESPONSE_ID", frame);
4821
+ return;
4822
+ }
4823
+ if (messageId(id)) bind(id);
4824
+ emit({ event: frame.event, data, ...frame.id !== void 0 ? { id: frame.id } : {} });
4825
+ if (frame.event === "arbi.message_queued") acknowledgement = payload;
4826
+ const patch = {};
4827
+ if (frame.event === "arbi.user_message" && !state.conversationId && typeof payload?.conversation_ext_id === "string")
4828
+ patch.conversationId = payload.conversation_ext_id;
4829
+ if (raw) {
4830
+ patch.rawResponse = raw;
4831
+ if (typeof raw.status === "string") patch.responseStatus = raw.status;
4832
+ if (Array.isArray(raw.output))
4833
+ patch.output = raw.output.filter((item2) => !!object(item2));
4834
+ const metadata = object(raw.metadata);
4835
+ const conversation = text(metadata?.conversation_ext_id) ?? text(metadata?.conversation_id) ?? text(raw.conversation_id);
4836
+ if (conversation && (!state.conversationId || state.conversationId === conversation))
4837
+ patch.conversationId = conversation;
4838
+ if (typeof metadata?.content === "string") patch.displayText = metadata.content;
4839
+ }
4840
+ const item = object(payload?.item);
4841
+ if ((frame.event === "response.output_item.added" || frame.event === "response.output_item.done") && item) {
4842
+ const output = [...state.output];
4843
+ const index = output.findIndex((existing) => existing.id === item.id);
4844
+ if (index >= 0 && item.id) output[index] = item;
4845
+ else
4846
+ output.splice(
4847
+ typeof payload?.output_index === "number" ? payload.output_index : output.length,
4848
+ 0,
4849
+ item
4850
+ );
4851
+ patch.output = output;
4852
+ }
4853
+ const itemId = text(payload?.item_id);
4854
+ const delta = text(payload?.delta);
4855
+ if (itemId && [
4856
+ "response.content_part.added",
4857
+ "response.output_text.delta",
4858
+ "response.output_text.done",
4859
+ "response.function_call_arguments.delta",
4860
+ "response.reasoning_summary_text.delta"
4861
+ ].includes(frame.event)) {
4862
+ const output = [...patch.output ?? state.output];
4863
+ let index = output.findIndex((existing) => existing.id === itemId);
4864
+ if (index < 0) {
4865
+ index = output.length;
4866
+ output.push({
4867
+ id: itemId,
4868
+ type: frame.event.includes("function_call") ? "function_call" : frame.event.includes("reasoning") ? "reasoning" : "message"
4869
+ });
4870
+ }
4871
+ const current = { ...output[index] };
4872
+ if (frame.event === "response.function_call_arguments.delta")
4873
+ current.arguments = (text(current.arguments) ?? "") + (delta ?? "");
4874
+ else {
4875
+ const key = frame.event.includes("reasoning") ? "summary" : "content";
4876
+ const content = Array.isArray(current[key]) ? [...current[key]] : [];
4877
+ const partIndex = typeof payload?.content_index === "number" ? payload.content_index : typeof payload?.summary_index === "number" ? payload.summary_index : 0;
4878
+ const part = {
4879
+ ...object(content[partIndex]) ?? {
4880
+ type: key === "summary" ? "summary_text" : "output_text",
4881
+ text: ""
4882
+ }
4883
+ };
4884
+ if (frame.event === "response.content_part.added")
4885
+ content[partIndex] = object(payload?.part) ?? part;
4886
+ else {
4887
+ part.text = frame.event === "response.output_text.done" ? text(payload?.text) ?? "" : (text(part.text) ?? "") + (delta ?? "");
4888
+ content[partIndex] = part;
4889
+ }
4890
+ current[key] = content;
4891
+ }
4892
+ output[index] = current;
4893
+ patch.output = output;
4894
+ }
4895
+ if (frame.event === "response.output_text.delta" && delta)
4896
+ patch.displayText = state.displayText + delta;
4897
+ if (frame.event === "response.output_text.done" && typeof payload?.text === "string")
4898
+ patch.displayText = payload.text;
4899
+ update(patch);
4900
+ const terminal = /^response\.(completed|failed|cancelled|incomplete)$/.exec(
4901
+ frame.event
4902
+ )?.[1];
4903
+ if (terminal && bound) {
4904
+ const status = raw?.status;
4905
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : terminal;
4906
+ const error = resolved === "failed" || raw?.error ? new ArbiApiError(
4907
+ text(object(raw?.error)?.message) ?? "Response failed.",
4908
+ { response: raw },
4909
+ void 0,
4910
+ { ...apiErrorMetadata({ response: raw }), responseId: state.id }
4911
+ ) : void 0;
4912
+ finish({
4913
+ status: resolved,
4914
+ responseId: state.id,
4915
+ ...raw ? { response: raw } : {},
4916
+ ...error ? { error } : {}
4917
+ });
4918
+ }
4919
+ };
4920
+ controller.signal.addEventListener("abort", abort, { once: true });
4921
+ if (controller.signal.aborted) abort();
4922
+ else if (options.id) bind(options.id);
4923
+ void (async () => {
4924
+ const decoder = new TextDecoder();
4925
+ const frames = new ResponseEventDecoder();
4926
+ try {
4927
+ while (!finished) {
4928
+ const { value, done } = await reader.read();
4929
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
4930
+ process(frame);
4931
+ if (done) break;
4932
+ }
4933
+ if (!finished) {
4934
+ if (!bound && acknowledgement) {
4935
+ const value = { status: "acknowledged", responseId: null };
4936
+ resolveStart({
4937
+ kind: "acknowledged",
4938
+ acknowledgement: immutable(acknowledgement),
4939
+ outcome: immutable(value)
4940
+ });
4941
+ finish(value);
4942
+ } else {
4943
+ if (!bound)
4944
+ rejectStart(
4945
+ new ArbiApiError(
4946
+ "Stream ended before response identity was established.",
4947
+ void 0,
4948
+ void 0,
4949
+ { code: "MISSING_RESPONSE_ID" }
4950
+ )
4951
+ );
4952
+ finish({
4953
+ status: "disconnected",
4954
+ responseId: bound ? state.id : null,
4955
+ reason: "connection_closed"
4956
+ });
4957
+ }
4958
+ }
4959
+ } catch (cause) {
4960
+ if (!finished) {
4961
+ const error = transportError(cause, bound ? state.id : void 0);
4962
+ if (!bound) rejectStart(error);
4963
+ finish({
4964
+ status: "disconnected",
4965
+ responseId: bound ? state.id : null,
4966
+ reason: error.name === "AbortError" ? "aborted" : "connection_error",
4967
+ ...error instanceof ArbiError ? { error } : {}
4968
+ });
4969
+ }
4970
+ } finally {
4971
+ reader.releaseLock();
4972
+ }
4973
+ })();
4974
+ return start;
4975
+ }
4976
+
4444
4977
  // src/operations/documents.ts
4445
4978
  var documents_exports = {};
4446
4979
  __export(documents_exports, {
@@ -5381,18 +5914,18 @@ async function searchConversations(arbi, body) {
5381
5914
  "Failed to search conversations"
5382
5915
  );
5383
5916
  }
5384
- async function getMessage(arbi, messageId) {
5917
+ async function getMessage(arbi, messageId2) {
5385
5918
  return requireData(
5386
5919
  await arbi.fetch.GET("/v1/conversation/message/{message_ext_id}", {
5387
- params: { path: { message_ext_id: messageId } }
5920
+ params: { path: { message_ext_id: messageId2 } }
5388
5921
  }),
5389
5922
  "Failed to fetch message"
5390
5923
  );
5391
5924
  }
5392
- async function deleteMessage(arbi, messageId) {
5925
+ async function deleteMessage(arbi, messageId2) {
5393
5926
  return requireData(
5394
5927
  await arbi.fetch.DELETE("/v1/conversation/message/{message_ext_id}", {
5395
- params: { path: { message_ext_id: messageId } }
5928
+ params: { path: { message_ext_id: messageId2 } }
5396
5929
  }),
5397
5930
  "Failed to delete message"
5398
5931
  );
@@ -5560,7 +6093,7 @@ async function retrieve(options) {
5560
6093
  tools,
5561
6094
  ...model ? { model } : {}
5562
6095
  };
5563
- const { data, error } = await arbi.fetch.POST("/v1/assistant/retrieve", { body });
6096
+ const { data, error, response } = await arbi.fetch.POST("/v1/assistant/retrieve", { body });
5564
6097
  if (error) {
5565
6098
  const detail = error?.detail;
5566
6099
  let message;
@@ -5572,7 +6105,9 @@ async function retrieve(options) {
5572
6105
  } else {
5573
6106
  message = JSON.stringify(error);
5574
6107
  }
5575
- throw new Error(`Retrieve failed: ${message}`);
6108
+ throw new ArbiApiError(`Retrieve failed: ${message}`, error, response.status, {
6109
+ requestId: response.headers.get("x-request-id") ?? void 0
6110
+ });
5576
6111
  }
5577
6112
  return data;
5578
6113
  }
@@ -5609,7 +6144,7 @@ async function queryAssistant(options) {
5609
6144
  return authenticatedFetch({
5610
6145
  baseUrl,
5611
6146
  accessToken,
5612
- path: "/v1/assistant/query",
6147
+ path: "/v1/responses",
5613
6148
  method: "POST",
5614
6149
  body: JSON.stringify(buildTurnRequest(request)),
5615
6150
  headers: { "Content-Type": "application/json" },
@@ -5619,8 +6154,8 @@ async function queryAssistant(options) {
5619
6154
  var AssistantTurnRefused = class extends ArbiApiError {
5620
6155
  /** Set when the refusal is the project's used-up AI usage. */
5621
6156
  quota;
5622
- constructor(message, status, quota = null) {
5623
- super(message, void 0, status);
6157
+ constructor(message, status, quota = null, apiError, options = {}) {
6158
+ super(message, apiError, status, options);
5624
6159
  this.name = "AssistantTurnRefused";
5625
6160
  this.quota = quota;
5626
6161
  }
@@ -5648,54 +6183,36 @@ function quotaFromStreamError(error) {
5648
6183
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
5649
6184
  return { spend, budget, projectExtId: match.groups.project ?? null };
5650
6185
  }
5651
- async function readDetail(response) {
5652
- try {
5653
- return (await response.json())?.detail;
5654
- } catch {
5655
- return void 0;
5656
- }
5657
- }
5658
6186
  async function refusal(response) {
5659
6187
  const { status } = response;
5660
- if (status === 409) {
5661
- const detail2 = await readDetail(response);
5662
- return new AssistantTurnRefused(
5663
- detailText(detail2) || "This message has failed. Please retry from the previous message.",
5664
- status
5665
- );
5666
- }
5667
- if (status === 503) {
5668
- return new AssistantTurnRefused(
5669
- "The selected LLM is not responding. Please retry again in a minute or select another model.",
5670
- status
5671
- );
5672
- }
5673
- if (status === 402) {
5674
- const detail2 = await readDetail(response);
5675
- const quota = quotaExceededFrom(detail2);
5676
- const message = quota?.message ?? (typeof detail2 === "string" ? detail2 : void 0) ?? detail2?.message ?? "This project's AI usage for this month is used up.";
5677
- return new AssistantTurnRefused(
5678
- message || "This project's AI usage for this month is used up.",
5679
- status,
5680
- quota
5681
- );
5682
- }
5683
- const detail = await readDetail(response);
6188
+ const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6189
+ const detail = parsed.apiError?.detail;
6190
+ const quota = status === 402 ? quotaExceededFrom(detail) : null;
6191
+ 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;
5684
6192
  return new AssistantTurnRefused(
5685
- detailText(detail) || `HTTP error! status: ${status}`,
5686
- status
6193
+ quota?.message || parsed.detail || fallback,
6194
+ status,
6195
+ quota,
6196
+ parsed.apiError,
6197
+ { code: parsed.code, requestId: parsed.requestId, responseId: parsed.responseId }
5687
6198
  );
5688
6199
  }
5689
6200
  async function openTurnStream(auth, body, signal) {
5690
- const response = await fetch(`${auth.baseUrl}/v1/assistant/query`, {
6201
+ const response = await fetch(`${auth.baseUrl}/v1/responses`, {
5691
6202
  method: "POST",
5692
6203
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${auth.accessToken}` },
5693
6204
  body: JSON.stringify(body),
5694
6205
  signal,
5695
6206
  credentials: "include"
6207
+ }).catch((error) => {
6208
+ throw transportError(error);
5696
6209
  });
5697
- if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
5698
- if (!response.ok || !response.body) throw await refusal(response);
6210
+ if (response.status === 401) throw await apiErrorFromResponse(response, SESSION_EXPIRED_MESSAGE);
6211
+ if (!response.ok) throw await refusal(response);
6212
+ if (!response.body)
6213
+ throw new ArbiApiError("Response has no stream body.", void 0, response.status, {
6214
+ code: "MISSING_RESPONSE_BODY"
6215
+ });
5699
6216
  return response;
5700
6217
  }
5701
6218
  async function openRunStream(auth, responseId, signal) {
@@ -5707,15 +6224,23 @@ async function openRunStream(auth, responseId, signal) {
5707
6224
  signal,
5708
6225
  credentials: "include"
5709
6226
  }
5710
- );
5711
- if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
5712
- if (!response.ok || !response.body) {
5713
- throw new ArbiApiError(
6227
+ ).catch((error) => {
6228
+ throw transportError(error, responseId);
6229
+ });
6230
+ if (response.status === 401)
6231
+ throw await apiErrorFromResponse(response, SESSION_EXPIRED_MESSAGE, { responseId });
6232
+ if (!response.ok) {
6233
+ throw await apiErrorFromResponse(
6234
+ response,
5714
6235
  response.status === 404 ? "This run is no longer active." : `HTTP ${response.status}`,
5715
- void 0,
5716
- response.status
6236
+ { responseId }
5717
6237
  );
5718
6238
  }
6239
+ if (!response.body)
6240
+ throw new ArbiApiError("Response has no stream body.", void 0, response.status, {
6241
+ code: "MISSING_RESPONSE_BODY",
6242
+ responseId
6243
+ });
5719
6244
  return response;
5720
6245
  }
5721
6246
  async function interject(arbi, assistantMessageExtId, answer) {
@@ -6737,7 +7262,7 @@ async function listChatMessages(arbi, chatExtId, options) {
6737
7262
  "Failed to load messages"
6738
7263
  );
6739
7264
  }
6740
- async function sendChatMessage(arbi, ring, text, options = {}) {
7265
+ async function sendChatMessage(arbi, ring, text2, options = {}) {
6741
7266
  const attachments = options.attachments ?? [];
6742
7267
  checkChatAttachmentLimits(attachments);
6743
7268
  const key = keyFor(ring, ring.currentVersion);
@@ -6745,7 +7270,7 @@ async function sendChatMessage(arbi, ring, text, options = {}) {
6745
7270
  await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
6746
7271
  params: { path: { chat_ext_id: ring.chatExtId } },
6747
7272
  body: {
6748
- content: await encryptWithChatKey(text, key),
7273
+ content: await encryptWithChatKey(text2, key),
6749
7274
  key_version: ring.currentVersion,
6750
7275
  kind: "text",
6751
7276
  ...attachments.length ? {
@@ -6760,7 +7285,7 @@ async function sendChatMessage(arbi, ring, text, options = {}) {
6760
7285
  );
6761
7286
  return {
6762
7287
  ...created,
6763
- content: text,
7288
+ content: text2,
6764
7289
  ...attachments.length ? { attachmentFiles: attachments } : {}
6765
7290
  };
6766
7291
  }
@@ -6820,9 +7345,9 @@ async function resolveRecipient(arbi, ref) {
6820
7345
  }
6821
7346
  return null;
6822
7347
  }
6823
- async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
7348
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text2, options) {
6824
7349
  const chat = await openDirectChat(arbi, peerExtId);
6825
- return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
7350
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text2, options);
6826
7351
  }
6827
7352
  async function loadDecryptedChat(arbi, crypto2, chat, options) {
6828
7353
  const ring = await openChatKeyRing(chat, crypto2);
@@ -7549,19 +8074,19 @@ function minorDigits(currency) {
7549
8074
  throw new Error(`Unknown currency "${currency}": use an ISO 4217 code such as GBP or USD`);
7550
8075
  }
7551
8076
  }
7552
- function parseBudget(text) {
7553
- const t2 = text.trim();
8077
+ function parseBudget(text2) {
8078
+ const t2 = text2.trim();
7554
8079
  const after = /^([0-9][0-9,_]*(?:\.[0-9]+)?)\s*([A-Za-z]{3})$/.exec(t2);
7555
8080
  const before = /^([A-Za-z]{3})\s*([0-9][0-9,_]*(?:\.[0-9]+)?)$/.exec(t2);
7556
8081
  const [amountText, code] = after ? [after[1], after[2]] : before ? [before[2], before[1]] : [];
7557
8082
  if (!amountText || !code)
7558
- throw new Error(`Invalid budget "${text}": use an amount and a currency, e.g. 6000GBP`);
8083
+ throw new Error(`Invalid budget "${text2}": use an amount and a currency, e.g. 6000GBP`);
7559
8084
  const currency = code.toUpperCase();
7560
8085
  const digits = minorDigits(currency);
7561
8086
  const major = Number(amountText.replace(/[,_]/g, ""));
7562
8087
  const amount = Math.round(major * 10 ** digits);
7563
8088
  if (!Number.isFinite(major) || Math.abs(major * 10 ** digits - amount) > 1e-6)
7564
- throw new Error(`Invalid budget "${text}": ${currency} has ${digits} decimal places`);
8089
+ throw new Error(`Invalid budget "${text2}": ${currency} has ${digits} decimal places`);
7565
8090
  return { amount, currency };
7566
8091
  }
7567
8092
  function formatBudget(budget) {
@@ -8819,15 +9344,15 @@ function listMessages(mail, options) {
8819
9344
  if (options.limit) params.set("limit", String(options.limit));
8820
9345
  return json(mail(`${accountPath(options.accountId ?? NATIVE_ACCOUNT)}/messages?${params}`));
8821
9346
  }
8822
- function getMessage2(mail, messageId, accountId = NATIVE_ACCOUNT) {
8823
- return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}`));
9347
+ function getMessage2(mail, messageId2, accountId = NATIVE_ACCOUNT) {
9348
+ return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`));
8824
9349
  }
8825
- async function downloadAttachment(mail, messageId, attachmentId, accountId = NATIVE_ACCOUNT) {
8826
- const path2 = `${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`;
9350
+ async function downloadAttachment(mail, messageId2, attachmentId, accountId = NATIVE_ACCOUNT) {
9351
+ const path2 = `${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}/attachments/${encodeURIComponent(attachmentId)}`;
8827
9352
  return new Uint8Array(await (await mail(path2)).arrayBuffer());
8828
9353
  }
8829
- async function updateMessage(mail, messageId, update, accountId = NATIVE_ACCOUNT) {
8830
- await mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}`, {
9354
+ async function updateMessage(mail, messageId2, update, accountId = NATIVE_ACCOUNT) {
9355
+ await mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`, {
8831
9356
  method: "PATCH",
8832
9357
  body: JSON.stringify(update)
8833
9358
  });
@@ -9462,10 +9987,10 @@ var LANGUAGE_PATTERN = /^[a-z]{2}$/;
9462
9987
  var PROMPT_MAX_CHARS = 500;
9463
9988
  var PROMPT_CONTEXT_CHARS = 200;
9464
9989
  function continuityPrompt(previous) {
9465
- const text = previous?.replace(/\s+/g, " ").trim();
9466
- if (!text) return void 0;
9467
- if (text.length <= PROMPT_CONTEXT_CHARS) return text;
9468
- const tail = text.slice(-PROMPT_CONTEXT_CHARS);
9990
+ const text2 = previous?.replace(/\s+/g, " ").trim();
9991
+ if (!text2) return void 0;
9992
+ if (text2.length <= PROMPT_CONTEXT_CHARS) return text2;
9993
+ const tail = text2.slice(-PROMPT_CONTEXT_CHARS);
9469
9994
  const space = tail.indexOf(" ");
9470
9995
  const trimmed = space >= 0 && space < tail.length - 1 ? tail.slice(space + 1) : tail;
9471
9996
  return trimmed || void 0;
@@ -10294,11 +10819,15 @@ var Arbi = class {
10294
10819
  await this.targetWorkspace(workspaceId);
10295
10820
  return createTag(this.requireClient(), { ...options, workspaceId });
10296
10821
  }
10297
- /** The workspace a call names, opened for this session; `undefined` for the current one. */
10822
+ /**
10823
+ * The workspace a call acts on, captured when it is called: the one it names (opened for this session, not
10824
+ * switched to), else the current one. The request names it, so a switch while it is in flight cannot move it.
10825
+ * `undefined` only when no workspace is known here (the server's open one then applies, as before).
10826
+ */
10298
10827
  async targetWorkspace(workspaceId) {
10299
- if (!workspaceId || workspaceId === this.currentWorkspaceId) return void 0;
10300
- await this.openWorkspace(workspaceId);
10301
- return workspaceId;
10828
+ const target = workspaceId ?? this.currentWorkspaceId ?? void 0;
10829
+ if (target) await this.openWorkspace(target);
10830
+ return target;
10302
10831
  }
10303
10832
  /**
10304
10833
  * Make a workspace the CURRENT one: decrypt its key, open it on the server (which makes it the
@@ -11005,8 +11534,8 @@ var Arbi = class {
11005
11534
  });
11006
11535
  return runConversation(client, conversationId);
11007
11536
  },
11008
- getMessage: (messageId) => getMessage(this.requireClient(), messageId),
11009
- deleteMessage: (messageId) => deleteMessage(this.requireClient(), messageId),
11537
+ getMessage: (messageId2) => getMessage(this.requireClient(), messageId2),
11538
+ deleteMessage: (messageId2) => deleteMessage(this.requireClient(), messageId2),
11010
11539
  /**
11011
11540
  * Post a human comment (no assistant run) — see `postConversationMessage`. A thread in another
11012
11541
  * workspace than the current one works too: its key is handed to the session on demand.
@@ -11092,8 +11621,53 @@ var Arbi = class {
11092
11621
  });
11093
11622
  }
11094
11623
  };
11624
+ async openResponseHandle(open, options, id) {
11625
+ const controller = new AbortController();
11626
+ const abort = () => controller.abort();
11627
+ options.signal?.addEventListener("abort", abort, { once: true });
11628
+ if (options.signal?.aborted) controller.abort();
11629
+ const cleanup = () => options.signal?.removeEventListener("abort", abort);
11630
+ try {
11631
+ const response = await this.recovering(() => open(controller.signal));
11632
+ return await consumeResponse(
11633
+ response,
11634
+ controller,
11635
+ (responseId) => this.assistant.cancel(responseId),
11636
+ { id, cleanup }
11637
+ );
11638
+ } catch (error) {
11639
+ cleanup();
11640
+ controller.abort();
11641
+ throw error;
11642
+ }
11643
+ }
11095
11644
  // ── Assistant ─────────────────────────────────────────────────────────
11096
11645
  assistant = {
11646
+ /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
11647
+ startResponse: async (request, options = {}) => {
11648
+ const body = buildTurnRequest({
11649
+ ...request,
11650
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
11651
+ });
11652
+ return this.openResponseHandle(
11653
+ (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
11654
+ options
11655
+ );
11656
+ },
11657
+ /** Attach to retained replay/live events for an existing msg; never resubmits a turn. */
11658
+ attachResponse: async (id, options = {}) => {
11659
+ if (!/^msg-[\w-]+$/.test(id))
11660
+ throw new ArbiError("Expected an assistant message ID (msg-\u2026).", {
11661
+ code: "INVALID_RESPONSE_ID"
11662
+ });
11663
+ const result = await this.openResponseHandle(
11664
+ (signal) => openRunStream(this.getAuthHeaders(), id, signal),
11665
+ options,
11666
+ id
11667
+ );
11668
+ if (result.kind !== "response") throw new ArbiError("Expected a response attachment.");
11669
+ return result.handle;
11670
+ },
11097
11671
  /**
11098
11672
  * Ask the assistant: send one turn (the body is `buildTurnRequest`) and stream it into
11099
11673
  * `handlers`. Resolves with the accumulated result when the stream ends.
@@ -11122,12 +11696,20 @@ var Arbi = class {
11122
11696
  if (isAbort(error)) throw error;
11123
11697
  if (error instanceof AssistantTurnRefused) {
11124
11698
  if (error.quota) onQuotaExceeded?.(error.quota);
11125
- return refuse(error.message);
11699
+ callbacks.onErrorDetails?.(error);
11700
+ return refuse(error.message, error);
11126
11701
  }
11127
11702
  if (error instanceof ArbiSessionExpiredError || error instanceof ArbiApiError && error.status === 401) {
11128
11703
  const message = SESSION_EXPIRED_MESSAGE;
11129
- return refuse(message, new ArbiSessionExpiredError(message));
11704
+ const expired = error instanceof ArbiSessionExpiredError ? error : new ArbiSessionExpiredError(message, {
11705
+ cause: error,
11706
+ requestId: error.requestId,
11707
+ responseId: error.responseId
11708
+ });
11709
+ callbacks.onErrorDetails?.(expired);
11710
+ return refuse(message, expired);
11130
11711
  }
11712
+ if (error instanceof ArbiError) callbacks.onErrorDetails?.(error);
11131
11713
  onError?.(error);
11132
11714
  throw error;
11133
11715
  }
@@ -11214,8 +11796,8 @@ var Arbi = class {
11214
11796
  */
11215
11797
  /** The open workspace's tags, or `query.workspaceId`'s (opened for this session, not switched to). */
11216
11798
  list: async (query2) => {
11217
- await this.targetWorkspace(query2?.workspaceId);
11218
- return listTags(this.requireClient(), query2);
11799
+ const workspaceId = await this.targetWorkspace(query2?.workspaceId);
11800
+ return listTags(this.requireClient(), { ...query2, workspaceId });
11219
11801
  },
11220
11802
  create: (options) => this.createTagIn(options.workspaceId ?? this.requireWorkspace(), options),
11221
11803
  delete: (tagId) => deleteTag(this.requireClient(), tagId),
@@ -11439,12 +12021,12 @@ var Arbi = class {
11439
12021
  );
11440
12022
  },
11441
12023
  /** Post plaintext to a chat (encrypted under its current epoch). Returns it decrypted. */
11442
- send: async (chat, text, options) => {
12024
+ send: async (chat, text2, options) => {
11443
12025
  const ready = await this.readyChat(chat);
11444
12026
  return sendChatMessage(
11445
12027
  this.requireClient(),
11446
12028
  await this.chatRing(ready),
11447
- text,
12029
+ text2,
11448
12030
  options
11449
12031
  );
11450
12032
  },
@@ -11706,7 +12288,7 @@ var Arbi = class {
11706
12288
  * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
11707
12289
  * chat and posts under the pair key. The caller passes plaintext and never handles keys.
11708
12290
  */
11709
- send: async (recipient, text) => {
12291
+ send: async (recipient, text2) => {
11710
12292
  const client = this.requireClient();
11711
12293
  const resolved = await resolveRecipient(client, recipient);
11712
12294
  if (!resolved) {
@@ -11718,15 +12300,15 @@ var Arbi = class {
11718
12300
  client,
11719
12301
  await this.requireChatCrypto(),
11720
12302
  resolved.extId,
11721
- text
12303
+ text2
11722
12304
  );
11723
12305
  },
11724
12306
  /** Send to a peer whose external id is already known, skipping directory resolution. */
11725
- sendTo: async (peerExtId, text) => sendDirectMessage(
12307
+ sendTo: async (peerExtId, text2) => sendDirectMessage(
11726
12308
  this.requireClient(),
11727
12309
  await this.requireChatCrypto(),
11728
12310
  peerExtId,
11729
- text
12311
+ text2
11730
12312
  ),
11731
12313
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
11732
12314
  resolveRecipient: (recipient) => resolveRecipient(this.requireClient(), recipient),
@@ -12400,8 +12982,8 @@ function getStepDisplay(step, docInfo = {}) {
12400
12982
  function getAgentStepLabel(step, docInfo = {}) {
12401
12983
  const { label, summary, isMultiLine } = getStepDisplay(step, docInfo);
12402
12984
  const narrative = summary && !isMultiLine && !step.reasoning ? summary : null;
12403
- const text = narrative ? `${label} \u2014 ${narrative}` : label;
12404
- return text.length > 120 ? `${text.slice(0, 119)}\u2026` : text;
12985
+ const text2 = narrative ? `${label} \u2014 ${narrative}` : label;
12986
+ return text2.length > 120 ? `${text2.slice(0, 119)}\u2026` : text2;
12405
12987
  }
12406
12988
  function getCurrentStep(steps) {
12407
12989
  const merged = mergeAgentSteps(steps);
@@ -12465,9 +13047,9 @@ function newestThread(threads) {
12465
13047
  function pickMainThread(threads) {
12466
13048
  return newestThread(threads.filter((t2) => !t2.history.some((m2) => getSubagentBranchRecord(m2)))) ?? threads.find((t2) => tailTaskMessageIndex(t2.history) < 0) ?? threads[0];
12467
13049
  }
12468
- function findSubagentRunId(threads, messageId) {
13050
+ function findSubagentRunId(threads, messageId2) {
12469
13051
  for (const thread of threads) {
12470
- const index = thread.history.findIndex((m2) => m2.external_id === messageId);
13052
+ const index = thread.history.findIndex((m2) => m2.external_id === messageId2);
12471
13053
  if (index < 0) continue;
12472
13054
  const taskIndex = tailTaskMessageIndex(thread.history);
12473
13055
  if (taskIndex >= 0 && taskIndex <= index) {
@@ -12623,6 +13205,6 @@ function getRunToAttach(localGeneration, messages) {
12623
13205
  return getAttachableRunId(messages);
12624
13206
  }
12625
13207
 
12626
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, 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, chats_exports as chats, 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, 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, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, mail_exports as mail, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, 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 };
13208
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, 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, chats_exports as chats, 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, 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, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, mail_exports as mail, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, 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 };
12627
13209
  //# sourceMappingURL=browser.js.map
12628
13210
  //# sourceMappingURL=browser.js.map