@arbidocs/sdk 0.5.55 → 0.5.56

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
@@ -3491,14 +3491,20 @@ var init_libsodium_wrappers = __esm({
3491
3491
 
3492
3492
  // src/errors.ts
3493
3493
  var ArbiError = class extends Error {
3494
- constructor(message) {
3495
- super(message);
3494
+ code;
3495
+ requestId;
3496
+ responseId;
3497
+ constructor(message, options = {}) {
3498
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
3499
+ this.code = options.code;
3500
+ this.requestId = options.requestId;
3501
+ this.responseId = options.responseId;
3496
3502
  this.name = "ArbiError";
3497
3503
  }
3498
3504
  };
3499
3505
  var ArbiSessionExpiredError = class extends ArbiError {
3500
- constructor(message = "Your session expired. Sign in again.") {
3501
- super(message);
3506
+ constructor(message = "Your session expired. Sign in again.", options = {}) {
3507
+ super(message, { ...options, code: "SESSION_EXPIRED" });
3502
3508
  this.name = "ArbiSessionExpiredError";
3503
3509
  }
3504
3510
  };
@@ -3527,7 +3533,7 @@ function detailText(detail) {
3527
3533
  return messages.length ? messages.join("; ") : void 0;
3528
3534
  }
3529
3535
  if (!detail || typeof detail !== "object") return void 0;
3530
- const message = typeof detail.message === "string" ? detail.message : void 0;
3536
+ const message = typeof detail.message === "string" ? detail.message : typeof detail.hint === "string" ? detail.hint : void 0;
3531
3537
  const fields = detail.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields) ? Object.entries(detail.fields).map(([name, problem]) => `${name}: ${String(problem)}`).join("; ") : "";
3532
3538
  if (message) return fields ? `${message} (${fields})` : message;
3533
3539
  return fields || void 0;
@@ -3536,21 +3542,80 @@ function apiErrorDetail(apiError) {
3536
3542
  if (typeof apiError === "string") return apiError || void 0;
3537
3543
  if (!apiError || typeof apiError !== "object") return void 0;
3538
3544
  const body = apiError;
3539
- return detailText(body.detail) || (typeof body.message === "string" ? body.message : void 0);
3545
+ return detailText(body.detail) || (typeof body.message === "string" ? body.message : void 0) || (typeof body.error === "string" ? body.error : detailText(errorRecord(body.error)));
3540
3546
  }
3541
3547
  var ArbiApiError = class extends ArbiError {
3542
3548
  status;
3543
3549
  apiError;
3544
3550
  /** Why the server refused, in its words (e.g. "run_at must be in the future"), when it said. */
3545
3551
  detail;
3546
- constructor(message, apiError, status) {
3547
- super(message);
3552
+ constructor(message, apiError, status, options = {}) {
3553
+ super(message, {
3554
+ ...apiErrorMetadata(apiError, status),
3555
+ ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0))
3556
+ });
3548
3557
  this.name = "ArbiApiError";
3549
3558
  this.apiError = apiError;
3550
3559
  this.status = status;
3551
3560
  this.detail = apiErrorDetail(apiError);
3552
3561
  }
3553
3562
  };
3563
+ function errorRecord(value) {
3564
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3565
+ }
3566
+ function firstString(...values) {
3567
+ return values.find((value) => typeof value === "string" && value.length > 0);
3568
+ }
3569
+ function apiErrorMetadata(apiError, status) {
3570
+ const body = errorRecord(apiError);
3571
+ const response = errorRecord(body?.response);
3572
+ const detail = errorRecord(body?.detail);
3573
+ const error = errorRecord(response?.error) ?? errorRecord(body?.error);
3574
+ return {
3575
+ code: firstString(error?.code, detail?.code, body?.code) ?? (status !== void 0 ? `HTTP_${status}` : void 0),
3576
+ requestId: firstString(body?.request_id, detail?.request_id, error?.request_id),
3577
+ responseId: firstString(
3578
+ response?.id,
3579
+ body?.response_id,
3580
+ typeof body?.status === "string" ? body?.id : void 0,
3581
+ detail?.response_id,
3582
+ error?.response_id
3583
+ )
3584
+ };
3585
+ }
3586
+ async function apiErrorFromResponse(response, fallback, options = {}) {
3587
+ let body;
3588
+ try {
3589
+ const text2 = await response.text();
3590
+ if (text2) {
3591
+ try {
3592
+ body = JSON.parse(text2);
3593
+ } catch {
3594
+ body = text2.length < 200 ? text2 : void 0;
3595
+ }
3596
+ }
3597
+ } catch {
3598
+ }
3599
+ return new ArbiApiError(fallback, body, response.status, {
3600
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? void 0,
3601
+ ...options
3602
+ });
3603
+ }
3604
+ var ArbiTransportError = class extends ArbiError {
3605
+ constructor(cause, responseId) {
3606
+ super(cause instanceof Error ? cause.message : String(cause), {
3607
+ code: "TRANSPORT_ERROR",
3608
+ cause,
3609
+ responseId
3610
+ });
3611
+ this.name = "ArbiTransportError";
3612
+ }
3613
+ };
3614
+ function transportError(error, responseId) {
3615
+ if (error instanceof ArbiError || error instanceof Error && error.name === "AbortError")
3616
+ return error;
3617
+ return new ArbiTransportError(error, responseId);
3618
+ }
3554
3619
  var DuplicateContactError = class extends ArbiApiError {
3555
3620
  contactId;
3556
3621
  constructor(message, contactId, apiError) {
@@ -3565,13 +3630,17 @@ function refusalReason(err, fallback) {
3565
3630
  }
3566
3631
  function requireData(result, message) {
3567
3632
  if (result.error || !result.data) {
3568
- throw new ArbiApiError(message, result.error, result.response?.status);
3633
+ throw new ArbiApiError(message, result.error, result.response?.status, {
3634
+ requestId: result.response?.headers?.get("x-request-id") ?? void 0
3635
+ });
3569
3636
  }
3570
3637
  return result.data;
3571
3638
  }
3572
3639
  function requireOk(result, message) {
3573
3640
  if (result.error) {
3574
- throw new ArbiApiError(message, result.error, result.response?.status);
3641
+ throw new ArbiApiError(message, result.error, result.response?.status, {
3642
+ requestId: result.response?.headers?.get("x-request-id") ?? void 0
3643
+ });
3575
3644
  }
3576
3645
  }
3577
3646
  function getErrorMessage(err) {
@@ -3601,7 +3670,8 @@ function getErrorCode(err) {
3601
3670
  while (current && !seen.has(current)) {
3602
3671
  seen.add(current);
3603
3672
  const code = current.code;
3604
- if (typeof code === "string") return code;
3673
+ if (typeof code === "string" && !(current instanceof ArbiTransportError && current.cause instanceof Error))
3674
+ return code;
3605
3675
  current = current.cause instanceof Error ? current.cause : void 0;
3606
3676
  }
3607
3677
  return void 0;
@@ -3614,39 +3684,30 @@ var STATUS_FALLBACKS = {
3614
3684
  404: "Resource not found.",
3615
3685
  503: "The selected LLM is not responding. Please retry or select another model."
3616
3686
  };
3617
- async function extractErrorMessage(res) {
3618
- let bodyDetail;
3619
- try {
3620
- const text = await res.text();
3621
- if (text) {
3622
- try {
3623
- const json2 = JSON.parse(text);
3624
- bodyDetail = detailText(json2.detail) || json2.message || json2.error || void 0;
3625
- } catch {
3626
- if (text.length < 200) bodyDetail = text;
3627
- }
3628
- }
3629
- } catch {
3630
- }
3631
- if (bodyDetail) return `Request failed (${res.status}): ${bodyDetail}`;
3632
- const fallback = STATUS_FALLBACKS[res.status];
3633
- if (fallback) return fallback;
3634
- return `Request failed: ${res.status} ${res.statusText}`;
3635
- }
3636
3687
  async function authenticatedFetch(options) {
3637
3688
  const { baseUrl, accessToken, path: path5, method, body, headers, signal } = options;
3638
- const res = await fetch(`${baseUrl}${path5}`, {
3639
- method: method ?? (body ? "POST" : "GET"),
3640
- headers: {
3641
- Authorization: `Bearer ${accessToken}`,
3642
- ...headers
3643
- },
3644
- body,
3645
- signal
3646
- });
3689
+ let res;
3690
+ try {
3691
+ res = await fetch(`${baseUrl}${path5}`, {
3692
+ method: method ?? (body ? "POST" : "GET"),
3693
+ headers: {
3694
+ Authorization: `Bearer ${accessToken}`,
3695
+ ...headers
3696
+ },
3697
+ body,
3698
+ signal
3699
+ });
3700
+ } catch (error) {
3701
+ throw transportError(error);
3702
+ }
3647
3703
  if (!res.ok) {
3648
- const message = await extractErrorMessage(res);
3649
- throw new ArbiApiError(message, { status: res.status, statusText: res.statusText }, res.status);
3704
+ const error = await apiErrorFromResponse(
3705
+ res,
3706
+ STATUS_FALLBACKS[res.status] ?? `Request failed: ${res.status} ${res.statusText}`
3707
+ );
3708
+ const detail = error.detail || (typeof error.apiError === "string" ? error.apiError : void 0);
3709
+ if (detail) error.message = `Request failed (${res.status}): ${detail}`;
3710
+ throw error;
3650
3711
  }
3651
3712
  return res;
3652
3713
  }
@@ -3963,8 +4024,8 @@ async function requestDeviceCode(domain, clientId, audience, scope = "openid ema
3963
4024
  body
3964
4025
  });
3965
4026
  if (!res.ok) {
3966
- const text = await res.text();
3967
- throw new DeviceFlowError(`Device code request failed: ${res.status} ${text}`);
4027
+ const text2 = await res.text();
4028
+ throw new DeviceFlowError(`Device code request failed: ${res.status} ${text2}`);
3968
4029
  }
3969
4030
  return await res.json();
3970
4031
  }
@@ -4337,9 +4398,9 @@ function buildDocNameMap(docs) {
4337
4398
  }
4338
4399
  return map;
4339
4400
  }
4340
- function resolveDocRefs(text, docNames) {
4341
- if (!docNames) return text;
4342
- return text.replace(/\{(doc-[^}]+)\}/g, (_match, id) => docNames[id] ?? id);
4401
+ function resolveDocRefs(text2, docNames) {
4402
+ if (!docNames) return text2;
4403
+ return text2.replace(/\{(doc-[^}]+)\}/g, (_match, id) => docNames[id] ?? id);
4343
4404
  }
4344
4405
  function resolveStepDocName(step, docNames) {
4345
4406
  if (!docNames) return void 0;
@@ -4418,13 +4479,16 @@ function parseSSEEvents(chunk2, buffer) {
4418
4479
  return { events, remaining };
4419
4480
  }
4420
4481
  async function streamSSE(response, callbacks = {}) {
4482
+ if (!response.ok) throw await apiErrorFromResponse(response, `HTTP ${response.status}`);
4421
4483
  if (!response.body) {
4422
- throw new Error("No response body");
4484
+ throw new ArbiApiError("No response body", void 0, response.status, {
4485
+ code: "MISSING_RESPONSE_BODY"
4486
+ });
4423
4487
  }
4424
4488
  const reader = response.body.getReader();
4425
4489
  const decoder = new TextDecoder("utf-8");
4426
4490
  let sseBuffer = "";
4427
- let text = "";
4491
+ let text2 = "";
4428
4492
  let assistantMessageExtId = null;
4429
4493
  const agentSteps = [];
4430
4494
  let toolCallCount = 0;
@@ -4435,6 +4499,35 @@ async function streamSSE(response, callbacks = {}) {
4435
4499
  let usage = null;
4436
4500
  let context = null;
4437
4501
  let completed = false;
4502
+ let terminal = false;
4503
+ let outcome;
4504
+ let acknowledged = false;
4505
+ const errorDetails = [];
4506
+ const reportError = (error) => {
4507
+ errorDetails.push(error);
4508
+ errors.push(error.message);
4509
+ callbacks.onErrorDetails?.(error);
4510
+ callbacks.onError?.(error.message);
4511
+ };
4512
+ const settle = (payload, fallback) => {
4513
+ const status = payload?.status;
4514
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : fallback;
4515
+ const id = typeof payload?.id === "string" && payload.id ? payload.id : assistantMessageExtId;
4516
+ assistantMessageExtId = id;
4517
+ const rawError = payload?.error;
4518
+ let error;
4519
+ if (resolved === "failed" || rawError) {
4520
+ const body = { response: payload };
4521
+ const message = rawError && typeof rawError === "object" && "message" in rawError && typeof rawError.message === "string" ? rawError.message : "Unknown streaming error";
4522
+ error = new ArbiApiError(message, body, void 0, {
4523
+ code: apiErrorMetadata(body).code ?? "RESPONSE_FAILED",
4524
+ responseId: id ?? void 0
4525
+ });
4526
+ reportError(error);
4527
+ }
4528
+ outcome = { status: resolved, responseId: id, response: payload, ...error ? { error } : {} };
4529
+ terminal = true;
4530
+ };
4438
4531
  const eventHandlers = {
4439
4532
  // OpenAI Responses API events (dot-separated names from server)
4440
4533
  "response.created": (raw) => {
@@ -4455,7 +4548,7 @@ async function streamSSE(response, callbacks = {}) {
4455
4548
  "response.output_text.delta": (raw) => {
4456
4549
  const data = JSON.parse(raw);
4457
4550
  if (data.delta) {
4458
- text += data.delta;
4551
+ text2 += data.delta;
4459
4552
  if (callbacks.onOutputTextDelta) {
4460
4553
  callbacks.onOutputTextDelta({ item_id: data.item_id ?? "", delta: data.delta });
4461
4554
  } else {
@@ -4465,7 +4558,7 @@ async function streamSSE(response, callbacks = {}) {
4465
4558
  },
4466
4559
  "response.output_text.done": (raw) => {
4467
4560
  const data = JSON.parse(raw);
4468
- text = data.text;
4561
+ text2 = data.text;
4469
4562
  callbacks.onTextDone?.(data.text);
4470
4563
  },
4471
4564
  "response.function_call_arguments.delta": (raw) => {
@@ -4486,6 +4579,7 @@ async function streamSSE(response, callbacks = {}) {
4486
4579
  "response.completed": (raw) => {
4487
4580
  const data = JSON.parse(raw);
4488
4581
  completed = true;
4582
+ settle(data.response, "completed");
4489
4583
  if (data.response?.usage) {
4490
4584
  usage = data.response.usage;
4491
4585
  callbacks.onUsage?.(data.response.usage);
@@ -4497,7 +4591,7 @@ async function streamSSE(response, callbacks = {}) {
4497
4591
  }
4498
4592
  const finalText = data.response?.metadata?.content;
4499
4593
  if (finalText) {
4500
- text = finalText;
4594
+ text2 = finalText;
4501
4595
  callbacks.onTextDone?.(finalText);
4502
4596
  }
4503
4597
  if (data.context) {
@@ -4509,12 +4603,17 @@ async function streamSSE(response, callbacks = {}) {
4509
4603
  },
4510
4604
  "response.failed": (raw) => {
4511
4605
  const data = JSON.parse(raw);
4512
- const message = data.response?.error?.message || "Unknown streaming error";
4513
- errors.push(message);
4514
- callbacks.onError?.(message);
4606
+ settle(data.response, "failed");
4607
+ },
4608
+ "response.cancelled": (raw) => {
4609
+ settle(JSON.parse(raw).response, "cancelled");
4610
+ },
4611
+ "response.incomplete": (raw) => {
4612
+ settle(JSON.parse(raw).response, "incomplete");
4515
4613
  },
4516
4614
  // ARBI-specific events (dot-prefixed from server)
4517
4615
  "arbi.message_queued": (raw) => {
4616
+ acknowledged = true;
4518
4617
  const data = JSON.parse(raw);
4519
4618
  if (data.user_message) {
4520
4619
  userMessage = data.user_message;
@@ -4537,6 +4636,7 @@ async function streamSSE(response, callbacks = {}) {
4537
4636
  callbacks.onUserInputRequest?.(data);
4538
4637
  },
4539
4638
  "arbi.probe_answer": (raw) => {
4639
+ acknowledged = true;
4540
4640
  const data = JSON.parse(raw);
4541
4641
  callbacks.onProbeAnswer?.(data);
4542
4642
  },
@@ -4545,6 +4645,7 @@ async function streamSSE(response, callbacks = {}) {
4545
4645
  callbacks.onDeferredInterjection?.(data);
4546
4646
  },
4547
4647
  "arbi.agent_control_state": (raw) => {
4648
+ acknowledged = true;
4548
4649
  const data = JSON.parse(raw);
4549
4650
  callbacks.onAgentControlState?.(data);
4550
4651
  },
@@ -4560,47 +4661,81 @@ async function streamSSE(response, callbacks = {}) {
4560
4661
  "arbi.error": (raw) => {
4561
4662
  const data = JSON.parse(raw);
4562
4663
  const message = typeof data?.message === "string" && data.message.length > 0 ? data.message : data.code;
4664
+ const error = new ArbiApiError(message, data, void 0, {
4665
+ responseId: assistantMessageExtId ?? void 0
4666
+ });
4667
+ errorDetails.push(error);
4563
4668
  errors.push(message);
4669
+ callbacks.onErrorDetails?.(error);
4670
+ outcome = { status: "failed", responseId: assistantMessageExtId, error };
4564
4671
  callbacks.onArbiError?.(data);
4565
4672
  callbacks.onError?.(message);
4566
4673
  }
4567
4674
  };
4568
4675
  const processEvents = (events) => {
4569
4676
  for (const { event, data } of events) {
4677
+ if (terminal) break;
4678
+ if (event === "reasoning") {
4679
+ callbacks.onReasoningDelta?.(data);
4680
+ continue;
4681
+ }
4682
+ const handler = eventHandlers[event];
4683
+ if (!handler) {
4684
+ console.warn(`[arbi-sse] unhandled SSE event: ${event}`);
4685
+ continue;
4686
+ }
4570
4687
  try {
4571
- if (event === "reasoning") {
4572
- callbacks.onReasoningDelta?.(data);
4573
- continue;
4574
- }
4575
- const handler = eventHandlers[event];
4576
- if (handler) {
4577
- handler(data);
4578
- } else {
4579
- console.warn(`[arbi-sse] unhandled SSE event: ${event}`);
4580
- }
4688
+ JSON.parse(data);
4581
4689
  } catch {
4690
+ continue;
4582
4691
  }
4692
+ handler(data);
4583
4693
  }
4584
4694
  };
4585
- while (true) {
4586
- const { done, value } = await reader.read();
4587
- if (done) break;
4588
- const { events, remaining } = parseSSEEvents(decoder.decode(value, { stream: true }), sseBuffer);
4589
- sseBuffer = remaining;
4590
- processEvents(events);
4591
- if (completed) {
4592
- sseBuffer = "";
4593
- void reader.cancel().catch(() => {
4594
- });
4595
- break;
4695
+ try {
4696
+ while (true) {
4697
+ let chunk2;
4698
+ try {
4699
+ chunk2 = await reader.read();
4700
+ } catch (cause) {
4701
+ const error = transportError(cause, assistantMessageExtId ?? void 0);
4702
+ const aborted = error.name === "AbortError";
4703
+ const disconnected = {
4704
+ status: "disconnected",
4705
+ responseId: assistantMessageExtId,
4706
+ reason: aborted ? "aborted" : "connection_error",
4707
+ ...error instanceof ArbiError ? { error } : {}
4708
+ };
4709
+ if (error instanceof ArbiError) callbacks.onErrorDetails?.(error);
4710
+ callbacks.onOutcome?.(disconnected);
4711
+ throw error;
4712
+ }
4713
+ const { done, value } = chunk2;
4714
+ if (done) break;
4715
+ const { events, remaining } = parseSSEEvents(
4716
+ decoder.decode(value, { stream: true }),
4717
+ sseBuffer
4718
+ );
4719
+ sseBuffer = remaining;
4720
+ processEvents(events);
4721
+ if (terminal) {
4722
+ sseBuffer = "";
4723
+ void reader.cancel().catch(() => {
4724
+ });
4725
+ break;
4726
+ }
4596
4727
  }
4728
+ if (sseBuffer.trim()) {
4729
+ const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
4730
+ processEvents(events);
4731
+ }
4732
+ } finally {
4733
+ reader.releaseLock();
4597
4734
  }
4598
- if (sseBuffer.trim()) {
4599
- const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
4600
- processEvents(events);
4601
- }
4735
+ outcome ??= acknowledged && !assistantMessageExtId ? { status: "acknowledged", responseId: null } : { status: "disconnected", responseId: assistantMessageExtId, reason: "connection_closed" };
4736
+ callbacks.onOutcome?.(outcome);
4602
4737
  return {
4603
- text,
4738
+ text: text2,
4604
4739
  assistantMessageExtId,
4605
4740
  agentSteps,
4606
4741
  toolCallCount,
@@ -4610,7 +4745,9 @@ async function streamSSE(response, callbacks = {}) {
4610
4745
  artifacts,
4611
4746
  usage,
4612
4747
  context,
4613
- completed
4748
+ completed,
4749
+ outcome,
4750
+ errorDetails
4614
4751
  };
4615
4752
  }
4616
4753
  function formatStreamSummary(result, elapsedTime) {
@@ -4883,10 +5020,10 @@ function isNotification(msg) {
4883
5020
  function formatWsMessage(msg) {
4884
5021
  if (client.isMessageType(msg, "task_update")) {
4885
5022
  const progress = msg.progress > 0 ? ` (${Math.round(msg.progress)}%)` : "";
4886
- const text = `${msg.file_name} \u2014 ${msg.status}${progress}`;
4887
- if (msg.status === "completed") return { text, level: "success" };
4888
- if (msg.status === "failed") return { text, level: "error" };
4889
- return { text, level: "info" };
5023
+ const text2 = `${msg.file_name} \u2014 ${msg.status}${progress}`;
5024
+ if (msg.status === "completed") return { text: text2, level: "success" };
5025
+ if (msg.status === "failed") return { text: text2, level: "error" };
5026
+ return { text: text2, level: "info" };
4890
5027
  }
4891
5028
  if (client.isMessageType(msg, "batch_complete")) {
4892
5029
  const count = msg.doc_ext_ids.length;
@@ -4958,8 +5095,8 @@ function countCitations(metadata) {
4958
5095
  const responses = modelCitations?.tool_responses;
4959
5096
  return responses ? Object.keys(responses).length : 0;
4960
5097
  }
4961
- function stripCitationMarkdown(text) {
4962
- return text.replace(/\[([^\]]+)\]\(#cite-(\d+)\)/g, "$1[$2]");
5098
+ function stripCitationMarkdown(text2) {
5099
+ return text2.replace(/\[([^\]]+)\]\(#cite-(\d+)\)/g, "$1[$2]");
4963
5100
  }
4964
5101
  function buildCitationChunkData(message) {
4965
5102
  const merged = {};
@@ -4998,6 +5135,403 @@ function buildChunkLookup(tools) {
4998
5135
  return lookup;
4999
5136
  }
5000
5137
 
5138
+ // src/response-handle.ts
5139
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5140
+ var text = (value) => typeof value === "string" ? value : void 0;
5141
+ var messageId = (value) => typeof value === "string" && /^msg-[\w-]+$/.test(value);
5142
+ function immutable(value) {
5143
+ if (value && typeof value === "object" && !(value instanceof Error) && !Object.isFrozen(value)) {
5144
+ Object.freeze(value);
5145
+ for (const child of Object.values(value)) immutable(child);
5146
+ }
5147
+ return value;
5148
+ }
5149
+ function reportObserverError(error) {
5150
+ queueMicrotask(() => {
5151
+ throw error;
5152
+ });
5153
+ }
5154
+ var ResponseEventDecoder = class {
5155
+ buffer = "";
5156
+ event = "";
5157
+ data = [];
5158
+ id;
5159
+ push(chunk2, final = false) {
5160
+ this.buffer += chunk2;
5161
+ const frames = [];
5162
+ const dispatch = () => {
5163
+ if (this.data.length)
5164
+ frames.push({
5165
+ event: this.event || "message",
5166
+ data: this.data.join("\n"),
5167
+ ...this.id !== void 0 ? { id: this.id } : {}
5168
+ });
5169
+ this.event = "";
5170
+ this.data = [];
5171
+ this.id = void 0;
5172
+ };
5173
+ const line = (value) => {
5174
+ if (!value) {
5175
+ dispatch();
5176
+ return;
5177
+ }
5178
+ if (value.startsWith(":")) return;
5179
+ const colon = value.indexOf(":");
5180
+ const field = colon < 0 ? value : value.slice(0, colon);
5181
+ let content = colon < 0 ? "" : value.slice(colon + 1);
5182
+ if (content.startsWith(" ")) content = content.slice(1);
5183
+ if (field === "event") this.event = content;
5184
+ if (field === "data") this.data.push(content);
5185
+ if (field === "id" && !content.includes("\0")) this.id = content;
5186
+ };
5187
+ while (true) {
5188
+ const index = this.buffer.search(/[\r\n]/);
5189
+ if (index < 0 || !final && index === this.buffer.length - 1 && this.buffer[index] === "\r")
5190
+ break;
5191
+ const width = this.buffer[index] === "\r" && this.buffer[index + 1] === "\n" ? 2 : 1;
5192
+ line(this.buffer.slice(0, index));
5193
+ this.buffer = this.buffer.slice(index + width);
5194
+ }
5195
+ if (final) {
5196
+ if (this.buffer) line(this.buffer);
5197
+ this.buffer = "";
5198
+ dispatch();
5199
+ }
5200
+ return frames;
5201
+ }
5202
+ };
5203
+ function consumeResponse(response, controller, cancel, options = {}) {
5204
+ if (!response.body)
5205
+ return Promise.reject(
5206
+ new ArbiApiError("Response has no stream body.", void 0, response.status, {
5207
+ code: "MISSING_RESPONSE_BODY"
5208
+ })
5209
+ );
5210
+ const reader = response.body.getReader();
5211
+ let resolveStart;
5212
+ let rejectStart;
5213
+ const start = new Promise((resolve2, reject) => {
5214
+ resolveStart = resolve2;
5215
+ rejectStart = reject;
5216
+ });
5217
+ let resolveOutcome;
5218
+ const outcome = new Promise((resolve2) => {
5219
+ resolveOutcome = resolve2;
5220
+ });
5221
+ let state = immutable({
5222
+ id: options.id ?? "",
5223
+ conversationId: null,
5224
+ connection: "connecting",
5225
+ responseStatus: null,
5226
+ output: [],
5227
+ displayText: ""
5228
+ });
5229
+ let bound = false;
5230
+ let finished = false;
5231
+ let acknowledgement;
5232
+ const listeners = /* @__PURE__ */ new Set();
5233
+ const queue = [];
5234
+ let claimed = false;
5235
+ let iteratorClosed = false;
5236
+ let iteratorError;
5237
+ let pending;
5238
+ const emit = (event) => {
5239
+ if (!claimed || iteratorClosed) return;
5240
+ if (pending) {
5241
+ pending.resolve({ value: immutable(event), done: false });
5242
+ pending = void 0;
5243
+ } else if (queue.length < 256) queue.push(immutable(event));
5244
+ else {
5245
+ iteratorError = new ArbiError("Raw response event consumer fell behind.", {
5246
+ code: "RESPONSE_EVENT_OVERFLOW"
5247
+ });
5248
+ queue.length = 0;
5249
+ iteratorClosed = true;
5250
+ }
5251
+ };
5252
+ const notify = () => {
5253
+ for (const listener of [...listeners]) {
5254
+ try {
5255
+ listener(state);
5256
+ } catch (error) {
5257
+ reportObserverError(error);
5258
+ }
5259
+ }
5260
+ };
5261
+ const update = (patch) => {
5262
+ state = immutable({ ...state, ...patch });
5263
+ notify();
5264
+ };
5265
+ const finish = (value, detached = false) => {
5266
+ if (finished) return;
5267
+ finished = true;
5268
+ controller.signal.removeEventListener("abort", abort);
5269
+ options.cleanup?.();
5270
+ update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
5271
+ listeners.clear();
5272
+ resolveOutcome(state.outcome);
5273
+ if (pending) {
5274
+ pending.resolve({ value: void 0, done: true });
5275
+ pending = void 0;
5276
+ }
5277
+ void reader.cancel().catch(() => {
5278
+ });
5279
+ };
5280
+ const abort = () => {
5281
+ if (!bound) rejectStart(new DOMException("The operation was aborted.", "AbortError"));
5282
+ finish({ status: "disconnected", responseId: bound ? state.id : null, reason: "aborted" }, true);
5283
+ queue.length = 0;
5284
+ };
5285
+ const handle = {
5286
+ get id() {
5287
+ return state.id;
5288
+ },
5289
+ snapshot: () => state,
5290
+ subscribe(listener) {
5291
+ if (!finished) listeners.add(listener);
5292
+ try {
5293
+ listener(state);
5294
+ } catch (error) {
5295
+ reportObserverError(error);
5296
+ }
5297
+ return () => {
5298
+ listeners.delete(listener);
5299
+ };
5300
+ },
5301
+ outcome,
5302
+ detach: () => {
5303
+ if (!finished) controller.abort();
5304
+ },
5305
+ cancel: () => cancel(state.id),
5306
+ events() {
5307
+ if (claimed)
5308
+ throw new ArbiError("A response handle supports one raw event iterator.", {
5309
+ code: "RESPONSE_EVENTS_ALREADY_CLAIMED"
5310
+ });
5311
+ claimed = true;
5312
+ const close = () => {
5313
+ iteratorClosed = true;
5314
+ queue.length = 0;
5315
+ if (pending) {
5316
+ pending.resolve({ value: void 0, done: true });
5317
+ pending = void 0;
5318
+ }
5319
+ };
5320
+ return {
5321
+ [Symbol.asyncIterator]() {
5322
+ return this;
5323
+ },
5324
+ next() {
5325
+ if (iteratorError) return Promise.reject(iteratorError);
5326
+ if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5327
+ if (finished || iteratorClosed)
5328
+ return Promise.resolve({ value: void 0, done: true });
5329
+ if (pending)
5330
+ return Promise.reject(
5331
+ new ArbiError("Concurrent iterator reads are unsupported.", {
5332
+ code: "RESPONSE_EVENTS_CONCURRENT_READ"
5333
+ })
5334
+ );
5335
+ return new Promise((resolve2, reject) => {
5336
+ pending = { resolve: resolve2, reject };
5337
+ });
5338
+ },
5339
+ async return() {
5340
+ close();
5341
+ return { value: void 0, done: true };
5342
+ },
5343
+ async throw(error) {
5344
+ close();
5345
+ throw error;
5346
+ }
5347
+ };
5348
+ }
5349
+ };
5350
+ const bind = (id) => {
5351
+ if (bound) return;
5352
+ bound = true;
5353
+ state = immutable({ ...state, id, connection: "streaming" });
5354
+ resolveStart({ kind: "response", handle });
5355
+ };
5356
+ const diagnostic = (code, frame) => emit({ event: "arbi.sdk.protocol_error", data: { code, frame } });
5357
+ const process2 = (frame) => {
5358
+ if (finished) return;
5359
+ let data;
5360
+ if (frame.event === "reasoning") {
5361
+ emit({
5362
+ event: frame.event,
5363
+ data: frame.data,
5364
+ ...frame.id !== void 0 ? { id: frame.id } : {}
5365
+ });
5366
+ return;
5367
+ }
5368
+ try {
5369
+ data = JSON.parse(frame.data);
5370
+ } catch {
5371
+ diagnostic("MALFORMED_JSON", frame);
5372
+ return;
5373
+ }
5374
+ const payload = object(data);
5375
+ const raw = object(payload?.response);
5376
+ const id = raw?.id;
5377
+ if (bound && typeof id === "string" && id !== state.id) {
5378
+ diagnostic("CONFLICTING_RESPONSE_ID", frame);
5379
+ return;
5380
+ }
5381
+ if (messageId(id)) bind(id);
5382
+ emit({ event: frame.event, data, ...frame.id !== void 0 ? { id: frame.id } : {} });
5383
+ if (frame.event === "arbi.message_queued") acknowledgement = payload;
5384
+ const patch = {};
5385
+ if (frame.event === "arbi.user_message" && !state.conversationId && typeof payload?.conversation_ext_id === "string")
5386
+ patch.conversationId = payload.conversation_ext_id;
5387
+ if (raw) {
5388
+ patch.rawResponse = raw;
5389
+ if (typeof raw.status === "string") patch.responseStatus = raw.status;
5390
+ if (Array.isArray(raw.output))
5391
+ patch.output = raw.output.filter((item2) => !!object(item2));
5392
+ const metadata = object(raw.metadata);
5393
+ const conversation = text(metadata?.conversation_ext_id) ?? text(metadata?.conversation_id) ?? text(raw.conversation_id);
5394
+ if (conversation && (!state.conversationId || state.conversationId === conversation))
5395
+ patch.conversationId = conversation;
5396
+ if (typeof metadata?.content === "string") patch.displayText = metadata.content;
5397
+ }
5398
+ const item = object(payload?.item);
5399
+ if ((frame.event === "response.output_item.added" || frame.event === "response.output_item.done") && item) {
5400
+ const output = [...state.output];
5401
+ const index = output.findIndex((existing) => existing.id === item.id);
5402
+ if (index >= 0 && item.id) output[index] = item;
5403
+ else
5404
+ output.splice(
5405
+ typeof payload?.output_index === "number" ? payload.output_index : output.length,
5406
+ 0,
5407
+ item
5408
+ );
5409
+ patch.output = output;
5410
+ }
5411
+ const itemId = text(payload?.item_id);
5412
+ const delta = text(payload?.delta);
5413
+ if (itemId && [
5414
+ "response.content_part.added",
5415
+ "response.output_text.delta",
5416
+ "response.output_text.done",
5417
+ "response.function_call_arguments.delta",
5418
+ "response.reasoning_summary_text.delta"
5419
+ ].includes(frame.event)) {
5420
+ const output = [...patch.output ?? state.output];
5421
+ let index = output.findIndex((existing) => existing.id === itemId);
5422
+ if (index < 0) {
5423
+ index = output.length;
5424
+ output.push({
5425
+ id: itemId,
5426
+ type: frame.event.includes("function_call") ? "function_call" : frame.event.includes("reasoning") ? "reasoning" : "message"
5427
+ });
5428
+ }
5429
+ const current = { ...output[index] };
5430
+ if (frame.event === "response.function_call_arguments.delta")
5431
+ current.arguments = (text(current.arguments) ?? "") + (delta ?? "");
5432
+ else {
5433
+ const key = frame.event.includes("reasoning") ? "summary" : "content";
5434
+ const content = Array.isArray(current[key]) ? [...current[key]] : [];
5435
+ const partIndex = typeof payload?.content_index === "number" ? payload.content_index : typeof payload?.summary_index === "number" ? payload.summary_index : 0;
5436
+ const part = {
5437
+ ...object(content[partIndex]) ?? {
5438
+ type: key === "summary" ? "summary_text" : "output_text",
5439
+ text: ""
5440
+ }
5441
+ };
5442
+ if (frame.event === "response.content_part.added")
5443
+ content[partIndex] = object(payload?.part) ?? part;
5444
+ else {
5445
+ part.text = frame.event === "response.output_text.done" ? text(payload?.text) ?? "" : (text(part.text) ?? "") + (delta ?? "");
5446
+ content[partIndex] = part;
5447
+ }
5448
+ current[key] = content;
5449
+ }
5450
+ output[index] = current;
5451
+ patch.output = output;
5452
+ }
5453
+ if (frame.event === "response.output_text.delta" && delta)
5454
+ patch.displayText = state.displayText + delta;
5455
+ if (frame.event === "response.output_text.done" && typeof payload?.text === "string")
5456
+ patch.displayText = payload.text;
5457
+ update(patch);
5458
+ const terminal = /^response\.(completed|failed|cancelled|incomplete)$/.exec(
5459
+ frame.event
5460
+ )?.[1];
5461
+ if (terminal && bound) {
5462
+ const status = raw?.status;
5463
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : terminal;
5464
+ const error = resolved === "failed" || raw?.error ? new ArbiApiError(
5465
+ text(object(raw?.error)?.message) ?? "Response failed.",
5466
+ { response: raw },
5467
+ void 0,
5468
+ { ...apiErrorMetadata({ response: raw }), responseId: state.id }
5469
+ ) : void 0;
5470
+ finish({
5471
+ status: resolved,
5472
+ responseId: state.id,
5473
+ ...raw ? { response: raw } : {},
5474
+ ...error ? { error } : {}
5475
+ });
5476
+ }
5477
+ };
5478
+ controller.signal.addEventListener("abort", abort, { once: true });
5479
+ if (controller.signal.aborted) abort();
5480
+ else if (options.id) bind(options.id);
5481
+ void (async () => {
5482
+ const decoder = new TextDecoder();
5483
+ const frames = new ResponseEventDecoder();
5484
+ try {
5485
+ while (!finished) {
5486
+ const { value, done } = await reader.read();
5487
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5488
+ process2(frame);
5489
+ if (done) break;
5490
+ }
5491
+ if (!finished) {
5492
+ if (!bound && acknowledgement) {
5493
+ const value = { status: "acknowledged", responseId: null };
5494
+ resolveStart({
5495
+ kind: "acknowledged",
5496
+ acknowledgement: immutable(acknowledgement),
5497
+ outcome: immutable(value)
5498
+ });
5499
+ finish(value);
5500
+ } else {
5501
+ if (!bound)
5502
+ rejectStart(
5503
+ new ArbiApiError(
5504
+ "Stream ended before response identity was established.",
5505
+ void 0,
5506
+ void 0,
5507
+ { code: "MISSING_RESPONSE_ID" }
5508
+ )
5509
+ );
5510
+ finish({
5511
+ status: "disconnected",
5512
+ responseId: bound ? state.id : null,
5513
+ reason: "connection_closed"
5514
+ });
5515
+ }
5516
+ }
5517
+ } catch (cause) {
5518
+ if (!finished) {
5519
+ const error = transportError(cause, bound ? state.id : void 0);
5520
+ if (!bound) rejectStart(error);
5521
+ finish({
5522
+ status: "disconnected",
5523
+ responseId: bound ? state.id : null,
5524
+ reason: error.name === "AbortError" ? "aborted" : "connection_error",
5525
+ ...error instanceof ArbiError ? { error } : {}
5526
+ });
5527
+ }
5528
+ } finally {
5529
+ reader.releaseLock();
5530
+ }
5531
+ })();
5532
+ return start;
5533
+ }
5534
+
5001
5535
  // src/operations/documents.ts
5002
5536
  var documents_exports = {};
5003
5537
  __export(documents_exports, {
@@ -5961,18 +6495,18 @@ async function searchConversations(arbi, body) {
5961
6495
  "Failed to search conversations"
5962
6496
  );
5963
6497
  }
5964
- async function getMessage(arbi, messageId) {
6498
+ async function getMessage(arbi, messageId2) {
5965
6499
  return requireData(
5966
6500
  await arbi.fetch.GET("/v1/conversation/message/{message_ext_id}", {
5967
- params: { path: { message_ext_id: messageId } }
6501
+ params: { path: { message_ext_id: messageId2 } }
5968
6502
  }),
5969
6503
  "Failed to fetch message"
5970
6504
  );
5971
6505
  }
5972
- async function deleteMessage(arbi, messageId) {
6506
+ async function deleteMessage(arbi, messageId2) {
5973
6507
  return requireData(
5974
6508
  await arbi.fetch.DELETE("/v1/conversation/message/{message_ext_id}", {
5975
- params: { path: { message_ext_id: messageId } }
6509
+ params: { path: { message_ext_id: messageId2 } }
5976
6510
  }),
5977
6511
  "Failed to delete message"
5978
6512
  );
@@ -6140,7 +6674,7 @@ async function retrieve(options) {
6140
6674
  tools,
6141
6675
  ...model ? { model } : {}
6142
6676
  };
6143
- const { data, error } = await arbi.fetch.POST("/v1/assistant/retrieve", { body });
6677
+ const { data, error, response } = await arbi.fetch.POST("/v1/assistant/retrieve", { body });
6144
6678
  if (error) {
6145
6679
  const detail = error?.detail;
6146
6680
  let message;
@@ -6152,7 +6686,9 @@ async function retrieve(options) {
6152
6686
  } else {
6153
6687
  message = JSON.stringify(error);
6154
6688
  }
6155
- throw new Error(`Retrieve failed: ${message}`);
6689
+ throw new ArbiApiError(`Retrieve failed: ${message}`, error, response.status, {
6690
+ requestId: response.headers.get("x-request-id") ?? void 0
6691
+ });
6156
6692
  }
6157
6693
  return data;
6158
6694
  }
@@ -6189,7 +6725,7 @@ async function queryAssistant(options) {
6189
6725
  return authenticatedFetch({
6190
6726
  baseUrl,
6191
6727
  accessToken,
6192
- path: "/v1/assistant/query",
6728
+ path: "/v1/responses",
6193
6729
  method: "POST",
6194
6730
  body: JSON.stringify(buildTurnRequest(request)),
6195
6731
  headers: { "Content-Type": "application/json" },
@@ -6199,8 +6735,8 @@ async function queryAssistant(options) {
6199
6735
  var AssistantTurnRefused = class extends ArbiApiError {
6200
6736
  /** Set when the refusal is the project's used-up AI usage. */
6201
6737
  quota;
6202
- constructor(message, status, quota = null) {
6203
- super(message, void 0, status);
6738
+ constructor(message, status, quota = null, apiError, options = {}) {
6739
+ super(message, apiError, status, options);
6204
6740
  this.name = "AssistantTurnRefused";
6205
6741
  this.quota = quota;
6206
6742
  }
@@ -6228,54 +6764,36 @@ function quotaFromStreamError(error) {
6228
6764
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6229
6765
  return { spend, budget, projectExtId: match.groups.project ?? null };
6230
6766
  }
6231
- async function readDetail(response) {
6232
- try {
6233
- return (await response.json())?.detail;
6234
- } catch {
6235
- return void 0;
6236
- }
6237
- }
6238
6767
  async function refusal(response) {
6239
6768
  const { status } = response;
6240
- if (status === 409) {
6241
- const detail2 = await readDetail(response);
6242
- return new AssistantTurnRefused(
6243
- detailText(detail2) || "This message has failed. Please retry from the previous message.",
6244
- status
6245
- );
6246
- }
6247
- if (status === 503) {
6248
- return new AssistantTurnRefused(
6249
- "The selected LLM is not responding. Please retry again in a minute or select another model.",
6250
- status
6251
- );
6252
- }
6253
- if (status === 402) {
6254
- const detail2 = await readDetail(response);
6255
- const quota = quotaExceededFrom(detail2);
6256
- const message = quota?.message ?? (typeof detail2 === "string" ? detail2 : void 0) ?? detail2?.message ?? "This project's AI usage for this month is used up.";
6257
- return new AssistantTurnRefused(
6258
- message || "This project's AI usage for this month is used up.",
6259
- status,
6260
- quota
6261
- );
6262
- }
6263
- const detail = await readDetail(response);
6769
+ const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6770
+ const detail = parsed.apiError?.detail;
6771
+ const quota = status === 402 ? quotaExceededFrom(detail) : null;
6772
+ 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;
6264
6773
  return new AssistantTurnRefused(
6265
- detailText(detail) || `HTTP error! status: ${status}`,
6266
- status
6774
+ quota?.message || parsed.detail || fallback,
6775
+ status,
6776
+ quota,
6777
+ parsed.apiError,
6778
+ { code: parsed.code, requestId: parsed.requestId, responseId: parsed.responseId }
6267
6779
  );
6268
6780
  }
6269
6781
  async function openTurnStream(auth, body, signal) {
6270
- const response = await fetch(`${auth.baseUrl}/v1/assistant/query`, {
6782
+ const response = await fetch(`${auth.baseUrl}/v1/responses`, {
6271
6783
  method: "POST",
6272
6784
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${auth.accessToken}` },
6273
6785
  body: JSON.stringify(body),
6274
6786
  signal,
6275
6787
  credentials: "include"
6788
+ }).catch((error) => {
6789
+ throw transportError(error);
6276
6790
  });
6277
- if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6278
- if (!response.ok || !response.body) throw await refusal(response);
6791
+ if (response.status === 401) throw await apiErrorFromResponse(response, SESSION_EXPIRED_MESSAGE);
6792
+ if (!response.ok) throw await refusal(response);
6793
+ if (!response.body)
6794
+ throw new ArbiApiError("Response has no stream body.", void 0, response.status, {
6795
+ code: "MISSING_RESPONSE_BODY"
6796
+ });
6279
6797
  return response;
6280
6798
  }
6281
6799
  async function openRunStream(auth, responseId, signal) {
@@ -6287,15 +6805,23 @@ async function openRunStream(auth, responseId, signal) {
6287
6805
  signal,
6288
6806
  credentials: "include"
6289
6807
  }
6290
- );
6291
- if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6292
- if (!response.ok || !response.body) {
6293
- throw new ArbiApiError(
6808
+ ).catch((error) => {
6809
+ throw transportError(error, responseId);
6810
+ });
6811
+ if (response.status === 401)
6812
+ throw await apiErrorFromResponse(response, SESSION_EXPIRED_MESSAGE, { responseId });
6813
+ if (!response.ok) {
6814
+ throw await apiErrorFromResponse(
6815
+ response,
6294
6816
  response.status === 404 ? "This run is no longer active." : `HTTP ${response.status}`,
6295
- void 0,
6296
- response.status
6817
+ { responseId }
6297
6818
  );
6298
6819
  }
6820
+ if (!response.body)
6821
+ throw new ArbiApiError("Response has no stream body.", void 0, response.status, {
6822
+ code: "MISSING_RESPONSE_BODY",
6823
+ responseId
6824
+ });
6299
6825
  return response;
6300
6826
  }
6301
6827
  async function interject(arbi, assistantMessageExtId, answer) {
@@ -7333,7 +7859,7 @@ async function listChatMessages(arbi, chatExtId, options) {
7333
7859
  "Failed to load messages"
7334
7860
  );
7335
7861
  }
7336
- async function sendChatMessage(arbi, ring, text, options = {}) {
7862
+ async function sendChatMessage(arbi, ring, text2, options = {}) {
7337
7863
  const attachments = options.attachments ?? [];
7338
7864
  checkChatAttachmentLimits(attachments);
7339
7865
  const key = keyFor(ring, ring.currentVersion);
@@ -7341,7 +7867,7 @@ async function sendChatMessage(arbi, ring, text, options = {}) {
7341
7867
  await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
7342
7868
  params: { path: { chat_ext_id: ring.chatExtId } },
7343
7869
  body: {
7344
- content: await client.encryptWithChatKey(text, key),
7870
+ content: await client.encryptWithChatKey(text2, key),
7345
7871
  key_version: ring.currentVersion,
7346
7872
  kind: "text",
7347
7873
  ...attachments.length ? {
@@ -7356,7 +7882,7 @@ async function sendChatMessage(arbi, ring, text, options = {}) {
7356
7882
  );
7357
7883
  return {
7358
7884
  ...created,
7359
- content: text,
7885
+ content: text2,
7360
7886
  ...attachments.length ? { attachmentFiles: attachments } : {}
7361
7887
  };
7362
7888
  }
@@ -7416,9 +7942,9 @@ async function resolveRecipient(arbi, ref) {
7416
7942
  }
7417
7943
  return null;
7418
7944
  }
7419
- async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
7945
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text2, options) {
7420
7946
  const chat = await openDirectChat(arbi, peerExtId);
7421
- return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
7947
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text2, options);
7422
7948
  }
7423
7949
  async function loadDecryptedChat(arbi, crypto2, chat, options) {
7424
7950
  const ring = await openChatKeyRing(chat, crypto2);
@@ -8150,19 +8676,19 @@ function minorDigits(currency) {
8150
8676
  throw new Error(`Unknown currency "${currency}": use an ISO 4217 code such as GBP or USD`);
8151
8677
  }
8152
8678
  }
8153
- function parseBudget(text) {
8154
- const t2 = text.trim();
8679
+ function parseBudget(text2) {
8680
+ const t2 = text2.trim();
8155
8681
  const after = /^([0-9][0-9,_]*(?:\.[0-9]+)?)\s*([A-Za-z]{3})$/.exec(t2);
8156
8682
  const before = /^([A-Za-z]{3})\s*([0-9][0-9,_]*(?:\.[0-9]+)?)$/.exec(t2);
8157
8683
  const [amountText, code] = after ? [after[1], after[2]] : before ? [before[2], before[1]] : [];
8158
8684
  if (!amountText || !code)
8159
- throw new Error(`Invalid budget "${text}": use an amount and a currency, e.g. 6000GBP`);
8685
+ throw new Error(`Invalid budget "${text2}": use an amount and a currency, e.g. 6000GBP`);
8160
8686
  const currency = code.toUpperCase();
8161
8687
  const digits = minorDigits(currency);
8162
8688
  const major = Number(amountText.replace(/[,_]/g, ""));
8163
8689
  const amount = Math.round(major * 10 ** digits);
8164
8690
  if (!Number.isFinite(major) || Math.abs(major * 10 ** digits - amount) > 1e-6)
8165
- throw new Error(`Invalid budget "${text}": ${currency} has ${digits} decimal places`);
8691
+ throw new Error(`Invalid budget "${text2}": ${currency} has ${digits} decimal places`);
8166
8692
  return { amount, currency };
8167
8693
  }
8168
8694
  function formatBudget(budget) {
@@ -9420,15 +9946,15 @@ function listMessages(mail, options) {
9420
9946
  if (options.limit) params.set("limit", String(options.limit));
9421
9947
  return json(mail(`${accountPath(options.accountId ?? NATIVE_ACCOUNT)}/messages?${params}`));
9422
9948
  }
9423
- function getMessage2(mail, messageId, accountId = NATIVE_ACCOUNT) {
9424
- return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}`));
9949
+ function getMessage2(mail, messageId2, accountId = NATIVE_ACCOUNT) {
9950
+ return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`));
9425
9951
  }
9426
- async function downloadAttachment(mail, messageId, attachmentId, accountId = NATIVE_ACCOUNT) {
9427
- const path5 = `${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`;
9952
+ async function downloadAttachment(mail, messageId2, attachmentId, accountId = NATIVE_ACCOUNT) {
9953
+ const path5 = `${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}/attachments/${encodeURIComponent(attachmentId)}`;
9428
9954
  return new Uint8Array(await (await mail(path5)).arrayBuffer());
9429
9955
  }
9430
- async function updateMessage(mail, messageId, update, accountId = NATIVE_ACCOUNT) {
9431
- await mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}`, {
9956
+ async function updateMessage(mail, messageId2, update, accountId = NATIVE_ACCOUNT) {
9957
+ await mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`, {
9432
9958
  method: "PATCH",
9433
9959
  body: JSON.stringify(update)
9434
9960
  });
@@ -10063,10 +10589,10 @@ var LANGUAGE_PATTERN = /^[a-z]{2}$/;
10063
10589
  var PROMPT_MAX_CHARS = 500;
10064
10590
  var PROMPT_CONTEXT_CHARS = 200;
10065
10591
  function continuityPrompt(previous) {
10066
- const text = previous?.replace(/\s+/g, " ").trim();
10067
- if (!text) return void 0;
10068
- if (text.length <= PROMPT_CONTEXT_CHARS) return text;
10069
- const tail = text.slice(-PROMPT_CONTEXT_CHARS);
10592
+ const text2 = previous?.replace(/\s+/g, " ").trim();
10593
+ if (!text2) return void 0;
10594
+ if (text2.length <= PROMPT_CONTEXT_CHARS) return text2;
10595
+ const tail = text2.slice(-PROMPT_CONTEXT_CHARS);
10070
10596
  const space = tail.indexOf(" ");
10071
10597
  const trimmed = space >= 0 && space < tail.length - 1 ? tail.slice(space + 1) : tail;
10072
10598
  return trimmed || void 0;
@@ -11606,8 +12132,8 @@ var Arbi = class {
11606
12132
  });
11607
12133
  return runConversation(client, conversationId);
11608
12134
  },
11609
- getMessage: (messageId) => getMessage(this.requireClient(), messageId),
11610
- deleteMessage: (messageId) => deleteMessage(this.requireClient(), messageId),
12135
+ getMessage: (messageId2) => getMessage(this.requireClient(), messageId2),
12136
+ deleteMessage: (messageId2) => deleteMessage(this.requireClient(), messageId2),
11611
12137
  /**
11612
12138
  * Post a human comment (no assistant run) — see `postConversationMessage`. A thread in another
11613
12139
  * workspace than the current one works too: its key is handed to the session on demand.
@@ -11693,8 +12219,53 @@ var Arbi = class {
11693
12219
  });
11694
12220
  }
11695
12221
  };
12222
+ async openResponseHandle(open, options, id) {
12223
+ const controller = new AbortController();
12224
+ const abort = () => controller.abort();
12225
+ options.signal?.addEventListener("abort", abort, { once: true });
12226
+ if (options.signal?.aborted) controller.abort();
12227
+ const cleanup = () => options.signal?.removeEventListener("abort", abort);
12228
+ try {
12229
+ const response = await this.recovering(() => open(controller.signal));
12230
+ return await consumeResponse(
12231
+ response,
12232
+ controller,
12233
+ (responseId) => this.assistant.cancel(responseId),
12234
+ { id, cleanup }
12235
+ );
12236
+ } catch (error) {
12237
+ cleanup();
12238
+ controller.abort();
12239
+ throw error;
12240
+ }
12241
+ }
11696
12242
  // ── Assistant ─────────────────────────────────────────────────────────
11697
12243
  assistant = {
12244
+ /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
12245
+ startResponse: async (request, options = {}) => {
12246
+ const body = buildTurnRequest({
12247
+ ...request,
12248
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
12249
+ });
12250
+ return this.openResponseHandle(
12251
+ (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12252
+ options
12253
+ );
12254
+ },
12255
+ /** Attach to retained replay/live events for an existing msg; never resubmits a turn. */
12256
+ attachResponse: async (id, options = {}) => {
12257
+ if (!/^msg-[\w-]+$/.test(id))
12258
+ throw new ArbiError("Expected an assistant message ID (msg-\u2026).", {
12259
+ code: "INVALID_RESPONSE_ID"
12260
+ });
12261
+ const result = await this.openResponseHandle(
12262
+ (signal) => openRunStream(this.getAuthHeaders(), id, signal),
12263
+ options,
12264
+ id
12265
+ );
12266
+ if (result.kind !== "response") throw new ArbiError("Expected a response attachment.");
12267
+ return result.handle;
12268
+ },
11698
12269
  /**
11699
12270
  * Ask the assistant: send one turn (the body is `buildTurnRequest`) and stream it into
11700
12271
  * `handlers`. Resolves with the accumulated result when the stream ends.
@@ -11723,12 +12294,20 @@ var Arbi = class {
11723
12294
  if (isAbort(error)) throw error;
11724
12295
  if (error instanceof AssistantTurnRefused) {
11725
12296
  if (error.quota) onQuotaExceeded?.(error.quota);
11726
- return refuse(error.message);
12297
+ callbacks.onErrorDetails?.(error);
12298
+ return refuse(error.message, error);
11727
12299
  }
11728
12300
  if (error instanceof ArbiSessionExpiredError || error instanceof ArbiApiError && error.status === 401) {
11729
12301
  const message = SESSION_EXPIRED_MESSAGE;
11730
- return refuse(message, new ArbiSessionExpiredError(message));
12302
+ const expired = error instanceof ArbiSessionExpiredError ? error : new ArbiSessionExpiredError(message, {
12303
+ cause: error,
12304
+ requestId: error.requestId,
12305
+ responseId: error.responseId
12306
+ });
12307
+ callbacks.onErrorDetails?.(expired);
12308
+ return refuse(message, expired);
11731
12309
  }
12310
+ if (error instanceof ArbiError) callbacks.onErrorDetails?.(error);
11732
12311
  onError?.(error);
11733
12312
  throw error;
11734
12313
  }
@@ -12040,12 +12619,12 @@ var Arbi = class {
12040
12619
  );
12041
12620
  },
12042
12621
  /** Post plaintext to a chat (encrypted under its current epoch). Returns it decrypted. */
12043
- send: async (chat, text, options) => {
12622
+ send: async (chat, text2, options) => {
12044
12623
  const ready = await this.readyChat(chat);
12045
12624
  return sendChatMessage(
12046
12625
  this.requireClient(),
12047
12626
  await this.chatRing(ready),
12048
- text,
12627
+ text2,
12049
12628
  options
12050
12629
  );
12051
12630
  },
@@ -12307,7 +12886,7 @@ var Arbi = class {
12307
12886
  * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
12308
12887
  * chat and posts under the pair key. The caller passes plaintext and never handles keys.
12309
12888
  */
12310
- send: async (recipient, text) => {
12889
+ send: async (recipient, text2) => {
12311
12890
  const client = this.requireClient();
12312
12891
  const resolved = await resolveRecipient(client, recipient);
12313
12892
  if (!resolved) {
@@ -12319,15 +12898,15 @@ var Arbi = class {
12319
12898
  client,
12320
12899
  await this.requireChatCrypto(),
12321
12900
  resolved.extId,
12322
- text
12901
+ text2
12323
12902
  );
12324
12903
  },
12325
12904
  /** Send to a peer whose external id is already known, skipping directory resolution. */
12326
- sendTo: async (peerExtId, text) => sendDirectMessage(
12905
+ sendTo: async (peerExtId, text2) => sendDirectMessage(
12327
12906
  this.requireClient(),
12328
12907
  await this.requireChatCrypto(),
12329
12908
  peerExtId,
12330
- text
12909
+ text2
12331
12910
  ),
12332
12911
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
12333
12912
  resolveRecipient: (recipient) => resolveRecipient(this.requireClient(), recipient),
@@ -14074,8 +14653,8 @@ function getStepDisplay(step, docInfo = {}) {
14074
14653
  function getAgentStepLabel(step, docInfo = {}) {
14075
14654
  const { label, summary, isMultiLine } = getStepDisplay(step, docInfo);
14076
14655
  const narrative = summary && !isMultiLine && !step.reasoning ? summary : null;
14077
- const text = narrative ? `${label} \u2014 ${narrative}` : label;
14078
- return text.length > 120 ? `${text.slice(0, 119)}\u2026` : text;
14656
+ const text2 = narrative ? `${label} \u2014 ${narrative}` : label;
14657
+ return text2.length > 120 ? `${text2.slice(0, 119)}\u2026` : text2;
14079
14658
  }
14080
14659
  function getCurrentStep(steps) {
14081
14660
  const merged = mergeAgentSteps(steps);
@@ -14139,9 +14718,9 @@ function newestThread(threads) {
14139
14718
  function pickMainThread(threads) {
14140
14719
  return newestThread(threads.filter((t2) => !t2.history.some((m2) => getSubagentBranchRecord(m2)))) ?? threads.find((t2) => tailTaskMessageIndex(t2.history) < 0) ?? threads[0];
14141
14720
  }
14142
- function findSubagentRunId(threads, messageId) {
14721
+ function findSubagentRunId(threads, messageId2) {
14143
14722
  for (const thread of threads) {
14144
- const index = thread.history.findIndex((m2) => m2.external_id === messageId);
14723
+ const index = thread.history.findIndex((m2) => m2.external_id === messageId2);
14145
14724
  if (index < 0) continue;
14146
14725
  const taskIndex = tailTaskMessageIndex(thread.history);
14147
14726
  if (taskIndex >= 0 && taskIndex <= index) {
@@ -14302,6 +14881,7 @@ exports.Arbi = Arbi;
14302
14881
  exports.ArbiApiError = ArbiApiError;
14303
14882
  exports.ArbiError = ArbiError;
14304
14883
  exports.ArbiSessionExpiredError = ArbiSessionExpiredError;
14884
+ exports.ArbiTransportError = ArbiTransportError;
14305
14885
  exports.ArbiWorkspaceChangedError = ArbiWorkspaceChangedError;
14306
14886
  exports.ArbiWorkspaceSupersededError = ArbiWorkspaceSupersededError;
14307
14887
  exports.CallApiError = CallApiError;