@dudko.dev/agent-web 0.0.43 → 0.0.45

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.
Files changed (34) hide show
  1. package/README.md +56 -3
  2. package/dist/agent-web.js +167 -161
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/{chunk-DAREMCXF.js → chunk-236RCVAZ.js} +40 -8
  5. package/dist/chunk-236RCVAZ.js.map +1 -0
  6. package/dist/{chunk-2MLHZ6LQ.js → chunk-Y4MIIBPB.js} +2 -2
  7. package/dist/{chunk-ZSZSSJS4.js → chunk-Y6CD3WOK.js} +176 -10
  8. package/dist/chunk-Y6CD3WOK.js.map +1 -0
  9. package/dist/{chunk-YPCHD6DV.js → chunk-YGWIOO27.js} +31 -12
  10. package/dist/chunk-YGWIOO27.js.map +1 -0
  11. package/dist/index.cjs +1300 -171
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +1794 -1466
  14. package/dist/index.d.ts +1794 -1466
  15. package/dist/index.js +1044 -145
  16. package/dist/index.js.map +1 -1
  17. package/dist/mcp.cjs +136 -5
  18. package/dist/mcp.cjs.map +1 -1
  19. package/dist/mcp.d.cts +5 -2
  20. package/dist/mcp.d.ts +5 -2
  21. package/dist/mcp.js +19 -8
  22. package/dist/mcp.js.map +1 -1
  23. package/dist/{sandbox-3VRX47UY.js → sandbox-7CGSIIIZ.js} +4 -4
  24. package/dist/sandbox-worker.cjs +30 -11
  25. package/dist/sandbox-worker.cjs.map +1 -1
  26. package/dist/sandbox-worker.js +1 -1
  27. package/dist/{elicitation-DS-84_bF.d.cts → vault-Mar2CY0J.d.cts} +526 -526
  28. package/dist/{elicitation-DS-84_bF.d.ts → vault-Mar2CY0J.d.ts} +526 -526
  29. package/package.json +1 -1
  30. package/dist/chunk-DAREMCXF.js.map +0 -1
  31. package/dist/chunk-YPCHD6DV.js.map +0 -1
  32. package/dist/chunk-ZSZSSJS4.js.map +0 -1
  33. /package/dist/{chunk-2MLHZ6LQ.js.map → chunk-Y4MIIBPB.js.map} +0 -0
  34. /package/dist/{sandbox-3VRX47UY.js.map → sandbox-7CGSIIIZ.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -585,8 +585,174 @@ var init_webllm = __esm({
585
585
  }
586
586
  });
587
587
 
588
+ // src/sync/tab.ts
589
+ var TAB_TEST, LOCKS_TEST, SYNC_VERSION, SYNC_ID_RE, randomId, TABS, tabs, currentTab, hubOf, heldExclusively, lockManager, isRecord, scopeOf, newSyncId;
590
+ var init_tab = __esm({
591
+ "src/sync/tab.ts"() {
592
+ "use strict";
593
+ TAB_TEST = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:tab-test");
594
+ LOCKS_TEST = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:locks-test");
595
+ SYNC_VERSION = 1;
596
+ SYNC_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
597
+ randomId = () => {
598
+ const c = globalThis.crypto;
599
+ if (c?.randomUUID) return c.randomUUID().replace(/-/g, "");
600
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
601
+ };
602
+ TABS = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:tabs");
603
+ tabs = globalThis[TABS] ??= /* @__PURE__ */ new Map();
604
+ currentTab = () => {
605
+ const seam = globalThis[TAB_TEST];
606
+ const named = typeof seam === "function" ? seam() : void 0;
607
+ const key = typeof named === "string" ? named : "";
608
+ let tab = tabs.get(key);
609
+ if (!tab) {
610
+ tab = { id: randomId(), held: /* @__PURE__ */ new Set(), hubs: /* @__PURE__ */ new Map() };
611
+ tabs.set(key, tab);
612
+ }
613
+ return tab;
614
+ };
615
+ hubOf = (tab, name) => {
616
+ const Channel = globalThis.BroadcastChannel;
617
+ if (typeof Channel !== "function") return void 0;
618
+ const known = tab.hubs.get(name);
619
+ if (known) return known;
620
+ let channel;
621
+ const listeners = /* @__PURE__ */ new Set();
622
+ const open = () => {
623
+ if (channel) return channel;
624
+ const opened = new Channel(name);
625
+ opened.unref?.();
626
+ opened.onmessage = (event) => {
627
+ for (const listener of [...listeners]) {
628
+ try {
629
+ listener(event.data);
630
+ } catch {
631
+ }
632
+ }
633
+ };
634
+ channel = opened;
635
+ return opened;
636
+ };
637
+ const hub = {
638
+ post(message) {
639
+ try {
640
+ open().postMessage(message);
641
+ } catch {
642
+ }
643
+ },
644
+ listen(listener) {
645
+ try {
646
+ open();
647
+ } catch {
648
+ return () => void 0;
649
+ }
650
+ listeners.add(listener);
651
+ return () => {
652
+ listeners.delete(listener);
653
+ if (listeners.size === 0 && channel) {
654
+ channel.onmessage = null;
655
+ channel.close();
656
+ channel = void 0;
657
+ }
658
+ };
659
+ }
660
+ };
661
+ tab.hubs.set(name, hub);
662
+ return hub;
663
+ };
664
+ heldExclusively = async (locks, name) => {
665
+ if (typeof locks.query !== "function") return void 0;
666
+ try {
667
+ const state = await locks.query();
668
+ return (state?.held ?? []).some((l) => l?.name === name && l?.mode !== "shared");
669
+ } catch {
670
+ return void 0;
671
+ }
672
+ };
673
+ lockManager = () => {
674
+ const seam = globalThis[LOCKS_TEST];
675
+ if (seam === null) return void 0;
676
+ if (seam && typeof seam.request === "function") {
677
+ return seam;
678
+ }
679
+ const locks = globalThis.navigator?.locks;
680
+ return locks && typeof locks.request === "function" ? locks : void 0;
681
+ };
682
+ isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
683
+ scopeOf = (dbName) => encodeURIComponent(dbName);
684
+ newSyncId = () => randomId().slice(0, 32);
685
+ }
686
+ });
687
+
688
+ // src/sync/notices.ts
689
+ var STORAGE_CHANGE_KINDS, OPS, MAX_NOTICE_KEY_CHARS, MAX_NOTICE_NAMESPACE_CHARS, KEYLESS, storageChannelName, nameOk, storageChangeOf, postStorageChangeFrom, postStorageChange, onStorageChange;
690
+ var init_notices = __esm({
691
+ "src/sync/notices.ts"() {
692
+ "use strict";
693
+ init_tab();
694
+ STORAGE_CHANGE_KINDS = [
695
+ "credentials",
696
+ "oauth",
697
+ "files",
698
+ "session",
699
+ "runs",
700
+ "skills",
701
+ "chats"
702
+ ];
703
+ OPS = ["put", "delete", "clear"];
704
+ MAX_NOTICE_KEY_CHARS = 1024;
705
+ MAX_NOTICE_NAMESPACE_CHARS = 256;
706
+ KEYLESS = /* @__PURE__ */ new Set(["credentials", "oauth"]);
707
+ storageChannelName = (dbName) => `@dudko.dev/agent-web/storage:${scopeOf(dbName)}`;
708
+ nameOk = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
709
+ storageChangeOf = (data) => {
710
+ if (!isRecord(data) || data.v !== SYNC_VERSION || data.t !== "change") return void 0;
711
+ if (typeof data.from !== "string" || !SYNC_ID_RE.test(data.from)) return void 0;
712
+ const kind = data.kind;
713
+ const op = data.op;
714
+ if (!STORAGE_CHANGE_KINDS.includes(kind) || !OPS.includes(op)) return void 0;
715
+ if (data.key !== void 0 && (KEYLESS.has(kind) || !nameOk(data.key, MAX_NOTICE_KEY_CHARS))) {
716
+ return void 0;
717
+ }
718
+ if (data.ns !== void 0 && !nameOk(data.ns, MAX_NOTICE_NAMESPACE_CHARS)) return void 0;
719
+ return {
720
+ kind,
721
+ op,
722
+ ...data.key !== void 0 ? { key: data.key } : {},
723
+ ...data.ns !== void 0 ? { namespace: data.ns } : {}
724
+ };
725
+ };
726
+ postStorageChangeFrom = (tab, dbName, change) => {
727
+ if (!dbName) return;
728
+ const message = {
729
+ v: SYNC_VERSION,
730
+ t: "change",
731
+ from: tab.id,
732
+ kind: change.kind,
733
+ op: change.op,
734
+ ...change.key !== void 0 && !KEYLESS.has(change.kind) ? { key: change.key } : {},
735
+ ...change.namespace !== void 0 ? { ns: change.namespace } : {}
736
+ };
737
+ if (!storageChangeOf(message)) return;
738
+ hubOf(tab, storageChannelName(dbName))?.post(message);
739
+ };
740
+ postStorageChange = (dbName, change) => postStorageChangeFrom(currentTab(), dbName, change);
741
+ onStorageChange = (dbName, listener) => {
742
+ if (!dbName) return () => void 0;
743
+ const tab = currentTab();
744
+ const hub = hubOf(tab, storageChannelName(dbName));
745
+ if (!hub) return () => void 0;
746
+ return hub.listen((data) => {
747
+ const change = storageChangeOf(data);
748
+ if (change) listener(change);
749
+ });
750
+ };
751
+ }
752
+ });
753
+
588
754
  // src/mcp/skills.ts
