@astralbeam/sdk 0.30.0 → 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.
package/README.md CHANGED
@@ -34,7 +34,7 @@ Without npm or a bundler, import the same entry from jsDelivr in a module script
34
34
  ```html
35
35
  <div id="sidebar" style="height:100dvh"></div>
36
36
  <script type="module">
37
- import { mountAstralBeamChat } from "https://cdn.jsdelivr.net/npm/@astralbeam/sdk@0.30.0/dist/client.js"
37
+ import { mountAstralBeamChat } from "https://cdn.jsdelivr.net/npm/@astralbeam/sdk@0.30.2/dist/client.js"
38
38
 
39
39
  mountAstralBeamChat(document.getElementById("sidebar"), {})
40
40
  </script>
package/dist/client.js CHANGED
@@ -48,4 +48,4 @@ import{s as e}from"./constants-C-Yp0Vhg.js";import{t}from"./debug-DLDY8CZb.js";i
48
48
  <header><span data-slot="chat-loading-title"></span></header>
49
49
  <button type="button" aria-label="Close chat">×</button>
50
50
  <div data-slot="chat-loading-status" role="status" data-loading>Loading chat…</div>
51
- `,c.append(l);let u=l.querySelector(`header`),d=l.querySelector(`[data-slot="chat-loading-title"]`),f=l.querySelector(`button`),p=l.querySelector(`[role="status"]`),m=()=>{d.textContent=a.title??`AstralBeam`,u.hidden=a.showHeader===!1,f.hidden=!a.onClose};m(),f.onclick=e=>{e.detail<2&&a.onClose?.()};let h=matchMedia(`(prefers-color-scheme: dark)`),g=/* @__PURE__ */ new Set,v=()=>{let{colorScheme:e,dark:t}=r(c,g,a,h.matches);o?.(`theme`,`color scheme "${e}" resolved to ${t?`dark`:`light`}`,{themeVariables:[...g]})};v(),h.addEventListener(`change`,v);let y=!1,b;return import(`./widget-Dv4lVfPt.js`).then(({renderChat:e})=>{o?.(`mount`,`chat chunk loaded`),y||(b=e(s,c,a))}).catch(()=>{y||(delete p.dataset.loading,p.textContent=`Could not load chat. Reload this page to try again.`)}),{update:e=>{let n={...a,...e};if(_(n),!!n.chat!=!!a.chat)throw Error(`Remount chat to change session ownership`);a=n,o=t(a.debug),o?.(`mount`,`options updated`,{changed:Object.keys(e)}),v(),m(),b?.update(a)},unmount:()=>{o?.(`mount`,`unmounting chat widget`),y=!0,h.removeEventListener(`change`,v),b?.dispose(),b=void 0,c.remove()}}}export{i as defineTool,a as defineWidget,v as mountAstralBeamChat,g as mountAstralBeamMcpServers,o as mountAstralBeamTenantList,s as mountAstralBeamTenantUserList,c as mountAstralBeamThreadList};
51
+ `,c.append(l);let u=l.querySelector(`header`),d=l.querySelector(`[data-slot="chat-loading-title"]`),f=l.querySelector(`button`),p=l.querySelector(`[role="status"]`),m=()=>{d.textContent=a.title??`AstralBeam`,u.hidden=a.showHeader===!1,f.hidden=!a.onClose};m(),f.onclick=e=>{e.detail<2&&a.onClose?.()};let h=matchMedia(`(prefers-color-scheme: dark)`),g=/* @__PURE__ */ new Set,v=()=>{let{colorScheme:e,dark:t}=r(c,g,a,h.matches);o?.(`theme`,`color scheme "${e}" resolved to ${t?`dark`:`light`}`,{themeVariables:[...g]})};v(),h.addEventListener(`change`,v);let y=!1,b;return import(`./widget-BY5hZkCs.js`).then(({renderChat:e})=>{o?.(`mount`,`chat chunk loaded`),y||(b=e(s,c,a))}).catch(()=>{y||(delete p.dataset.loading,p.textContent=`Could not load chat. Reload this page to try again.`)}),{update:e=>{let n={...a,...e};if(_(n),!!n.chat!=!!a.chat)throw Error(`Remount chat to change session ownership`);a=n,o=t(a.debug),o?.(`mount`,`options updated`,{changed:Object.keys(e)}),v(),m(),b?.update(a)},unmount:()=>{o?.(`mount`,`unmounting chat widget`),y=!0,h.removeEventListener(`change`,v),b?.dispose(),b=void 0,c.remove()}}}export{i as defineTool,a as defineWidget,v as mountAstralBeamChat,g as mountAstralBeamMcpServers,o as mountAstralBeamTenantList,s as mountAstralBeamTenantUserList,c as mountAstralBeamThreadList};
@@ -11392,9 +11392,9 @@ function buildHostTools(tools, debug, guardHostExecution) {
11392
11392
  context?.abortSignal?.throwIfAborted();
11393
11393
  const current = resolve?.() ?? tool;
11394
11394
  started = true;
11395
- const output = await current.execute(validated);
11395
+ let output = await current.execute(validated);
11396
11396
  try {
11397
- canonicalInterruptJson(output);
11397
+ output = cloneAndDeepFreezeJson(output);
11398
11398
  } catch {
11399
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.`);
11400
11400
  }
