@astralbeam/sdk 0.29.6 → 0.30.2

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.
@@ -532,7 +532,7 @@ function normalizeMessagesDates(messages) {
532
532
  return messages.map(normalizeMessageDates);
533
533
  }
534
534
  //#endregion
535
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/ag-ui-usage.js
535
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/ag-ui-usage.js
536
536
  function definedDetails(value) {
537
537
  return Object.keys(value).length > 0 ? value : void 0;
538
538
  }
@@ -577,7 +577,7 @@ function fromSpecTokenUsage(usage, leftover) {
577
577
  };
578
578
  }
579
579
  //#endregion
580
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/merge-metadata.js
580
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/merge-metadata.js
581
581
  function isPlainRecord$1(value) {
582
582
  return value != null && typeof value === "object" && !Array.isArray(value);
583
583
  }
@@ -656,7 +656,7 @@ let EventType = /* @__PURE__ */ function(EventType) {
656
656
  return EventType;
657
657
  }({});
658
658
  //#endregion
659
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/tool-call-arguments.js
659
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/tool-call-arguments.js
660
660
  function sameJsonValue(left, right) {
661
661
  if (Object.is(left, right)) return true;
662
662
  if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((value, index) => sameJsonValue(value, right[index]));
@@ -821,7 +821,7 @@ function finishToolCallArguments(streamed, end) {
821
821
  };
822
822
  }
823
823
  //#endregion