589
- var MCP_SKILLS_EXTENSION, MCP_SKILL_MAX_RESOURCES, MCP_SKILL_MAX_TOTAL_BYTES, MCP_SKILLS_MAX_PER_SERVER, MCP_SKILLS_MAX_TOTAL, MCP_SKILL_DESCRIPTION_MAX_CHARS, MCP_SKILL_BODY_MAX_CHARS, MCP_SKILL_FILE_MAX_CHARS, MCP_SKILL_FILES_SHOWN_MAX, MCP_SKILL_SERVER_LABEL_MAX_CHARS, INVISIBLE, cleanMcpSkillText, oneLine, MCP_SKILL_NAME_PATTERN, DIGEST, SKILL_URI, isRecord, mcpSkillPath, mcpSkillFilePath, mcpSkillEntryRefusal, mcpSkillRecordOf, labelOf, segmentOf, assignMcpSkillNames, isMcpSkillName, selectMcpSkills, clipped, shownUri, mcpSkillTag, mcpSkillDescription, mcpSkillPreamble, mcpSkillBodyPreview, mcpSkillBodyText, mcpSkillFileText, resolveMcpSkillFile, MCP_SKILL_DIRECTORY_ENTRIES_MAX, skillDirectoryRef, isPlainPath, skillDirectoryChildren, skillDirectoryOf, resolveMcpSkillPath, mcpSkillDirectoryNote, skillDirectoryListing, MCP_SKILL_URI_MAX_CHARS, mcpSkillUriRefusal, resolveMcpSkillServer, mcpSkillRoomRefusal, assignAddedMcpSkillName, mcpSkillEnclosingUri, mcpSkillLoadByUriNote, MCP_SKILL_CONSENTS, MCP_SKILL_CONSENT_DEFAULT, consentList, mcpSkillConsentOf, resolveMcpSkillConsent, createMcpSkillGrants, createMcpSkillRunConsent, mcpSkillGrantKey, decideMcpSkillConsent, recordMcpSkillConsent, mcpSkillConsentView, mcpSkillDeniedMessage, MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES, MCP_SKILL_SNAPSHOT_MAX_DEPTH, MCP_SKILL_SNAPSHOTS_MAX_BYTES, createMcpSkillSnapshotMemory, MCP_SKILLS_MARK, collectMcpSkillSources;
755
+ var MCP_SKILLS_EXTENSION, MCP_SKILL_MAX_RESOURCES, MCP_SKILL_MAX_TOTAL_BYTES, MCP_SKILLS_MAX_PER_SERVER, MCP_SKILLS_MAX_TOTAL, MCP_SKILL_DESCRIPTION_MAX_CHARS, MCP_SKILL_BODY_MAX_CHARS, MCP_SKILL_FILE_MAX_CHARS, MCP_SKILL_FILES_SHOWN_MAX, MCP_SKILL_SERVER_LABEL_MAX_CHARS, INVISIBLE, cleanMcpSkillText, oneLine, MCP_SKILL_NAME_PATTERN, DIGEST, SKILL_URI, isRecord2, mcpSkillPath, mcpSkillFilePath, mcpSkillEntryRefusal, mcpSkillRecordOf, labelOf, segmentOf, assignMcpSkillNames, isMcpSkillName, selectMcpSkills, clipped, shownUri, mcpSkillTag, mcpSkillDescription, mcpSkillPreamble, mcpSkillBodyPreview, mcpSkillBodyText, mcpSkillFileText, resolveMcpSkillFile, MCP_SKILL_DIRECTORY_ENTRIES_MAX, skillDirectoryRef, isPlainPath, skillDirectoryChildren, skillDirectoryOf, resolveMcpSkillPath, mcpSkillDirectoryNote, skillDirectoryListing, MCP_SKILL_URI_MAX_CHARS, mcpSkillUriRefusal, resolveMcpSkillServer, mcpSkillRoomRefusal, assignAddedMcpSkillName, mcpSkillEnclosingUri, mcpSkillLoadByUriNote, MCP_SKILL_CONSENTS, MCP_SKILL_CONSENT_DEFAULT, consentList, mcpSkillConsentOf, resolveMcpSkillConsent, createMcpSkillGrants, createMcpSkillRunConsent, mcpSkillGrantKey, decideMcpSkillConsent, recordMcpSkillConsent, mcpSkillConsentView, mcpSkillDeniedMessage, MCP_SKILL_SNAPSHOT_MAX_DIRECTORIES, MCP_SKILL_SNAPSHOT_MAX_DEPTH, MCP_SKILL_SNAPSHOTS_MAX_BYTES, createMcpSkillSnapshotMemory, MCP_SKILLS_MARK, collectMcpSkillSources;
590
756
  var init_skills = __esm({
591
757
  "src/mcp/skills.ts"() {
592
758
  "use strict";
@@ -606,7 +772,7 @@ var init_skills = __esm({
606
772
  MCP_SKILL_NAME_PATTERN = /^(?!-)(?!.*--)[a-z0-9-]{1,64}(?<!-)$/;
607
773
  DIGEST = /^sha256:[0-9a-f]{64}$/;
608
774
  SKILL_URI = /^([a-z][a-z0-9+.-]*):\/\/(.+)\/SKILL\.md$/i;
609
- isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
775
+ isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
610
776
  mcpSkillPath = (uri) => {
611
777
  if (typeof uri !== "string") return void 0;
612
778
  const m = SKILL_URI.exec(uri);
@@ -630,11 +796,11 @@ var init_skills = __esm({
630
796
  return path;
631
797
  };
632
798
  mcpSkillEntryRefusal = (entry, options = {}) => {
633
- if (!isRecord(entry) || typeof entry.uri !== "string") return "not a skill entry (no uri)";
799
+ if (!isRecord2(entry) || typeof entry.uri !== "string") return "not a skill entry (no uri)";
634
800
  const path = mcpSkillPath(entry.uri);
635
801
  if (!path) return `${entry.uri} is not the SKILL.md of a named skill directory`;
636
802
  const frontmatter = entry.frontmatter;
637
- if (!isRecord(frontmatter)) return "the entry has no frontmatter";
803
+ if (!isRecord2(frontmatter)) return "the entry has no frontmatter";
638
804
  const name = frontmatter.name;
639
805
  if (typeof name !== "string" || !MCP_SKILL_NAME_PATTERN.test(name)) {
640
806
  return `the frontmatter name ${JSON.stringify(name)} is not a skill name (1-64 lowercase letters, digits and single hyphens)`;
@@ -657,7 +823,7 @@ var init_skills = __esm({
657
823
  let bytes = 0;
658
824
  let listsSelf = false;
659
825
  for (const r of resources) {
660
- if (!isRecord(r) || typeof r.uri !== "string") return "a file of the entry has no uri";
826
+ if (!isRecord2(r) || typeof r.uri !== "string") return "a file of the entry has no uri";
661
827
  if (seen.has(r.uri)) return `${r.uri} is listed more than once`;
662
828
  seen.add(r.uri);
663
829
  if (typeof r.digest !== "string" || !DIGEST.test(r.digest)) {
@@ -984,7 +1150,7 @@ var init_skills = __esm({
984
1150
  const seen = /* @__PURE__ */ new Set();
985
1151
  for (const tool8 of Object.values(tools)) {
986
1152
  const mark = tool8 && typeof tool8 === "object" ? tool8[MCP_SKILLS_MARK] : void 0;
987
- if (!isRecord(mark)) continue;
1153
+ if (!isRecord2(mark)) continue;
988
1154
  const source = mark;
989
1155
  if (typeof source.server !== "string" || seen.has(source.server)) continue;
990
1156
  if (typeof source.load !== "function" || typeof source.readFile !== "function") continue;
@@ -997,7 +1163,7 @@ var init_skills = __esm({
997
1163
  });
998
1164
 
999
1165
  // src/tools/approval.ts
1000
- var TOOL_APPROVAL_MODES, TOOL_APPROVAL_TIMEOUT_MS, MAX_TIMER_MS, resolveApprovalTimeout, ToolDeniedError, markReadOnly, markCodeExecution, isCodeExecutionTool, isReadOnlyTool, globToRegExp, matchRule, decideToolPermission, decideByPolicy, normalizeDecision, createApprovalState, seq, gateToolCall, askMcpSkillConsent, namedError, withDeadline;
1166
+ var TOOL_APPROVAL_MODES, TOOL_APPROVAL_TIMEOUT_MS, MAX_TIMER_MS, resolveApprovalTimeout, ToolDeniedError, markReadOnly, markCodeExecution, isCodeExecutionTool, isReadOnlyTool, globToRegExp, matchRule, decideToolPermission, decideByPolicy, PARK_REFUSED_REASON, normalizeDecision, createApprovalState, seq, gateToolCall, askMcpSkillConsent, namedError, withDeadline;
1001
1167
  var init_approval = __esm({
1002
1168
  "src/tools/approval.ts"() {
1003
1169
  "use strict";
@@ -1076,7 +1242,11 @@ var init_approval = __esm({
1076
1242
  return "ask";
1077
1243
  }
1078
1244
  };
1079
- normalizeDecision = (d) => typeof d === "boolean" ? { approved: d } : { approved: Boolean(d?.approved), reason: d?.reason, remember: d?.remember };
1245
+ PARK_REFUSED_REASON = "parking ({ park: true }) is the server package's (@dudko.dev/agent): a run in a page cannot wait for an answer outside it, so the call is denied";
1246
+ normalizeDecision = (d) => typeof d === "boolean" ? { approved: d } : (
1247
+ // A host ported from the server agent: the call is denied as before, and now says why.
1248
+ d?.park === true ? { approved: false, reason: PARK_REFUSED_REASON } : { approved: Boolean(d?.approved), reason: d?.reason, remember: d?.remember }
1249
+ );
1080
1250
  createApprovalState = (config) => ({
1081
1251
  mode: config?.mode ?? "autopilot",
1082
1252
  config: config ?? {},
@@ -1545,7 +1715,8 @@ var init_wrap = __esm({
1545
1715
  ...o.subagent ? { subagent: o.subagent } : {},
1546
1716
  ...o.elicitations ? { elicitations: o.elicitations } : {},
1547
1717
  ...o.clock ? { clock: o.clock } : {},
1548
- ...o.mcpSkills ? { mcpSkills: o.mcpSkills } : {}
1718
+ ...o.mcpSkills ? { mcpSkills: o.mcpSkills } : {},
1719
+ ...o.sessionLocks ? { sessionLocks: o.sessionLocks } : {}
1549
1720
  };
1550
1721
  return execute.call(t, input, { ...options, agentRun });
1551
1722
  };
@@ -1662,6 +1833,8 @@ var init_vfs = __esm({
1662
1833
  "src/files/vfs.ts"() {
1663
1834
  "use strict";
1664
1835
  init_db();
1836
+ init_notices();
1837
+ init_tab();
1665
1838
  MIME = {
1666
1839
  txt: "text/plain",
1667
1840
  md: "text/markdown",
@@ -1707,21 +1880,44 @@ var init_vfs = __esm({
1707
1880
  return btoa(bin);
1708
1881
  };
1709
1882
  VirtualFileSystem = class {
1710
- memory;
1883
+ /**
1884
+ * The IndexedDB database the files live in - and the name the other tabs hear of a change
1885
+ * under (`files` notices, see `onStorageChange`). Undefined for an in-memory file system:
1886
+ * nothing of it is shared.
1887
+ */
1711
1888
  dbName;
1889
+ /** Isolates several file systems in one database: a `files` notice carries it. */
1890
+ namespace;
1891
+ memory;
1712
1892
  ns;
1713
1893
  maxFileBytes;
1714
1894
  listeners = /* @__PURE__ */ new Set();
1895
+ tab;
1715
1896
  constructor(opts = {}) {
1716
1897
  if (opts.memory) this.memory = /* @__PURE__ */ new Map();
1717
- this.dbName = opts.dbName;
1898
+ this.dbName = opts.memory ? void 0 : opts.dbName ?? "agent-web";
1718
1899
  this.ns = opts.namespace ?? "default";
1900
+ this.namespace = this.ns;
1719
1901
  this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024;
1902
+ this.tab = currentTab();
1720
1903
  }
1721
1904
  key(path) {
1722
1905
  return `${this.ns}:${path}`;
1723
1906
  }
1724
- /** Subscribe to writes and deletes (e.g. to refresh a file list). Returns an unsubscribe. */
1907
+ /** After a write committed: the other tabs hear which file (never its content). */
1908
+ announce(op, path) {
1909
+ postStorageChangeFrom(this.tab, this.dbName, {
1910
+ kind: "files",
1911
+ op,
1912
+ key: path,
1913
+ namespace: this.ns
1914
+ });
1915
+ }
1916
+ /**
1917
+ * Subscribe to writes and deletes made through THIS file system (e.g. to refresh a file list).
1918
+ * Another tab's changes come as `files` notices (`onStorageChange(vfs.dbName, ...)`). Returns
1919
+ * an unsubscribe.
1920
+ */
1725
1921
  onChange(listener) {
1726
1922
  this.listeners.add(listener);
1727
1923
  return () => this.listeners.delete(listener);
@@ -1755,6 +1951,7 @@ var init_vfs = __esm({
1755
1951
  else {
1756
1952
  const db = await openAgentWebDB({ dbName: this.dbName });
1757
1953
  await db.put(FILES_STORE, file, this.key(p));
1954
+ this.announce("put", p);
1758
1955
  }
1759
1956
  this.notify("write", p);
1760
1957
  const { content: _drop, ...info } = file;
@@ -1787,6 +1984,7 @@ var init_vfs = __esm({
1787
1984
  const db = await openAgentWebDB({ dbName: this.dbName });
1788
1985
  existed = await db.get(FILES_STORE, this.key(p)) !== void 0;
1789
1986
  await db.delete(FILES_STORE, this.key(p));
1987
+ if (existed) this.announce("delete", p);
1790
1988
  }
1791
1989
  if (existed) this.notify("delete", p);
1792
1990
  return existed;
@@ -2368,6 +2566,11 @@ var init_engine = __esm({
2368
2566
  if (finished) {
2369
2567
  return;
2370
2568
  }
2569
+ if (overTime()) {
2570
+ interrupted = true;
2571
+ finish(timedOut());
2572
+ return;
2573
+ }
2371
2574
  entryAt = Date.now();
2372
2575
  try {
2373
2576
  fn();
@@ -2413,19 +2616,20 @@ var init_engine = __esm({
2413
2616
  out.push(line);
2414
2617
  outChars += line.length;
2415
2618
  });
2416
- expose("timer", (idHandle, msHandle) => {
2417
- const id = ctx.getNumber(idHandle);
2418
- const ms = ctx.getNumber(msHandle);
2419
- const previous = hostTimers.get(id);
2420
- if (previous !== void 0) {
2421
- clearTimeout(previous);
2422
- } else if (hostTimers.size >= MAX_TIMERS) {
2423
- throw guestError("RangeError", "too many timers");
2424
- }
2619
+ const schedule = (id, due) => {
2425
2620
  hostTimers.set(
2426
2621
  id,
2427
2622
  setTimeout(
2428
2623
  () => {
2624
+ if (Date.now() < due) {
2625
+ if (overTime()) {
2626
+ interrupted = true;
2627
+ finish(timedOut());
2628
+ } else {
2629
+ schedule(id, due);
2630
+ }
2631
+ return;
2632
+ }
2429
2633
  hostTimers.delete(id);
2430
2634
  enter(() => {
2431
2635
  const r = ctx.callFunction(internals.fire, ctx.undefined, ctx.newNumber(id));
@@ -2434,10 +2638,23 @@ var init_engine = __esm({
2434
2638
  }
2435
2639
  });
2436
2640
  },
2437
- // A timer past the deadline never fires: the watchdog ends the run first.
2438
- Math.min(Math.max(0, ms), limits.timeoutMs + 1)
2641
+ // timeoutMs + 1, not the budget left + 1: the wall clock is not judged while a file call
2642
+ // waits, so what is left can be spent then, and the timer would wake every millisecond
2643
+ // until the answer came.
2644
+ Math.max(0, Math.min(due - Date.now(), limits.timeoutMs + 1))
2439
2645
  )
2440
2646
  );
2647
+ };
2648
+ expose("timer", (idHandle, msHandle) => {
2649
+ const id = ctx.getNumber(idHandle);
2650
+ const ms = ctx.getNumber(msHandle);
2651
+ const previous = hostTimers.get(id);
2652
+ if (previous !== void 0) {
2653
+ clearTimeout(previous);
2654
+ } else if (hostTimers.size >= MAX_TIMERS) {
2655
+ throw guestError("RangeError", "too many timers");
2656
+ }
2657
+ schedule(id, Date.now() + Math.max(0, ms));
2441
2658
  });
2442
2659
  expose("clear", (idHandle) => {
2443
2660
  const id = ctx.getNumber(idHandle);
@@ -3139,12 +3356,17 @@ __export(src_exports, {
3139
3356
  MemoryRunStore: () => MemoryRunStore,
3140
3357
  MemorySkillStore: () => MemorySkillStore,
3141
3358
  MemoryStore: () => MemoryStore,
3359
+ NO_ATTACHMENT_NOTE: () => NO_ATTACHMENT_NOTE,
3142
3360
  PIPELINE_LIMITS: () => PIPELINE_LIMITS,
3143
3361
  PIPELINE_ROUTER_SYSTEM: () => PIPELINE_ROUTER_SYSTEM,
3144
3362
  PipelineNodeError: () => PipelineNodeError,
3145
3363
  PipelineValidationError: () => PipelineValidationError,
3146
3364
  PlanSchema: () => PlanSchema,
3147
3365
  PlanStepSchema: () => PlanStepSchema,
3366
+ RELAY_MAX_REPLAYS_PER_SECOND: () => RELAY_MAX_REPLAYS_PER_SECOND,
3367
+ RELAY_MAX_SENDS: () => RELAY_MAX_SENDS,
3368
+ RELAY_MAX_SEND_CHARS: () => RELAY_MAX_SEND_CHARS,
3369
+ RELAY_MAX_STRING: () => RELAY_MAX_STRING,
3148
3370
  REPLAY_NOTE: () => REPLAY_NOTE,
3149
3371
  RUNS_STORE: () => RUNS_STORE,
3150
3372
  ReplanSchema: () => ReplanSchema,
@@ -3163,11 +3385,14 @@ __export(src_exports, {
3163
3385
  SEARCH_PROVIDERS: () => SEARCH_PROVIDERS,
3164
3386
  SECRETS_STORE: () => SECRETS_STORE,
3165
3387
  SESSIONS_STORE: () => SESSIONS_STORE,
3388
+ SESSION_LOCK_MODES: () => SESSION_LOCK_MODES,
3166
3389
  SKILL_TOOL_NAMES: () => SKILL_TOOL_NAMES,
3167
3390
  SPAWN_INPUT_SCHEMA: () => SPAWN_INPUT_SCHEMA,
3168
3391
  SPAWN_SUBAGENT_TOOL: () => SPAWN_SUBAGENT_TOOL,
3392
+ STORAGE_CHANGE_KINDS: () => STORAGE_CHANGE_KINDS,
3169
3393
  SUBAGENT_DEFAULTS: () => SUBAGENT_DEFAULTS,
3170
3394
  SUBAGENT_MAX_DEPTH_LIMIT: () => SUBAGENT_MAX_DEPTH_LIMIT,
3395
+ SessionBusyError: () => SessionBusyError,
3171
3396
  SubagentSpawnError: () => SubagentSpawnError,
3172
3397
  TOOL_APPROVAL_MODES: () => TOOL_APPROVAL_MODES,
3173
3398
  TOOL_APPROVAL_TIMEOUT_MS: () => TOOL_APPROVAL_TIMEOUT_MS,
@@ -3276,6 +3501,7 @@ __export(src_exports, {
3276
3501
  normalizeSkillName: () => normalizeSkillName,
3277
3502
  normalizeSteps: () => normalizeSteps,
3278
3503
  normalizeUsage: () => normalizeUsage,
3504
+ onStorageChange: () => onStorageChange,
3279
3505
  openAgentWebDB: () => openAgentWebDB,
3280
3506
  outputCapNotice: () => outputCapNotice,
3281
3507
  parseExecutorResponse: () => parseExecutorResponse,
@@ -3286,6 +3512,7 @@ __export(src_exports, {
3286
3512
  parseSkillMarkdown: () => parseSkillMarkdown,
3287
3513
  pickPipelineRoute: () => pickPipelineRoute,
3288
3514
  pickTier: () => pickTier,
3515
+ postStorageChange: () => postStorageChange,
3289
3516
  preloadWebLLMModel: () => preloadWebLLMModel,
3290
3517
  preparePipeline: () => preparePipeline,
3291
3518
  promptHintOf: () => promptHintOf,
@@ -3324,6 +3551,7 @@ __export(src_exports, {
3324
3551
  sniffMediaType: () => sniffMediaType,
3325
3552
  splitBlocker: () => splitBlocker,
3326
3553
  stageOutputCap: () => stageOutputCap,
3554
+ stageReasons: () => stageReasons,
3327
3555
  stream: () => stream,
3328
3556
  supportsImages: () => supportsImages,
3329
3557
  supportsNativeTools: () => supportsNativeTools,
@@ -3340,6 +3568,7 @@ __export(src_exports, {
3340
3568
  toolRunContextOf: () => toolRunContextOf,
3341
3569
  unloadWebLLMModel: () => unloadWebLLMModel,
3342
3570
  validatePipeline: () => validatePipeline,
3571
+ watchSession: () => watchSession,
3343
3572
  webLLMContextWindow: () => webLLMContextWindow,
3344
3573
  withRollingBreakpoint: () => withRollingBreakpoint,
3345
3574
  withSystem: () => withSystem,
@@ -3456,6 +3685,16 @@ var BUDGET_SHARES = {
3456
3685
  compaction: { num: 1, den: 125, min: 256, max: 4096 }
3457
3686
  };
3458
3687
  var share = (window, s) => Math.min(s.max, Math.max(s.min, Math.round(window * s.num / s.den)));
3688
+ var reasoningStages = /* @__PURE__ */ new WeakMap();
3689
+ var stageReasons = (c, stage) => reasoningStages.get(c)?.has(stage) === true;
3690
+ var observeReasoning = (c, stage, contextWindowTokens, finishReason, reasoningTokens) => {
3691
+ if (!(typeof reasoningTokens === "number" && reasoningTokens > 0)) return false;
3692
+ const cap2 = stageOutputCap(c, stage, contextWindowTokens);
3693
+ const seen = reasoningStages.get(c) ?? /* @__PURE__ */ new Set();
3694
+ seen.add(stage);
3695
+ reasoningStages.set(c, seen);
3696
+ return finishReason === "length" && cap2.derived && cap2.tokens !== void 0;
3697
+ };
3459
3698
  var stageOutputCap = (c, stage, contextWindowTokens) => {
3460
3699
  const set = c.limits?.perCall?.[stage] ?? c.budgets?.[stage];
3461
3700
  if (typeof set === "number" && Number.isFinite(set)) {
@@ -3463,6 +3702,7 @@ var stageOutputCap = (c, stage, contextWindowTokens) => {
3463
3702
  }
3464
3703
  const thinking = resolveThinking(thinkingFor(stage, c.thinking, c.stageThinking));
3465
3704
  if (thinking.reasoning && thinking.reasoning !== "none") return { derived: false };
3705
+ if (stageReasons(c, stage)) return { derived: false };
3466
3706
  return { tokens: share(contextWindowTokens, BUDGET_SHARES[stage]), derived: true };
3467
3707
  };
3468
3708
  var outputCapNotice = (c, stage, contextWindowTokens, finishReason) => {
@@ -3726,6 +3966,8 @@ var resolveModel = (input, credentials, clientName) => buildModelFromStage(resol
3726
3966
 
3727
3967
  // src/learning.ts
3728
3968
  var import_zod = require("zod");
3969
+ init_notices();
3970
+ init_tab();
3729
3971
 
3730
3972
  // src/skills.ts
3731
3973
  var import_ai4 = require("ai");
@@ -4240,9 +4482,24 @@ var ORIGIN_FILE = ".origin.json";
4240
4482
  var VfsSkillStore = class {
4241
4483
  vfs;
4242
4484
  dir;
4485
+ tab;
4243
4486
  constructor(vfs, dir = "/skills") {
4244
4487
  this.vfs = vfs;
4245
4488
  this.dir = dir.replace(/\/+$/, "") || "/skills";
4489
+ this.tab = currentTab();
4490
+ }
4491
+ /** The file system's database (undefined in memory): where its `skills` notices go out. */
4492
+ get dbName() {
4493
+ return this.vfs.dbName;
4494
+ }
4495
+ /** The other tabs hear which lesson, in which folder - never its text. */
4496
+ announce(op, name) {
4497
+ postStorageChangeFrom(this.tab, this.vfs.dbName, {
4498
+ kind: "skills",
4499
+ op,
4500
+ key: name,
4501
+ namespace: this.dir
4502
+ });
4246
4503
  }
4247
4504
  async list() {
4248
4505
  const out = [];
@@ -4276,12 +4533,14 @@ ${skill.content.trim()}
4276
4533
  mimeType: "application/json"
4277
4534
  });
4278
4535
  }
4536
+ this.announce("put", skill.name);
4279
4537
  }
4280
4538
  async remove(name) {
4281
4539
  if (!SKILL_NAME_RE.test(name)) return false;
4282
4540
  const folder = `${this.dir}/${name}`;
4283
4541
  const had = await this.vfs.delete(`${folder}/SKILL.md`);
4284
4542
  await this.vfs.delete(`${folder}/${ORIGIN_FILE}`);
4543
+ if (had) this.announce("delete", name);
4285
4544
  return had;
4286
4545
  }
4287
4546
  };
@@ -4289,12 +4548,10 @@ var createLearning = async (cfg, skills, warn) => {
4289
4548
  const store = cfg.store ?? new MemorySkillStore();
4290
4549
  const maxSkills = Math.max(1, cfg.maxSkills ?? DEFAULT_MAX_LEARNED_SKILLS);
4291
4550
  const maxChars = Math.max(MIN_INSTRUCTIONS_CHARS, cfg.maxSkillChars ?? DEFAULT_MAX_SKILL_CHARS);
4551
+ const lessonOf = (stored) => defineSkill({ ...stored, origin: stored.origin ?? { kind: "learned", at: 0, revision: 1 } });
4292
4552
  for (const stored of await store.list()) {
4293
4553
  try {
4294
- const skill = defineSkill({
4295
- ...stored,
4296
- origin: stored.origin ?? { kind: "learned", at: 0, revision: 1 }
4297
- });
4554
+ const skill = lessonOf(stored);
4298
4555
  if (skills.some((s) => s.name === skill.name)) {
4299
4556
  warn(
4300
4557
  `[learning] a stored lesson named "${skill.name}" clashes with a configured skill; skipped`
@@ -4307,6 +4564,27 @@ var createLearning = async (cfg, skills, warn) => {
4307
4564
  }
4308
4565
  }
4309
4566
  const learned = () => skills.filter((s) => s.origin?.kind === "learned");
4567
+ const reload = async () => {
4568
+ const fresh = /* @__PURE__ */ new Map();
4569
+ for (const stored of await store.list()) {
4570
+ try {
4571
+ const skill = lessonOf(stored);
4572
+ if (skills.some((s) => s.name === skill.name && s.origin?.kind !== "learned")) continue;
4573
+ fresh.set(skill.name, skill);
4574
+ } catch {
4575
+ }
4576
+ }
4577
+ for (let i = skills.length - 1; i >= 0; i -= 1) {
4578
+ const s = skills[i];
4579
+ if (s.origin?.kind === "learned" && !fresh.has(s.name)) skills.splice(i, 1);
4580
+ }
4581
+ for (const [name, skill] of fresh) {
4582
+ const at = skills.findIndex((s) => s.name === name);
4583
+ if (at >= 0) skills[at] = skill;
4584
+ else skills.push(skill);
4585
+ }
4586
+ return learned();
4587
+ };
4310
4588
  const save = async (input, options) => {
4311
4589
  const name = normalizeSkillName(input.name);
4312
4590
  if (!name) {
@@ -4417,7 +4695,7 @@ var createLearning = async (cfg, skills, warn) => {
4417
4695
  }
4418
4696
  })
4419
4697
  };
4420
- return { tools, learned, forget };
4698
+ return { tools, learned, forget, reload };
4421
4699
  };
4422
4700
 
4423
4701
  // src/prompts.ts
@@ -4427,14 +4705,22 @@ var stateBlock = (state) => state && state.trim() ? `
4427
4705
 
4428
4706
  STATE:
4429
4707
  ${state}` : "";
4430
- var historyBlock = (history) => {
4708
+ var ATTACHED_MARK = /\n\[attached: [^\]\n]*\]$/;
4709
+ var historyLine = (content, max) => {
4710
+ const mark = ATTACHED_MARK.exec(content)?.[0];
4711
+ if (!mark || content.length <= max) return clip(content, max);
4712
+ return `${clip(content.slice(0, -mark.length), Math.max(1, max - mark.length))}${mark}`;
4713
+ };
4714
+ var historyBlock = (history, perMessage = 400) => {
4431
4715
  if (!history || history.length === 0) return "";
4432
- const lines = history.slice(-8).map((m) => `${m.role}: ${clip(m.content, 400)}`);
4716
+ const lines = history.slice(-8).map((m) => `${m.role}: ${historyLine(m.content, perMessage)}`);
4433
4717
  return `
4434
4718
 
4435
4719
  CONVERSATION SO FAR:
4436
4720
  ${lines.join("\n")}`;
4437
4721
  };
4722
+ var hasAttachedMark = (content) => ATTACHED_MARK.test(content);
4723
+ var NO_ATTACHMENT_NOTE = `NOTE: nothing is attached to THIS message. The files of earlier messages (marked "[attached: ...]" in the conversation) are not visible to you now - only what was said about them then is. If this message is about a file you cannot see, say so and ask the user to attach it again; never describe a file you cannot see.`;
4438
4724
  var section = (title, body) => body && body.trim() ? `
4439
4725
 
4440
4726
  ${title}:
@@ -4463,17 +4749,17 @@ var PLANNER_RULES = `- Act autonomously: whenever the TOOLS can do the work or l
4463
4749
  - Never repeat or pad steps.`;
4464
4750
  var PLANNER_NATIVE = `You are the PLANNER of an autonomous tool-using agent that works step by step.
4465
4751
  Produce a brief "thought" and an ordered "steps" list (1\u20136 DISTINCT, self-contained steps).
4466
- Return an EMPTY steps list ONLY for a pure greeting, thanks or small talk, or a question you can answer completely from the STATE and general knowledge without any tool \u2014 then put the answer itself in "thought".
4752
+ Return an EMPTY steps list ONLY for a pure greeting, thanks or small talk, or a question that can be answered completely from the conversation, the STATE, what is attached to the message and general knowledge without any tool. Do NOT write the answer yourself: it is written right after you, from the same message. "thought" is your private one-sentence note; the user never sees it.
4467
4753
  ${PLANNER_RULES}`;
4468
4754
  var PLANNER_PROMPTED = `You are the PLANNER of an autonomous tool-using agent that works step by step.
4469
4755
 
4470
4756
  Reply with a single JSON object, nothing else:
4471
4757
  { "reply": string, "plan": string[], "skills": string[] }
4472
- - For a real goal: "reply" is one short sentence; "plan" is 1\u20136 DISTINCT, self-contained steps.
4473
- - Set "plan": [] ONLY for a pure greeting, thanks or small talk, or a question you can answer completely from the STATE and general knowledge without any tool \u2014 then put the answer itself in "reply".
4758
+ - "reply" is your private one-sentence note (the user never sees it); for a real goal "plan" is 1\u20136 DISTINCT, self-contained steps.
4759
+ - Set "plan": [] ONLY for a pure greeting, thanks or small talk, or a question that can be answered completely from the conversation, the STATE and general knowledge without any tool. Do NOT write the answer yourself: it is written right after you, from the same message.
4474
4760
  ${PLANNER_RULES}`;
4475
4761
  var PLANNER_SKILLS = `
4476
- If a SKILLS list is present, list the names of the skills that apply to this goal in "skills" (or leave it empty).`;
4762
+ "skills" takes names from the SKILLS list ONLY - packaged instructions, not tools: list the ones that apply to this goal, or leave it empty. Never put a name from TOOLS there.`;
4477
4763
  var COMPLEXITY_LEVELS = `low = mechanical work (a lookup, one obvious tool call, copying or reformatting data); medium = ordinary work (a few tool calls, some judgement); high = hard work (multi-part reasoning, analysis, writing or fixing code, weighing conflicting data). When unsure between two, choose the higher.`;
4478
4764
  var PLANNER_TIERS_NATIVE = `
4479
4765
  Steps run on models of different strength: set "complexity" on every step. ${COMPLEXITY_LEVELS}`;
@@ -4524,6 +4810,13 @@ var SYNTHESIZER_SYSTEM = `You are the SYNTHESIZER. Answer the user's goal from w
4524
4810
  - Mention any assumption the agent made. If something could not be done, say so plainly and why.
4525
4811
  - Do not ask follow-up questions unless the goal genuinely cannot be completed without the user.
4526
4812
  - Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON, no code.`;
4813
+ var SYNTHESIZER_DIRECT = `You are the SYNTHESIZER of an autonomous tool-using agent. The planner found that this message needs no tool, so no tool was run: write the answer to the user yourself.
4814
+ - Answer the message under GOAL from the CONVERSATION SO FAR, the STATE, anything attached to this message and general knowledge.
4815
+ - Nothing was done in this turn: never say that something was looked up, changed or created now. If the message needs an action or data you do not have, say plainly what is missing.
4816
+ - Answer in the language of the user's message. Be concise and friendly. Plain text (light markdown is fine) \u2014 no JSON.`;
4817
+ var DIRECT_HISTORY_CHARS = 2e3;
4818
+ var noteLine = (note) => note && note.trim() ? `
4819
+ ${note.trim()}` : "";
4527
4820
  var defaultPrompts = {
4528
4821
  planner: (ctx) => ({
4529
4822
  system: (ctx.mode === "prompted" ? PLANNER_PROMPTED : PLANNER_NATIVE) + (ctx.skills ? PLANNER_SKILLS : "") + (ctx.tiers ? ctx.mode === "prompted" ? PLANNER_TIERS_PROMPTED : PLANNER_TIERS_NATIVE : "") + (ctx.searchMode ? PLANNER_SEARCH : "") + (ctx.sandbox ? `
@@ -4531,13 +4824,13 @@ ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ct
4531
4824
 
4532
4825
  TOOLS:
4533
4826
  ${ctx.toolCatalog}`,
4534
- prompt: `GOAL: ${ctx.goal}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
4827
+ prompt: `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}${historyBlock(ctx.history)}${stateBlock(ctx.state)}`
4535
4828
  }),
4536
4829
  executor: (ctx) => ({
4537
4830
  system: (ctx.mode === "prompted" ? EXECUTOR_PROMPTED : EXECUTOR_NATIVE) + (ctx.searchMode ? EXECUTOR_SEARCH : "") + (ctx.skills ? EXECUTOR_SKILLS : "") + (ctx.learning ? executorLearning(ctx.learning.fetch) : "") + (ctx.sandbox ? `
4538
4831
  - ${ctx.sandbox}` : "") + section("HELPERS", ctx.subagents) + section("SKILLS", ctx.skills) + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
4539
4832
  prompt: [
4540
- `GOAL: ${ctx.goal}`,
4833
+ `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
4541
4834
  stateBlock(ctx.state).trimStart(),
4542
4835
  ctx.mode === "prompted" ? `TOOLS:
4543
4836
  ${ctx.toolCatalog}` : "",
@@ -4561,10 +4854,16 @@ ${numbered(ctx.remaining, "(none)")}`,
4561
4854
  ].filter(Boolean).join("\n\n")
4562
4855
  }),
4563
4856
  synthesizer: (ctx) => ({
4564
- system: SYNTHESIZER_SYSTEM + (ctx.sandbox ? `
4857
+ system: (ctx.direct ? SYNTHESIZER_DIRECT : SYNTHESIZER_SYSTEM) + (ctx.sandbox ? `
4565
4858
  - ${ctx.sandbox}` : "") + section("ACTIVE SKILL INSTRUCTIONS", ctx.activeSkills),
4566
- prompt: [
4567
- `GOAL: ${ctx.goal}`,
4859
+ prompt: ctx.direct ? [
4860
+ `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
4861
+ historyBlock(ctx.history, DIRECT_HISTORY_CHARS).trimStart(),
4862
+ stateBlock(ctx.state).trimStart(),
4863
+ updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
4864
+ "Write the answer for the user."
4865
+ ].filter(Boolean).join("\n\n") : [
4866
+ `GOAL: ${ctx.goal}${noteLine(ctx.attachments)}`,
4568
4867
  stateBlock(ctx.state).trimStart(),
4569
4868
  updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
4570
4869
  `What was done:
@@ -6781,6 +7080,12 @@ var followHumanWaits = (clock) => {
6781
7080
 
6782
7081
  // src/agent/control.ts
6783
7082
  var ports = /* @__PURE__ */ new WeakMap();
7083
+ var queuedEvent = (m) => ({
7084
+ type: "message.queued",
7085
+ id: m.id,
7086
+ text: m.text,
7087
+ ...m.origin ? { origin: m.origin } : {}
7088
+ });
6784
7089
  var portOf = (control) => {
6785
7090
  if (!control) return void 0;
6786
7091
  const port = ports.get(control);
@@ -6793,15 +7098,20 @@ var createRunControl = () => {
6793
7098
  let emit;
6794
7099
  let ended = false;
6795
7100
  const children = /* @__PURE__ */ new Map();
7101
+ const queueMessage = (text, origin) => {
7102
+ const clean = typeof text === "string" ? text.trim() : "";
7103
+ if (!clean || ended) return false;
7104
+ const message = {
7105
+ id: `msg-${seq4 += 1}`,
7106
+ text: clean,
7107
+ ...origin ? { origin } : {}
7108
+ };
7109
+ queue.push(message);
7110
+ emit?.(queuedEvent(message));
7111
+ return true;
7112
+ };
6796
7113
  const control = {
6797
- send(text) {
6798
- const clean = typeof text === "string" ? text.trim() : "";
6799
- if (!clean || ended) return false;
6800
- const message = { id: `msg-${seq4 += 1}`, text: clean };
6801
- queue.push(message);
6802
- emit?.({ type: "message.queued", id: message.id, text: message.text });
6803
- return true;
6804
- },
7114
+ send: (text) => queueMessage(text),
6805
7115
  pending: () => queue.map((m) => m.text),
6806
7116
  subagents: () => [...children.values()].map((c) => c.info).sort((a, b) => a.startedAt - b.startedAt),
6807
7117
  stopSubagent(id) {
@@ -6819,7 +7129,7 @@ var createRunControl = () => {
6819
7129
  }
6820
7130
  emit = next;
6821
7131
  ended = false;
6822
- for (const m of queue) next({ type: "message.queued", id: m.id, text: m.text });
7132
+ for (const m of queue) next(queuedEvent(m));
6823
7133
  },
6824
7134
  detach() {
6825
7135
  emit = void 0;
@@ -6832,6 +7142,7 @@ var createRunControl = () => {
6832
7142
  queue = [];
6833
7143
  return out;
6834
7144
  },
7145
+ sendFrom: (text, origin) => queueMessage(text, origin),
6835
7146
  registerSubagent(info, stop) {
6836
7147
  children.set(info.id, { info, stop });
6837
7148
  return () => {
@@ -7265,6 +7576,7 @@ init_tiers();
7265
7576
 
7266
7577
  // src/agent/internal.ts
7267
7578
  var import_ai11 = require("ai");
7579
+ init_util();
7268
7580
  init_images();
7269
7581
  var promptFor = (ctx, prompt) => ctx.images?.length ? {
7270
7582
  messages: [
@@ -7284,6 +7596,7 @@ var imageRefusal = (ctx, err, model) => {
7284
7596
  return unsupportedAttachment(modelLabel(model), kind, detail && `the provider said: ${detail}`);
7285
7597
  };
7286
7598
  var systemFor = (ctx, base) => withSystem(base, ctx.raw.systemPrompt);
7599
+ var aborted = (ctx) => ctx.signal?.aborted === true;
7287
7600
  var stageCall = (ctx, stage, baseSystem) => {
7288
7601
  const withMcp = ctx.mcpInstructions && (stage === "planner" || stage === "executor") ? `${baseSystem}
7289
7602
 
@@ -7295,23 +7608,44 @@ ${ctx.mcpInstructions}` : baseSystem;
7295
7608
  cachingProviderOptions(caching, ctx.config.clientName, stage),
7296
7609
  thinking.providerOptions
7297
7610
  );
7611
+ const cap2 = stageReasons(ctx.raw, stage) ? stageOutputCap(ctx.raw, stage, capWindow(ctx, stage)).tokens ?? 0 : ctx.config.budgets[stage];
7298
7612
  return {
7299
7613
  system: cachedInstructions(system, caching),
7300
7614
  ...thinking.reasoning ? { reasoning: thinking.reasoning } : {},
7301
7615
  ...providerOptions ? { providerOptions } : {},
7302
- ...ctx.config.budgets[stage] > 0 ? { maxOutputTokens: ctx.config.budgets[stage] } : {}
7616
+ ...cap2 > 0 ? { maxOutputTokens: cap2 } : {}
7303
7617
  };
7304
7618
  };
7305
- var capNotice = (ctx, stage, finishReason) => outputCapNotice(
7306
- ctx.raw,
7307
- stage,
7308
- (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens,
7309
- finishReason
7310
- );
7619
+ var capWindow = (ctx, stage) => (stage === "executor" ? ctx.executorWindowTokens : void 0) ?? ctx.config.compaction.contextWindowTokens;
7620
+ var cutWhileReasoning = (ctx, stage, finishReason, usage) => observeReasoning(ctx.raw, stage, capWindow(ctx, stage), finishReason, usage?.reasoningTokens);
7621
+ var withReasoningRoom = async (ctx, stage, phase, run, onWasted) => {
7622
+ const again = (why, spent2) => {
7623
+ onWasted(spent2);
7624
+ const message = `${why} - the model spent ${spent2.reasoningTokens ?? 0} of them reasoning: repeating the call without the default cap (this stage is not capped for this agent from now on)`;
7625
+ ctx.log.warn(message);
7626
+ ctx.emit({ type: "retry", phase, attempt: 1, error: message });
7627
+ return run();
7628
+ };
7629
+ let first;
7630
+ try {
7631
+ first = await run();
7632
+ } catch (err) {
7633
+ if (aborted(ctx) || !import_ai11.NoObjectGeneratedError.isInstance(err)) throw err;
7634
+ withCapHint(ctx, stage, err);
7635
+ const spent2 = usageOfError(err);
7636
+ if (!cutWhileReasoning(ctx, stage, err.finishReason, spent2)) throw err;
7637
+ return again(err.message, spent2);
7638
+ }
7639
+ const spent = normalizeUsage(first.usage);
7640
+ const notice = capNotice(ctx, stage, first.finishReason);
7641
+ if (!cutWhileReasoning(ctx, stage, first.finishReason, spent)) return first;
7642
+ return again(notice ?? `[${stage}] the model's output was cut off`, spent);
7643
+ };
7644
+ var capNotice = (ctx, stage, finishReason) => outputCapNotice(ctx.raw, stage, capWindow(ctx, stage), finishReason);
7311
7645
  var withCapHint = (ctx, stage, err) => {
7312
7646
  if (import_ai11.NoObjectGeneratedError.isInstance(err)) {
7313
7647
  const notice = capNotice(ctx, stage, err.finishReason);
7314
- if (notice) err.message = `${err.message} - ${notice}`;
7648
+ if (notice && !err.message.includes(notice)) err.message = `${err.message} - ${notice}`;
7315
7649
  }
7316
7650
  return err;
7317
7651
  };
@@ -7540,14 +7874,14 @@ var shareSubagentBudget = (parent, running, settings) => {
7540
7874
  var createSpawnGate = (max) => {
7541
7875
  let active = 0;
7542
7876
  const queue = [];
7543
- const aborted2 = () => {
7877
+ const aborted3 = () => {
7544
7878
  const e = new Error("Aborted");
7545
7879
  e.name = "AbortError";
7546
7880
  return e;
7547
7881
  };
7548
7882
  return (signal) => new Promise((resolve, reject) => {
7549
7883
  if (signal?.aborted) {
7550
- reject(aborted2());
7884
+ reject(aborted3());
7551
7885
  return;
7552
7886
  }
7553
7887
  const grant = () => {
@@ -7568,7 +7902,7 @@ var createSpawnGate = (max) => {
7568
7902
  if (i >= 0) {
7569
7903
  queue.splice(i, 1);
7570
7904
  }
7571
- reject(aborted2());
7905
+ reject(aborted3());
7572
7906
  }
7573
7907
  if (active < max) {
7574
7908
  grant();
@@ -7657,6 +7991,7 @@ var executeStep = async (base, goal, step, index, total, done, attempt = {}) =>
7657
7991
  const active = ctx.activeSkills?.() ?? [];
7658
7992
  const parts = ctx.prompts.executor({
7659
7993
  goal,
7994
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
7660
7995
  state,
7661
7996
  step: step.description,
7662
7997
  index,
@@ -7730,6 +8065,7 @@ ${renderEarlierAttempts(attempt.earlier)}` : parts.prompt;
7730
8065
  ctx.log.debug("executor text:", loop.text);
7731
8066
  const cut = capNotice(ctx, "executor", loop.finishReason);
7732
8067
  if (cut) ctx.log.warn(cut);
8068
+ cutWhileReasoning(ctx, "executor", loop.finishReason, loop.usage);
7733
8069
  const { summary, blocked } = splitBlocker(loop.text);
7734
8070
  return {
7735
8071
  result: {
@@ -7857,6 +8193,26 @@ var recordResume = async (persistence, resumed, attempt, warn) => {
7857
8193
  );
7858
8194
  }
7859
8195
  };
8196
+ var SERVER_ONLY = "is the server package's (@dudko.dev/agent), not this browser package's";
8197
+ var refuseServerOnlyConfig = (config) => {
8198
+ const c = config;
8199
+ for (const key of ["runLease", "sharedLimits"]) {
8200
+ if (c[key] !== void 0) {
8201
+ throw new Error(`${key} ${SERVER_ONLY}: a run in a page has no other worker to share with`);
8202
+ }
8203
+ }
8204
+ const persistence = c.persistence;
8205
+ if (persistence?.journal !== void 0) {
8206
+ throw new Error(
8207
+ `persistence.journal ${SERVER_ONLY}: a page's run is not resumed by another worker, and IndexedDB in a tab that may close at any moment is not the fail-closed store a journal needs`
8208
+ );
8209
+ }
8210
+ };
8211
+ var refuseServerOnlyRunOptions = (opts) => {
8212
+ if (opts.answers !== void 0) {
8213
+ throw new Error(`run({ answers }) ${SERVER_ONLY}: there are no parked runs here to answer`);
8214
+ }
8215
+ };
7860
8216
 
7861
8217
  // src/agent/planner.ts
7862
8218
  init_context_window();
@@ -7874,7 +8230,11 @@ var TieredPlanStepSchema = PlanStepSchema.extend({
7874
8230
  complexity: import_zod5.z.enum(["low", "medium", "high"]).optional()
7875
8231
  });
7876
8232
  var PlanSchema = import_zod5.z.object({
7877
- /** One short sentence. For a greeting/small talk, holds the answer and steps is empty. */
8233
+ /**
8234
+ * The planner's private one-sentence note. Never shown as an answer: with an empty `steps` (a
8235
+ * greeting, small talk, a question that needs no tool) the answer is written by the answering
8236
+ * stage.
8237
+ */
7878
8238
  thought: import_zod5.z.string(),
7879
8239
  steps: import_zod5.z.array(PlanStepSchema),
7880
8240
  /** Names of the configured skills that apply to this goal. */
@@ -7911,6 +8271,7 @@ ${nudge}` : goal;
7911
8271
  toolCatalog: ctx.toolCatalog,
7912
8272
  mode,
7913
8273
  history: ctx.history,
8274
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
7914
8275
  skills: skillIndex,
7915
8276
  searchMode: ctx.strategy === "search",
7916
8277
  ...ctx.sandbox ? { sandbox: ctx.sandbox.planner } : {},
@@ -7940,15 +8301,23 @@ ${nudge}` : goal;
7940
8301
  let wasted = normalizeUsage();
7941
8302
  if (ctx.plannerMode === "native") {
7942
8303
  try {
7943
- const result2 = await generateStructured(
7944
- ctx.plannerModel,
7945
- ctx.tiers ? TieredPlanSchema : PlanSchema,
7946
- commonFor("native")
8304
+ const result2 = await withReasoningRoom(
8305
+ ctx,
8306
+ "planner",
8307
+ "plan",
8308
+ () => generateStructured(
8309
+ ctx.plannerModel,
8310
+ ctx.tiers ? TieredPlanSchema : PlanSchema,
8311
+ commonFor("native")
8312
+ ),
8313
+ (spent) => {
8314
+ wasted = addUsage(wasted, spent);
8315
+ }
7947
8316
  );
7948
8317
  ctx.log.debug("planner (native):", result2.object);
7949
8318
  return {
7950
8319
  plan: { thought: result2.object.thought, steps: toSteps(result2.object.steps, cap2) },
7951
- usage: normalizeUsage(result2.usage),
8320
+ usage: addUsage(wasted, normalizeUsage(result2.usage)),
7952
8321
  skills: validSkills(result2.object.skills)
7953
8322
  };
7954
8323
  } catch (err) {
@@ -7957,16 +8326,26 @@ ${nudge}` : goal;
7957
8326
  if (refused) throw refused;
7958
8327
  const overflow = contextOverflowOf(err, ctx.plannerModel);
7959
8328
  if (overflow) throw overflow;
7960
- wasted = usageOfError(err);
8329
+ wasted = addUsage(wasted, usageOfError(err));
7961
8330
  const why = asMessage(withCapHint(ctx, "planner", err));
7962
8331
  ctx.log.warn("planner: native structured output failed, salvaging:", why);
7963
8332
  ctx.emit({ type: "retry", phase: "plan", attempt: 1, error: why });
7964
8333
  }
7965
8334
  }
7966
- const result = await generate(ctx.plannerModel, commonFor("prompted")).catch((err) => {
8335
+ const result = await withReasoningRoom(
8336
+ ctx,
8337
+ "planner",
8338
+ "plan",
8339
+ () => generate(ctx.plannerModel, commonFor("prompted")),
8340
+ (spent) => {
8341
+ wasted = addUsage(wasted, spent);
8342
+ }
8343
+ ).catch((err) => {
7967
8344
  throw imageRefusal(ctx, err, ctx.plannerModel) ?? contextOverflowOf(err, ctx.plannerModel) ?? err;
7968
8345
  });
7969
8346
  const parsed = parsePlannerResponse(result.text);
8347
+ const cut = result.finishReason === "length";
8348
+ const failed = parsed.plan.length === 0 && (cut || !result.text.trim()) ? capNotice(ctx, "planner", result.finishReason) ?? (cut ? "[planner] the model's output was cut off before it wrote a plan" : `[planner] the model returned no text (finish reason: ${result.finishReason})`) : void 0;
7970
8349
  ctx.log.debug("planner (prompted) raw:", result.text);
7971
8350
  ctx.log.debug("planner (prompted) parsed:", parsed);
7972
8351
  return {
@@ -7981,7 +8360,8 @@ ${nudge}` : goal;
7981
8360
  )
7982
8361
  },
7983
8362
  usage: addUsage(wasted, normalizeUsage(result.usage)),
7984
- skills: validSkills(parsed.skills)
8363
+ skills: validSkills(parsed.skills),
8364
+ ...failed ? { failed } : {}
7985
8365
  };
7986
8366
  };
7987
8367
  var asMessage = (err) => err instanceof Error ? err.message : String(err);
@@ -8294,23 +8674,39 @@ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
8294
8674
  let wasted = normalizeUsage();
8295
8675
  if (ctx.plannerMode === "native") {
8296
8676
  try {
8297
- const result = await generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native"));
8677
+ const result = await withReasoningRoom(
8678
+ ctx,
8679
+ "replanner",
8680
+ "replan",
8681
+ () => generateStructured(ctx.plannerModel, ReplanSchema, commonFor("native")),
8682
+ (spent) => {
8683
+ wasted = addUsage(wasted, spent);
8684
+ }
8685
+ );
8298
8686
  return {
8299
8687
  decision: result.object.decision,
8300
8688
  reason: result.object.reason,
8301
8689
  plan: result.object.plan ?? [],
8302
- usage: normalizeUsage(result.usage)
8690
+ usage: addUsage(wasted, normalizeUsage(result.usage))
8303
8691
  };
8304
8692
  } catch (err) {
8305
8693
  if (ctx.signal?.aborted) throw err;
8306
- wasted = usageOfError(err);
8694
+ wasted = addUsage(wasted, usageOfError(err));
8307
8695
  const why = asMessage2(withCapHint(ctx, "replanner", err));
8308
8696
  ctx.log.warn("replanner: native structured output failed, salvaging:", why);
8309
8697
  ctx.emit({ type: "retry", phase: "replan", attempt: 1, error: why });
8310
8698
  }
8311
8699
  }
8312
8700
  try {
8313
- const result = await generate(ctx.plannerModel, commonFor("prompted"));
8701
+ const result = await withReasoningRoom(
8702
+ ctx,
8703
+ "replanner",
8704
+ "replan",
8705
+ () => generate(ctx.plannerModel, commonFor("prompted")),
8706
+ (spent) => {
8707
+ wasted = addUsage(wasted, spent);
8708
+ }
8709
+ );
8314
8710
  const parsed = parseReplannerResponse(result.text);
8315
8711
  return {
8316
8712
  decision: parsed.decision,
@@ -8372,7 +8768,7 @@ var asMessage2 = (err) => err instanceof Error ? err.message : String(err);
8372
8768
  init_context_window();
8373
8769
  init_generate();
8374
8770
  init_util();
8375
- var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8771
+ var synthesizeAnswer = async (ctx, goal, done, findings = [], options = {}) => {
8376
8772
  const state = await ctx.state();
8377
8773
  const active = ctx.activeSkills?.() ?? [];
8378
8774
  const parts = ctx.prompts.synthesizer({
@@ -8382,8 +8778,32 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8382
8778
  findings,
8383
8779
  activeSkills: active.length ? renderActiveSkills(active) : void 0,
8384
8780
  updates: ctx.userUpdates?.(),
8385
- ...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {}
8781
+ ...ctx.sandbox ? { sandbox: ctx.sandbox.synthesizer } : {},
8782
+ ...ctx.attachmentsNote ? { attachments: ctx.attachmentsNote } : {},
8783
+ ...options.direct ? { direct: true, history: ctx.history } : {}
8386
8784
  });
8785
+ const first = await streamAnswer(ctx, parts);
8786
+ let last = first;
8787
+ let usage = first.usage;
8788
+ if (cutWhileReasoning(ctx, "synthesizer", first.finishReason, first.usage) && !first.shown) {
8789
+ const message = `${first.cut ?? "[synthesizer] the model's output was cut off"} - the model spent ${first.usage.reasoningTokens ?? 0} of them reasoning: repeating the call without the default cap`;
8790
+ ctx.log.warn(message);
8791
+ ctx.emit({ type: "retry", phase: "synthesize", attempt: 1, error: message });
8792
+ last = await streamAnswer(ctx, parts);
8793
+ usage = addUsage(usage, last.usage);
8794
+ } else if (first.cut) {
8795
+ ctx.log.warn(first.cut);
8796
+ }
8797
+ const text = parsePlainText(last.text);
8798
+ return {
8799
+ text,
8800
+ usage,
8801
+ ...text ? {} : {
8802
+ empty: last.cut ?? `[synthesizer] the model returned no text (finish reason: ${last.finishReason ?? "unknown"})`
8803
+ }
8804
+ };
8805
+ };
8806
+ var streamAnswer = async (ctx, parts) => {
8387
8807
  const result = stream(ctx.synthesizerModel, {
8388
8808
  ...stageCall(ctx, "synthesizer", parts.system),
8389
8809
  ...promptFor(ctx, parts.prompt),
@@ -8392,6 +8812,11 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8392
8812
  timeoutMs: ctx.config.chatTimeoutMs
8393
8813
  });
8394
8814
  let text = "";
8815
+ let shown = false;
8816
+ const show = (delta) => {
8817
+ shown = true;
8818
+ ctx.emit({ type: "final.text-delta", delta });
8819
+ };
8395
8820
  let verdict = "unknown";
8396
8821
  for await (const part of result.fullStream) {
8397
8822
  if (part.type === "reasoning-delta") {
@@ -8412,19 +8837,19 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
8412
8837
  verdict = looksLikeJson(lead) ? "suppress" : "emit";
8413
8838
  if (verdict === "emit") {
8414
8839
  const visible = text.includes("</think>") ? text.slice(text.lastIndexOf("</think>") + "</think>".length).trimStart() : text;
8415
- if (visible) ctx.emit({ type: "final.text-delta", delta: visible });
8840
+ if (visible) show(visible);
8416
8841
  }
8417
8842
  } else if (verdict === "emit") {
8418
- ctx.emit({ type: "final.text-delta", delta });
8843
+ show(delta);
8419
8844
  }
8420
8845
  }
8421
8846
  const [usage, finishReason] = await Promise.all([result.usage, result.finishReason]);
8422
- const cut = capNotice(ctx, "synthesizer", finishReason);
8423
- if (cut) ctx.log.warn(cut);
8424
- const clean = parsePlainText(text);
8425
8847
  return {
8426
- text: clean || "Done \u2014 the changes have been applied.",
8427
- usage: normalizeUsage(usage)
8848
+ text,
8849
+ usage: normalizeUsage(usage),
8850
+ finishReason,
8851
+ cut: capNotice(ctx, "synthesizer", finishReason),
8852
+ shown
8428
8853
  };
8429
8854
  };
8430
8855
 
@@ -8802,7 +9227,488 @@ var createDynamicSubagentTool = (deps) => {
8802
9227
  return markReadOnly(t);
8803
9228
  };
8804
9229
 
9230
+ // src/sync/session.ts
9231
+ init_tab();
9232
+ var SESSION_LOCK_MODES = ["wait", "fail", "off"];
9233
+ var SessionBusyError = class extends Error {
9234
+ sessionId;
9235
+ heldBy;
9236
+ constructor(sessionId, heldBy) {
9237
+ super(
9238
+ `session "${sessionId}" is already running ${heldBy === "this-tab" ? "in this tab" : "in another tab"}; with sessionLock 'fail' a run does not wait for it`
9239
+ );
9240
+ this.name = "SessionBusyError";
9241
+ this.sessionId = sessionId;
9242
+ this.heldBy = heldBy;
9243
+ }
9244
+ };
9245
+ var sessionLockName = (dbName, sessionId) => `@dudko.dev/agent-web/session:${scopeOf(dbName)}:${encodeURIComponent(sessionId)}`;
9246
+ var RELAY_MAX_STRING = 8e3;
9247
+ var RELAY_MAX_ARRAY = 200;
9248
+ var RELAY_MAX_KEYS = 100;
9249
+ var RELAY_MAX_DEPTH = 8;
9250
+ var RELAY_MAX_REPLAY_EVENTS = 2e3;
9251
+ var RELAY_MAX_REPLAY_CHARS = 2e6;
9252
+ var RELAY_MAX_SEND_CHARS = 32e3;
9253
+ var RELAY_MAX_SENDS = 50;
9254
+ var RELAY_MAX_REPLAYS_PER_SECOND = 8;
9255
+ var WATCH_RESYNC_MS = 1e3;
9256
+ var WATCH_HOLDER_POLL_MS = 1e3;
9257
+ var WATCH_MAX_PENDING = 500;
9258
+ var ACK_TIMEOUT_MS = 3e3;
9259
+ var GONE_GRACE_MS = 300;
9260
+ var RUN_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
9261
+ var EVENT_TYPE_RE = /^[a-z][a-z0-9.-]{0,63}$/;
9262
+ var UNSAFE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
9263
+ var clipText = (s) => s.length > RELAY_MAX_STRING ? `${s.slice(0, RELAY_MAX_STRING - 1)}\u2026` : s;
9264
+ var slimEvent = (value, depth = 0) => {
9265
+ if (typeof value === "string") return clipText(value);
9266
+ if (typeof value === "number" || typeof value === "boolean" || value === null) return value;
9267
+ if (typeof value === "bigint") return value.toString();
9268
+ if (typeof value !== "object") return void 0;
9269
+ if (value instanceof Error) return clipText(value.message);
9270
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
9271
+ return `[${value.byteLength} bytes]`;
9272
+ }
9273
+ if (depth >= RELAY_MAX_DEPTH) return "[\u2026]";
9274
+ if (Array.isArray(value)) {
9275
+ const out2 = value.slice(0, RELAY_MAX_ARRAY).map((v) => slimEvent(v, depth + 1) ?? null);
9276
+ if (value.length > RELAY_MAX_ARRAY) out2.push(`[\u2026 ${value.length - RELAY_MAX_ARRAY} more]`);
9277
+ return out2;
9278
+ }
9279
+ const out = {};
9280
+ let keys = 0;
9281
+ for (const [k, v] of Object.entries(value)) {
9282
+ if (UNSAFE_KEYS.has(k)) continue;
9283
+ if (keys >= RELAY_MAX_KEYS) break;
9284
+ keys += 1;
9285
+ const s = slimEvent(v, depth + 1);
9286
+ if (s !== void 0) out[k] = s;
9287
+ }
9288
+ return out;
9289
+ };
9290
+ var charsOf = (value) => {
9291
+ if (typeof value === "string") return value.length;
9292
+ if (Array.isArray(value)) return value.reduce((n, v) => n + charsOf(v), 2);
9293
+ if (isRecord(value)) {
9294
+ let n = 2;
9295
+ for (const [k, v] of Object.entries(value)) n += k.length + charsOf(v);
9296
+ return n;
9297
+ }
9298
+ return 4;
9299
+ };
9300
+ var relayedEventOf = (value) => {
9301
+ if (!isRecord(value) || typeof value.type !== "string" || !EVENT_TYPE_RE.test(value.type)) {
9302
+ return void 0;
9303
+ }
9304
+ return slimEvent(value);
9305
+ };
9306
+ var idOk = (value) => typeof value === "string" && SYNC_ID_RE.test(value);
9307
+ var watcherMessageOf = (data) => {
9308
+ if (!isRecord(data) || data.v !== SYNC_VERSION || !idOk(data.from) || !idOk(data.id)) {
9309
+ return void 0;
9310
+ }
9311
+ if (data.t === "hello" || data.t === "stop") return { t: data.t, id: data.id };
9312
+ if (data.t === "send" && typeof data.text === "string") {
9313
+ return { t: "send", id: data.id, text: data.text };
9314
+ }
9315
+ return void 0;
9316
+ };
9317
+ var countOk = (value, min) => typeof value === "number" && Number.isSafeInteger(value) && value >= min;
9318
+ var holderMessageOf = (data) => {
9319
+ if (!isRecord(data) || data.v !== SYNC_VERSION || !idOk(data.from)) return void 0;
9320
+ if (data.t === "ack") {
9321
+ return idOk(data.id) && typeof data.ok === "boolean" ? { t: "ack", id: data.id, ok: data.ok } : void 0;
9322
+ }
9323
+ if (typeof data.runId !== "string" || !RUN_ID_RE.test(data.runId)) return void 0;
9324
+ const runId = data.runId;
9325
+ switch (data.t) {
9326
+ case "run":
9327
+ return data.state === "running" || data.state === "idle" ? { t: "run", runId, state: data.state, stopped: data.stopped === true } : void 0;
9328
+ case "event": {
9329
+ const event = relayedEventOf(data.event);
9330
+ return countOk(data.n, 1) && event ? { t: "event", runId, n: data.n, event } : void 0;
9331
+ }
9332
+ case "replay": {
9333
+ if (!idOk(data.to) || !countOk(data.n, 0) || !Array.isArray(data.events)) return void 0;
9334
+ if (data.events.length > RELAY_MAX_REPLAY_EVENTS) return void 0;
9335
+ const ns = data.ns;
9336
+ const top = data.n;
9337
+ if (!Array.isArray(ns) || ns.length !== data.events.length) return void 0;
9338
+ if (!ns.every((x, i) => countOk(x, 1) && x <= top && (i === 0 || x > ns[i - 1]))) {
9339
+ return void 0;
9340
+ }
9341
+ const events = [];
9342
+ for (const raw of data.events) {
9343
+ const event = relayedEventOf(raw);
9344
+ if (!event) return void 0;
9345
+ events.push(event);
9346
+ }
9347
+ return {
9348
+ t: "replay",
9349
+ to: data.to,
9350
+ runId,
9351
+ n: data.n,
9352
+ ns,
9353
+ events,
9354
+ truncated: data.truncated === true
9355
+ };
9356
+ }
9357
+ default:
9358
+ return void 0;
9359
+ }
9360
+ };
9361
+ var inheritedLocks = /* @__PURE__ */ new WeakMap();
9362
+ var withSessionLocks = (options, names) => {
9363
+ if (names.length) inheritedLocks.set(options, [...names]);
9364
+ return options;
9365
+ };
9366
+ var sessionLocksOf = (options) => inheritedLocks.get(options) ?? [];
9367
+ var abortError2 = () => {
9368
+ const err = new Error("The run was stopped while it waited for the session");
9369
+ err.name = "AbortError";
9370
+ return err;
9371
+ };
9372
+ var acquireSessionLock = async (o) => {
9373
+ const take = (options) => new Promise((resolve, reject) => {
9374
+ let granted = false;
9375
+ let request = void 0;
9376
+ request = o.locks.request(o.name, options, (lock) => {
9377
+ granted = true;
9378
+ if (!lock) {
9379
+ resolve(null);
9380
+ return void 0;
9381
+ }
9382
+ return new Promise((free) => {
9383
+ o.tab.held.add(o.name);
9384
+ let released;
9385
+ resolve({
9386
+ name: o.name,
9387
+ release: () => {
9388
+ if (!released) {
9389
+ o.tab.held.delete(o.name);
9390
+ free();
9391
+ released = request.then(
9392
+ () => void 0,
9393
+ () => void 0
9394
+ );
9395
+ }
9396
+ return released;
9397
+ }
9398
+ });
9399
+ });
9400
+ }).catch((err) => {
9401
+ if (!granted) reject(err);
9402
+ });
9403
+ });
9404
+ if (o.signal?.aborted) throw abortError2();
9405
+ let now;
9406
+ try {
9407
+ now = await take({ ifAvailable: true });
9408
+ } catch (err) {
9409
+ return { unavailable: err };
9410
+ }
9411
+ if (now) return { hold: now };
9412
+ const exclusive = await heldExclusively(o.locks, o.name);
9413
+ const busy = exclusive !== false;
9414
+ if (busy) {
9415
+ const heldBy = o.tab.held.has(o.name) ? "this-tab" : "another-tab";
9416
+ if (o.mode === "fail") throw new SessionBusyError(o.sessionId, heldBy);
9417
+ o.onBusy(heldBy);
9418
+ }
9419
+ const started = Date.now();
9420
+ try {
9421
+ const hold = await take(o.signal ? { signal: o.signal } : {});
9422
+ return { hold, ...busy ? { waitedMs: Date.now() - started } : {} };
9423
+ } catch (err) {
9424
+ if (o.signal?.aborted) throw abortError2();
9425
+ return { unavailable: err };
9426
+ }
9427
+ };
9428
+ var DELTAS = /* @__PURE__ */ new Set([
9429
+ "plan.thought-delta",
9430
+ "step.text-delta",
9431
+ "step.reasoning-delta",
9432
+ "final.text-delta",
9433
+ "final.reasoning-delta"
9434
+ ]);
9435
+ var deltaKey = (e) => `${String(e.type)}\0${String(e.step?.id ?? "")}\0${String(e.nodeId ?? "")}\0${String(e.visit ?? "")}`;
9436
+ var anySignal = (host, own) => {
9437
+ if (!host) return own;
9438
+ const any = AbortSignal.any;
9439
+ if (typeof any === "function") return any([host, own]);
9440
+ const both = new AbortController();
9441
+ for (const s of [host, own]) {
9442
+ if (s.aborted) both.abort(s.reason);
9443
+ else s.addEventListener("abort", () => both.abort(s.reason), { once: true });
9444
+ }
9445
+ return both.signal;
9446
+ };
9447
+ var startSessionRelay = (o) => {
9448
+ const hub = hubOf(o.tab, sessionLockName(o.dbName, o.sessionId));
9449
+ if (!hub) return void 0;
9450
+ const stopper = new AbortController();
9451
+ const signal = anySignal(o.signal, stopper.signal);
9452
+ const from = o.tab.id;
9453
+ const buffer = [];
9454
+ let chars = 0;
9455
+ let truncated2 = false;
9456
+ let n = 0;
9457
+ let sends = 0;
9458
+ let ended = false;
9459
+ let watched = false;
9460
+ const replayed = /* @__PURE__ */ new Set();
9461
+ const recentReplays = [];
9462
+ const port = o.remoteControl ? portOf(o.control) : void 0;
9463
+ const post = (message) => hub.post({ v: SYNC_VERSION, from, runId: o.runId, ...message });
9464
+ const ack = (id, ok) => hub.post({ v: SYNC_VERSION, from, t: "ack", id, ok });
9465
+ const keep = (event) => {
9466
+ const last = buffer[buffer.length - 1];
9467
+ const key = DELTAS.has(String(event.type)) ? deltaKey(event) : void 0;
9468
+ if (key && last?.key === key) {
9469
+ const joined = `${String(last.event.delta ?? "")}${String(event.delta ?? "")}`;
9470
+ if (joined.length <= RELAY_MAX_STRING) {
9471
+ chars += String(event.delta ?? "").length;
9472
+ last.event = { ...last.event, delta: joined, ...event.seq ? { seq: event.seq } : {} };
9473
+ last.n = n;
9474
+ return;
9475
+ }
9476
+ }
9477
+ buffer.push({ n, event, ...key ? { key } : {} });
9478
+ chars += charsOf(event);
9479
+ while (buffer.length > 1 && (buffer.length > RELAY_MAX_REPLAY_EVENTS || chars > RELAY_MAX_REPLAY_CHARS)) {
9480
+ const [dropped] = buffer.splice(1, 1);
9481
+ chars -= charsOf(dropped.event);
9482
+ truncated2 = true;
9483
+ }
9484
+ };
9485
+ const unlisten = hub.listen((data) => {
9486
+ if (ended) return;
9487
+ const m = watcherMessageOf(data);
9488
+ if (!m) return;
9489
+ if (m.t === "hello") {
9490
+ if (replayed.has(m.id)) return;
9491
+ if (replayed.size >= 4096) replayed.clear();
9492
+ replayed.add(m.id);
9493
+ watched = true;
9494
+ const now = Date.now();
9495
+ while (recentReplays.length && now - recentReplays[0] >= 1e3) recentReplays.shift();
9496
+ const full = recentReplays.length < RELAY_MAX_REPLAYS_PER_SECOND;
9497
+ if (full) recentReplays.push(now);
9498
+ post({
9499
+ t: "replay",
9500
+ to: m.id,
9501
+ n,
9502
+ events: full ? buffer.map((b) => b.event) : [],
9503
+ ns: full ? buffer.map((b) => b.n) : [],
9504
+ ...truncated2 || !full ? { truncated: true } : {}
9505
+ });
9506
+ return;
9507
+ }
9508
+ if (!o.remoteControl) {
9509
+ ack(m.id, false);
9510
+ return;
9511
+ }
9512
+ if (m.t === "stop") {
9513
+ stopper.abort();
9514
+ ack(m.id, true);
9515
+ return;
9516
+ }
9517
+ const text = m.text.trim();
9518
+ if (!port || !text || text.length > RELAY_MAX_SEND_CHARS || sends >= RELAY_MAX_SENDS) {
9519
+ ack(m.id, false);
9520
+ return;
9521
+ }
9522
+ sends += 1;
9523
+ ack(m.id, port.sendFrom(text, "another-tab"));
9524
+ });
9525
+ post({ t: "run", state: "running" });
9526
+ return {
9527
+ signal,
9528
+ event(event) {
9529
+ if (ended) return;
9530
+ const slim = slimEvent(event);
9531
+ n += 1;
9532
+ if (watched) post({ t: "event", n, event: slim });
9533
+ keep(slim);
9534
+ },
9535
+ end(stopped) {
9536
+ if (ended) return;
9537
+ ended = true;
9538
+ post({ t: "run", state: "idle", ...stopped ? { stopped: true } : {} });
9539
+ unlisten();
9540
+ }
9541
+ };
9542
+ };
9543
+ var watchSession = (options) => {
9544
+ const dbName = options.dbName ?? "agent-web";
9545
+ const name = sessionLockName(dbName, String(options.sessionId ?? ""));
9546
+ const tab = currentTab();
9547
+ const hub = options.sessionId ? hubOf(tab, name) : void 0;
9548
+ let state = { running: false };
9549
+ const inert = {
9550
+ get state() {
9551
+ return state;
9552
+ },
9553
+ send: async () => false,
9554
+ stop: async () => false,
9555
+ close: () => void 0
9556
+ };
9557
+ if (!hub) return inert;
9558
+ let id = newSyncId();
9559
+ let closed = false;
9560
+ let following;
9561
+ let lastN = 0;
9562
+ let pending = [];
9563
+ let lastHello = 0;
9564
+ let epoch = 0;
9565
+ const acks = /* @__PURE__ */ new Map();
9566
+ let holderPoll;
9567
+ const setState = (next) => {
9568
+ state = next;
9569
+ try {
9570
+ options.onState?.(next);
9571
+ } catch {
9572
+ }
9573
+ };
9574
+ const deliver = (event) => {
9575
+ try {
9576
+ options.onEvent?.(event);
9577
+ } catch {
9578
+ }
9579
+ };
9580
+ const hello = () => {
9581
+ id = newSyncId();
9582
+ lastHello = Date.now();
9583
+ hub.post({ v: SYNC_VERSION, from: tab.id, t: "hello", id });
9584
+ };
9585
+ const resync = () => {
9586
+ if (Date.now() - lastHello >= WATCH_RESYNC_MS) hello();
9587
+ };
9588
+ const stopPolling = () => {
9589
+ if (holderPoll !== void 0) clearInterval(holderPoll);
9590
+ holderPoll = void 0;
9591
+ };
9592
+ const endRun = (ended) => {
9593
+ stopPolling();
9594
+ setState({ running: false, ...state.runId ? { runId: state.runId } : {}, ended });
9595
+ following = void 0;
9596
+ pending = [];
9597
+ };
9598
+ const seeRun = (runId, truncated2 = false) => {
9599
+ if (!(state.running && state.runId === runId)) epoch += 1;
9600
+ setState({ running: true, runId, ...truncated2 ? { truncated: true } : {} });
9601
+ watchForEnd();
9602
+ };
9603
+ const watchForEnd = () => {
9604
+ const locks = lockManager();
9605
+ if (!locks || typeof locks.query !== "function" || holderPoll !== void 0 || closed) return;
9606
+ const armed = epoch;
9607
+ let checking = false;
9608
+ holderPoll = setInterval(() => {
9609
+ if (checking) return;
9610
+ checking = true;
9611
+ void heldExclusively(locks, name).then((held) => {
9612
+ checking = false;
9613
+ if (held !== false || closed || epoch !== armed || !state.running) return;
9614
+ stopPolling();
9615
+ setTimeout(() => {
9616
+ if (!closed && state.running && epoch === armed) endRun("gone");
9617
+ }, GONE_GRACE_MS);
9618
+ });
9619
+ }, WATCH_HOLDER_POLL_MS);
9620
+ holderPoll.unref?.();
9621
+ };
9622
+ const unlisten = hub.listen((data) => {
9623
+ if (closed) return;
9624
+ const m = holderMessageOf(data);
9625
+ if (!m) return;
9626
+ switch (m.t) {
9627
+ case "ack":
9628
+ acks.get(m.id)?.(m.ok);
9629
+ return;
9630
+ case "run":
9631
+ if (m.state === "running") {
9632
+ if (following === m.runId) return;
9633
+ seeRun(m.runId);
9634
+ hello();
9635
+ } else if (state.running && state.runId === m.runId) {
9636
+ endRun(m.stopped ? "stopped" : "done");
9637
+ }
9638
+ return;
9639
+ case "event":
9640
+ if (following === m.runId) {
9641
+ if (m.n <= lastN) return;
9642
+ if (m.n !== lastN + 1) {
9643
+ resync();
9644
+ return;
9645
+ }
9646
+ lastN = m.n;
9647
+ deliver(m.event);
9648
+ } else if (pending.length < WATCH_MAX_PENDING) {
9649
+ pending.push({ runId: m.runId, n: m.n, event: m.event });
9650
+ }
9651
+ return;
9652
+ case "replay": {
9653
+ if (m.to !== id) return;
9654
+ const known = following === m.runId ? lastN : 0;
9655
+ const later = pending.filter((p) => p.runId === m.runId && p.n > m.n).sort((a, b) => a.n - b.n);
9656
+ pending = [];
9657
+ following = m.runId;
9658
+ if (!(state.running && state.runId === m.runId)) seeRun(m.runId, m.truncated);
9659
+ else if (m.truncated && !state.truncated) setState({ ...state, truncated: true });
9660
+ m.events.forEach((event, i) => {
9661
+ if (m.ns[i] > known) deliver(event);
9662
+ });
9663
+ lastN = Math.max(known, m.n);
9664
+ for (const p of later) {
9665
+ if (p.n !== lastN + 1) break;
9666
+ lastN = p.n;
9667
+ deliver(p.event);
9668
+ }
9669
+ return;
9670
+ }
9671
+ }
9672
+ });
9673
+ const ask = (message) => {
9674
+ if (closed || !state.running) return Promise.resolve(false);
9675
+ const requestId = newSyncId();
9676
+ return new Promise((resolve) => {
9677
+ const timer = setTimeout(() => {
9678
+ acks.delete(requestId);
9679
+ resolve(false);
9680
+ }, ACK_TIMEOUT_MS);
9681
+ acks.set(requestId, (ok) => {
9682
+ clearTimeout(timer);
9683
+ acks.delete(requestId);
9684
+ resolve(ok);
9685
+ });
9686
+ hub.post({ v: SYNC_VERSION, from: tab.id, id: requestId, ...message });
9687
+ });
9688
+ };
9689
+ hello();
9690
+ return {
9691
+ get state() {
9692
+ return state;
9693
+ },
9694
+ send: (text) => {
9695
+ const clean = typeof text === "string" ? text.trim() : "";
9696
+ if (!clean || clean.length > RELAY_MAX_SEND_CHARS) return Promise.resolve(false);
9697
+ return ask({ t: "send", text: clean });
9698
+ },
9699
+ stop: () => ask({ t: "stop" }),
9700
+ close: () => {
9701
+ if (closed) return;
9702
+ closed = true;
9703
+ unlisten();
9704
+ stopPolling();
9705
+ for (const resolve of [...acks.values()]) resolve(false);
9706
+ }
9707
+ };
9708
+ };
9709
+
8805
9710
  // src/agent/runner.ts
9711
+ init_tab();
8806
9712
  var newRunId = () => globalThis.crypto?.randomUUID?.() ?? `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
8807
9713
  var errMessage = (err) => err instanceof Error ? err.message : String(err);
8808
9714
  var modelIdOf2 = (model) => typeof model === "string" ? model : model.modelId ?? "unknown";
@@ -8824,7 +9730,21 @@ var asJson2 = (v) => {
8824
9730
  var FINDING_CHARS = 600;
8825
9731
  var FINDINGS_BUDGET = 6e3;
8826
9732
  var createAgent = async (config) => {
9733
+ refuseServerOnlyConfig(config);
8827
9734
  const cfg = resolveConfig(config);
9735
+ const lockMode = config.sessionLock ?? "wait";
9736
+ if (!SESSION_LOCK_MODES.includes(lockMode)) {
9737
+ throw new Error(`unknown sessionLock "${String(lockMode)}" (${SESSION_LOCK_MODES.join(" | ")})`);
9738
+ }
9739
+ const sharedDb = typeof config.memory?.dbName === "string" && config.memory.dbName ? config.memory.dbName : void 0;
9740
+ const tab = currentTab();
9741
+ let warnedNoLocks = false;
9742
+ let warnedBusy = false;
9743
+ const relayOn = config.sessionRelay !== false;
9744
+ const relayControl = typeof config.sessionRelay === "object" && config.sessionRelay !== null ? config.sessionRelay.control !== false : true;
9745
+ if (config.sessionRelay !== void 0 && config.sessionRelay !== false && (typeof config.sessionRelay !== "object" || config.sessionRelay === null)) {
9746
+ throw new Error("sessionRelay must be false or { control?: boolean }");
9747
+ }
8828
9748
  const dynamicSubagents = resolveDynamicSubagents(config.subagents);
8829
9749
  const seed = spawnSeedOf(config);
8830
9750
  const buildStage = (override, stageName) => buildModelFromStage(
@@ -9030,21 +9950,114 @@ ${renderActiveSkills(active)}`
9030
9950
  spentAll = addUsage(spentAll, u);
9031
9951
  spentBySession.set(sessionId, addUsage(spentBySession.get(sessionId) ?? emptyUsage(), u));
9032
9952
  };
9033
- const runCore = async (goal, opts, track, port) => {
9034
- const ownRunId = await resolveRunId(config.persistence, opts.runId, opts.resumeFromRunId);
9035
- const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
9953
+ const announce = (onEvent, event) => {
9954
+ try {
9955
+ onEvent?.(event);
9956
+ } catch {
9957
+ }
9958
+ };
9959
+ const noLocks = (why) => {
9960
+ if (!warnedNoLocks) {
9961
+ warnedNoLocks = true;
9962
+ log.warn(`sessionLock: ${why} - runs of one session in two tabs are not kept apart`);
9963
+ }
9964
+ return void 0;
9965
+ };
9966
+ const lockSession = async (given, mode = lockMode === "fail" ? "fail" : "wait") => {
9967
+ if (!sharedDb || lockMode === "off") return void 0;
9968
+ if (given.runId !== void 0) assertSafeRunId(given.runId, "runId");
9969
+ const sessionId = given.resumeFromRunId !== void 0 ? (await resolveResume(config.persistence, given.resumeFromRunId)).sessionId : given.sessionId ?? cfg.sessionId;
9970
+ const name = sessionLockName(sharedDb, sessionId);
9971
+ if (sessionLocksOf(given).includes(name)) return void 0;
9972
+ const locks = lockManager();
9973
+ if (!locks) return noLocks("this browser has no Web Locks (navigator.locks)");
9974
+ const taken = await acquireSessionLock({
9975
+ locks,
9976
+ tab,
9977
+ name,
9978
+ sessionId,
9979
+ mode,
9980
+ signal: given.signal,
9981
+ onBusy: (heldBy) => {
9982
+ if (!warnedBusy) {
9983
+ warnedBusy = true;
9984
+ log.warn(
9985
+ `session "${sessionId}" is already running ${heldBy === "this-tab" ? "in this tab" : "in another tab"}: this run waits for it (sessionLock 'wait'; 'fail' refuses, 'off' runs both)`
9986
+ );
9987
+ } else log.info(`session "${sessionId}" is running ${heldBy}; waiting for it`);
9988
+ announce(given.onEvent, { type: "session.busy", sessionId, heldBy });
9989
+ }
9990
+ });
9991
+ if (taken.unavailable !== void 0 || !taken.hold) {
9992
+ return noLocks(`the lock manager refused (${errMessage(taken.unavailable)})`);
9993
+ }
9994
+ if (taken.waitedMs !== void 0) {
9995
+ announce(given.onEvent, { type: "session.acquired", sessionId, waitedMs: taken.waitedMs });
9996
+ }
9997
+ return taken.hold;
9998
+ };
9999
+ const runCore = async (goal, given, track, port) => {
10000
+ let hold;
10001
+ try {
10002
+ hold = await lockSession(given);
10003
+ } catch (err) {
10004
+ if (!given.signal?.aborted) throw err;
10005
+ announce(given.onEvent, { type: "stopped" });
10006
+ return {
10007
+ runId: given.resumeFromRunId ?? given.runId ?? newRunId(),
10008
+ goal: goal.trim(),
10009
+ final: "",
10010
+ plan: { thought: "", steps: [] },
10011
+ trace: [],
10012
+ steps: 0,
10013
+ applied: 0,
10014
+ stopped: true,
10015
+ usage: emptyUsage(),
10016
+ skills: []
10017
+ };
10018
+ }
10019
+ let relay;
10020
+ if (hold) {
10021
+ const held = hold;
10022
+ track.end = (stopped) => {
10023
+ relay?.end(stopped);
10024
+ return held.release();
10025
+ };
10026
+ }
10027
+ const ownRunId = await resolveRunId(config.persistence, given.runId, given.resumeFromRunId);
10028
+ const resumed = await resolveResume(config.persistence, given.resumeFromRunId);
10029
+ const sessionId = resumed?.sessionId ?? given.sessionId ?? cfg.sessionId;
10030
+ const runId = resumed?.runId ?? ownRunId ?? newRunId();
10031
+ if (hold && sharedDb && sessionLockName(sharedDb, sessionId) !== hold.name) {
10032
+ throw new Error(
10033
+ `persistence changed the session of run "${runId}" while it waited for it; refusing to run it`
10034
+ );
10035
+ }
10036
+ if (hold && sharedDb && relayOn) {
10037
+ relay = startSessionRelay({
10038
+ tab,
10039
+ dbName: sharedDb,
10040
+ sessionId,
10041
+ runId,
10042
+ remoteControl: relayControl,
10043
+ ...given.control ? { control: given.control } : {},
10044
+ ...given.signal ? { signal: given.signal } : {}
10045
+ });
10046
+ }
10047
+ const opts = relay ? { ...given, signal: relay.signal } : given;
10048
+ const sessionLocks = hold ? [...sessionLocksOf(given), hold.name] : sessionLocksOf(given);
9036
10049
  const attempt = resumed ? resumeAttemptOf(resumed) : 1;
9037
10050
  let seq4 = 0;
9038
10051
  const emit = (event) => {
10052
+ const numbered2 = { ...event, seq: ++seq4, attempt };
9039
10053
  try {
9040
- opts.onEvent?.({ ...event, seq: ++seq4, attempt });
10054
+ opts.onEvent?.(numbered2);
9041
10055
  } catch {
9042
10056
  }
10057
+ relay?.event(numbered2);
9043
10058
  };
9044
10059
  if (resumed) await recordResume(config.persistence, resumed, attempt, (m) => log.warn(m));
9045
10060
  let text = (resumed?.goal ?? goal).trim();
9046
- const sessionId = resumed?.sessionId ?? opts.sessionId ?? cfg.sessionId;
9047
- const runId = resumed?.runId ?? ownRunId ?? newRunId();
9048
10061
  const startedAt = resumed?.startedAt ?? Date.now();
9049
10062
  let usage = resumed ? { ...resumed.usage } : emptyUsage();
9050
10063
  const result = {
@@ -9202,7 +10215,8 @@ ${renderActiveSkills(active)}`
9202
10215
  fetched,
9203
10216
  stepWrites: () => stepWrites,
9204
10217
  clock,
9205
- mcpSkills: mcpSkillsActing
10218
+ mcpSkills: mcpSkillsActing,
10219
+ sessionLocks: () => sessionLocks
9206
10220
  }
9207
10221
  );
9208
10222
  const deliver = (at) => {
@@ -9210,7 +10224,13 @@ ${renderActiveSkills(active)}`
9210
10224
  const taken = port.drain();
9211
10225
  for (const m of taken) {
9212
10226
  userUpdates.push({ text: m.text, reconciled: false });
9213
- emit({ type: "message.delivered", id: m.id, text: m.text, at });
10227
+ emit({
10228
+ type: "message.delivered",
10229
+ id: m.id,
10230
+ text: m.text,
10231
+ at,
10232
+ ...m.origin ? { origin: m.origin } : {}
10233
+ });
9214
10234
  log.info(`message from the user (delivered at ${at}):`, m.text);
9215
10235
  void remember({ role: "user", content: m.text });
9216
10236
  }
@@ -9347,6 +10367,9 @@ ${renderActiveSkills(active)}`
9347
10367
  currentStep = step;
9348
10368
  },
9349
10369
  images: images.length ? images : void 0,
10370
+ // No file now, but one in an earlier turn: the model is told, or it answers about a
10371
+ // picture it only read the name of.
10372
+ ...!images.length && history.some((m) => m.role === "user" && hasAttachedMark(m.content)) ? { attachmentsNote: NO_ATTACHMENT_NOTE } : {},
9350
10373
  userUpdates: () => userUpdates.map((u) => u.text),
9351
10374
  ...port ? { takeRoundUpdates: () => deliver("round") } : {}
9352
10375
  };
@@ -9366,7 +10389,14 @@ ${renderActiveSkills(active)}`
9366
10389
  let planned = resumed ? { plan: resumed.plan, usage: emptyUsage(), skills: [] } : await createPlan(ctx, text);
9367
10390
  if (!resumed) bumpUsage(planned.usage, "plan");
9368
10391
  if (isAborted()) return stop();
9369
- if (planned.plan.steps.length === 0 && text.split(/\s+/).length > 2) {
10392
+ if (planned.failed) {
10393
+ log.warn("planner failed:", planned.failed);
10394
+ emit({ type: "error", phase: "run", error: planned.failed, code: "no-plan" });
10395
+ result.final = planned.failed;
10396
+ track.error = planned.failed;
10397
+ return result;
10398
+ }
10399
+ if (planned.plan.steps.length === 0 && plannerMode === "prompted" && catalog.length > 0 && text.split(/\s+/).length > 2) {
9370
10400
  log.warn(
9371
10401
  "planner returned no steps for a multi-word goal \u2014 retrying with a nudge. thought:",
9372
10402
  planned.plan.thought
@@ -9383,10 +10413,27 @@ ${renderActiveSkills(active)}`
9383
10413
  if (isAborted()) return stop();
9384
10414
  if (planned.plan.steps.length === 0) {
9385
10415
  log.info("no plan \u2014 answering directly (no tools will run)");
9386
- const answer = planned.plan.thought.trim() || "Tell me what you'd like to do.";
9387
- emit({ type: "final", text: answer });
9388
- await remember({ role: "assistant", content: answer });
9389
- result.final = answer;
10416
+ deliver("final");
10417
+ let direct;
10418
+ try {
10419
+ direct = await synthesizeAnswer(ctx, text, [], [], { direct: true });
10420
+ } catch (err) {
10421
+ if (isAborted()) return stop();
10422
+ throw err;
10423
+ }
10424
+ bumpUsage(direct.usage, "synthesize");
10425
+ if (isAborted()) return stop();
10426
+ if (!direct.text) {
10427
+ const message = direct.empty ?? "[synthesizer] the model returned no answer";
10428
+ log.warn(message);
10429
+ emit({ type: "error", phase: "run", error: message, code: "no-answer" });
10430
+ result.final = message;
10431
+ track.error = message;
10432
+ return result;
10433
+ }
10434
+ emit({ type: "final", text: direct.text });
10435
+ await remember({ role: "assistant", content: direct.text });
10436
+ result.final = direct.text;
9390
10437
  return result;
9391
10438
  }
9392
10439
  log.info(
@@ -9406,6 +10453,7 @@ ${renderActiveSkills(active)}`
9406
10453
  let remaining = resumed ? [...resumed.remaining] : [...planned.plan.steps];
9407
10454
  let iter = resumed?.iterations ?? 0;
9408
10455
  let revisions = resumed?.revisions ?? 0;
10456
+ let inFlight;
9409
10457
  const buildSnapshot = (status, extra = {}) => ({
9410
10458
  runId,
9411
10459
  startedAt,
@@ -9414,12 +10462,12 @@ ${renderActiveSkills(active)}`
9414
10462
  sessionId,
9415
10463
  plan: planned.plan,
9416
10464
  // Copies: a store that keeps the object must not watch the loop mutate it.
9417
- remaining: [...remaining],
10465
+ remaining: inFlight ? [inFlight, ...remaining] : [...remaining],
9418
10466
  trace: [...result.trace],
9419
10467
  done: [...done],
9420
10468
  findings: [...findings],
9421
10469
  usage: { ...usage },
9422
- iterations: iter,
10470
+ iterations: inFlight ? iter - 1 : iter,
9423
10471
  revisions,
9424
10472
  toolCalls: counter.calls,
9425
10473
  applied: result.applied,
@@ -9468,6 +10516,7 @@ ${renderActiveSkills(active)}`
9468
10516
  }
9469
10517
  iter += 1;
9470
10518
  const step = remaining.shift();
10519
+ inFlight = step;
9471
10520
  const stepNo = result.trace.length + 1;
9472
10521
  const total = stepNo + remaining.length;
9473
10522
  const routed = tiers ? pickTier(step.complexity, tiers.configured) : void 0;
@@ -9574,6 +10623,7 @@ ${renderActiveSkills(active)}`
9574
10623
  stepWrites = void 0;
9575
10624
  }
9576
10625
  result.trace.push(stepResult);
10626
+ inFlight = void 0;
9577
10627
  const applied = stepResult.toolCalls.filter((c) => c.ok && !isReplayed(c)).length;
9578
10628
  const failed = stepResult.toolCalls.length - applied;
9579
10629
  result.applied += applied;
@@ -9740,20 +10790,27 @@ ${renderActiveSkills(active)}`
9740
10790
  }
9741
10791
  };
9742
10792
  const run = async (goal, opts = {}) => {
10793
+ refuseServerOnlyRunOptions(opts);
9743
10794
  const port = portOf(opts.control);
9744
10795
  const track = {};
9745
- let result;
10796
+ let stopped = false;
9746
10797
  try {
9747
- result = await runCore(goal, opts, track, port);
9748
- } catch (err) {
9749
- port?.detach();
9750
- track.error = err instanceof Error ? err.message : String(err);
9751
- await track.complete?.(void 0);
9752
- throw err;
10798
+ let result;
10799
+ try {
10800
+ result = await runCore(goal, opts, track, port);
10801
+ } catch (err) {
10802
+ port?.detach();
10803
+ track.error = err instanceof Error ? err.message : String(err);
10804
+ await track.complete?.(void 0);
10805
+ throw err;
10806
+ }
10807
+ if (port) result.undelivered = port.detach();
10808
+ await track.complete?.(result);
10809
+ stopped = result.stopped;
10810
+ return result;
10811
+ } finally {
10812
+ await track.end?.(stopped);
9753
10813
  }
9754
- if (port) result.undelivered = port.detach();
9755
- await track.complete?.(result);
9756
- return result;
9757
10814
  };
9758
10815
  const compact = async (o = {}) => {
9759
10816
  const empty = {
@@ -9764,6 +10821,18 @@ ${renderActiveSkills(active)}`
9764
10821
  };
9765
10822
  if (!config.memory) return empty;
9766
10823
  const sessionId = o.sessionId ?? cfg.sessionId;
10824
+ const hold = await lockSession(
10825
+ { sessionId, ...o.signal ? { signal: o.signal } : {} },
10826
+ o.wait === false || lockMode === "fail" ? "fail" : "wait"
10827
+ );
10828
+ try {
10829
+ return await compactSession(sessionId, o, empty);
10830
+ } finally {
10831
+ await hold?.release();
10832
+ }
10833
+ };
10834
+ const compactSession = async (sessionId, o, empty) => {
10835
+ if (!config.memory) return empty;
9767
10836
  const transcript = await config.memory.load(sessionId);
9768
10837
  const beforeTokens = messageTokens(transcript);
9769
10838
  let usage = emptyUsage();
@@ -9940,6 +11009,7 @@ ${renderActiveSkills(active)}`
9940
11009
  };
9941
11010
  },
9942
11011
  forgetSkill: async (name, onEvent) => learning ? learning.forget(name, onEvent) : false,
11012
+ reloadLearnedSkills: async () => learning ? (await learning.reload()).map((s) => ({ ...s })) : [],
9943
11013
  capabilities: { images: accepts.image, pdf: accepts.pdf, files: accepts.file },
9944
11014
  models: {
9945
11015
  planner: plannerModel,
@@ -9955,6 +11025,7 @@ ${renderActiveSkills(active)}`
9955
11025
  init_tiers();
9956
11026
 
9957
11027
  // src/pipeline/index.ts
11028
+ var import_ai15 = require("ai");
9958
11029
  var import_zod6 = require("zod");
9959
11030
  init_generate();
9960
11031
  init_util();
@@ -10453,18 +11524,18 @@ var testPipelineCondition = (when, output, matcher) => {
10453
11524
  return false;
10454
11525
  }
10455
11526
  };
10456
- var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11527
+ var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
10457
11528
  var isId = (v) => typeof v === "string" && v.trim().length > 0;
10458
- var edgeIdOf = (edge, index) => isRecord2(edge) && isId(edge.id) ? edge.id : `e${index}`;
11529
+ var edgeIdOf = (edge, index) => isRecord3(edge) && isId(edge.id) ? edge.id : `e${index}`;
10459
11530
  var edgeRef = (edge, index) => ({
10460
11531
  edgeId: edgeIdOf(edge, index),
10461
11532
  edgeIndex: index
10462
11533
  });
10463
11534
  var normalizePipeline = (definition) => {
10464
11535
  const def = JSON.parse(JSON.stringify(definition));
10465
- if (isRecord2(def) && Array.isArray(def.edges)) {
11536
+ if (isRecord3(def) && Array.isArray(def.edges)) {
10466
11537
  def.edges.forEach((edge, index) => {
10467
- if (isRecord2(edge)) edge.id = edgeIdOf(edge, index);
11538
+ if (isRecord3(edge)) edge.id = edgeIdOf(edge, index);
10468
11539
  });
10469
11540
  }
10470
11541
  return def;
@@ -10478,7 +11549,7 @@ var validatePipeline = (definition) => {
10478
11549
  };
10479
11550
  const done = () => ({ ok: errors.length === 0, errors, warnings });
10480
11551
  const def = definition;
10481
- if (!isRecord2(def)) {
11552
+ if (!isRecord3(def)) {
10482
11553
  error("definition", "a pipeline definition must be an object");
10483
11554
  return done();
10484
11555
  }
@@ -10498,7 +11569,7 @@ var validatePipeline = (definition) => {
10498
11569
  const ids = /* @__PURE__ */ new Set();
10499
11570
  const routesOf = /* @__PURE__ */ new Map();
10500
11571
  for (const [index, node] of (nodes ?? []).entries()) {
10501
- if (!isRecord2(node) || !isId(node.id)) {
11572
+ if (!isRecord3(node) || !isId(node.id)) {
10502
11573
  error("node.id", `node #${index + 1} has no id`);
10503
11574
  continue;
10504
11575
  }
@@ -10521,7 +11592,7 @@ var validatePipeline = (definition) => {
10521
11592
  );
10522
11593
  } else {
10523
11594
  for (const route of node.routes) {
10524
- if (!isRecord2(route) || !isId(route.label)) {
11595
+ if (!isRecord3(route) || !isId(route.label)) {
10525
11596
  error("node.routes", `node "${nodeId}": a route has no label`, { nodeId });
10526
11597
  } else if (labels.includes(route.label)) {
10527
11598
  error("node.routes", `node "${nodeId}": duplicate route "${route.label}"`, { nodeId });
@@ -10545,7 +11616,7 @@ var validatePipeline = (definition) => {
10545
11616
  for (const [index, edge] of (edges ?? []).entries()) {
10546
11617
  const at = edgeRef(edge, index);
10547
11618
  const label = `edge "${at.edgeId}"`;
10548
- if (!isRecord2(edge)) {
11619
+ if (!isRecord3(edge)) {
10549
11620
  error("edge", `${label} is not an object`, at);
10550
11621
  continue;
10551
11622
  }
@@ -10562,7 +11633,7 @@ var validatePipeline = (definition) => {
10562
11633
  if (fromOk && toOk) out.set(from, [...out.get(from) ?? [], to]);
10563
11634
  const when = edge.when;
10564
11635
  if (when === void 0) continue;
10565
- if (!isRecord2(when) || !CONDITION_KINDS.includes(when.kind)) {
11636
+ if (!isRecord3(when) || !CONDITION_KINDS.includes(when.kind)) {
10566
11637
  error("edge.when", `${label} has an unknown condition`, at);
10567
11638
  continue;
10568
11639
  }
@@ -10605,7 +11676,7 @@ var validatePipeline = (definition) => {
10605
11676
  }
10606
11677
  }
10607
11678
  if (def.limits !== void 0) {
10608
- if (!isRecord2(def.limits)) {
11679
+ if (!isRecord3(def.limits)) {
10609
11680
  error("limits", "`limits` must be an object");
10610
11681
  } else {
10611
11682
  const { maxNodeVisits, maxRuns } = def.limits;
@@ -10722,7 +11793,7 @@ var matchPipelineRoute = (node, answer) => {
10722
11793
  value = text;
10723
11794
  }
10724
11795
  }
10725
- if (isRecord2(value)) value = value.route;
11796
+ if (isRecord3(value)) value = value.route;
10726
11797
  if (typeof value !== "string") return void 0;
10727
11798
  const wanted = value.trim().replace(/^["'`]+|["'`.]+$/g, "").toLowerCase();
10728
11799
  return labels.find((label) => label.toLowerCase() === wanted);
@@ -10815,7 +11886,7 @@ var passReach = (plan) => {
10815
11886
  return seen.has(to);
10816
11887
  };
10817
11888
  };
10818
- var abortError2 = () => {
11889
+ var abortError3 = () => {
10819
11890
  if (typeof DOMException === "function") return new DOMException("Aborted", "AbortError");
10820
11891
  const error = new Error("Aborted");
10821
11892
  error.name = "AbortError";
@@ -10845,7 +11916,7 @@ var createStopper = () => {
10845
11916
  const abort = () => {
10846
11917
  if (signal.aborted) return;
10847
11918
  signal.aborted = true;
10848
- signal.reason = abortError2();
11919
+ signal.reason = abortError3();
10849
11920
  const event = { type: "abort", target: signal };
10850
11921
  const call = (fn, thisArg) => {
10851
11922
  try {
@@ -10907,7 +11978,7 @@ ${t.text}`).join("\n\n");
10907
11978
  if (halted) return;
10908
11979
  halted = "aborted";
10909
11980
  stopper.abort();
10910
- halt(abortError2());
11981
+ halt(abortError3());
10911
11982
  };
10912
11983
  const visit = async (nodeId, activations) => {
10913
11984
  const node = plan.nodes.get(nodeId);
@@ -11040,38 +12111,50 @@ ${t.text}`).join("\n\n");
11040
12111
  };
11041
12112
 
11042
12113
  // src/pipeline/index.ts
11043
- var aborted = () => new DOMException("Aborted", "AbortError");
12114
+ var aborted2 = () => new DOMException("Aborted", "AbortError");
11044
12115
  var pickRoute = async ({ agent, config }, node, text, signal) => {
11045
12116
  const cfg = resolveConfig(config);
11046
12117
  const labels = (node.routes ?? []).map((r) => r.label);
11047
- const call = {
11048
- system: PIPELINE_ROUTER_SYSTEM,
11049
- prompt: renderPipelineRoutePrompt(node, text),
11050
- // 0 = no cap (the host turned it off, or the stage thinks).
11051
- ...cfg.budgets.replanner > 0 ? { maxOutputTokens: cfg.budgets.replanner } : {},
11052
- temperature: cfg.temperature,
11053
- abortSignal: signal,
11054
- timeoutMs: cfg.chatTimeoutMs
12118
+ const window = cfg.compaction.contextWindowTokens;
12119
+ const call = () => {
12120
+ const cap2 = stageOutputCap(config, "replanner", window).tokens;
12121
+ return {
12122
+ system: PIPELINE_ROUTER_SYSTEM,
12123
+ prompt: renderPipelineRoutePrompt(node, text),
12124
+ // No cap: the host turned it off, or the stage thinks.
12125
+ ...cap2 ? { maxOutputTokens: cap2 } : {},
12126
+ temperature: cfg.temperature,
12127
+ abortSignal: signal,
12128
+ timeoutMs: cfg.chatTimeoutMs
12129
+ };
11055
12130
  };
11056
12131
  let wasted = normalizeUsage();
11057
- try {
11058
- const schema = import_zod6.z.object({
11059
- route: import_zod6.z.enum(labels).describe("The label of the chosen route")
11060
- });
11061
- const r = await generateStructured(agent.models.planner, schema, call);
11062
- return { route: matchPipelineRoute(node, r.object), usage: normalizeUsage(r.usage) };
11063
- } catch (err) {
11064
- if (signal.aborted) throw aborted();
11065
- wasted = usageOfError(err);
12132
+ const schema = import_zod6.z.object({
12133
+ route: import_zod6.z.enum(labels).describe("The label of the chosen route")
12134
+ });
12135
+ for (let attempt = 0; attempt < 2; attempt += 1) {
12136
+ try {
12137
+ const r = await generateStructured(agent.models.planner, schema, call());
12138
+ return {
12139
+ route: matchPipelineRoute(node, r.object),
12140
+ usage: addUsage(wasted, normalizeUsage(r.usage))
12141
+ };
12142
+ } catch (err) {
12143
+ if (signal.aborted) throw aborted2();
12144
+ const spent = usageOfError(err);
12145
+ wasted = addUsage(wasted, spent);
12146
+ const finishReason = import_ai15.NoObjectGeneratedError.isInstance(err) ? err.finishReason : void 0;
12147
+ if (!observeReasoning(config, "replanner", window, finishReason, spent.reasoningTokens)) break;
12148
+ }
11066
12149
  }
11067
12150
  try {
11068
- const r = await generate(agent.models.planner, call);
12151
+ const r = await generate(agent.models.planner, call());
11069
12152
  return {
11070
12153
  route: matchPipelineRoute(node, r.text),
11071
12154
  usage: addUsage(wasted, normalizeUsage(r.usage))
11072
12155
  };
11073
12156
  } catch {
11074
- if (signal.aborted) throw aborted();
12157
+ if (signal.aborted) throw aborted2();
11075
12158
  return { usage: wasted };
11076
12159
  }
11077
12160
  };
@@ -11084,7 +12167,7 @@ var pickRouteWithDecisionModel = async ({ agent, config }, node, text, signal, e
11084
12167
  try {
11085
12168
  outcome = await askDecisionModel(model, question, config.decision, signal);
11086
12169
  } catch (err) {
11087
- if (signal.aborted) throw aborted();
12170
+ if (signal.aborted) throw aborted2();
11088
12171
  throw err;
11089
12172
  }
11090
12173
  const usage = decisionUsageOf(outcome);
@@ -11141,7 +12224,7 @@ var createPipeline = (definition, options) => {
11141
12224
  ctx.emit(event);
11142
12225
  }
11143
12226
  });
11144
- if (result.stopped || ctx.signal.aborted) throw aborted();
12227
+ if (result.stopped || ctx.signal.aborted) throw aborted2();
11145
12228
  if (failure !== void 0) throw new Error(failure);
11146
12229
  if (!node.routes?.length) return { text: result.final, usage: result.usage };
11147
12230
  const picked = await pickPipelineRoute(node, result.final, {
@@ -11201,7 +12284,7 @@ var nodeResolver = (options) => async (node) => {
11201
12284
  };
11202
12285
 
11203
12286
  // src/subagent/tool.ts
11204
- var import_ai15 = require("ai");
12287
+ var import_ai16 = require("ai");
11205
12288
  init_util();
11206
12289
  init_approval();
11207
12290
  init_wrap();
@@ -11225,7 +12308,7 @@ var safePost = (target, message) => {
11225
12308
  };
11226
12309
 
11227
12310
  // src/subagent/tool.ts
11228
- var abortError3 = () => {
12311
+ var abortError4 = () => {
11229
12312
  const e = new Error("The subagent was aborted");
11230
12313
  e.name = "AbortError";
11231
12314
  return e;
@@ -11243,7 +12326,7 @@ var createSemaphore = (size) => {
11243
12326
  const onAbort = () => {
11244
12327
  const i = queue.indexOf(go);
11245
12328
  if (i >= 0) queue.splice(i, 1);
11246
- reject(abortError3());
12329
+ reject(abortError4());
11247
12330
  };
11248
12331
  queue.push(go);
11249
12332
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -11348,21 +12431,27 @@ var createSubagentTool = (opts) => {
11348
12431
  })
11349
12432
  );
11350
12433
  };
11351
- const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations) => {
12434
+ const runInProcess = async (task, signal, forward, hostTools, profile, id, elicitations, sessionLocks) => {
11352
12435
  const config = { ...opts.config, ...profile?.config };
11353
12436
  const agent = await createAgent({
11354
12437
  ...config,
11355
12438
  tools: { ...asSubagentCalls(config.tools, id, elicitations), ...hostTools }
11356
12439
  });
11357
12440
  let runError;
11358
- const result = await agent.run(task, {
11359
- signal,
11360
- onEvent: (e) => {
11361
- if (e.type === "error" && e.phase === "run") runError = e.error;
11362
- forward(e);
11363
- }
11364
- });
11365
- if (result.stopped) throw abortError3();
12441
+ const result = await agent.run(
12442
+ task,
12443
+ withSessionLocks(
12444
+ {
12445
+ signal,
12446
+ onEvent: (e) => {
12447
+ if (e.type === "error" && e.phase === "run") runError = e.error;
12448
+ forward(e);
12449
+ }
12450
+ },
12451
+ sessionLocks
12452
+ )
12453
+ );
12454
+ if (result.stopped) throw abortError4();
11366
12455
  if (runError) throw new Error(runError);
11367
12456
  return { text: result.final, usage: result.usage };
11368
12457
  };
@@ -11370,7 +12459,7 @@ var createSubagentTool = (opts) => {
11370
12459
  Object.entries(opts.tools ?? {}).map(async ([name, t2]) => ({
11371
12460
  name,
11372
12461
  description: typeof t2.description === "string" ? t2.description : "",
11373
- inputSchema: toCloneable(await (0, import_ai15.asSchema)(t2.inputSchema).jsonSchema),
12462
+ inputSchema: toCloneable(await (0, import_ai16.asSchema)(t2.inputSchema).jsonSchema),
11374
12463
  readOnly: isReadOnlyTool(t2)
11375
12464
  }))
11376
12465
  );
@@ -11386,9 +12475,9 @@ var createSubagentTool = (opts) => {
11386
12475
  return toCloneable({ ...cfg, model });
11387
12476
  };
11388
12477
  const runInWorker2 = async (task, signal, forward, hostTools, profile, clock) => {
11389
- if (signal?.aborted) throw abortError3();
12478
+ if (signal?.aborted) throw abortError4();
11390
12479
  const [config, proxied] = await Promise.all([workerConfigFor(profile), proxiedSpecs()]);
11391
- if (signal?.aborted) throw abortError3();
12480
+ if (signal?.aborted) throw abortError4();
11392
12481
  const worker = opts.worker();
11393
12482
  return new Promise((resolve, reject) => {
11394
12483
  let settled = false;
@@ -11405,7 +12494,7 @@ var createSubagentTool = (opts) => {
11405
12494
  };
11406
12495
  const onAbort = () => {
11407
12496
  safePost(worker, { type: "abort" });
11408
- finish(() => reject(abortError3()));
12497
+ finish(() => reject(abortError4()));
11409
12498
  };
11410
12499
  const onError = (ev) => finish(() => reject(new Error(`subagent worker failed: ${ev?.message ?? "unknown error"}`)));
11411
12500
  const callHostTool = async (callId, name, input) => {
@@ -11455,9 +12544,9 @@ var createSubagentTool = (opts) => {
11455
12544
 
11456
12545
  Optional \`profile\` (omit it for the default):
11457
12546
  ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
11458
- const t = (0, import_ai15.tool)({
12547
+ const t = (0, import_ai16.tool)({
11459
12548
  description,
11460
- inputSchema: (0, import_ai15.jsonSchema)({
12549
+ inputSchema: (0, import_ai16.jsonSchema)({
11461
12550
  type: "object",
11462
12551
  properties: {
11463
12552
  task: {
@@ -11536,7 +12625,8 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
11536
12625
  hostTools,
11537
12626
  profile,
11538
12627
  id,
11539
- runCtx?.elicitations
12628
+ runCtx?.elicitations,
12629
+ runCtx?.sessionLocks?.() ?? []
11540
12630
  )).catch((err) => {
11541
12631
  if (stoppedByUser)
11542
12632
  throw new Error(
@@ -11573,7 +12663,11 @@ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : o
11573
12663
  };
11574
12664
 
11575
12665
  // src/subagent/worker.ts
11576
- var import_ai16 = require("ai");
12666
+ var import_ai17 = require("ai");
12667
+
12668
+ // src/secrets/store.ts
12669
+ init_notices();
12670
+ init_tab();
11577
12671
 
11578
12672
  // src/secrets/vault.ts
11579
12673
  init_db();
@@ -11670,18 +12764,25 @@ var IndexedDBVault = class {
11670
12764
 
11671
12765
  // src/secrets/store.ts
11672
12766
  var VaultCredentialStore = class {
12767
+ /** The database the vault lives in, and the name its change notices go out under. */
12768
+ dbName;
11673
12769
  vault;
12770
+ tab;
11674
12771
  constructor(opts = {}) {
11675
- this.vault = new IndexedDBVault(opts);
12772
+ this.dbName = opts.dbName ?? "agent-web";
12773
+ this.vault = new IndexedDBVault({ ...opts, dbName: this.dbName });
12774
+ this.tab = currentTab();
11676
12775
  }
11677
12776
  getApiKey(ref) {
11678
12777
  return this.vault.getSecret(ref);
11679
12778
  }
11680
- setApiKey(ref, key) {
11681
- return this.vault.setSecret(ref, key);
12779
+ async setApiKey(ref, key) {
12780
+ await this.vault.setSecret(ref, key);
12781
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "credentials", op: "put" });
11682
12782
  }
11683
- deleteApiKey(ref) {
11684
- return this.vault.deleteSecret(ref);
12783
+ async deleteApiKey(ref) {
12784
+ await this.vault.deleteSecret(ref);
12785
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "credentials", op: "delete" });
11685
12786
  }
11686
12787
  };
11687
12788
  var MemoryCredentialStore = class {
@@ -11720,9 +12821,9 @@ var serveSubagentWorker = (opts = {}) => {
11720
12821
  const caller = createWaitClock();
11721
12822
  let callerResume;
11722
12823
  const proxy = (spec) => {
11723
- const t = (0, import_ai16.dynamicTool)({
12824
+ const t = (0, import_ai17.dynamicTool)({
11724
12825
  description: spec.description,
11725
- inputSchema: (0, import_ai16.jsonSchema)(spec.inputSchema),
12826
+ inputSchema: (0, import_ai17.jsonSchema)(spec.inputSchema),
11726
12827
  execute: (input, options) => new Promise((resolve, reject) => {
11727
12828
  const callId = `call-${callSeq += 1}`;
11728
12829
  const signal = options?.abortSignal;
@@ -11855,10 +12956,15 @@ var MemoryStore = class {
11855
12956
 
11856
12957
  // src/memory/sessions.ts
11857
12958
  init_db();
12959
+ init_notices();
12960
+ init_tab();
11858
12961
  var IndexedDBStore = class {
12962
+ /** The database it lives in - and the name its tabs share it under (`sessionLock`, notices). */
11859
12963
  dbName;
12964
+ tab;
11860
12965
  constructor(opts = {}) {
11861
- this.dbName = opts.dbName;
12966
+ this.dbName = opts.dbName ?? "agent-web";
12967
+ this.tab = currentTab();
11862
12968
  }
11863
12969
  async load(sessionId) {
11864
12970
  const db = await openAgentWebDB({ dbName: this.dbName });
@@ -11868,6 +12974,7 @@ var IndexedDBStore = class {
11868
12974
  async replace(sessionId, messages) {
11869
12975
  const db = await openAgentWebDB({ dbName: this.dbName });
11870
12976
  await db.put(SESSIONS_STORE, messages, sessionId);
12977
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "session", op: "put", key: sessionId });
11871
12978
  }
11872
12979
  async append(sessionId, message) {
11873
12980
  const current = await this.load(sessionId);
@@ -11877,6 +12984,7 @@ var IndexedDBStore = class {
11877
12984
  async clear(sessionId) {
11878
12985
  const db = await openAgentWebDB({ dbName: this.dbName });
11879
12986
  await db.delete(SESSIONS_STORE, sessionId);
12987
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "session", op: "delete", key: sessionId });
11880
12988
  }
11881
12989
  /** List all stored session ids. */
11882
12990
  async listSessions() {
@@ -11887,6 +12995,8 @@ var IndexedDBStore = class {
11887
12995
 
11888
12996
  // src/memory/runs.ts
11889
12997
  init_db();
12998
+ init_notices();
12999
+ init_tab();
11890
13000
  var resumableOf = (all, sessionId) => all.filter(
11891
13001
  (s) => s.status !== "complete" && (sessionId === void 0 || s.sessionId === sessionId)
11892
13002
  ).sort((a, b) => b.startedAt - a.startedAt);
@@ -11935,11 +13045,14 @@ var jsonSafe2 = (value) => JSON.parse(
11935
13045
  )
11936
13046
  );
11937
13047
  var IndexedDBRunStore = class {
13048
+ /** The database it lives in, and the name its change notices (`runs`) go out under. */
11938
13049
  dbName;
11939
13050
  keepCompleted;
13051
+ tab;
11940
13052
  constructor(opts = {}) {
11941
- this.dbName = opts.dbName;
13053
+ this.dbName = opts.dbName ?? "agent-web";
11942
13054
  this.keepCompleted = opts.keepCompleted ?? false;
13055
+ this.tab = currentTab();
11943
13056
  }
11944
13057
  async put(snapshot) {
11945
13058
  const db = await openAgentWebDB({ dbName: this.dbName });
@@ -11949,6 +13062,7 @@ var IndexedDBRunStore = class {
11949
13062
  if (err?.name !== "DataCloneError") throw err;
11950
13063
  await db.put(RUNS_STORE, jsonSafe2(snapshot), snapshot.runId);
11951
13064
  }
13065
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "runs", op: "put", key: snapshot.runId });
11952
13066
  }
11953
13067
  onRunStart(snapshot) {
11954
13068
  return this.put(snapshot);
@@ -11983,15 +13097,18 @@ var IndexedDBRunStore = class {
11983
13097
  async delete(runId) {
11984
13098
  const db = await openAgentWebDB({ dbName: this.dbName });
11985
13099
  await db.delete(RUNS_STORE, runId);
13100
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "runs", op: "delete", key: runId });
11986
13101
  }
11987
13102
  async clear() {
11988
13103
  const db = await openAgentWebDB({ dbName: this.dbName });
11989
13104
  await db.clear(RUNS_STORE);
13105
+ postStorageChangeFrom(this.tab, this.dbName, { kind: "runs", op: "clear" });
11990
13106
  }
11991
13107
  };
11992
13108
 
11993
13109
  // src/index.ts
11994
13110
  init_compress();
13111
+ init_notices();
11995
13112
 
11996
13113
  // src/mcp/apps.ts
11997
13114
  var MCP_APPS_EXTENSION = "io.modelcontextprotocol/ui";
@@ -12082,12 +13199,17 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
12082
13199
  MemoryRunStore,
12083
13200
  MemorySkillStore,
12084
13201
  MemoryStore,
13202
+ NO_ATTACHMENT_NOTE,
12085
13203
  PIPELINE_LIMITS,
12086
13204
  PIPELINE_ROUTER_SYSTEM,
12087
13205
  PipelineNodeError,
12088
13206
  PipelineValidationError,
12089
13207
  PlanSchema,
12090
13208
  PlanStepSchema,
13209
+ RELAY_MAX_REPLAYS_PER_SECOND,
13210
+ RELAY_MAX_SENDS,
13211
+ RELAY_MAX_SEND_CHARS,
13212
+ RELAY_MAX_STRING,
12091
13213
  REPLAY_NOTE,
12092
13214
  RUNS_STORE,
12093
13215
  ReplanSchema,
@@ -12106,11 +13228,14 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
12106
13228
  SEARCH_PROVIDERS,
12107
13229
  SECRETS_STORE,
12108
13230
  SESSIONS_STORE,
13231
+ SESSION_LOCK_MODES,
12109
13232
  SKILL_TOOL_NAMES,
12110
13233
  SPAWN_INPUT_SCHEMA,
12111
13234
  SPAWN_SUBAGENT_TOOL,
13235
+ STORAGE_CHANGE_KINDS,
12112
13236
  SUBAGENT_DEFAULTS,
12113
13237
  SUBAGENT_MAX_DEPTH_LIMIT,
13238
+ SessionBusyError,
12114
13239
  SubagentSpawnError,
12115
13240
  TOOL_APPROVAL_MODES,
12116
13241
  TOOL_APPROVAL_TIMEOUT_MS,
@@ -12219,6 +13344,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
12219
13344
  normalizeSkillName,
12220
13345
  normalizeSteps,
12221
13346
  normalizeUsage,
13347
+ onStorageChange,
12222
13348
  openAgentWebDB,
12223
13349
  outputCapNotice,
12224
13350
  parseExecutorResponse,
@@ -12229,6 +13355,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
12229
13355
  parseSkillMarkdown,
12230
13356
  pickPipelineRoute,
12231
13357
  pickTier,
13358
+ postStorageChange,
12232
13359
  preloadWebLLMModel,
12233
13360
  preparePipeline,
12234
13361
  promptHintOf,
@@ -12267,6 +13394,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
12267
13394
  sniffMediaType,
12268
13395
  splitBlocker,
12269
13396
  stageOutputCap,
13397
+ stageReasons,
12270
13398
  stream,
12271
13399
  supportsImages,
12272
13400
  supportsNativeTools,
@@ -12283,6 +13411,7 @@ var MCP_APP_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
12283
13411
  toolRunContextOf,
12284
13412
  unloadWebLLMModel,
12285
13413
  validatePipeline,
13414
+ watchSession,
12286
13415
  webLLMContextWindow,
12287
13416
  withRollingBreakpoint,
12288
13417
  withSystem,