@@ -11402,8 +11402,9 @@ function buildHostTools(tools, debug, guardHostExecution) {
11402
11402
  return output;
11403
11403
  } catch (error) {
11404
11404
  debug?.("error", `host tool "${name}" threw`, { error });
11405
- if (!started && error instanceof Error) Object.assign(error, { [HOST_TOOL_NOT_EXECUTED]: true });
11406
- 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;
11407
11408
  }
11408
11409
  }));
11409
11410
  }
@@ -11935,6 +11936,7 @@ function createAstralBeamChat(options, deferStart = false) {
11935
11936
  };
11936
11937
  let submission;
11937
11938
  const submissions = /* @__PURE__ */ new Map();
11939
+ let historyRead;
11938
11940
  let clientStatus = "ready";
11939
11941
  let operation;
11940
11942
  const update = (next) => {
@@ -11942,12 +11944,15 @@ function createAstralBeamChat(options, deferStart = false) {
11942
11944
  state = {
11943
11945
  ...state,
11944
11946
  ...next,
11945
- status
11947
+ status,
11948
+ history: historyRead?.phase ?? "idle"
11946
11949
  };
11947
11950
  for (const listener of listeners) listener();
11948
11951
  };
11952
+ const currentAuthority = (owner) => owner.client === client && owner.selection === selectionGeneration;
11953
+ const currentOperation = (owner) => operation === owner && currentAuthority(owner);
11949
11954
  const finishOperation = (owner) => {
11950
- if (operation !== owner) return;
11955
+ if (!currentOperation(owner)) return;
11951
11956
  operation = void 0;
11952
11957
  update({});
11953
11958
  };
@@ -11974,12 +11979,12 @@ function createAstralBeamChat(options, deferStart = false) {
11974
11979
  if (sent === submission) update({ submission: project(sent) });
11975
11980
  return true;
11976
11981
  };
11977
- const current = (sent, attempt) => sent === submission && operation === attempt;
11978
- const owns = (sent, attempt) => current(sent, attempt) && sent.phase === "submitting";
11979
- 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."));
11980
11985
  const releaseSubmission = (reason) => {
11981
11986
  const released = submission;
11982
- 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));
11983
11988
  if (released?.phase === "refused") released.onRefused?.();
11984
11989
  submission = void 0;
11985
11990
  return released;
@@ -11995,8 +12000,23 @@ function createAstralBeamChat(options, deferStart = false) {
11995
12000
  let started = false;
11996
12001
  let selectionGeneration = 0;
11997
12002
  let toolExecutionGeneration = 0;
11998
- let historyGeneration = 0;
11999
- 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
+ };
12000
12020
  let requestController = new AbortController();
12001
12021
  let threadKey;
12002
12022
  let startWithNewThread = false;
@@ -12277,22 +12297,22 @@ function createAstralBeamChat(options, deferStart = false) {
12277
12297
  return tools;
12278
12298
  };
12279
12299
  const forwardedProps = () => live.debug ? { debug: true } : {};