824
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/reasoning-encrypted-value.js
824
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/reasoning-encrypted-value.js
825
825
  /**
826
826
  * Id prefix for the reasoning message of a redacted thinking block (Anthropic
827
827
  * `redacted_thinking`). AG-UI's `encryptedValue` does not say what kind of
@@ -833,7 +833,7 @@ function isRedactedThinkingId(id) {
833
833
  return typeof id === "string" && id.startsWith("redacted_thinking-");
834
834
  }
835
835
  //#endregion
836
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupt-serialization.js
836
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupt-serialization.js
837
837
  var SHA256_K = new Uint32Array([
838
838
  1116352408,
839
839
  1899447441,
@@ -1008,7 +1008,7 @@ function cloneAndDeepFreezeJson(value) {
1008
1008
  return clone;
1009
1009
  }
1010
1010
  //#endregion
1011
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupts.js
1011
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupts.js
1012
1012
  function canonicalizeInterruptResolutions(resolutions) {
1013
1013
  const frozen = cloneAndDeepFreezeJson([...resolutions].sort((left, right) => left.interruptId.localeCompare(right.interruptId)));
1014
1014
  const canonicalResolutions = canonicalInterruptJson(frozen);
@@ -1019,7 +1019,7 @@ function canonicalizeInterruptResolutions(resolutions) {
1019
1019
  });
1020
1020
  }
1021
1021
  //#endregion
1022
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/schema-converter.js
1022
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/schema-converter.js
1023
1023
  /**
1024
1024
  * Build a JSONSchema object from any plain key/value source. The `JSONSchema`
1025
1025
  * interface's `[key: string]: any` index signature makes every property
@@ -1287,7 +1287,7 @@ async function validateWithStandardSchema(schema, data) {
1287
1287
  };
1288
1288
  }
1289
1289
  //#endregion
1290
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/approval-schema.js
1290
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/approval-schema.js
1291
1291
  var jsonSchemaKeywords = /* @__PURE__ */ new Set([
1292
1292
  "$schema",
1293
1293
  "$id",
@@ -1401,7 +1401,7 @@ function hashSchemaInput(schema) {
1401
1401
  return digestInterruptJson(canonicalInterruptJson(schemaToWire(schema).jsonSchema ?? { standardValidator: "unserialized" }));
1402
1402
  }
1403
1403
  //#endregion
1404
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupt-resume.js
1404
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupt-resume.js
1405
1405
  /**
1406
1406
  * The `Interrupt.metadata` key under which this package's resume binding
1407
1407
  * travels.
@@ -1522,7 +1522,7 @@ function readInterruptBinding(descriptor) {
1522
1522
  };
1523
1523
  }
1524
1524
  //#endregion
1525
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupt-definition.js
1525
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/interrupt-definition.js
1526
1526
  var INTERRUPT_PAYLOAD_METADATA_KEY = "tanstack:interruptPayload";
1527
1527
  function schemaJson(schema, name) {
1528
1528
  if (!isStandardJSONSchema(schema)) throw new TypeError(`${name} must be a Standard Schema with a JSON Schema converter.`);
@@ -1547,7 +1547,7 @@ function hashInterruptDefinitionSchema(schema) {
1547
1547
  return digestInterruptJson(schemaJson(schema, "Interrupt schema").canonicalJson);
1548
1548
  }
1549
1549
  //#endregion
1550
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/generic-interrupt-continuation.js
1550
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/generic-interrupt-continuation.js
1551
1551
  /**
1552
1552
  * `ResumeEntry.metadata` key for a first-party generic request.
1553
1553
  *
@@ -1586,7 +1586,7 @@ function genericInterruptContinuationFromDescriptor(interrupt) {
1586
1586
  };
1587
1587
  }
1588
1588
  //#endregion
1589
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/subagent-wire.js
1589
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/subagent-wire.js
1590
1590
  function isRecord$2(value) {
1591
1591
  return typeof value === "object" && value !== null && !Array.isArray(value);
1592
1592
  }
@@ -1700,7 +1700,7 @@ function splitSubagentWire(messages) {
1700
1700
  };
1701
1701
  }
1702
1702
  //#endregion
1703
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/provider-executed.js
1703
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/provider-executed.js
1704
1704
  /**
1705
1705
  * Narrow a tool call's opaque `metadata` to the provider-executed convention.
1706
1706
  * Returns the typed metadata when the call is provider-executed, else `null`.
@@ -1730,7 +1730,7 @@ function isAssistantSegmentOf(id, parentId) {
1730
1730
  return id?.startsWith(`${parentId}-segment-`) === true;
1731
1731
  }
1732
1732
  //#endregion
1733
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/tool-result.js
1733
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/tool-result.js
1734
1734
  var CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
1735
1735
  "text",
1736
1736
  "image",
@@ -1791,7 +1791,7 @@ function normalizeToolResult(result) {
1791
1791
  return JSON.stringify(result);
1792
1792
  }
1793
1793
  //#endregion
1794
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/block-order.js
1794
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/block-order.js
1795
1795
  /**
1796
1796
  * The order map for these entries in produced order, or undefined when they
1797
1797
  * are in the default order (all thinking, then text, then tool calls).
@@ -1879,7 +1879,7 @@ function orderedAssistantBlocks(message) {
1879
1879
  return blocks;
1880
1880
  }
1881
1881
  //#endregion
1882
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/messages.js
1882
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/messages.js
1883
1883
  function isRecord$1(value) {
1884
1884
  return typeof value === "object" && value !== null && !Array.isArray(value);
1885
1885
  }
@@ -2591,7 +2591,7 @@ function generateMessageId() {
2591
2591
  return `msg-${Date.now()}-${Math.random().toString(36).substring(7)}`;
2592
2592
  }
2593
2593
  //#endregion
2594
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/ag-ui-wire.js
2594
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/ag-ui-wire.js
2595
2595
  function isRecord(value) {
2596
2596
  return typeof value === "object" && value !== null && !Array.isArray(value);
2597
2597
  }
@@ -2974,7 +2974,7 @@ function hashContent(s) {
2974
2974
  return Math.abs(h).toString(36);
2975
2975
  }
2976
2976
  //#endregion
2977
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/restore-inbound-chunk.js
2977
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/restore-inbound-chunk.js
2978
2978
  /**
2979
2979
  * Rebuild TanStack `TokenUsage` (`promptTokens`) from spec `usage[]` plus
2980
2980
  * leftover fields in `metadata.tanstack.usage`. Restore the in-process field
@@ -3011,7 +3011,7 @@ function restoreInboundChunk(chunk) {
3011
3011
  return next;
3012
3012
  }
3013
3013
  //#endregion
3014
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/tool-definition.js
3014
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/tools/tool-definition.js
3015
3015
  /**
3016
3016
  * Create an isomorphic tool definition that can be used directly or instantiated for server/client
3017
3017
  *
@@ -3109,7 +3109,7 @@ function toolDefinition(config) {
3109
3109
  };
3110
3110
  }
3111
3111
  //#endregion
3112
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/chunk-ids.js
3112
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/chunk-ids.js
3113
3113
  function stringField(value) {
3114
3114
  return typeof value === "string" && value !== "" ? value : void 0;
3115
3115
  }
@@ -3212,7 +3212,7 @@ var require_options = /* @__PURE__ */ __commonJSMin(((exports) => {
3212
3212
  exports.default = exports.Allow;
3213
3213
  }));
3214
3214
  //#endregion
3215
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/json-parser.js
3215
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/json-parser.js
3216
3216
  var import_dist = (/* @__PURE__ */ __commonJSMin(((exports, module, this$1) => {
3217
3217
  var __createBinding = this$1 && this$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
3218
3218
  if (k2 === void 0) k2 = k;
@@ -3434,7 +3434,7 @@ function parsePartialJSON(jsonString) {
3434
3434
  return defaultJSONParser.parse(jsonString);
3435
3435
  }
3436
3436
  //#endregion
3437
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/strategies.js
3437
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/strategies.js
3438
3438
  /**
3439
3439
  * Immediate Strategy - emit on every chunk (default behavior)
3440
3440
  */
@@ -3444,7 +3444,7 @@ var ImmediateStrategy = class {
3444
3444
  }
3445
3445
  };
3446
3446
  //#endregion
3447
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/errors.js
3447
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/utilities/errors.js
3448
3448
  /**
3449
3449
  * Convert an AG-UI RUN_ERROR event to the Error shape exposed to consumers.
3450
3450
  * Preserves the provider code and sanitized raw event when available.
@@ -4105,7 +4105,7 @@ var fast_json_patch_default = Object.assign({}, core_exports, duplex_exports, {
4105
4105
  unescapePathComponent
4106
4106
  });
4107
4107
  //#endregion
4108
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/activity-records.js
4108
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/activity-records.js
4109
4109
  function isActivityPart(part) {
4110
4110
  return part.type === "activity";
4111
4111
  }
@@ -4181,7 +4181,7 @@ function applyActivityDeltaToUIMessages(messages, chunk) {
4181
4181
  }
4182
4182
  }
4183
4183
  //#endregion
4184
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/message-updaters.js
4184
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/message-updaters.js
4185
4185
  /**
4186
4186
  * Message Updaters (Internal)
4187
4187
  *
@@ -4483,7 +4483,7 @@ function updateThinkingPart(messages, messageId, stepId, content, signature) {
4483
4483
  });
4484
4484
  }
4485
4485
  //#endregion
4486
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/processor.js
4486
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/activities/chat/stream/processor.js
4487
4487
  /**
4488
4488
  * Unified Stream Processor
4489
4489
  *
@@ -4569,6 +4569,7 @@ var StreamProcessor = class StreamProcessor {
4569
4569
  sealedMessageIds = /* @__PURE__ */ new Set();
4570
4570
  thinkingOwners = /* @__PURE__ */ new Map();
4571
4571
  runToolCallIds = [];
4572
+ handOverAtStreamEnd = false;
4572
4573
  toolCallsSentToClient = /* @__PURE__ */ new Set();
4573
4574
  childProcessors = /* @__PURE__ */ new Map();
4574
4575
  childToolCalls = /* @__PURE__ */ new Map();
@@ -6007,6 +6008,7 @@ var StreamProcessor = class StreamProcessor {
6007
6008
  if (this.activeRuns.size === 0) {
6008
6009
  this.runToolCallIds = [];
6009
6010
  this.toolCallsSentToClient.clear();
6011
+ this.handOverAtStreamEnd = false;
6010
6012
  this.streamEndEmitted = false;
6011
6013
  }
6012
6014
  this.activeRuns.add(chunk.runId);
@@ -6041,6 +6043,7 @@ var StreamProcessor = class StreamProcessor {
6041
6043
  this.completeAllToolCalls();
6042
6044
  if (this.finishReason === "tool_calls" && chunk.outcome?.type !== "interrupt") {
6043
6045
  for (const id of ids) this.sealedMessageIds.add(id);
6046
+ this.handOverAtStreamEnd = this.subagentRunId === void 0;
6044
6047
  return;
6045
6048
  }
6046
6049
  if (!chunk.outcome || chunk.outcome.type === "success") this.handlePendingToolCalls(chunk.outcome?.pendingToolCallIds);
@@ -6449,6 +6452,10 @@ var StreamProcessor = class StreamProcessor {
6449
6452
  * @see docs/chat-architecture.md#single-shot-text-response — Finalization step
6450
6453
  */
6451
6454
  finalizeStream() {
6455
+ if (this.handOverAtStreamEnd) {
6456
+ this.handOverAtStreamEnd = false;
6457
+ if (!this.hasError) this.handlePendingToolCalls();
6458
+ }
6452
6459
  this.isDone = true;
6453
6460
  for (const event of this.closeChunk()) this.dispatchChunk(event);
6454
6461
  this.closeChildChunkLanes();
@@ -6574,6 +6581,7 @@ var StreamProcessor = class StreamProcessor {
6574
6581
  this.thinkingOwners.clear();
6575
6582
  this.openChunk = null;
6576
6583
  this.finishReason = null;
6584
+ this.handOverAtStreamEnd = false;
6577
6585
  this.hasError = false;
6578
6586
  this.isDone = false;
6579
6587
  this.streamEndEmitted = false;
@@ -6612,7 +6620,7 @@ function createReplayStream(recording) {
6612
6620
  } };
6613
6621
  }
6614
6622
  //#endregion
6615
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/byok/errors.js
6623
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/byok/errors.js
6616
6624
  var ByokMissingError = class extends Error {
6617
6625
  provider;
6618
6626
  constructor(provider) {
@@ -6638,14 +6646,14 @@ var ByokUnresolvedProviderError = class extends Error {
6638
6646
  }
6639
6647
  };
6640
6648
  //#endregion
6641
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/byok/providers.js
6649
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/byok/providers.js
6642
6650
  /** `[a-z][a-z0-9-]{0,63}` — lowercase, no underscores, max 64 chars. */
6643
6651
  var BYOK_PROVIDER_ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
6644
6652
  function isProviderId(value) {
6645
6653
  return typeof value === "string" && BYOK_PROVIDER_ID_PATTERN.test(value);
6646
6654
  }
6647
6655
  //#endregion
6648
- //#region ../node_modules/.bun/@tanstack+ai@1.0.1+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/byok/missing.js
6656
+ //#region ../node_modules/.bun/@tanstack+ai@1.2.0+ac75b968c23456b3/node_modules/@tanstack/ai/dist/esm/byok/missing.js
6649
6657
  function isByokMissingBody(value) {
6650
6658
  if (typeof value !== "object" || value === null) return false;
6651
6659
  if (!("error" in value)) return false;
@@ -11384,9 +11392,9 @@ function buildHostTools(tools, debug, guardHostExecution) {
11384
11392
  context?.abortSignal?.throwIfAborted();
11385
11393
  const current = resolve?.() ?? tool;
11386
11394
  started = true;
11387
- const output = await current.execute(validated);
11395
+ let output = await current.execute(validated);
11388
11396
  try {
11389
- canonicalInterruptJson(output);
11397
+ output = cloneAndDeepFreezeJson(output);
11390
11398
  } catch {
11391
11399
  throw new Error(`Tool "${name}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`);
11392
11400
  }
@@ -11394,8 +11402,9 @@ function buildHostTools(tools, debug, guardHostExecution) {
11394
11402
  return output;
11395
11403
  } catch (error) {
11396
11404
  debug?.("error", `host tool "${name}" threw`, { error });
11397
- if (!started && error instanceof Error) Object.assign(error, { [HOST_TOOL_NOT_EXECUTED]: true });
11398
- throw error;
11405
+ const failure = error instanceof Error ? error : new Error(String(error));
11406
+ if (!started) Object.assign(failure, { [HOST_TOOL_NOT_EXECUTED]: true });
11407
+ throw failure;
11399
11408
  }
11400
11409
  }));
11401
11410
  }
@@ -11927,6 +11936,7 @@ function createAstralBeamChat(options, deferStart = false) {
11927
11936
  };
11928
11937
  let submission;
11929
11938
  const submissions = /* @__PURE__ */ new Map();
11939
+ let historyRead;
11930
11940
  let clientStatus = "ready";
11931
11941
  let operation;
11932
11942
  const update = (next) => {
@@ -11934,12 +11944,15 @@ function createAstralBeamChat(options, deferStart = false) {
11934
11944
  state = {
11935
11945
  ...state,
11936
11946
  ...next,
11937
- status
11947
+ status,
11948
+ history: historyRead?.phase ?? "idle"
11938
11949
  };
11939
11950
  for (const listener of listeners) listener();
11940
11951
  };
11952
+ const currentAuthority = (owner) => owner.client === client && owner.selection === selectionGeneration;
11953
+ const currentOperation = (owner) => operation === owner && currentAuthority(owner);
11941
11954
  const finishOperation = (owner) => {
11942
- if (operation !== owner) return;
11955
+ if (!currentOperation(owner)) return;
11943
11956
  operation = void 0;
11944
11957
  update({});
11945
11958
  };
@@ -11966,12 +11979,12 @@ function createAstralBeamChat(options, deferStart = false) {
11966
11979
  if (sent === submission) update({ submission: project(sent) });
11967
11980
  return true;
11968
11981
  };
11969
- const current = (sent, attempt) => sent === submission && operation === attempt;
11970
- const owns = (sent, attempt) => current(sent, attempt) && sent.phase === "submitting";
11971
- const endUnaccepted = (sent, error) => settle(sent, sent.tools ? "failed" : "refused", error ?? (sent.tools ? /* @__PURE__ */ new Error("This message may not have been sent. Retry to send it.") : void 0));
11982
+ const currentAttempt = (attempt) => attempt.submission === submission && currentOperation(attempt);
11983
+ const ownsAttempt = (attempt) => currentAttempt(attempt) && attempt.submission.phase === "submitting";
11984
+ const endUnaccepted = (sent, error) => sent.delivery.state === "undispatched" ? settle(sent, "refused", error) : settle(sent, "failed", error ?? /* @__PURE__ */ new Error("This message may not have been sent. Retry to send it."));
11972
11985
  const releaseSubmission = (reason) => {
11973
11986
  const released = submission;
11974
- if (released?.phase === "submitting") endUnaccepted(released, released.tools ? void 0 : new Error(reason));
11987
+ if (released?.phase === "submitting") endUnaccepted(released, released.delivery.state === "uncertain" ? void 0 : new Error(reason));
11975
11988
  if (released?.phase === "refused") released.onRefused?.();
11976
11989
  submission = void 0;
11977
11990
  return released;
@@ -11987,8 +12000,23 @@ function createAstralBeamChat(options, deferStart = false) {
11987
12000
  let started = false;
11988
12001
  let selectionGeneration = 0;
11989
12002
  let toolExecutionGeneration = 0;
11990
- let historyGeneration = 0;
11991
- let hydration = Promise.resolve();
12003
+ const waitForHistory = async (owner) => {
12004
+ while (currentAuthority(owner)) {
12005
+ const read = historyRead;
12006
+ try {
12007
+ await read?.completion;
12008
+ } catch (error) {
12009
+ if (read === historyRead) throw error;
12010
+ }
12011
+ if (read === historyRead) return;
12012
+ }
12013
+ };
12014
+ const waitToDispatch = async (attempt) => {
12015
+ await waitForHistory(attempt).catch(() => void 0);
12016
+ if (!ownsAttempt(attempt)) return false;
12017
+ if (state.history === "failed") throw new Error(HISTORY_FAILED);
12018
+ return true;
12019
+ };
11992
12020
  let requestController = new AbortController();
11993
12021
  let threadKey;
11994
12022
  let startWithNewThread = false;
@@ -12269,22 +12297,22 @@ function createAstralBeamChat(options, deferStart = false) {
12269
12297
  return tools;
12270
12298
  };
12271
12299
  const forwardedProps = () => live.debug ? { debug: true } : {};
12272
- const threadRequest = async (init, auth) => {
12300
+ const threadRequest = async (init, auth, owner) => {
12301
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12273
12302
  const thread = state.thread;
12274
12303
  if (!thread || typeof init.body !== "string") throw new Error("Open a conversation before sending.");
12275
- const generation = selectionGeneration;
12276
12304
  const body = JSON.parse(init.body);
12277
12305
  let path = getRunChatUrl();
12278
12306
  let payload;
12279
- const sent = body.messages.at(-1)?.role === "user" && submission?.phase === "submitting" ? submission : void 0;
12280
- const previouslyAttempted = sent?.tools !== void 0;
12307
+ const sent = body.messages.at(-1)?.role === "user" && owner.kind === "submission" && ownsAttempt(owner) ? owner.submission : void 0;
12308
+ const previousDelivery = sent?.delivery;
12281
12309
  if (sent) payload = {
12282
12310
  ...body,
12283
12311
  threadId: thread.id,
12284
12312
  resume: void 0,
12285
12313
  parentRunId: void 0,
12286
12314
  messages: [body.messages.at(-1)],
12287
- tools: sent.tools ??= body.tools,
12315
+ tools: previousDelivery?.state === "uncertain" ? previousDelivery.tools : body.tools,
12288
12316
  forwardedProps: {
12289
12317
  ...body.forwardedProps,
12290
12318
  clientId
@@ -12293,7 +12321,7 @@ function createAstralBeamChat(options, deferStart = false) {
12293
12321
  else {
12294
12322
  scopeCompletedToolCalls();
12295
12323
  const history = await loadThreadMessages(thread.id, auth, void 0, liveToolMessageIds);
12296
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12324
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12297
12325
  update({ thread: threadFromRecord(history.thread, history.messages.length > 0) });
12298
12326
  retainToolResults(history);
12299
12327
  const available = history.pendingInteractions.filter((pending) => toolResults.has(toolResultKey(pending.toolCallId)));
@@ -12320,24 +12348,30 @@ function createAstralBeamChat(options, deferStart = false) {
12320
12348
  update({ activeToolCallIds: [] });
12321
12349
  const headers = new Headers(init.headers);
12322
12350
  if (sent) headers.set("Idempotency-Key", sent.key);
12351
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12352
+ if (sent && sent.delivery.state === "undispatched") sent.delivery = {
12353
+ state: "uncertain",
12354
+ tools: body.tools
12355
+ };
12323
12356
  const response = await astralBeamChatFetch(path, {
12324
12357
  ...auth,
12325
12358
  ...init,
12326
12359
  headers,
12327
12360
  body: JSON.stringify(payload)
12328
12361
  }).catch((error) => {
12362
+ if (!currentOperation(owner)) throw error;
12363
+ if (sent && previousDelivery?.state === "undispatched" && isAstralBeamApiError(error) && (error.status === 400 || error.status === 413 || error.status === 429)) sent.delivery = { state: "undispatched" };
12329
12364
  const limit = isAstralBeamApiError(error) ? error.body?.usage_limit : void 0;
12330
12365
  if (limit) update({ usageLimitReached: {
12331
12366
  name: limit.name,
12332
12367
  resetsAt: limit.resets_at
12333
12368
  } });
12334
- if (sent && !previouslyAttempted && isAstralBeamApiError(error) && (error.status === 400 || error.status === 413 || error.status === 429)) delete sent.tools;
12335
12369
  throw error;
12336
12370
  });
12337
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12371
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12338
12372
  if (response.headers.get("Content-Type")?.includes("application/json")) {
12339
12373
  const receipt = await response.json();
12340
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12374
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12341
12375
  update({
12342
12376
  thread: {
12343
12377
  ...state.thread,
@@ -12350,7 +12384,7 @@ function createAstralBeamChat(options, deferStart = false) {
12350
12384
  });
12351
12385
  if (sent) {
12352
12386
  const history = await loadThreadMessages(thread.id, auth, void 0, liveToolMessageIds);
12353
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12387
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12354
12388
  const accepted = history.messages.find((message) => message.id === receipt.accepted_message_id);
12355
12389
  if (accepted) replaceAcceptedMessage(accepted);
12356
12390
  acceptSubmission();
@@ -12360,23 +12394,14 @@ function createAstralBeamChat(options, deferStart = false) {
12360
12394
  return response;
12361
12395
  };
12362
12396
  const connection = fetchServerSentEvents(() => resolveApiUrl(getRunChatUrl(), authentication.apiUrl), async () => {
12363
- const previousIdentity = identity;
12364
- const token = await getValidChatAuthToken(authentication);
12365
- if (previousIdentity !== void 0 && previousIdentity !== identity) throw new DOMException("Identity changed", "AbortError");
12366
- return { fetchClient: (_input, init) => {
12367
- const auth = {
12368
- apiUrl: authentication.apiUrl,
12369
- astralBeamToken: token,
12370
- ...init?.signal ? { signal: init.signal } : {},
12371
- cache: "no-store",
12372
- fetchClient: (input, request) => fetchAuthenticatedChat({
12373
- ...authentication,
12374
- input,
12375
- init: request
12376
- })
12377
- };
12378
- return threadRequest(init ?? {}, auth);
12379
- } };
12397
+ const owner = operation;
12398
+ if (!owner || !currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12399
+ const auth = await requestOptions();
12400
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12401
+ return { fetchClient: (_input, init) => threadRequest(init ?? {}, {
12402
+ ...auth,
12403
+ signal: init?.signal ?? auth.signal
12404
+ }, owner) };
12380
12405
  });
12381
12406
  const connect = connection.connect;
12382
12407
  connection.connect = async function* (...args) {
@@ -12427,11 +12452,11 @@ function createAstralBeamChat(options, deferStart = false) {
12427
12452
  page: { truncated: false }
12428
12453
  });
12429
12454
  const older = options?.before !== void 0;
12430
- const readGeneration = older ? historyGeneration : ++historyGeneration;
12431
- if (!options?.before) update({
12432
- olderMessagesLoading: false,
12433
- history: state.messages.length > 0 || state.thread?.hasMessages === false ? "refreshing" : "loading"
12434
- });
12455
+ const owner = older ? historyRead?.owner : {
12456
+ client: next,
12457
+ selection: selectionGeneration
12458
+ };
12459
+ const currentRead = () => owner !== void 0 && historyRead?.owner === owner && currentAuthority(owner);
12435
12460
  const read = (async () => {
12436
12461
  let history = await loadThreadMessages(threadId, await requestOptions(), options?.before, liveToolMessageIds);
12437
12462
  while (options?.before && history.messages.every((message) => message.role === "tool") && history.page_after) {
@@ -12441,7 +12466,7 @@ function createAstralBeamChat(options, deferStart = false) {
12441
12466
  messages: [...earlier.messages, ...history.messages]
12442
12467
  };
12443
12468
  }
12444
- if (client !== next || readGeneration !== historyGeneration) throw new DOMException("Conversation changed", "AbortError");
12469
+ if (!currentRead()) throw new DOMException("Conversation changed", "AbortError");
12445
12470
  if (!older) retainToolResults(history);
12446
12471
  threadRecords = older ? [...history.messages, ...threadRecords] : history.messages;
12447
12472
  const pageIds = new Set(history.messages.map((message) => message.id));
@@ -12469,15 +12494,22 @@ function createAstralBeamChat(options, deferStart = false) {
12469
12494
  } : { truncated: false }
12470
12495
  };
12471
12496
  })();
12472
- if (!older) {
12473
- hydration = read.then(() => "idle", () => "failed").then((history) => new Promise((resolve) => queueMicrotask(() => {
12474
- if (client === next && readGeneration === historyGeneration) {
12497
+ if (!older && owner) {
12498
+ const completion = read.then(() => "idle", () => "failed").then((history) => {
12499
+ if (historyRead && currentRead()) {
12500
+ historyRead.phase = history;
12475
12501
  if (unsubscribeSnapshot) observeSnapshot();
12476
- update({ history });
12502
+ update({});
12477
12503
  }
12478
- resolve();
12479
- }))).then(() => read);
12480
- hydration.catch(() => void 0);
12504
+ return read;
12505
+ });
12506
+ historyRead = {
12507
+ owner,
12508
+ phase: state.messages.length > 0 || state.thread?.hasMessages === false ? "refreshing" : "loading",
12509
+ completion
12510
+ };
12511
+ completion.catch(() => void 0);
12512
+ update({ olderMessagesLoading: false });
12481
12513
  }
12482
12514
  return read;
12483
12515
  }
@@ -12596,6 +12628,7 @@ function createAstralBeamChat(options, deferStart = false) {
12596
12628
  const replaceClient = (messages) => {
12597
12629
  const previous = client;
12598
12630
  operation = void 0;
12631
+ historyRead = void 0;
12599
12632
  unsubscribeSnapshot?.();
12600
12633
  unsubscribeSnapshot = void 0;
12601
12634
  snapshotMessages = void 0;
@@ -12643,6 +12676,7 @@ function createAstralBeamChat(options, deferStart = false) {
12643
12676
  threadToolResults.set(previousId, toolResults);
12644
12677
  }
12645
12678
  selectionGeneration++;
12679
+ historyRead = void 0;
12646
12680
  selectedId = threadId;
12647
12681
  requestController.abort();
12648
12682
  requestController = new AbortController();
@@ -12668,7 +12702,6 @@ function createAstralBeamChat(options, deferStart = false) {
12668
12702
  pendingInteractions: [],
12669
12703
  serverToolTitles: {},
12670
12704
  unavailableMcpConnections: [],
12671
- history: "idle",
12672
12705
  messagesCursor: void 0,
12673
12706
  olderMessagesLoading: false
12674
12707
  });
@@ -12681,7 +12714,10 @@ function createAstralBeamChat(options, deferStart = false) {
12681
12714
  if (submission) update({ submission: project(submission) });
12682
12715
  try {
12683
12716
  if (!started) attachClient();
12684
- await hydration;
12717
+ await waitForHistory({
12718
+ client,
12719
+ selection: generation
12720
+ });
12685
12721
  if (generation !== selectionGeneration) return;
12686
12722
  if (threadKey) selectedThread(threadKey, id);
12687
12723
  } catch (error) {
@@ -12707,11 +12743,12 @@ function createAstralBeamChat(options, deferStart = false) {
12707
12743
  else openThread(selected, restoring);
12708
12744
  } else if (!restoring) newThread();
12709
12745
  };
12710
- const ensureThread = async (sent, attempt) => {
12746
+ const ensureThread = async (attempt) => {
12711
12747
  if (state.thread) return;
12712
12748
  const options = await requestOptions();
12749
+ if (!ownsAttempt(attempt)) throw new DOMException("Send cancelled", "AbortError");
12713
12750
  const record = await createChatThread(live.agentId ? { agent_id: live.agentId } : {}, options);
12714
- if (!owns(sent, attempt)) throw new DOMException("Send cancelled", "AbortError");
12751
+ if (!ownsAttempt(attempt)) throw new DOMException("Send cancelled", "AbortError");
12715
12752
  selectedId = record.id;
12716
12753
  update({ thread: threadFromRecord(record, false) });
12717
12754
  resolveCapabilities();
@@ -12723,7 +12760,10 @@ function createAstralBeamChat(options, deferStart = false) {
12723
12760
  try {
12724
12761
  client.detach();
12725
12762
  attachClient();
12726
- await hydration;
12763
+ await waitForHistory({
12764
+ client,
12765
+ selection: generation
12766
+ });
12727
12767
  if (explicit && generation === selectionGeneration) update({ error: void 0 });
12728
12768
  } catch (error) {
12729
12769
  if (generation !== selectionGeneration) return;
@@ -12781,40 +12821,49 @@ function createAstralBeamChat(options, deferStart = false) {
12781
12821
  return;
12782
12822
  }
12783
12823
  const current = authenticationState(authentication);
12824
+ const key = toolResultKey(result.toolCallId);
12784
12825
  const pending = state.pendingInteractions.find((item) => item.toolCallId === result.toolCallId);
12785
12826
  const closure = !("tool" in result) && pending && (state.thread?.role === "manager" || current.status === "ready" && pending.targetTenantUserId === current.currentUser.user.id);
12786
12827
  const questionnaire = "tool" in result && result.tool === "ask_questionnaire" && current.status === "ready" && pending?.targetTenantUserId === current.currentUser.user.id;
12787
- if (state.thread?.role === "viewer" || !liveToolCalls.has(result.toolCallId) && !questionnaire && !closure && !toolResults.has(toolResultKey(result.toolCallId))) {
12828
+ if (state.thread?.role === "viewer" || !liveToolCalls.has(result.toolCallId) && !questionnaire && !closure && !toolResults.has(key)) {
12788
12829
  reportError(/* @__PURE__ */ new Error("This tool call belongs to another session and cannot be executed here."));
12789
12830
  return;
12790
12831
  }
12791
- if (closure && !toolResults.has(toolResultKey(result.toolCallId))) toolResults.set(toolResultKey(result.toolCallId), {
12792
- outcome: "unknown",
12793
- output: null
12794
- });
12795
- else if (!toolResults.has(toolResultKey(result.toolCallId)) && "tool" in result) {
12796
- const output = result.output;
12797
- toolResults.set(toolResultKey(result.toolCallId), {
12798
- outcome: result.state === "output-error" ? "failed" : "succeeded",
12799
- output: output ?? null
12832
+ if (!toolResults.has(key)) {
12833
+ if (closure) toolResults.set(key, {
12834
+ outcome: "unknown",
12835
+ output: null
12800
12836
  });
12837
+ else if ("tool" in result) {
12838
+ const output = result.output;
12839
+ toolResults.set(key, {
12840
+ outcome: result.state === "output-error" ? "failed" : "succeeded",
12841
+ output: output ?? null
12842
+ });
12843
+ }
12801
12844
  }
12802
- const owner = operation = {};
12845
+ const owner = {
12846
+ kind: "tool-result",
12847
+ client,
12848
+ selection: generation
12849
+ };
12850
+ operation = owner;
12803
12851
  try {
12804
12852
  update({});
12805
- if (operation !== owner) return;
12853
+ if (!currentOperation(owner)) return;
12806
12854
  scopeCompletedToolCalls();
12855
+ if (!currentOperation(owner)) return;
12807
12856
  if (pending) {
12808
- client.stop();
12857
+ owner.client.stop();
12809
12858
  await refreshThread(false);
12810
- if (operation !== owner || generation !== selectionGeneration) return;
12811
- await client.append({
12859
+ if (!currentOperation(owner)) return;
12860
+ await owner.client.append({
12812
12861
  role: "tool",
12813
12862
  toolCallId: result.toolCallId,
12814
12863
  content: JSON.stringify(toolResults.get(toolResultKey(result.toolCallId)))
12815
12864
  });
12816
- } else if ("tool" in result) await client.addToolResult(result);
12817
- if (operation === owner && generation === selectionGeneration) await refreshThread(false);
12865
+ } else if ("tool" in result) await owner.client.addToolResult(result);
12866
+ if (currentOperation(owner)) await refreshThread(false);
12818
12867
  } finally {
12819
12868
  finishOperation(owner);
12820
12869
  }
@@ -12822,23 +12871,28 @@ function createAstralBeamChat(options, deferStart = false) {
12822
12871
  const abandonToolCall = (toolCallId) => addToolResult({ toolCallId });
12823
12872
  const deliver = async (sent) => {
12824
12873
  if (sent !== submission || sent.phase !== "submitting") return project(sent);
12825
- const attempt = operation = {};
12874
+ const attempt = {
12875
+ kind: "submission",
12876
+ submission: sent,
12877
+ client,
12878
+ selection: selectionGeneration
12879
+ };
12880
+ operation = attempt;
12826
12881
  try {
12827
12882
  await getValidChatAuthToken(authentication);
12828
- await hydration.catch(() => void 0);
12829
- if (!owns(sent, attempt)) return project(sent);
12830
- if (state.history === "failed") throw new Error(HISTORY_FAILED);
12831
- await ensureThread(sent, attempt);
12832
- if (!owns(sent, attempt)) return project(sent);
12883
+ if (!await waitToDispatch(attempt)) return project(sent);
12884
+ await ensureThread(attempt);
12885
+ if (!ownsAttempt(attempt)) return project(sent);
12833
12886
  sent.callbacks?.onThreadReady?.(state.thread.id);
12834
- if (!owns(sent, attempt)) return project(sent);
12887
+ if (!ownsAttempt(attempt)) return project(sent);
12835
12888
  scopeCompletedToolCalls();
12836
- await client.sendMessage(sent.content);
12837
- if (!current(sent, attempt)) return project(sent);
12838
- endUnaccepted(sent, client.getError());
12839
- await refreshThread(false);
12889
+ if (!await waitToDispatch(attempt)) return project(sent);
12890
+ await attempt.client.sendMessage(sent.content);
12891
+ if (!currentAttempt(attempt)) return project(sent);
12892
+ endUnaccepted(sent, attempt.client.getError());
12893
+ if (currentAttempt(attempt)) await refreshThread(false);
12840
12894
  } catch (error) {
12841
- if (!current(sent, attempt)) return project(sent);
12895
+ if (!currentAttempt(attempt)) return project(sent);
12842
12896
  const failure = error instanceof Error ? error : new Error(String(error));
12843
12897
  if (failure.name === "AbortError") endUnaccepted(sent);
12844
12898
  else if (endUnaccepted(sent, failure)) notifyError(failure);
@@ -12860,6 +12914,7 @@ function createAstralBeamChat(options, deferStart = false) {
12860
12914
  content,
12861
12915
  phase: "submitting",
12862
12916
  key: newUuid(),
12917
+ delivery: { state: "undispatched" },
12863
12918
  callbacks
12864
12919
  };
12865
12920
  submission = sent;
@@ -13105,6 +13160,7 @@ function createAstralBeamChat(options, deferStart = false) {
13105
13160
  dispose: () => {
13106
13161
  releaseSubmission("The chat closed before this was sent.");
13107
13162
  operation = void 0;
13163
+ historyRead = void 0;
13108
13164
  unsubscribeSnapshot?.();
13109
13165
  unsubscribeSnapshot = void 0;
13110
13166
  client.detach();