@arbidocs/sdk 0.5.54 → 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.js CHANGED
@@ -3482,14 +3482,20 @@ var init_libsodium_wrappers = __esm({
3482
3482
 
3483
3483
  // src/errors.ts
3484
3484
  var ArbiError = class extends Error {
3485
- constructor(message) {
3486
- super(message);
3485
+ code;
3486
+ requestId;
3487
+ responseId;
3488
+ constructor(message, options = {}) {
3489
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
3490
+ this.code = options.code;
3491
+ this.requestId = options.requestId;
3492
+ this.responseId = options.responseId;
3487
3493
  this.name = "ArbiError";
3488
3494
  }
3489
3495
  };
3490
3496
  var ArbiSessionExpiredError = class extends ArbiError {
3491
- constructor(message = "Your session expired. Sign in again.") {
3492
- super(message);
3497
+ constructor(message = "Your session expired. Sign in again.", options = {}) {
3498
+ super(message, { ...options, code: "SESSION_EXPIRED" });
3493
3499
  this.name = "ArbiSessionExpiredError";
3494
3500
  }
3495
3501
  };
@@ -3518,7 +3524,7 @@ function detailText(detail) {
3518
3524
  return messages.length ? messages.join("; ") : void 0;
3519
3525
  }
3520
3526
  if (!detail || typeof detail !== "object") return void 0;
3521
- const message = typeof detail.message === "string" ? detail.message : void 0;
3527
+ const message = typeof detail.message === "string" ? detail.message : typeof detail.hint === "string" ? detail.hint : void 0;
3522
3528
  const fields = detail.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields) ? Object.entries(detail.fields).map(([name, problem]) => `${name}: ${String(problem)}`).join("; ") : "";
3523
3529
  if (message) return fields ? `${message} (${fields})` : message;
3524
3530
  return fields || void 0;
@@ -3527,21 +3533,80 @@ function apiErrorDetail(apiError) {
3527
3533
  if (typeof apiError === "string") return apiError || void 0;
3528
3534
  if (!apiError || typeof apiError !== "object") return void 0;
3529
3535
  const body = apiError;
3530
- return detailText(body.detail) || (typeof body.message === "string" ? body.message : void 0);
3536
+ return detailText(body.detail) || (typeof body.message === "string" ? body.message : void 0) || (typeof body.error === "string" ? body.error : detailText(errorRecord(body.error)));
3531
3537
  }
3532
3538
  var ArbiApiError = class extends ArbiError {
3533
3539
  status;
3534
3540
  apiError;
3535
3541
  /** Why the server refused, in its words (e.g. "run_at must be in the future"), when it said. */
3536
3542
  detail;
3537
- constructor(message, apiError, status) {
3538
- super(message);
3543
+ constructor(message, apiError, status, options = {}) {
3544
+ super(message, {
3545
+ ...apiErrorMetadata(apiError, status),
3546
+ ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0))
3547
+ });
3539
3548
  this.name = "ArbiApiError";
3540
3549
  this.apiError = apiError;
3541
3550
  this.status = status;
3542
3551
  this.detail = apiErrorDetail(apiError);
3543
3552
  }
3544
3553
  };
3554
+ function errorRecord(value) {
3555
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3556
+ }
3557
+ function firstString(...values) {
3558
+ return values.find((value) => typeof value === "string" && value.length > 0);
3559
+ }
3560
+ function apiErrorMetadata(apiError, status) {
3561
+ const body = errorRecord(apiError);
3562
+ const response = errorRecord(body?.response);
3563
+ const detail = errorRecord(body?.detail);
3564
+ const error = errorRecord(response?.error) ?? errorRecord(body?.error);
3565
+ return {
3566
+ code: firstString(error?.code, detail?.code, body?.code) ?? (status !== void 0 ? `HTTP_${status}` : void 0),
3567
+ requestId: firstString(body?.request_id, detail?.request_id, error?.request_id),
3568
+ responseId: firstString(
3569
+ response?.id,
3570
+ body?.response_id,
3571
+ typeof body?.status === "string" ? body?.id : void 0,
3572
+ detail?.response_id,
3573
+ error?.response_id
3574
+ )
3575
+ };
3576
+ }
3577
+ async function apiErrorFromResponse(response, fallback, options = {}) {
3578
+ let body;
3579
+ try {
3580
+ const text2 = await response.text();
3581
+ if (text2) {
3582
+ try {
3583
+ body = JSON.parse(text2);
3584
+ } catch {
3585
+ body = text2.length < 200 ? text2 : void 0;
3586
+ }
3587
+ }
3588
+ } catch {
3589
+ }
3590
+ return new ArbiApiError(fallback, body, response.status, {
3591
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? void 0,
3592
+ ...options
3593
+ });
3594
+ }
3595
+ var ArbiTransportError = class extends ArbiError {
3596
+ constructor(cause, responseId) {
3597
+ super(cause instanceof Error ? cause.message : String(cause), {
3598
+ code: "TRANSPORT_ERROR",
3599
+ cause,
3600
+ responseId
3601
+ });
3602
+ this.name = "ArbiTransportError";
3603
+ }
3604
+ };
3605
+ function transportError(error, responseId) {
3606
+ if (error instanceof ArbiError || error instanceof Error && error.name === "AbortError")
3607
+ return error;
3608
+ return new ArbiTransportError(error, responseId);
3609
+ }
3545
3610
  var DuplicateContactError = class extends ArbiApiError {
3546
3611
  contactId;
3547
3612
  constructor(message, contactId, apiError) {
@@ -3556,13 +3621,17 @@ function refusalReason(err, fallback) {
3556
3621
  }
3557
3622
  function requireData(result, message) {
3558
3623
  if (result.error || !result.data) {
3559
- throw new ArbiApiError(message, result.error, result.response?.status);
3624
+ throw new ArbiApiError(message, result.error, result.response?.status, {
3625
+ requestId: result.response?.headers?.get("x-request-id") ?? void 0
3626
+ });
3560
3627
  }
3561
3628
  return result.data;
3562
3629
  }
3563
3630
  function requireOk(result, message) {
3564
3631
  if (result.error) {
3565
- throw new ArbiApiError(message, result.error, result.response?.status);
3632
+ throw new ArbiApiError(message, result.error, result.response?.status, {
3633
+ requestId: result.response?.headers?.get("x-request-id") ?? void 0
3634
+ });
3566
3635
  }
3567
3636
  }
3568
3637
  function getErrorMessage(err) {
@@ -3592,7 +3661,8 @@ function getErrorCode(err) {
3592
3661
  while (current && !seen.has(current)) {
3593
3662
  seen.add(current);
3594
3663
  const code = current.code;
3595
- if (typeof code === "string") return code;
3664
+ if (typeof code === "string" && !(current instanceof ArbiTransportError && current.cause instanceof Error))
3665
+ return code;
3596
3666
  current = current.cause instanceof Error ? current.cause : void 0;
3597
3667
  }
3598
3668
  return void 0;
@@ -3605,39 +3675,30 @@ var STATUS_FALLBACKS = {
3605
3675
  404: "Resource not found.",
3606
3676
  503: "The selected LLM is not responding. Please retry or select another model."
3607
3677
  };
3608
- async function extractErrorMessage(res) {
3609
- let bodyDetail;
3610
- try {
3611
- const text = await res.text();
3612
- if (text) {
3613
- try {
3614
- const json2 = JSON.parse(text);
3615
- bodyDetail = detailText(json2.detail) || json2.message || json2.error || void 0;
3616
- } catch {
3617
- if (text.length < 200) bodyDetail = text;
3618
- }
3619
- }
3620
- } catch {
3621
- }
3622
- if (bodyDetail) return `Request failed (${res.status}): ${bodyDetail}`;
3623
- const fallback = STATUS_FALLBACKS[res.status];
3624
- if (fallback) return fallback;
3625
- return `Request failed: ${res.status} ${res.statusText}`;
3626
- }
3627
3678
  async function authenticatedFetch(options) {
3628
3679
  const { baseUrl, accessToken, path: path5, method, body, headers, signal } = options;
3629
- const res = await fetch(`${baseUrl}${path5}`, {
3630
- method: method ?? (body ? "POST" : "GET"),
3631
- headers: {
3632
- Authorization: `Bearer ${accessToken}`,
3633
- ...headers
3634
- },
3635
- body,
3636
- signal
3637
- });
3680
+ let res;
3681
+ try {
3682
+ res = await fetch(`${baseUrl}${path5}`, {
3683
+ method: method ?? (body ? "POST" : "GET"),
3684
+ headers: {
3685
+ Authorization: `Bearer ${accessToken}`,
3686
+ ...headers
3687
+ },
3688
+ body,
3689
+ signal
3690
+ });
3691
+ } catch (error) {
3692
+ throw transportError(error);
3693
+ }
3638
3694
  if (!res.ok) {
3639
- const message = await extractErrorMessage(res);
3640
- throw new ArbiApiError(message, { status: res.status, statusText: res.statusText }, res.status);
3695
+ const error = await apiErrorFromResponse(
3696
+ res,
3697
+ STATUS_FALLBACKS[res.status] ?? `Request failed: ${res.status} ${res.statusText}`
3698
+ );
3699
+ const detail = error.detail || (typeof error.apiError === "string" ? error.apiError : void 0);
3700
+ if (detail) error.message = `Request failed (${res.status}): ${detail}`;
3701
+ throw error;
3641
3702
  }
3642
3703
  return res;
3643
3704
  }
@@ -3954,8 +4015,8 @@ async function requestDeviceCode(domain, clientId, audience, scope = "openid ema
3954
4015
  body
3955
4016
  });
3956
4017
  if (!res.ok) {
3957
- const text = await res.text();
3958
- throw new DeviceFlowError(`Device code request failed: ${res.status} ${text}`);
4018
+ const text2 = await res.text();
4019
+ throw new DeviceFlowError(`Device code request failed: ${res.status} ${text2}`);
3959
4020
  }
3960
4021
  return await res.json();
3961
4022
  }
@@ -4328,9 +4389,9 @@ function buildDocNameMap(docs) {
4328
4389
  }
4329
4390
  return map;
4330
4391
  }
4331
- function resolveDocRefs(text, docNames) {
4332
- if (!docNames) return text;
4333
- return text.replace(/\{(doc-[^}]+)\}/g, (_match, id) => docNames[id] ?? id);
4392
+ function resolveDocRefs(text2, docNames) {
4393
+ if (!docNames) return text2;
4394
+ return text2.replace(/\{(doc-[^}]+)\}/g, (_match, id) => docNames[id] ?? id);
4334
4395
  }
4335
4396
  function resolveStepDocName(step, docNames) {
4336
4397
  if (!docNames) return void 0;
@@ -4409,13 +4470,16 @@ function parseSSEEvents(chunk2, buffer) {
4409
4470
  return { events, remaining };
4410
4471
  }
4411
4472
  async function streamSSE(response, callbacks = {}) {
4473
+ if (!response.ok) throw await apiErrorFromResponse(response, `HTTP ${response.status}`);
4412
4474
  if (!response.body) {
4413
- throw new Error("No response body");
4475
+ throw new ArbiApiError("No response body", void 0, response.status, {
4476
+ code: "MISSING_RESPONSE_BODY"
4477
+ });
4414
4478
  }
4415
4479
  const reader = response.body.getReader();
4416
4480
  const decoder = new TextDecoder("utf-8");
4417
4481
  let sseBuffer = "";
4418
- let text = "";
4482
+ let text2 = "";
4419
4483
  let assistantMessageExtId = null;
4420
4484
  const agentSteps = [];
4421
4485
  let toolCallCount = 0;
@@ -4426,6 +4490,35 @@ async function streamSSE(response, callbacks = {}) {
4426
4490
  let usage = null;
4427
4491
  let context = null;
4428
4492
  let completed = false;
4493
+ let terminal = false;
4494
+ let outcome;
4495
+ let acknowledged = false;
4496
+ const errorDetails = [];
4497
+ const reportError = (error) => {
4498
+ errorDetails.push(error);
4499
+ errors.push(error.message);
4500
+ callbacks.onErrorDetails?.(error);
4501
+ callbacks.onError?.(error.message);
4502
+ };
4503
+ const settle = (payload, fallback) => {
4504
+ const status = payload?.status;
4505
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : fallback;
4506
+ const id = typeof payload?.id === "string" && payload.id ? payload.id : assistantMessageExtId;
4507
+ assistantMessageExtId = id;
4508
+ const rawError = payload?.error;
4509
+ let error;
4510
+ if (resolved === "failed" || rawError) {
4511
+ const body = { response: payload };
4512
+ const message = rawError && typeof rawError === "object" && "message" in rawError && typeof rawError.message === "string" ? rawError.message : "Unknown streaming error";
4513
+ error = new ArbiApiError(message, body, void 0, {
4514
+ code: apiErrorMetadata(body).code ?? "RESPONSE_FAILED",
4515
+ responseId: id ?? void 0
4516
+ });
4517
+ reportError(error);
4518
+ }
4519
+ outcome = { status: resolved, responseId: id, response: payload, ...error ? { error } : {} };
4520
+ terminal = true;
4521
+ };
4429
4522
  const eventHandlers = {
4430
4523
  // OpenAI Responses API events (dot-separated names from server)
4431
4524
  "response.created": (raw) => {
@@ -4446,7 +4539,7 @@ async function streamSSE(response, callbacks = {}) {
4446
4539
  "response.output_text.delta": (raw) => {
4447
4540
  const data = JSON.parse(raw);
4448
4541
  if (data.delta) {
4449
- text += data.delta;
4542
+ text2 += data.delta;
4450
4543
  if (callbacks.onOutputTextDelta) {
4451
4544
  callbacks.onOutputTextDelta({ item_id: data.item_id ?? "", delta: data.delta });
4452
4545
  } else {
@@ -4456,7 +4549,7 @@ async function streamSSE(response, callbacks = {}) {
4456
4549
  },
4457
4550
  "response.output_text.done": (raw) => {
4458
4551
  const data = JSON.parse(raw);
4459
- text = data.text;
4552
+ text2 = data.text;
4460
4553
  callbacks.onTextDone?.(data.text);
4461
4554
  },
4462
4555
  "response.function_call_arguments.delta": (raw) => {
@@ -4477,6 +4570,7 @@ async function streamSSE(response, callbacks = {}) {
4477
4570
  "response.completed": (raw) => {
4478
4571
  const data = JSON.parse(raw);
4479
4572
  completed = true;
4573
+ settle(data.response, "completed");
4480
4574
  if (data.response?.usage) {
4481
4575
  usage = data.response.usage;
4482
4576
  callbacks.onUsage?.(data.response.usage);
@@ -4488,7 +4582,7 @@ async function streamSSE(response, callbacks = {}) {
4488
4582
  }
4489
4583
  const finalText = data.response?.metadata?.content;
4490
4584
  if (finalText) {
4491
- text = finalText;
4585
+ text2 = finalText;
4492
4586
  callbacks.onTextDone?.(finalText);
4493
4587
  }
4494
4588
  if (data.context) {
@@ -4500,12 +4594,17 @@ async function streamSSE(response, callbacks = {}) {
4500
4594
  },
4501
4595
  "response.failed": (raw) => {
4502
4596
  const data = JSON.parse(raw);
4503
- const message = data.response?.error?.message || "Unknown streaming error";
4504
- errors.push(message);
4505
- callbacks.onError?.(message);
4597
+ settle(data.response, "failed");
4598
+ },
4599
+ "response.cancelled": (raw) => {
4600
+ settle(JSON.parse(raw).response, "cancelled");
4601
+ },
4602
+ "response.incomplete": (raw) => {
4603
+ settle(JSON.parse(raw).response, "incomplete");
4506
4604
  },
4507
4605
  // ARBI-specific events (dot-prefixed from server)
4508
4606
  "arbi.message_queued": (raw) => {
4607
+ acknowledged = true;
4509
4608
  const data = JSON.parse(raw);
4510
4609
  if (data.user_message) {
4511
4610
  userMessage = data.user_message;
@@ -4528,6 +4627,7 @@ async function streamSSE(response, callbacks = {}) {
4528
4627
  callbacks.onUserInputRequest?.(data);
4529
4628
  },
4530
4629
  "arbi.probe_answer": (raw) => {
4630
+ acknowledged = true;
4531
4631
  const data = JSON.parse(raw);
4532
4632
  callbacks.onProbeAnswer?.(data);
4533
4633
  },
@@ -4536,6 +4636,7 @@ async function streamSSE(response, callbacks = {}) {
4536
4636
  callbacks.onDeferredInterjection?.(data);
4537
4637
  },
4538
4638
  "arbi.agent_control_state": (raw) => {
4639
+ acknowledged = true;
4539
4640
  const data = JSON.parse(raw);
4540
4641
  callbacks.onAgentControlState?.(data);
4541
4642
  },
@@ -4551,47 +4652,81 @@ async function streamSSE(response, callbacks = {}) {
4551
4652
  "arbi.error": (raw) => {
4552
4653
  const data = JSON.parse(raw);
4553
4654
  const message = typeof data?.message === "string" && data.message.length > 0 ? data.message : data.code;
4655
+ const error = new ArbiApiError(message, data, void 0, {
4656
+ responseId: assistantMessageExtId ?? void 0
4657
+ });
4658
+ errorDetails.push(error);
4554
4659
  errors.push(message);
4660
+ callbacks.onErrorDetails?.(error);
4661
+ outcome = { status: "failed", responseId: assistantMessageExtId, error };
4555
4662
  callbacks.onArbiError?.(data);
4556
4663
  callbacks.onError?.(message);
4557
4664
  }
4558
4665
  };
4559
4666
  const processEvents = (events) => {
4560
4667
  for (const { event, data } of events) {
4668
+ if (terminal) break;
4669
+ if (event === "reasoning") {
4670
+ callbacks.onReasoningDelta?.(data);
4671
+ continue;
4672
+ }
4673
+ const handler = eventHandlers[event];
4674
+ if (!handler) {
4675
+ console.warn(`[arbi-sse] unhandled SSE event: ${event}`);
4676
+ continue;
4677
+ }
4561
4678
  try {
4562
- if (event === "reasoning") {
4563
- callbacks.onReasoningDelta?.(data);
4564
- continue;
4565
- }
4566
- const handler = eventHandlers[event];
4567
- if (handler) {
4568
- handler(data);
4569
- } else {
4570
- console.warn(`[arbi-sse] unhandled SSE event: ${event}`);
4571
- }
4679
+ JSON.parse(data);
4572
4680
  } catch {
4681
+ continue;
4573
4682
  }
4683
+ handler(data);
4574
4684
  }
4575
4685
  };
4576
- while (true) {
4577
- const { done, value } = await reader.read();
4578
- if (done) break;
4579
- const { events, remaining } = parseSSEEvents(decoder.decode(value, { stream: true }), sseBuffer);
4580
- sseBuffer = remaining;
4581
- processEvents(events);
4582
- if (completed) {
4583
- sseBuffer = "";
4584
- void reader.cancel().catch(() => {
4585
- });
4586
- break;
4686
+ try {
4687
+ while (true) {
4688
+ let chunk2;
4689
+ try {
4690
+ chunk2 = await reader.read();
4691
+ } catch (cause) {
4692
+ const error = transportError(cause, assistantMessageExtId ?? void 0);
4693
+ const aborted = error.name === "AbortError";
4694
+ const disconnected = {
4695
+ status: "disconnected",
4696
+ responseId: assistantMessageExtId,
4697
+ reason: aborted ? "aborted" : "connection_error",
4698
+ ...error instanceof ArbiError ? { error } : {}
4699
+ };
4700
+ if (error instanceof ArbiError) callbacks.onErrorDetails?.(error);
4701
+ callbacks.onOutcome?.(disconnected);
4702
+ throw error;
4703
+ }
4704
+ const { done, value } = chunk2;
4705
+ if (done) break;
4706
+ const { events, remaining } = parseSSEEvents(
4707
+ decoder.decode(value, { stream: true }),
4708
+ sseBuffer
4709
+ );
4710
+ sseBuffer = remaining;
4711
+ processEvents(events);
4712
+ if (terminal) {
4713
+ sseBuffer = "";
4714
+ void reader.cancel().catch(() => {
4715
+ });
4716
+ break;
4717
+ }
4587
4718
  }
4719
+ if (sseBuffer.trim()) {
4720
+ const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
4721
+ processEvents(events);
4722
+ }
4723
+ } finally {
4724
+ reader.releaseLock();
4588
4725
  }
4589
- if (sseBuffer.trim()) {
4590
- const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
4591
- processEvents(events);
4592
- }
4726
+ outcome ??= acknowledged && !assistantMessageExtId ? { status: "acknowledged", responseId: null } : { status: "disconnected", responseId: assistantMessageExtId, reason: "connection_closed" };
4727
+ callbacks.onOutcome?.(outcome);
4593
4728
  return {
4594
- text,
4729
+ text: text2,
4595
4730
  assistantMessageExtId,
4596
4731
  agentSteps,
4597
4732
  toolCallCount,
@@ -4601,7 +4736,9 @@ async function streamSSE(response, callbacks = {}) {
4601
4736
  artifacts,
4602
4737
  usage,
4603
4738
  context,
4604
- completed
4739
+ completed,
4740
+ outcome,
4741
+ errorDetails
4605
4742
  };
4606
4743
  }
4607
4744
  function formatStreamSummary(result, elapsedTime) {
@@ -4874,10 +5011,10 @@ function isNotification(msg) {
4874
5011
  function formatWsMessage(msg) {
4875
5012
  if (isMessageType(msg, "task_update")) {
4876
5013
  const progress = msg.progress > 0 ? ` (${Math.round(msg.progress)}%)` : "";
4877
- const text = `${msg.file_name} \u2014 ${msg.status}${progress}`;
4878
- if (msg.status === "completed") return { text, level: "success" };
4879
- if (msg.status === "failed") return { text, level: "error" };
4880
- return { text, level: "info" };
5014
+ const text2 = `${msg.file_name} \u2014 ${msg.status}${progress}`;
5015
+ if (msg.status === "completed") return { text: text2, level: "success" };
5016
+ if (msg.status === "failed") return { text: text2, level: "error" };
5017
+ return { text: text2, level: "info" };
4881
5018
  }
4882
5019
  if (isMessageType(msg, "batch_complete")) {
4883
5020
  const count = msg.doc_ext_ids.length;
@@ -4949,8 +5086,8 @@ function countCitations(metadata) {
4949
5086
  const responses = modelCitations?.tool_responses;
4950
5087
  return responses ? Object.keys(responses).length : 0;
4951
5088
  }
4952
- function stripCitationMarkdown(text) {
4953
- return text.replace(/\[([^\]]+)\]\(#cite-(\d+)\)/g, "$1[$2]");
5089
+ function stripCitationMarkdown(text2) {
5090
+ return text2.replace(/\[([^\]]+)\]\(#cite-(\d+)\)/g, "$1[$2]");
4954
5091
  }
4955
5092
  function buildCitationChunkData(message) {
4956
5093
  const merged = {};
@@ -4989,6 +5126,403 @@ function buildChunkLookup(tools) {
4989
5126
  return lookup;
4990
5127
  }
4991
5128
 
5129
+ // src/response-handle.ts
5130
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5131
+ var text = (value) => typeof value === "string" ? value : void 0;
5132
+ var messageId = (value) => typeof value === "string" && /^msg-[\w-]+$/.test(value);
5133
+ function immutable(value) {
5134
+ if (value && typeof value === "object" && !(value instanceof Error) && !Object.isFrozen(value)) {
5135
+ Object.freeze(value);
5136
+ for (const child of Object.values(value)) immutable(child);
5137
+ }
5138
+ return value;
5139
+ }
5140
+ function reportObserverError(error) {
5141
+ queueMicrotask(() => {
5142
+ throw error;
5143
+ });
5144
+ }
5145
+ var ResponseEventDecoder = class {
5146
+ buffer = "";
5147
+ event = "";
5148
+ data = [];
5149
+ id;
5150
+ push(chunk2, final = false) {
5151
+ this.buffer += chunk2;
5152
+ const frames = [];
5153
+ const dispatch = () => {
5154
+ if (this.data.length)
5155
+ frames.push({
5156
+ event: this.event || "message",
5157
+ data: this.data.join("\n"),
5158
+ ...this.id !== void 0 ? { id: this.id } : {}
5159
+ });
5160
+ this.event = "";
5161
+ this.data = [];
5162
+ this.id = void 0;
5163
+ };
5164
+ const line = (value) => {
5165
+ if (!value) {
5166
+ dispatch();
5167
+ return;
5168
+ }
5169
+ if (value.startsWith(":")) return;
5170
+ const colon = value.indexOf(":");
5171
+ const field = colon < 0 ? value : value.slice(0, colon);
5172
+ let content = colon < 0 ? "" : value.slice(colon + 1);
5173
+ if (content.startsWith(" ")) content = content.slice(1);
5174
+ if (field === "event") this.event = content;
5175
+ if (field === "data") this.data.push(content);
5176
+ if (field === "id" && !content.includes("\0")) this.id = content;
5177
+ };
5178
+ while (true) {
5179
+ const index = this.buffer.search(/[\r\n]/);
5180
+ if (index < 0 || !final && index === this.buffer.length - 1 && this.buffer[index] === "\r")
5181
+ break;
5182
+ const width = this.buffer[index] === "\r" && this.buffer[index + 1] === "\n" ? 2 : 1;
5183
+ line(this.buffer.slice(0, index));
5184
+ this.buffer = this.buffer.slice(index + width);
5185
+ }
5186
+ if (final) {
5187
+ if (this.buffer) line(this.buffer);
5188
+ this.buffer = "";
5189
+ dispatch();
5190
+ }
5191
+ return frames;
5192
+ }
5193
+ };
5194
+ function consumeResponse(response, controller, cancel, options = {}) {
5195
+ if (!response.body)
5196
+ return Promise.reject(
5197
+ new ArbiApiError("Response has no stream body.", void 0, response.status, {
5198
+ code: "MISSING_RESPONSE_BODY"
5199
+ })
5200
+ );
5201
+ const reader = response.body.getReader();
5202
+ let resolveStart;
5203
+ let rejectStart;
5204
+ const start = new Promise((resolve2, reject) => {
5205
+ resolveStart = resolve2;
5206
+ rejectStart = reject;
5207
+ });
5208
+ let resolveOutcome;
5209
+ const outcome = new Promise((resolve2) => {
5210
+ resolveOutcome = resolve2;
5211
+ });
5212
+ let state = immutable({
5213
+ id: options.id ?? "",
5214
+ conversationId: null,
5215
+ connection: "connecting",
5216
+ responseStatus: null,
5217
+ output: [],
5218
+ displayText: ""
5219
+ });
5220
+ let bound = false;
5221
+ let finished = false;
5222
+ let acknowledgement;
5223
+ const listeners = /* @__PURE__ */ new Set();
5224
+ const queue = [];
5225
+ let claimed = false;
5226
+ let iteratorClosed = false;
5227
+ let iteratorError;
5228
+ let pending;
5229
+ const emit = (event) => {
5230
+ if (!claimed || iteratorClosed) return;
5231
+ if (pending) {
5232
+ pending.resolve({ value: immutable(event), done: false });
5233
+ pending = void 0;
5234
+ } else if (queue.length < 256) queue.push(immutable(event));
5235
+ else {
5236
+ iteratorError = new ArbiError("Raw response event consumer fell behind.", {
5237
+ code: "RESPONSE_EVENT_OVERFLOW"
5238
+ });
5239
+ queue.length = 0;
5240
+ iteratorClosed = true;
5241
+ }
5242
+ };
5243
+ const notify = () => {
5244
+ for (const listener of [...listeners]) {
5245
+ try {
5246
+ listener(state);
5247
+ } catch (error) {
5248
+ reportObserverError(error);
5249
+ }
5250
+ }
5251
+ };
5252
+ const update = (patch) => {
5253
+ state = immutable({ ...state, ...patch });
5254
+ notify();
5255
+ };
5256
+ const finish = (value, detached = false) => {
5257
+ if (finished) return;
5258
+ finished = true;
5259
+ controller.signal.removeEventListener("abort", abort);
5260
+ options.cleanup?.();
5261
+ update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
5262
+ listeners.clear();
5263
+ resolveOutcome(state.outcome);
5264
+ if (pending) {
5265
+ pending.resolve({ value: void 0, done: true });
5266
+ pending = void 0;
5267
+ }
5268
+ void reader.cancel().catch(() => {
5269
+ });
5270
+ };
5271
+ const abort = () => {
5272
+ if (!bound) rejectStart(new DOMException("The operation was aborted.", "AbortError"));
5273
+ finish({ status: "disconnected", responseId: bound ? state.id : null, reason: "aborted" }, true);
5274
+ queue.length = 0;
5275
+ };
5276
+ const handle = {
5277
+ get id() {
5278
+ return state.id;
5279
+ },
5280
+ snapshot: () => state,
5281
+ subscribe(listener) {
5282
+ if (!finished) listeners.add(listener);
5283
+ try {
5284
+ listener(state);
5285
+ } catch (error) {
5286
+ reportObserverError(error);
5287
+ }
5288
+ return () => {
5289
+ listeners.delete(listener);
5290
+ };
5291
+ },
5292
+ outcome,
5293
+ detach: () => {
5294
+ if (!finished) controller.abort();
5295
+ },
5296
+ cancel: () => cancel(state.id),
5297
+ events() {
5298
+ if (claimed)
5299
+ throw new ArbiError("A response handle supports one raw event iterator.", {
5300
+ code: "RESPONSE_EVENTS_ALREADY_CLAIMED"
5301
+ });
5302
+ claimed = true;
5303
+ const close = () => {
5304
+ iteratorClosed = true;
5305
+ queue.length = 0;
5306
+ if (pending) {
5307
+ pending.resolve({ value: void 0, done: true });
5308
+ pending = void 0;
5309
+ }
5310
+ };
5311
+ return {
5312
+ [Symbol.asyncIterator]() {
5313
+ return this;
5314
+ },
5315
+ next() {
5316
+ if (iteratorError) return Promise.reject(iteratorError);
5317
+ if (queue.length) return Promise.resolve({ value: queue.shift(), done: false });
5318
+ if (finished || iteratorClosed)
5319
+ return Promise.resolve({ value: void 0, done: true });
5320
+ if (pending)
5321
+ return Promise.reject(
5322
+ new ArbiError("Concurrent iterator reads are unsupported.", {
5323
+ code: "RESPONSE_EVENTS_CONCURRENT_READ"
5324
+ })
5325
+ );
5326
+ return new Promise((resolve2, reject) => {
5327
+ pending = { resolve: resolve2, reject };
5328
+ });
5329
+ },
5330
+ async return() {
5331
+ close();
5332
+ return { value: void 0, done: true };
5333
+ },
5334
+ async throw(error) {
5335
+ close();
5336
+ throw error;
5337
+ }
5338
+ };
5339
+ }
5340
+ };
5341
+ const bind = (id) => {
5342
+ if (bound) return;
5343
+ bound = true;
5344
+ state = immutable({ ...state, id, connection: "streaming" });
5345
+ resolveStart({ kind: "response", handle });
5346
+ };
5347
+ const diagnostic = (code, frame) => emit({ event: "arbi.sdk.protocol_error", data: { code, frame } });
5348
+ const process2 = (frame) => {
5349
+ if (finished) return;
5350
+ let data;
5351
+ if (frame.event === "reasoning") {
5352
+ emit({
5353
+ event: frame.event,
5354
+ data: frame.data,
5355
+ ...frame.id !== void 0 ? { id: frame.id } : {}
5356
+ });
5357
+ return;
5358
+ }
5359
+ try {
5360
+ data = JSON.parse(frame.data);
5361
+ } catch {
5362
+ diagnostic("MALFORMED_JSON", frame);
5363
+ return;
5364
+ }
5365
+ const payload = object(data);
5366
+ const raw = object(payload?.response);
5367
+ const id = raw?.id;
5368
+ if (bound && typeof id === "string" && id !== state.id) {
5369
+ diagnostic("CONFLICTING_RESPONSE_ID", frame);
5370
+ return;
5371
+ }
5372
+ if (messageId(id)) bind(id);
5373
+ emit({ event: frame.event, data, ...frame.id !== void 0 ? { id: frame.id } : {} });
5374
+ if (frame.event === "arbi.message_queued") acknowledgement = payload;
5375
+ const patch = {};
5376
+ if (frame.event === "arbi.user_message" && !state.conversationId && typeof payload?.conversation_ext_id === "string")
5377
+ patch.conversationId = payload.conversation_ext_id;
5378
+ if (raw) {
5379
+ patch.rawResponse = raw;
5380
+ if (typeof raw.status === "string") patch.responseStatus = raw.status;
5381
+ if (Array.isArray(raw.output))
5382
+ patch.output = raw.output.filter((item2) => !!object(item2));
5383
+ const metadata = object(raw.metadata);
5384
+ const conversation = text(metadata?.conversation_ext_id) ?? text(metadata?.conversation_id) ?? text(raw.conversation_id);
5385
+ if (conversation && (!state.conversationId || state.conversationId === conversation))
5386
+ patch.conversationId = conversation;
5387
+ if (typeof metadata?.content === "string") patch.displayText = metadata.content;
5388
+ }
5389
+ const item = object(payload?.item);
5390
+ if ((frame.event === "response.output_item.added" || frame.event === "response.output_item.done") && item) {
5391
+ const output = [...state.output];
5392
+ const index = output.findIndex((existing) => existing.id === item.id);
5393
+ if (index >= 0 && item.id) output[index] = item;
5394
+ else
5395
+ output.splice(
5396
+ typeof payload?.output_index === "number" ? payload.output_index : output.length,
5397
+ 0,
5398
+ item
5399
+ );
5400
+ patch.output = output;
5401
+ }
5402
+ const itemId = text(payload?.item_id);
5403
+ const delta = text(payload?.delta);
5404
+ if (itemId && [
5405
+ "response.content_part.added",
5406
+ "response.output_text.delta",
5407
+ "response.output_text.done",
5408
+ "response.function_call_arguments.delta",
5409
+ "response.reasoning_summary_text.delta"
5410
+ ].includes(frame.event)) {
5411
+ const output = [...patch.output ?? state.output];
5412
+ let index = output.findIndex((existing) => existing.id === itemId);
5413
+ if (index < 0) {
5414
+ index = output.length;
5415
+ output.push({
5416
+ id: itemId,
5417
+ type: frame.event.includes("function_call") ? "function_call" : frame.event.includes("reasoning") ? "reasoning" : "message"
5418
+ });
5419
+ }
5420
+ const current = { ...output[index] };
5421
+ if (frame.event === "response.function_call_arguments.delta")
5422
+ current.arguments = (text(current.arguments) ?? "") + (delta ?? "");
5423
+ else {
5424
+ const key = frame.event.includes("reasoning") ? "summary" : "content";
5425
+ const content = Array.isArray(current[key]) ? [...current[key]] : [];
5426
+ const partIndex = typeof payload?.content_index === "number" ? payload.content_index : typeof payload?.summary_index === "number" ? payload.summary_index : 0;
5427
+ const part = {
5428
+ ...object(content[partIndex]) ?? {
5429
+ type: key === "summary" ? "summary_text" : "output_text",
5430
+ text: ""
5431
+ }
5432
+ };
5433
+ if (frame.event === "response.content_part.added")
5434
+ content[partIndex] = object(payload?.part) ?? part;
5435
+ else {
5436
+ part.text = frame.event === "response.output_text.done" ? text(payload?.text) ?? "" : (text(part.text) ?? "") + (delta ?? "");
5437
+ content[partIndex] = part;
5438
+ }
5439
+ current[key] = content;
5440
+ }
5441
+ output[index] = current;
5442
+ patch.output = output;
5443
+ }
5444
+ if (frame.event === "response.output_text.delta" && delta)
5445
+ patch.displayText = state.displayText + delta;
5446
+ if (frame.event === "response.output_text.done" && typeof payload?.text === "string")
5447
+ patch.displayText = payload.text;
5448
+ update(patch);
5449
+ const terminal = /^response\.(completed|failed|cancelled|incomplete)$/.exec(
5450
+ frame.event
5451
+ )?.[1];
5452
+ if (terminal && bound) {
5453
+ const status = raw?.status;
5454
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : terminal;
5455
+ const error = resolved === "failed" || raw?.error ? new ArbiApiError(
5456
+ text(object(raw?.error)?.message) ?? "Response failed.",
5457
+ { response: raw },
5458
+ void 0,
5459
+ { ...apiErrorMetadata({ response: raw }), responseId: state.id }
5460
+ ) : void 0;
5461
+ finish({
5462
+ status: resolved,
5463
+ responseId: state.id,
5464
+ ...raw ? { response: raw } : {},
5465
+ ...error ? { error } : {}
5466
+ });
5467
+ }
5468
+ };
5469
+ controller.signal.addEventListener("abort", abort, { once: true });
5470
+ if (controller.signal.aborted) abort();
5471
+ else if (options.id) bind(options.id);
5472
+ void (async () => {
5473
+ const decoder = new TextDecoder();
5474
+ const frames = new ResponseEventDecoder();
5475
+ try {
5476
+ while (!finished) {
5477
+ const { value, done } = await reader.read();
5478
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done))
5479
+ process2(frame);
5480
+ if (done) break;
5481
+ }
5482
+ if (!finished) {
5483
+ if (!bound && acknowledgement) {
5484
+ const value = { status: "acknowledged", responseId: null };
5485
+ resolveStart({
5486
+ kind: "acknowledged",
5487
+ acknowledgement: immutable(acknowledgement),
5488
+ outcome: immutable(value)
5489
+ });
5490
+ finish(value);
5491
+ } else {
5492
+ if (!bound)
5493
+ rejectStart(
5494
+ new ArbiApiError(
5495
+ "Stream ended before response identity was established.",
5496
+ void 0,
5497
+ void 0,
5498
+ { code: "MISSING_RESPONSE_ID" }
5499
+ )
5500
+ );
5501
+ finish({
5502
+ status: "disconnected",
5503
+ responseId: bound ? state.id : null,
5504
+ reason: "connection_closed"
5505
+ });
5506
+ }
5507
+ }
5508
+ } catch (cause) {
5509
+ if (!finished) {
5510
+ const error = transportError(cause, bound ? state.id : void 0);
5511
+ if (!bound) rejectStart(error);
5512
+ finish({
5513
+ status: "disconnected",
5514
+ responseId: bound ? state.id : null,
5515
+ reason: error.name === "AbortError" ? "aborted" : "connection_error",
5516
+ ...error instanceof ArbiError ? { error } : {}
5517
+ });
5518
+ }
5519
+ } finally {
5520
+ reader.releaseLock();
5521
+ }
5522
+ })();
5523
+ return start;
5524
+ }
5525
+
4992
5526
  // src/operations/documents.ts
4993
5527
  var documents_exports = {};
4994
5528
  __export(documents_exports, {
@@ -5952,18 +6486,18 @@ async function searchConversations(arbi, body) {
5952
6486
  "Failed to search conversations"
5953
6487
  );
5954
6488
  }
5955
- async function getMessage(arbi, messageId) {
6489
+ async function getMessage(arbi, messageId2) {
5956
6490
  return requireData(
5957
6491
  await arbi.fetch.GET("/v1/conversation/message/{message_ext_id}", {
5958
- params: { path: { message_ext_id: messageId } }
6492
+ params: { path: { message_ext_id: messageId2 } }
5959
6493
  }),
5960
6494
  "Failed to fetch message"
5961
6495
  );
5962
6496
  }
5963
- async function deleteMessage(arbi, messageId) {
6497
+ async function deleteMessage(arbi, messageId2) {
5964
6498
  return requireData(
5965
6499
  await arbi.fetch.DELETE("/v1/conversation/message/{message_ext_id}", {
5966
- params: { path: { message_ext_id: messageId } }
6500
+ params: { path: { message_ext_id: messageId2 } }
5967
6501
  }),
5968
6502
  "Failed to delete message"
5969
6503
  );
@@ -6131,7 +6665,7 @@ async function retrieve(options) {
6131
6665
  tools,
6132
6666
  ...model ? { model } : {}
6133
6667
  };
6134
- const { data, error } = await arbi.fetch.POST("/v1/assistant/retrieve", { body });
6668
+ const { data, error, response } = await arbi.fetch.POST("/v1/assistant/retrieve", { body });
6135
6669
  if (error) {
6136
6670
  const detail = error?.detail;
6137
6671
  let message;
@@ -6143,7 +6677,9 @@ async function retrieve(options) {
6143
6677
  } else {
6144
6678
  message = JSON.stringify(error);
6145
6679
  }
6146
- throw new Error(`Retrieve failed: ${message}`);
6680
+ throw new ArbiApiError(`Retrieve failed: ${message}`, error, response.status, {
6681
+ requestId: response.headers.get("x-request-id") ?? void 0
6682
+ });
6147
6683
  }
6148
6684
  return data;
6149
6685
  }
@@ -6180,7 +6716,7 @@ async function queryAssistant(options) {
6180
6716
  return authenticatedFetch({
6181
6717
  baseUrl,
6182
6718
  accessToken,
6183
- path: "/v1/assistant/query",
6719
+ path: "/v1/responses",
6184
6720
  method: "POST",
6185
6721
  body: JSON.stringify(buildTurnRequest(request)),
6186
6722
  headers: { "Content-Type": "application/json" },
@@ -6190,8 +6726,8 @@ async function queryAssistant(options) {
6190
6726
  var AssistantTurnRefused = class extends ArbiApiError {
6191
6727
  /** Set when the refusal is the project's used-up AI usage. */
6192
6728
  quota;
6193
- constructor(message, status, quota = null) {
6194
- super(message, void 0, status);
6729
+ constructor(message, status, quota = null, apiError, options = {}) {
6730
+ super(message, apiError, status, options);
6195
6731
  this.name = "AssistantTurnRefused";
6196
6732
  this.quota = quota;
6197
6733
  }
@@ -6219,54 +6755,36 @@ function quotaFromStreamError(error) {
6219
6755
  if (!Number.isFinite(spend) || !Number.isFinite(budget)) return null;
6220
6756
  return { spend, budget, projectExtId: match.groups.project ?? null };
6221
6757
  }
6222
- async function readDetail(response) {
6223
- try {
6224
- return (await response.json())?.detail;
6225
- } catch {
6226
- return void 0;
6227
- }
6228
- }
6229
6758
  async function refusal(response) {
6230
6759
  const { status } = response;
6231
- if (status === 409) {
6232
- const detail2 = await readDetail(response);
6233
- return new AssistantTurnRefused(
6234
- detailText(detail2) || "This message has failed. Please retry from the previous message.",
6235
- status
6236
- );
6237
- }
6238
- if (status === 503) {
6239
- return new AssistantTurnRefused(
6240
- "The selected LLM is not responding. Please retry again in a minute or select another model.",
6241
- status
6242
- );
6243
- }
6244
- if (status === 402) {
6245
- const detail2 = await readDetail(response);
6246
- const quota = quotaExceededFrom(detail2);
6247
- const message = quota?.message ?? (typeof detail2 === "string" ? detail2 : void 0) ?? detail2?.message ?? "This project's AI usage for this month is used up.";
6248
- return new AssistantTurnRefused(
6249
- message || "This project's AI usage for this month is used up.",
6250
- status,
6251
- quota
6252
- );
6253
- }
6254
- const detail = await readDetail(response);
6760
+ const parsed = await apiErrorFromResponse(response, `HTTP error! status: ${status}`);
6761
+ const detail = parsed.apiError?.detail;
6762
+ const quota = status === 402 ? quotaExceededFrom(detail) : null;
6763
+ 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;
6255
6764
  return new AssistantTurnRefused(
6256
- detailText(detail) || `HTTP error! status: ${status}`,
6257
- status
6765
+ quota?.message || parsed.detail || fallback,
6766
+ status,
6767
+ quota,
6768
+ parsed.apiError,
6769
+ { code: parsed.code, requestId: parsed.requestId, responseId: parsed.responseId }
6258
6770
  );
6259
6771
  }
6260
6772
  async function openTurnStream(auth, body, signal) {
6261
- const response = await fetch(`${auth.baseUrl}/v1/assistant/query`, {
6773
+ const response = await fetch(`${auth.baseUrl}/v1/responses`, {
6262
6774
  method: "POST",
6263
6775
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${auth.accessToken}` },
6264
6776
  body: JSON.stringify(body),
6265
6777
  signal,
6266
6778
  credentials: "include"
6779
+ }).catch((error) => {
6780
+ throw transportError(error);
6267
6781
  });
6268
- if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6269
- if (!response.ok || !response.body) throw await refusal(response);
6782
+ if (response.status === 401) throw await apiErrorFromResponse(response, SESSION_EXPIRED_MESSAGE);
6783
+ if (!response.ok) throw await refusal(response);
6784
+ if (!response.body)
6785
+ throw new ArbiApiError("Response has no stream body.", void 0, response.status, {
6786
+ code: "MISSING_RESPONSE_BODY"
6787
+ });
6270
6788
  return response;
6271
6789
  }
6272
6790
  async function openRunStream(auth, responseId, signal) {
@@ -6278,15 +6796,23 @@ async function openRunStream(auth, responseId, signal) {
6278
6796
  signal,
6279
6797
  credentials: "include"
6280
6798
  }
6281
- );
6282
- if (response.status === 401) throw new ArbiApiError(SESSION_EXPIRED_MESSAGE, void 0, 401);
6283
- if (!response.ok || !response.body) {
6284
- throw new ArbiApiError(
6799
+ ).catch((error) => {
6800
+ throw transportError(error, responseId);
6801
+ });
6802
+ if (response.status === 401)
6803
+ throw await apiErrorFromResponse(response, SESSION_EXPIRED_MESSAGE, { responseId });
6804
+ if (!response.ok) {
6805
+ throw await apiErrorFromResponse(
6806
+ response,
6285
6807
  response.status === 404 ? "This run is no longer active." : `HTTP ${response.status}`,
6286
- void 0,
6287
- response.status
6808
+ { responseId }
6288
6809
  );
6289
6810
  }
6811
+ if (!response.body)
6812
+ throw new ArbiApiError("Response has no stream body.", void 0, response.status, {
6813
+ code: "MISSING_RESPONSE_BODY",
6814
+ responseId
6815
+ });
6290
6816
  return response;
6291
6817
  }
6292
6818
  async function interject(arbi, assistantMessageExtId, answer) {
@@ -7324,7 +7850,7 @@ async function listChatMessages(arbi, chatExtId, options) {
7324
7850
  "Failed to load messages"
7325
7851
  );
7326
7852
  }
7327
- async function sendChatMessage(arbi, ring, text, options = {}) {
7853
+ async function sendChatMessage(arbi, ring, text2, options = {}) {
7328
7854
  const attachments = options.attachments ?? [];
7329
7855
  checkChatAttachmentLimits(attachments);
7330
7856
  const key = keyFor(ring, ring.currentVersion);
@@ -7332,7 +7858,7 @@ async function sendChatMessage(arbi, ring, text, options = {}) {
7332
7858
  await arbi.fetch.POST("/v1/chats/{chat_ext_id}/messages", {
7333
7859
  params: { path: { chat_ext_id: ring.chatExtId } },
7334
7860
  body: {
7335
- content: await encryptWithChatKey(text, key),
7861
+ content: await encryptWithChatKey(text2, key),
7336
7862
  key_version: ring.currentVersion,
7337
7863
  kind: "text",
7338
7864
  ...attachments.length ? {
@@ -7347,7 +7873,7 @@ async function sendChatMessage(arbi, ring, text, options = {}) {
7347
7873
  );
7348
7874
  return {
7349
7875
  ...created,
7350
- content: text,
7876
+ content: text2,
7351
7877
  ...attachments.length ? { attachmentFiles: attachments } : {}
7352
7878
  };
7353
7879
  }
@@ -7407,9 +7933,9 @@ async function resolveRecipient(arbi, ref) {
7407
7933
  }
7408
7934
  return null;
7409
7935
  }
7410
- async function sendDirectMessage(arbi, crypto2, peerExtId, text, options) {
7936
+ async function sendDirectMessage(arbi, crypto2, peerExtId, text2, options) {
7411
7937
  const chat = await openDirectChat(arbi, peerExtId);
7412
- return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text, options);
7938
+ return sendChatMessage(arbi, await openChatKeyRing(chat, crypto2), text2, options);
7413
7939
  }
7414
7940
  async function loadDecryptedChat(arbi, crypto2, chat, options) {
7415
7941
  const ring = await openChatKeyRing(chat, crypto2);
@@ -8141,19 +8667,19 @@ function minorDigits(currency) {
8141
8667
  throw new Error(`Unknown currency "${currency}": use an ISO 4217 code such as GBP or USD`);
8142
8668
  }
8143
8669
  }
8144
- function parseBudget(text) {
8145
- const t2 = text.trim();
8670
+ function parseBudget(text2) {
8671
+ const t2 = text2.trim();
8146
8672
  const after = /^([0-9][0-9,_]*(?:\.[0-9]+)?)\s*([A-Za-z]{3})$/.exec(t2);
8147
8673
  const before = /^([A-Za-z]{3})\s*([0-9][0-9,_]*(?:\.[0-9]+)?)$/.exec(t2);
8148
8674
  const [amountText, code] = after ? [after[1], after[2]] : before ? [before[2], before[1]] : [];
8149
8675
  if (!amountText || !code)
8150
- throw new Error(`Invalid budget "${text}": use an amount and a currency, e.g. 6000GBP`);
8676
+ throw new Error(`Invalid budget "${text2}": use an amount and a currency, e.g. 6000GBP`);
8151
8677
  const currency = code.toUpperCase();
8152
8678
  const digits = minorDigits(currency);
8153
8679
  const major = Number(amountText.replace(/[,_]/g, ""));
8154
8680
  const amount = Math.round(major * 10 ** digits);
8155
8681
  if (!Number.isFinite(major) || Math.abs(major * 10 ** digits - amount) > 1e-6)
8156
- throw new Error(`Invalid budget "${text}": ${currency} has ${digits} decimal places`);
8682
+ throw new Error(`Invalid budget "${text2}": ${currency} has ${digits} decimal places`);
8157
8683
  return { amount, currency };
8158
8684
  }
8159
8685
  function formatBudget(budget) {
@@ -9411,15 +9937,15 @@ function listMessages(mail, options) {
9411
9937
  if (options.limit) params.set("limit", String(options.limit));
9412
9938
  return json(mail(`${accountPath(options.accountId ?? NATIVE_ACCOUNT)}/messages?${params}`));
9413
9939
  }
9414
- function getMessage2(mail, messageId, accountId = NATIVE_ACCOUNT) {
9415
- return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}`));
9940
+ function getMessage2(mail, messageId2, accountId = NATIVE_ACCOUNT) {
9941
+ return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`));
9416
9942
  }
9417
- async function downloadAttachment(mail, messageId, attachmentId, accountId = NATIVE_ACCOUNT) {
9418
- const path5 = `${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`;
9943
+ async function downloadAttachment(mail, messageId2, attachmentId, accountId = NATIVE_ACCOUNT) {
9944
+ const path5 = `${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}/attachments/${encodeURIComponent(attachmentId)}`;
9419
9945
  return new Uint8Array(await (await mail(path5)).arrayBuffer());
9420
9946
  }
9421
- async function updateMessage(mail, messageId, update, accountId = NATIVE_ACCOUNT) {
9422
- await mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId)}`, {
9947
+ async function updateMessage(mail, messageId2, update, accountId = NATIVE_ACCOUNT) {
9948
+ await mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`, {
9423
9949
  method: "PATCH",
9424
9950
  body: JSON.stringify(update)
9425
9951
  });
@@ -10054,10 +10580,10 @@ var LANGUAGE_PATTERN = /^[a-z]{2}$/;
10054
10580
  var PROMPT_MAX_CHARS = 500;
10055
10581
  var PROMPT_CONTEXT_CHARS = 200;
10056
10582
  function continuityPrompt(previous) {
10057
- const text = previous?.replace(/\s+/g, " ").trim();
10058
- if (!text) return void 0;
10059
- if (text.length <= PROMPT_CONTEXT_CHARS) return text;
10060
- const tail = text.slice(-PROMPT_CONTEXT_CHARS);
10583
+ const text2 = previous?.replace(/\s+/g, " ").trim();
10584
+ if (!text2) return void 0;
10585
+ if (text2.length <= PROMPT_CONTEXT_CHARS) return text2;
10586
+ const tail = text2.slice(-PROMPT_CONTEXT_CHARS);
10061
10587
  const space = tail.indexOf(" ");
10062
10588
  const trimmed = space >= 0 && space < tail.length - 1 ? tail.slice(space + 1) : tail;
10063
10589
  return trimmed || void 0;
@@ -11597,8 +12123,8 @@ var Arbi = class {
11597
12123
  });
11598
12124
  return runConversation(client, conversationId);
11599
12125
  },
11600
- getMessage: (messageId) => getMessage(this.requireClient(), messageId),
11601
- deleteMessage: (messageId) => deleteMessage(this.requireClient(), messageId),
12126
+ getMessage: (messageId2) => getMessage(this.requireClient(), messageId2),
12127
+ deleteMessage: (messageId2) => deleteMessage(this.requireClient(), messageId2),
11602
12128
  /**
11603
12129
  * Post a human comment (no assistant run) — see `postConversationMessage`. A thread in another
11604
12130
  * workspace than the current one works too: its key is handed to the session on demand.
@@ -11684,8 +12210,53 @@ var Arbi = class {
11684
12210
  });
11685
12211
  }
11686
12212
  };
12213
+ async openResponseHandle(open, options, id) {
12214
+ const controller = new AbortController();
12215
+ const abort = () => controller.abort();
12216
+ options.signal?.addEventListener("abort", abort, { once: true });
12217
+ if (options.signal?.aborted) controller.abort();
12218
+ const cleanup = () => options.signal?.removeEventListener("abort", abort);
12219
+ try {
12220
+ const response = await this.recovering(() => open(controller.signal));
12221
+ return await consumeResponse(
12222
+ response,
12223
+ controller,
12224
+ (responseId) => this.assistant.cancel(responseId),
12225
+ { id, cleanup }
12226
+ );
12227
+ } catch (error) {
12228
+ cleanup();
12229
+ controller.abort();
12230
+ throw error;
12231
+ }
12232
+ }
11687
12233
  // ── Assistant ─────────────────────────────────────────────────────────
11688
12234
  assistant = {
12235
+ /** Start one response with a composable observer; existing ask callbacks remain unchanged. */
12236
+ startResponse: async (request, options = {}) => {
12237
+ const body = buildTurnRequest({
12238
+ ...request,
12239
+ workspaceId: request.workspaceId ?? this.requireWorkspace()
12240
+ });
12241
+ return this.openResponseHandle(
12242
+ (signal) => openTurnStream(this.getAuthHeaders(), body, signal),
12243
+ options
12244
+ );
12245
+ },
12246
+ /** Attach to retained replay/live events for an existing msg; never resubmits a turn. */
12247
+ attachResponse: async (id, options = {}) => {
12248
+ if (!/^msg-[\w-]+$/.test(id))
12249
+ throw new ArbiError("Expected an assistant message ID (msg-\u2026).", {
12250
+ code: "INVALID_RESPONSE_ID"
12251
+ });
12252
+ const result = await this.openResponseHandle(
12253
+ (signal) => openRunStream(this.getAuthHeaders(), id, signal),
12254
+ options,
12255
+ id
12256
+ );
12257
+ if (result.kind !== "response") throw new ArbiError("Expected a response attachment.");
12258
+ return result.handle;
12259
+ },
11689
12260
  /**
11690
12261
  * Ask the assistant: send one turn (the body is `buildTurnRequest`) and stream it into
11691
12262
  * `handlers`. Resolves with the accumulated result when the stream ends.
@@ -11714,12 +12285,20 @@ var Arbi = class {
11714
12285
  if (isAbort(error)) throw error;
11715
12286
  if (error instanceof AssistantTurnRefused) {
11716
12287
  if (error.quota) onQuotaExceeded?.(error.quota);
11717
- return refuse(error.message);
12288
+ callbacks.onErrorDetails?.(error);
12289
+ return refuse(error.message, error);
11718
12290
  }
11719
12291
  if (error instanceof ArbiSessionExpiredError || error instanceof ArbiApiError && error.status === 401) {
11720
12292
  const message = SESSION_EXPIRED_MESSAGE;
11721
- return refuse(message, new ArbiSessionExpiredError(message));
12293
+ const expired = error instanceof ArbiSessionExpiredError ? error : new ArbiSessionExpiredError(message, {
12294
+ cause: error,
12295
+ requestId: error.requestId,
12296
+ responseId: error.responseId
12297
+ });
12298
+ callbacks.onErrorDetails?.(expired);
12299
+ return refuse(message, expired);
11722
12300
  }
12301
+ if (error instanceof ArbiError) callbacks.onErrorDetails?.(error);
11723
12302
  onError?.(error);
11724
12303
  throw error;
11725
12304
  }
@@ -12031,12 +12610,12 @@ var Arbi = class {
12031
12610
  );
12032
12611
  },
12033
12612
  /** Post plaintext to a chat (encrypted under its current epoch). Returns it decrypted. */
12034
- send: async (chat, text, options) => {
12613
+ send: async (chat, text2, options) => {
12035
12614
  const ready = await this.readyChat(chat);
12036
12615
  return sendChatMessage(
12037
12616
  this.requireClient(),
12038
12617
  await this.chatRing(ready),
12039
- text,
12618
+ text2,
12040
12619
  options
12041
12620
  );
12042
12621
  },
@@ -12298,7 +12877,7 @@ var Arbi = class {
12298
12877
  * Send an E2E-encrypted direct message: resolves the peer, opens (get-or-create) the direct
12299
12878
  * chat and posts under the pair key. The caller passes plaintext and never handles keys.
12300
12879
  */
12301
- send: async (recipient, text) => {
12880
+ send: async (recipient, text2) => {
12302
12881
  const client = this.requireClient();
12303
12882
  const resolved = await resolveRecipient(client, recipient);
12304
12883
  if (!resolved) {
@@ -12310,15 +12889,15 @@ var Arbi = class {
12310
12889
  client,
12311
12890
  await this.requireChatCrypto(),
12312
12891
  resolved.extId,
12313
- text
12892
+ text2
12314
12893
  );
12315
12894
  },
12316
12895
  /** Send to a peer whose external id is already known, skipping directory resolution. */
12317
- sendTo: async (peerExtId, text) => sendDirectMessage(
12896
+ sendTo: async (peerExtId, text2) => sendDirectMessage(
12318
12897
  this.requireClient(),
12319
12898
  await this.requireChatCrypto(),
12320
12899
  peerExtId,
12321
- text
12900
+ text2
12322
12901
  ),
12323
12902
  /** Resolve a recipient reference to `{ extId, pubKey }` (contacts → agents → workspace). */
12324
12903
  resolveRecipient: (recipient) => resolveRecipient(this.requireClient(), recipient),
@@ -14065,8 +14644,8 @@ function getStepDisplay(step, docInfo = {}) {
14065
14644
  function getAgentStepLabel(step, docInfo = {}) {
14066
14645
  const { label, summary, isMultiLine } = getStepDisplay(step, docInfo);
14067
14646
  const narrative = summary && !isMultiLine && !step.reasoning ? summary : null;
14068
- const text = narrative ? `${label} \u2014 ${narrative}` : label;
14069
- return text.length > 120 ? `${text.slice(0, 119)}\u2026` : text;
14647
+ const text2 = narrative ? `${label} \u2014 ${narrative}` : label;
14648
+ return text2.length > 120 ? `${text2.slice(0, 119)}\u2026` : text2;
14070
14649
  }
14071
14650
  function getCurrentStep(steps) {
14072
14651
  const merged = mergeAgentSteps(steps);
@@ -14130,9 +14709,9 @@ function newestThread(threads) {
14130
14709
  function pickMainThread(threads) {
14131
14710
  return newestThread(threads.filter((t2) => !t2.history.some((m2) => getSubagentBranchRecord(m2)))) ?? threads.find((t2) => tailTaskMessageIndex(t2.history) < 0) ?? threads[0];
14132
14711
  }
14133
- function findSubagentRunId(threads, messageId) {
14712
+ function findSubagentRunId(threads, messageId2) {
14134
14713
  for (const thread of threads) {
14135
- const index = thread.history.findIndex((m2) => m2.external_id === messageId);
14714
+ const index = thread.history.findIndex((m2) => m2.external_id === messageId2);
14136
14715
  if (index < 0) continue;
14137
14716
  const taskIndex = tailTaskMessageIndex(thread.history);
14138
14717
  if (taskIndex >= 0 && taskIndex <= index) {
@@ -14288,6 +14867,6 @@ function getRunToAttach(localGeneration, messages) {
14288
14867
  return getAttachableRunId(messages);
14289
14868
  }
14290
14869
 
14291
- export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, CallApiError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, 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, createDocumentWaiter, createIndexAssigner, databases_exports as databases, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, 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, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
14870
+ export { ACCOUNT_VENDOR, Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ArbiTransportError, ArbiWorkspaceChangedError, ArbiWorkspaceSupersededError, CallApiError, ClaudeOrchestrator, DEFAULT_AI_USD_PER_GBP, DOC_TERMINAL_STATUSES, DRIVE_SYNC_VENDORS, DuplicateContactError, ENTITY_KINDS, FLAT_TAG_KINDS, FileConfigStore, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, OpenClawOrchestrator, PRESENCE_KINDS, PROMPT_CONTEXT_CHARS, PlanStepsError, PublicBookingError, SHAREPOINT_VENDORS, STEP_FIELD_OPTION_TONES, STOP_ID_WAIT_MS, STOP_REPEAT_WINDOW_MS, TAG_KINDS, TAG_NESTING_MAX_DEPTH, WebSocketAuthError, account_exports as account, agentconfig_exports as agentconfig, agents_exports as agents, appendTranscriptionHints, assistant_exports as assistant, authenticatedFetch, bookPublicSlot, buildCitationChunkData, buildDocNameMap, 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, createDocumentWaiter, createIndexAssigner, databases_exports as databases, defaultKindForFormat, device_flow_exports as deviceFlow, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, estimateDraftTokens, extractDocumentIdsFromMessages, extractFactIdsFromMessages, extractSubagentLanes, facts_exports as facts, files_exports as files, filterDocumentTags, filterSkills, findLeafForTaskMessage, findMainSiblingLeaf, findReplyTarget, findSubagentRunId, firm_exports as firm, flattenTagTree, formatAgentStepLabel, formatFileSize, formatGbp, formatGbpPerMillionTokens, formatItemLabel, formatStreamSummary, formatTokens, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getAgentStepLabel, getAttachableRunId, getChildTags, getContextRemainingPercent, getContextUsedPercent, getContextUsedTokens, getCurrentStep, getEligibleParentTags, getErrorCode, getErrorMessage, getPublicBookingPage, getRawWorkspaceKey, getRunToAttach, getRunToCancel, getStepDisplay, getStepTool, getSubagentBranchRecord, getTagDescendantIds, health_exports as health, house_template_exports as houseTemplates, hydrateAgentSteps, identityErrorCode, identity_exports as identityVerification, isAnnotationTag, isConnectorVendorVisible, isDriveSyncVendor, isEntityTag, isFlatKind, isLabelTag, isMailboxSyncVendor, isNearAiUsageBudget, isPresenceTag, isSharePointVendor, isSharedSkill, isTraceItem, listen_exports as listen, mail_exports as mail, mail_node_exports as mailNode, mergeAgentSteps, notifications_exports as notifications, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, 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, signature_requests_exports as signatureRequests, sliceToSubagentThread, startDmListener, streamSSE, stripCitationMarkdown, subagentJobLabel, summarizeCitations, tagUseCount, tags_exports as tags, tagsForScope, tagsOfGroup, topLevelAgentSteps, uploadSkill, usdToGbp, work_exports as work, workflow_steps_exports as workflowSteps, workflows_exports as workflows, workspaces_exports as workspaces, wouldCreateTagCycle };
14292
14871
  //# sourceMappingURL=index.js.map
14293
14872
  //# sourceMappingURL=index.js.map