12280
- const threadRequest = async (init, auth) => {
12300
+ const threadRequest = async (init, auth, owner) => {
12301
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12281
12302
  const thread = state.thread;
12282
12303
  if (!thread || typeof init.body !== "string") throw new Error("Open a conversation before sending.");
12283
- const generation = selectionGeneration;
12284
12304
  const body = JSON.parse(init.body);
12285
12305
  let path = getRunChatUrl();
12286
12306
  let payload;
12287
- const sent = body.messages.at(-1)?.role === "user" && submission?.phase === "submitting" ? submission : void 0;
12288
- 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;
12289
12309
  if (sent) payload = {
12290
12310
  ...body,
12291
12311
  threadId: thread.id,
12292
12312
  resume: void 0,
12293
12313
  parentRunId: void 0,
12294
12314
  messages: [body.messages.at(-1)],
12295
- tools: sent.tools ??= body.tools,
12315
+ tools: previousDelivery?.state === "uncertain" ? previousDelivery.tools : body.tools,
12296
12316
  forwardedProps: {
12297
12317
  ...body.forwardedProps,
12298
12318
  clientId
@@ -12301,7 +12321,7 @@ function createAstralBeamChat(options, deferStart = false) {
12301
12321
  else {
12302
12322
  scopeCompletedToolCalls();
12303
12323
  const history = await loadThreadMessages(thread.id, auth, void 0, liveToolMessageIds);
12304
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12324
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12305
12325
  update({ thread: threadFromRecord(history.thread, history.messages.length > 0) });
12306
12326
  retainToolResults(history);
12307
12327
  const available = history.pendingInteractions.filter((pending) => toolResults.has(toolResultKey(pending.toolCallId)));
@@ -12328,24 +12348,30 @@ function createAstralBeamChat(options, deferStart = false) {
12328
12348
  update({ activeToolCallIds: [] });
12329
12349
  const headers = new Headers(init.headers);
12330
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
+ };
12331
12356
  const response = await astralBeamChatFetch(path, {
12332
12357
  ...auth,
12333
12358
  ...init,
12334
12359
  headers,
12335
12360
  body: JSON.stringify(payload)
12336
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" };
12337
12364
  const limit = isAstralBeamApiError(error) ? error.body?.usage_limit : void 0;
12338
12365
  if (limit) update({ usageLimitReached: {
12339
12366
  name: limit.name,
12340
12367
  resetsAt: limit.resets_at
12341
12368
  } });
12342
- if (sent && !previouslyAttempted && isAstralBeamApiError(error) && (error.status === 400 || error.status === 413 || error.status === 429)) delete sent.tools;
12343
12369
  throw error;
12344
12370
  });
12345
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12371
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12346
12372
  if (response.headers.get("Content-Type")?.includes("application/json")) {
12347
12373
  const receipt = await response.json();
12348
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12374
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12349
12375
  update({
12350
12376
  thread: {
12351
12377
  ...state.thread,
@@ -12358,7 +12384,7 @@ function createAstralBeamChat(options, deferStart = false) {
12358
12384
  });
12359
12385
  if (sent) {
12360
12386
  const history = await loadThreadMessages(thread.id, auth, void 0, liveToolMessageIds);
12361
- if (generation !== selectionGeneration) throw new DOMException("Conversation changed", "AbortError");
12387
+ if (!currentOperation(owner)) throw new DOMException("Request cancelled", "AbortError");
12362
12388
  const accepted = history.messages.find((message) => message.id === receipt.accepted_message_id);
12363
12389
  if (accepted) replaceAcceptedMessage(accepted);
12364
12390
  acceptSubmission();
@@ -12368,23 +12394,14 @@ function createAstralBeamChat(options, deferStart = false) {
12368
12394
  return response;
12369
12395
  };
12370
12396
  const connection = fetchServerSentEvents(() => resolveApiUrl(getRunChatUrl(), authentication.apiUrl), async () => {
12371
- const previousIdentity = identity;
12372
- const token = await getValidChatAuthToken(authentication);
12373
- if (previousIdentity !== void 0 && previousIdentity !== identity) throw new DOMException("Identity changed", "AbortError");
12374
- return { fetchClient: (_input, init) => {
12375
- const auth = {
12376
- apiUrl: authentication.apiUrl,
12377
- astralBeamToken: token,
12378
- ...init?.signal ? { signal: init.signal } : {},
12379
- cache: "no-store",
12380
- fetchClient: (input, request) => fetchAuthenticatedChat({
12381
- ...authentication,
12382
- input,
12383
- init: request
12384
- })
12385
- };
12386
- return threadRequest(init ?? {}, auth);
12387
- } };
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) };
12388
12405
  });
12389
12406
  const connect = connection.connect;
12390
12407
  connection.connect = async function* (...args) {
@@ -12435,11 +12452,11 @@ function createAstralBeamChat(options, deferStart = false) {
12435
12452
  page: { truncated: false }
12436
12453
  });
12437
12454
  const older = options?.before !== void 0;
12438
- const readGeneration = older ? historyGeneration : ++historyGeneration;
12439
- if (!options?.before) update({
12440
- olderMessagesLoading: false,
12441
- history: state.messages.length > 0 || state.thread?.hasMessages === false ? "refreshing" : "loading"
12442
- });
12455
+ const owner = older ? historyRead?.owner : {
12456
+ client: next,
12457
+ selection: selectionGeneration
12458
+ };
12459
+ const currentRead = () => owner !== void 0 && historyRead?.owner === owner && currentAuthority(owner);
12443
12460
  const read = (async () => {
12444
12461
  let history = await loadThreadMessages(threadId, await requestOptions(), options?.before, liveToolMessageIds);
12445
12462
  while (options?.before && history.messages.every((message) => message.role === "tool") && history.page_after) {
@@ -12449,7 +12466,7 @@ function createAstralBeamChat(options, deferStart = false) {
12449
12466
  messages: [...earlier.messages, ...history.messages]
12450
12467
  };
12451
12468
  }
12452
- if (client !== next || readGeneration !== historyGeneration) throw new DOMException("Conversation changed", "AbortError");
12469
+ if (!currentRead()) throw new DOMException("Conversation changed", "AbortError");
12453
12470
  if (!older) retainToolResults(history);
12454
12471
  threadRecords = older ? [...history.messages, ...threadRecords] : history.messages;
12455
12472
  const pageIds = new Set(history.messages.map((message) => message.id));
@@ -12477,15 +12494,22 @@ function createAstralBeamChat(options, deferStart = false) {
12477
12494
  } : { truncated: false }
12478
12495
  };
12479
12496
  })();
12480
- if (!older) {
12481
- hydration = read.then(() => "idle", () => "failed").then((history) => new Promise((resolve) => queueMicrotask(() => {
12482
- 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;
12483
12501
  if (unsubscribeSnapshot) observeSnapshot();
12484
- update({ history });
12502
+ update({});
12485
12503
  }
12486
- resolve();
12487
- }))).then(() => read);
12488
- 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 });
12489
12513
  }
12490
12514
  return read;
12491
12515
  }
@@ -12604,6 +12628,7 @@ function createAstralBeamChat(options, deferStart = false) {
12604
12628
  const replaceClient = (messages) => {
12605
12629
  const previous = client;
12606
12630
  operation = void 0;
12631
+ historyRead = void 0;
12607
12632
  unsubscribeSnapshot?.();
12608
12633
  unsubscribeSnapshot = void 0;
12609
12634
  snapshotMessages = void 0;
@@ -12651,6 +12676,7 @@ function createAstralBeamChat(options, deferStart = false) {
12651
12676
  threadToolResults.set(previousId, toolResults);
12652
12677
  }
12653
12678
  selectionGeneration++;
12679
+ historyRead = void 0;
12654
12680
  selectedId = threadId;
12655
12681
  requestController.abort();
12656
12682
  requestController = new AbortController();
@@ -12676,7 +12702,6 @@ function createAstralBeamChat(options, deferStart = false) {
12676
12702
  pendingInteractions: [],
12677
12703
  serverToolTitles: {},
12678
12704
  unavailableMcpConnections: [],
12679
- history: "idle",
12680
12705
  messagesCursor: void 0,
12681
12706
  olderMessagesLoading: false
12682
12707
  });
@@ -12689,7 +12714,10 @@ function createAstralBeamChat(options, deferStart = false) {
12689
12714
  if (submission) update({ submission: project(submission) });
12690
12715
  try {
12691
12716
  if (!started) attachClient();
12692
- await hydration;
12717
+ await waitForHistory({
12718
+ client,
12719
+ selection: generation
12720
+ });
12693
12721
  if (generation !== selectionGeneration) return;
12694
12722
  if (threadKey) selectedThread(threadKey, id);
12695
12723
  } catch (error) {
@@ -12715,11 +12743,12 @@ function createAstralBeamChat(options, deferStart = false) {
12715
12743
  else openThread(selected, restoring);
12716
12744
  } else if (!restoring) newThread();
12717
12745
  };
12718
- const ensureThread = async (sent, attempt) => {
12746
+ const ensureThread = async (attempt) => {
12719
12747
  if (state.thread) return;
12720
12748
  const options = await requestOptions();
12749
+ if (!ownsAttempt(attempt)) throw new DOMException("Send cancelled", "AbortError");
12721
12750
  const record = await createChatThread(live.agentId ? { agent_id: live.agentId } : {}, options);
12722
- if (!owns(sent, attempt)) throw new DOMException("Send cancelled", "AbortError");
12751
+ if (!ownsAttempt(attempt)) throw new DOMException("Send cancelled", "AbortError");
12723
12752
  selectedId = record.id;
12724
12753
  update({ thread: threadFromRecord(record, false) });
12725
12754
  resolveCapabilities();
@@ -12731,7 +12760,10 @@ function createAstralBeamChat(options, deferStart = false) {
12731
12760
  try {
12732
12761
  client.detach();
12733
12762
  attachClient();
12734
- await hydration;
12763
+ await waitForHistory({
12764
+ client,
12765
+ selection: generation
12766
+ });
12735
12767
  if (explicit && generation === selectionGeneration) update({ error: void 0 });
12736
12768
  } catch (error) {
12737
12769
  if (generation !== selectionGeneration) return;
@@ -12789,40 +12821,49 @@ function createAstralBeamChat(options, deferStart = false) {
12789
12821
  return;
12790
12822
  }
12791
12823
  const current = authenticationState(authentication);
12824
+ const key = toolResultKey(result.toolCallId);
12792
12825
  const pending = state.pendingInteractions.find((item) => item.toolCallId === result.toolCallId);
12793
12826
  const closure = !("tool" in result) && pending && (state.thread?.role === "manager" || current.status === "ready" && pending.targetTenantUserId === current.currentUser.user.id);
12794
12827
  const questionnaire = "tool" in result && result.tool === "ask_questionnaire" && current.status === "ready" && pending?.targetTenantUserId === current.currentUser.user.id;
12795
- 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)) {
12796
12829
  reportError(/* @__PURE__ */ new Error("This tool call belongs to another session and cannot be executed here."));
12797
12830
  return;
12798
12831
  }
12799
- if (closure && !toolResults.has(toolResultKey(result.toolCallId))) toolResults.set(toolResultKey(result.toolCallId), {
12800
- outcome: "unknown",
12801
- output: null
12802
- });
12803
- else if (!toolResults.has(toolResultKey(result.toolCallId)) && "tool" in result) {
12804
- const output = result.output;
12805
- toolResults.set(toolResultKey(result.toolCallId), {
12806
- outcome: result.state === "output-error" ? "failed" : "succeeded",
12807
- output: output ?? null
12832
+ if (!toolResults.has(key)) {
12833
+ if (closure) toolResults.set(key, {
12834
+ outcome: "unknown",
12835
+ output: null
12808
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
+ }
12809
12844
  }
12810
- const owner = operation = {};
12845
+ const owner = {
12846
+ kind: "tool-result",
12847
+ client,
12848
+ selection: generation
12849
+ };
12850
+ operation = owner;
12811
12851
  try {
12812
12852
  update({});
12813
- if (operation !== owner) return;
12853
+ if (!currentOperation(owner)) return;
12814
12854
  scopeCompletedToolCalls();
12855
+ if (!currentOperation(owner)) return;
12815
12856
  if (pending) {
12816
- client.stop();
12857
+ owner.client.stop();
12817
12858
  await refreshThread(false);
12818
- if (operation !== owner || generation !== selectionGeneration) return;
12819
- await client.append({
12859
+ if (!currentOperation(owner)) return;
12860
+ await owner.client.append({
12820
12861
  role: "tool",
12821
12862
  toolCallId: result.toolCallId,
12822
12863
  content: JSON.stringify(toolResults.get(toolResultKey(result.toolCallId)))
12823
12864
  });
12824
- } else if ("tool" in result) await client.addToolResult(result);
12825
- 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);
12826
12867
  } finally {
12827
12868
  finishOperation(owner);
12828
12869
  }
@@ -12830,23 +12871,28 @@ function createAstralBeamChat(options, deferStart = false) {
12830
12871
  const abandonToolCall = (toolCallId) => addToolResult({ toolCallId });
12831
12872
  const deliver = async (sent) => {
12832
12873
  if (sent !== submission || sent.phase !== "submitting") return project(sent);
12833
- const attempt = operation = {};
12874
+ const attempt = {
12875
+ kind: "submission",
12876
+ submission: sent,
12877
+ client,
12878
+ selection: selectionGeneration
12879
+ };
12880
+ operation = attempt;
12834
12881
  try {
12835
12882
  await getValidChatAuthToken(authentication);
12836
- await hydration.catch(() => void 0);
12837
- if (!owns(sent, attempt)) return project(sent);
12838
- if (state.history === "failed") throw new Error(HISTORY_FAILED);
12839
- await ensureThread(sent, attempt);
12840
- 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);
12841
12886
  sent.callbacks?.onThreadReady?.(state.thread.id);
12842
- if (!owns(sent, attempt)) return project(sent);
12887
+ if (!ownsAttempt(attempt)) return project(sent);
12843
12888
  scopeCompletedToolCalls();
12844
- await client.sendMessage(sent.content);
12845
- if (!current(sent, attempt)) return project(sent);
12846
- endUnaccepted(sent, client.getError());
12847
- 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);
12848
12894
  } catch (error) {
12849
- if (!current(sent, attempt)) return project(sent);
12895
+ if (!currentAttempt(attempt)) return project(sent);
12850
12896
  const failure = error instanceof Error ? error : new Error(String(error));
12851
12897
  if (failure.name === "AbortError") endUnaccepted(sent);
12852
12898
  else if (endUnaccepted(sent, failure)) notifyError(failure);
@@ -12868,6 +12914,7 @@ function createAstralBeamChat(options, deferStart = false) {
12868
12914
  content,
12869
12915
  phase: "submitting",
12870
12916
  key: newUuid(),
12917
+ delivery: { state: "undispatched" },
12871
12918
  callbacks
12872
12919
  };
12873
12920
  submission = sent;
@@ -13113,6 +13160,7 @@ function createAstralBeamChat(options, deferStart = false) {
13113
13160
  dispose: () => {
13114
13161
  releaseSubmission("The chat closed before this was sent.");
13115
13162
  operation = void 0;
13163
+ historyRead = void 0;
13116
13164
  unsubscribeSnapshot?.();
13117
13165
  unsubscribeSnapshot = void 0;
13118
13166
  client.detach();
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- export { h as ASK_QUESTIONNAIRE_TOOL, g as RENDER_WIDGET_TOOL, _ as SANDBOX_LIST_FILES_TOOL, v as SANDBOX_PUBLISH_ARTIFACT_TOOL, y as SANDBOX_READ_FILE_TOOL, b as SANDBOX_RUN_COMMAND_TOOL, x as SANDBOX_STATUS_EVENT, S as SANDBOX_WRITE_FILE_TOOL, m as buildAgentTools, i as collectSandboxActivity, r as createAstralBeamChat, t as defineTool, a as describeSandboxCommandRun, d as hasPendingToolRun, o as isSandboxTool, f as isSettledToolCall, p as lastPartInProgress, s as readSandboxArtifact, c as readSandboxCommandRun, l as readSandboxFileWrite, u as sandboxRefusal } from "./core-DIrcPvaf.js";
1
+ export { h as ASK_QUESTIONNAIRE_TOOL, g as RENDER_WIDGET_TOOL, _ as SANDBOX_LIST_FILES_TOOL, v as SANDBOX_PUBLISH_ARTIFACT_TOOL, y as SANDBOX_READ_FILE_TOOL, b as SANDBOX_RUN_COMMAND_TOOL, x as SANDBOX_STATUS_EVENT, S as SANDBOX_WRITE_FILE_TOOL, m as buildAgentTools, i as collectSandboxActivity, r as createAstralBeamChat, t as defineTool, a as describeSandboxCommandRun, d as hasPendingToolRun, o as isSandboxTool, f as isSettledToolCall, p as lastPartInProgress, s as readSandboxArtifact, c as readSandboxCommandRun, l as readSandboxFileWrite, u as sandboxRefusal } from "./core-CBrD2uRW.js";
package/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as CORE_OPTION_KEYS, r as createAstralBeamChat } from "./core-DIrcPvaf.js";
1
+ import { n as CORE_OPTION_KEYS, r as createAstralBeamChat } from "./core-CBrD2uRW.js";
2
2
  import { Kt as DEFAULT_COLOR_SCHEME } from "./api-CzXKVU8Z.js";
3
3
  import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";