@dudko.dev/agent-web 0.0.28 → 0.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,13 +2,14 @@ import {
2
2
  FILES_STORE,
3
3
  IndexedDBVault,
4
4
  KEYS_STORE,
5
+ RUNS_STORE,
5
6
  SECRETS_STORE,
6
7
  SESSIONS_STORE,
7
8
  decryptJSON,
8
9
  encryptJSON,
9
10
  getOrCreateVaultKey,
10
11
  openAgentWebDB
11
- } from "./chunk-V7COB2EA.js";
12
+ } from "./chunk-CPSDKXO6.js";
12
13
  import {
13
14
  AttachmentsNotSupportedError,
14
15
  ContextWindowExceededError,
@@ -360,6 +361,23 @@ var section = (title, body) => body && body.trim() ? `
360
361
 
361
362
  ${title}:
362
363
  ${body.trim()}` : "";
364
+ var quoted = (text) => text.trim().replace(/\n/g, "\n ");
365
+ var updatesBlock = (updates, fresh = 0, advice = "") => {
366
+ if (!updates || updates.length === 0) return "";
367
+ const firstNew = fresh > 0 ? updates.length - fresh : updates.length;
368
+ const lines = updates.map(
369
+ (u, i) => `${i + 1}. ${quoted(u)}${i >= firstNew ? " [NEW \u2014 not yet reflected in the plan]" : ""}`
370
+ );
371
+ const head = `MESSAGES FROM THE USER, sent while the agent was working (oldest first; they speak for the user and win over the original goal where they conflict):
372
+ ${lines.join("\n")}`;
373
+ return advice ? `${head}
374
+ ${advice}` : head;
375
+ };
376
+ var renderUserMessages = (texts) => `NEW MESSAGE FROM THE USER, sent while you were working:
377
+ ${texts.map((t) => `- ${quoted(t)}`).join(
378
+ "\n"
379
+ )}
380
+ It speaks for the user and wins over the goal and the plan where they conflict. Take it into account from here on, then carry on with this step \u2014 or finish the step now if the message makes the rest of it pointless.`;
363
381
  var PLANNER_RULES = `- Act autonomously: whenever the TOOLS can do the work or look up the answer, plan the steps \u2014 a question that needs data, a lookup or a check is a real goal too.
364
382
  - Never plan a step that asks the user something. If the request is ambiguous, pick the most reasonable interpretation and say which one you chose.
365
383
  - Plan realistic steps the available TOOLS can perform, grounded in the current STATE.
@@ -412,6 +430,8 @@ Reply with a single JSON object, nothing else:
412
430
  - "revise": replace the REMAINING steps with a better list in "plan"; never repeat done work.
413
431
  - "finish": the goal is already met \u2014 stop (omit "plan").
414
432
  ${REPLANNER_RULES}`;
433
+ var REPLANNER_UPDATES_ADVICE = `Weigh the [NEW] messages against the remaining plan: "revise" the remaining steps so they are honoured (and keep honouring the older ones), "finish" if the user says to stop or the goal is already met, "continue" only if the remaining steps already fit them.`;
434
+ var SYNTHESIZER_UPDATES_ADVICE = `Answer with these in mind: they changed what was asked. Say plainly if one of them could not be honoured in time.`;
415
435
  var SYNTHESIZER_SYSTEM = `You are the SYNTHESIZER. Answer the user's goal from what the agent did and found.
416
436
  - Lead with the result: the concrete data, from the FINDINGS verbatim when accuracy matters (names, numbers, ids), then \u2014 briefly \u2014 what was changed.
417
437
  - Mention any assumption the agent made. If something could not be done, say so plainly and why.
@@ -432,6 +452,7 @@ ${ctx.toolCatalog}`,
432
452
  stateBlock(ctx.state).trimStart(),
433
453
  ctx.mode === "prompted" ? `TOOLS:
434
454
  ${ctx.toolCatalog}` : "",
455
+ updatesBlock(ctx.updates),
435
456
  ctx.done.length ? `Already done:
436
457
  ${numbered(ctx.done, "")}` : "",
437
458
  `STEP ${ctx.index}/${ctx.total}: ${ctx.step}`
@@ -442,6 +463,7 @@ ${numbered(ctx.done, "")}` : "",
442
463
  prompt: [
443
464
  `GOAL: ${ctx.goal}`,
444
465
  stateBlock(ctx.state).trimStart(),
466
+ updatesBlock(ctx.updates, ctx.newUpdates, REPLANNER_UPDATES_ADVICE),
445
467
  `Already done:
446
468
  ${numbered(ctx.done, "(nothing yet)")}`,
447
469
  `Remaining plan:
@@ -454,6 +476,7 @@ ${numbered(ctx.remaining, "(none)")}`,
454
476
  prompt: [
455
477
  `GOAL: ${ctx.goal}`,
456
478
  stateBlock(ctx.state).trimStart(),
479
+ updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
457
480
  `What was done:
458
481
  ${numbered(ctx.done, "(no changes)")}`,
459
482
  ctx.findings?.length ? `FINDINGS (tool results):
@@ -990,7 +1013,8 @@ var wrapToolsForRun = (tools, o) => {
990
1013
  step: o.step(),
991
1014
  signal: o.signal,
992
1015
  addUsage: o.addUsage,
993
- approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro)
1016
+ approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),
1017
+ ...o.control ? { control: o.control } : {}
994
1018
  };
995
1019
  return execute.call(t, input, { ...options, agentRun });
996
1020
  };
@@ -1015,8 +1039,8 @@ var wrapToolsForRun = (tools, o) => {
1015
1039
  }
1016
1040
  return out;
1017
1041
  };
1018
- var createCallCounter = (cap) => {
1019
- let calls = 0;
1042
+ var createCallCounter = (cap, initial = 0) => {
1043
+ let calls = Math.max(0, Math.floor(initial));
1020
1044
  return {
1021
1045
  count: () => {
1022
1046
  if (cap && cap > 0 && calls >= cap) throw new ToolBudgetError(cap);
@@ -1060,6 +1084,69 @@ var schemaHintOf = async (t) => {
1060
1084
  }
1061
1085
  };
1062
1086
 
1087
+ // src/agent/control.ts
1088
+ var ports = /* @__PURE__ */ new WeakMap();
1089
+ var portOf = (control) => {
1090
+ if (!control) return void 0;
1091
+ const port = ports.get(control);
1092
+ if (!port) throw new TypeError("`control` must be created with createRunControl()");
1093
+ return port;
1094
+ };
1095
+ var createRunControl = () => {
1096
+ let seq3 = 0;
1097
+ let queue = [];
1098
+ let emit;
1099
+ let ended = false;
1100
+ const children = /* @__PURE__ */ new Map();
1101
+ const control = {
1102
+ send(text) {
1103
+ const clean = typeof text === "string" ? text.trim() : "";
1104
+ if (!clean || ended) return false;
1105
+ const message = { id: `msg-${seq3 += 1}`, text: clean };
1106
+ queue.push(message);
1107
+ emit?.({ type: "message.queued", id: message.id, text: message.text });
1108
+ return true;
1109
+ },
1110
+ pending: () => queue.map((m) => m.text),
1111
+ subagents: () => [...children.values()].map((c) => c.info).sort((a, b) => a.startedAt - b.startedAt),
1112
+ stopSubagent(id) {
1113
+ const child = children.get(id);
1114
+ if (!child) return false;
1115
+ child.stop();
1116
+ return true;
1117
+ }
1118
+ };
1119
+ ports.set(control, {
1120
+ attach(next) {
1121
+ if (ended) {
1122
+ queue = [];
1123
+ children.clear();
1124
+ }
1125
+ emit = next;
1126
+ ended = false;
1127
+ for (const m of queue) next({ type: "message.queued", id: m.id, text: m.text });
1128
+ },
1129
+ detach() {
1130
+ emit = void 0;
1131
+ ended = true;
1132
+ children.clear();
1133
+ return queue.map((m) => m.text);
1134
+ },
1135
+ drain() {
1136
+ const out = queue;
1137
+ queue = [];
1138
+ return out;
1139
+ },
1140
+ registerSubagent(info, stop) {
1141
+ children.set(info.id, { info, stop });
1142
+ return () => {
1143
+ children.delete(info.id);
1144
+ };
1145
+ }
1146
+ });
1147
+ return control;
1148
+ };
1149
+
1063
1150
  // src/llm/tool-loop.ts
1064
1151
  import {
1065
1152
  generateText,
@@ -1303,6 +1390,7 @@ var runNative = async (model, opts) => {
1303
1390
  const caching = opts.caching?.enabled ? opts.caching : void 0;
1304
1391
  const clear = opts.clearToolResults ? createToolResultClearer(opts.clearToolResults, opts.callbacks?.onToolResultsCleared) : void 0;
1305
1392
  const editMessages = caching || clear;
1393
+ const steered = opts.takeUpdates;
1306
1394
  const result = streamText({
1307
1395
  model,
1308
1396
  tools: opts.tools,
@@ -1310,13 +1398,18 @@ var runNative = async (model, opts) => {
1310
1398
  // Before every round: re-read the active set so tools activated mid-call
1311
1399
  // (find_tools) become callable; clear stale tool results; move the cache
1312
1400
  // breakpoint to the newest message.
1313
- ...dynamic || editMessages ? {
1314
- prepareStep: ({ messages }) => {
1315
- let next = clear ? clear(messages) : messages;
1401
+ ...dynamic || editMessages || steered ? {
1402
+ prepareStep: ({
1403
+ messages,
1404
+ stepNumber
1405
+ }) => {
1406
+ const said = steered && stepNumber > 0 ? steered() : [];
1407
+ let next = said.length ? [...messages, { role: "user", content: renderUserMessages(said) }] : messages;
1408
+ if (clear) next = clear(next);
1316
1409
  if (caching) next = withRollingBreakpoint(next, caching);
1317
1410
  return {
1318
1411
  ...dynamic ? { activeTools: activeOf(opts) } : {},
1319
- ...editMessages ? { messages: next } : {}
1412
+ ...editMessages || said.length ? { messages: next } : {}
1320
1413
  };
1321
1414
  }
1322
1415
  } : {},
@@ -1375,7 +1468,7 @@ var asJson = (value) => {
1375
1468
  return String(value);
1376
1469
  }
1377
1470
  };
1378
- var toolResultsPrompt = (results, newTools) => {
1471
+ var toolResultsPrompt = (results, newTools, said) => {
1379
1472
  const lines = results.map(
1380
1473
  (r) => `- ${r.name} ${clip(asJson(r.input), 160)} \u2192 ${r.ok ? "ok" : "FAILED"}: ${clip(asJson(r.output), 400)}`
1381
1474
  );
@@ -1384,6 +1477,8 @@ ${lines.join("\n")}
1384
1477
  ${newTools ? `
1385
1478
  TOOLS NOW AVAILABLE (call them by these exact names):
1386
1479
  ${newTools}
1480
+ ` : ""}${said.length ? `
1481
+ ${renderUserMessages(said)}
1387
1482
  ` : ""}
1388
1483
  Continue THIS step using the results above. Reply with a single JSON object, nothing else:
1389
1484
  { "reply": string, "actions": [ { "tool": string, "args": object } ] }
@@ -1440,7 +1535,8 @@ var runPrompted = async (model, opts) => {
1440
1535
  role: "user",
1441
1536
  content: toolResultsPrompt(
1442
1537
  results,
1443
- added.length && opts.describeTools ? opts.describeTools(added) : ""
1538
+ added.length && opts.describeTools ? opts.describeTools(added) : "",
1539
+ opts.takeUpdates?.() ?? []
1444
1540
  )
1445
1541
  });
1446
1542
  }
@@ -1579,7 +1675,8 @@ var executeStep = async (ctx, goal, step, index, total, done) => {
1579
1675
  mode: ctx.executorMode,
1580
1676
  skills: ctx.skills?.length ? renderSkillIndex(ctx.skills) : void 0,
1581
1677
  activeSkills: active.length ? renderActiveSkills(active) : void 0,
1582
- searchMode: searchMode && Boolean(ctx.tools[FIND_TOOLS_NAME])
1678
+ searchMode: searchMode && Boolean(ctx.tools[FIND_TOOLS_NAME]),
1679
+ updates: ctx.userUpdates?.()
1583
1680
  });
1584
1681
  const loop = await runToolLoop(ctx.executorModel, {
1585
1682
  mode: ctx.executorMode,
@@ -1591,6 +1688,7 @@ var executeStep = async (ctx, goal, step, index, total, done) => {
1591
1688
  describeTools: (names) => catalogFor(ctx, names),
1592
1689
  maxSteps: ctx.config.maxStepsPerTask,
1593
1690
  shouldStop: ctx.overBudget,
1691
+ ...ctx.takeRoundUpdates ? { takeUpdates: ctx.takeRoundUpdates } : {},
1594
1692
  maxOutputTokens: ctx.config.budgets.executor,
1595
1693
  temperature: ctx.config.temperature,
1596
1694
  abortSignal: ctx.signal,
@@ -1669,6 +1767,44 @@ var replanWanted = async (trigger, result, opts = {}) => {
1669
1767
  ]);
1670
1768
  };
1671
1769
 
1770
+ // src/agent/persistence.ts
1771
+ var SAFE_RUN_ID = /^[A-Za-z0-9_-]{1,128}$/;
1772
+ var assertSafeRunId = (runId, label = "runId") => {
1773
+ if (typeof runId !== "string" || !SAFE_RUN_ID.test(runId)) {
1774
+ throw new Error(`${label} must be 1-128 characters of letters, digits, "_" or "-"`);
1775
+ }
1776
+ return runId;
1777
+ };
1778
+ var resolveResume = async (persistence, resumeFromRunId) => {
1779
+ if (resumeFromRunId === void 0) return void 0;
1780
+ assertSafeRunId(resumeFromRunId, "resumeFromRunId");
1781
+ if (!persistence?.loadRun) {
1782
+ throw new Error("resumeFromRunId requires `persistence.loadRun` to be implemented");
1783
+ }
1784
+ const snapshot = await persistence.loadRun(resumeFromRunId);
1785
+ if (!snapshot) throw new Error(`No persisted run found for runId "${resumeFromRunId}"`);
1786
+ assertSafeRunId(snapshot.runId, "snapshot.runId");
1787
+ if (snapshot.runId !== resumeFromRunId) {
1788
+ throw new Error(
1789
+ `Persistence returned runId "${snapshot.runId}" for resumeFromRunId "${resumeFromRunId}"; refusing to resume on mismatch`
1790
+ );
1791
+ }
1792
+ if (snapshot.status === "complete") {
1793
+ throw new Error(`Run "${resumeFromRunId}" is already complete; nothing to resume`);
1794
+ }
1795
+ if (!snapshot.plan || !Array.isArray(snapshot.remaining) || !Array.isArray(snapshot.trace)) {
1796
+ throw new Error(
1797
+ `Run "${resumeFromRunId}" has no usable checkpoint (status="${snapshot.status}"); cannot resume`
1798
+ );
1799
+ }
1800
+ if (snapshot.remaining.length === 0) {
1801
+ throw new Error(
1802
+ `Run "${resumeFromRunId}" has no steps left to run (status="${snapshot.status}"); nothing to resume`
1803
+ );
1804
+ }
1805
+ return snapshot;
1806
+ };
1807
+
1672
1808
  // src/agent/schemas.ts
1673
1809
  import { z } from "zod";
1674
1810
  var PlanStepSchema = z.object({
@@ -1775,8 +1911,9 @@ ${nudge}` : goal;
1775
1911
  var asMessage = (err) => err instanceof Error ? err.message : String(err);
1776
1912
 
1777
1913
  // src/agent/replanner.ts
1778
- var decideReplan = async (ctx, goal, done, remaining) => {
1914
+ var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
1779
1915
  const state = await ctx.state();
1916
+ const updates = ctx.userUpdates?.();
1780
1917
  const active = ctx.activeSkills?.() ?? [];
1781
1918
  const commonFor = (mode) => {
1782
1919
  const parts = ctx.prompts.replanner({
@@ -1785,7 +1922,8 @@ var decideReplan = async (ctx, goal, done, remaining) => {
1785
1922
  done,
1786
1923
  remaining,
1787
1924
  mode,
1788
- activeSkills: active.length ? renderActiveSkills(active) : void 0
1925
+ activeSkills: active.length ? renderActiveSkills(active) : void 0,
1926
+ ...updates?.length ? { updates, newUpdates } : {}
1789
1927
  });
1790
1928
  return {
1791
1929
  ...stageCall(ctx, "replanner", parts.system),
@@ -1831,7 +1969,8 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
1831
1969
  state,
1832
1970
  done,
1833
1971
  findings,
1834
- activeSkills: active.length ? renderActiveSkills(active) : void 0
1972
+ activeSkills: active.length ? renderActiveSkills(active) : void 0,
1973
+ updates: ctx.userUpdates?.()
1835
1974
  });
1836
1975
  const result = stream(ctx.synthesizerModel, {
1837
1976
  ...stageCall(ctx, "synthesizer", parts.system),
@@ -1937,6 +2076,7 @@ var supportsPdf = (model) => {
1937
2076
  };
1938
2077
 
1939
2078
  // src/agent/runner.ts
2079
+ var newRunId = () => globalThis.crypto?.randomUUID?.() ?? `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1940
2080
  var errMessage = (err) => err instanceof Error ? err.message : String(err);
1941
2081
  var filterTools = (all, available, excluded) => {
1942
2082
  let entries = Object.entries(all);
@@ -2022,23 +2162,27 @@ var createAgent = async (config) => {
2022
2162
  log.info(
2023
2163
  `agent ready \u2014 ${catalog.length} tool(s) (${strategy}, ~${toolTokens || "?"} tokens), window ${cfg.compaction.contextWindowTokens}${modelWindow ? " (the model\u2019s)" : ""}, skills: [${[...skillNames].join(", ") || "none"}], planner mode: ${plannerMode}, executor mode: ${executorMode}, approval: ${approval.mode}`
2024
2164
  );
2025
- const run = async (goal, opts = {}) => {
2165
+ const runCore = async (goal, opts, track, port) => {
2166
+ const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
2026
2167
  const emit = (event) => {
2027
2168
  try {
2028
2169
  opts.onEvent?.(event);
2029
2170
  } catch {
2030
2171
  }
2031
2172
  };
2032
- const text = goal.trim();
2033
- const sessionId = opts.sessionId ?? cfg.sessionId;
2034
- let usage = emptyUsage();
2173
+ const text = (resumed?.goal ?? goal).trim();
2174
+ const sessionId = resumed?.sessionId ?? opts.sessionId ?? cfg.sessionId;
2175
+ const runId = resumed?.runId ?? newRunId();
2176
+ const startedAt = resumed?.startedAt ?? Date.now();
2177
+ let usage = resumed ? { ...resumed.usage } : emptyUsage();
2035
2178
  const result = {
2179
+ runId,
2036
2180
  goal: text,
2037
2181
  final: "",
2038
- plan: { thought: "", steps: [] },
2039
- trace: [],
2040
- steps: 0,
2041
- applied: 0,
2182
+ plan: resumed ? resumed.plan : { thought: "", steps: [] },
2183
+ trace: resumed ? [...resumed.trace] : [],
2184
+ steps: resumed ? resumed.trace.length : 0,
2185
+ applied: resumed?.applied ?? 0,
2042
2186
  stopped: false,
2043
2187
  usage,
2044
2188
  skills: []
@@ -2058,16 +2202,22 @@ var createAgent = async (config) => {
2058
2202
  } catch {
2059
2203
  }
2060
2204
  };
2061
- const activeSkillNames = /* @__PURE__ */ new Set();
2205
+ const activeSkillNames = new Set(
2206
+ (resumed?.skills ?? []).filter((n) => skillNames.has(n))
2207
+ );
2208
+ result.skills = [...activeSkillNames];
2062
2209
  const activateSkill = (name, by) => {
2063
2210
  if (activeSkillNames.has(name) || !skillNames.has(name)) return;
2064
2211
  activeSkillNames.add(name);
2065
2212
  result.skills = [...activeSkillNames];
2066
2213
  emit({ type: "skill.activated", name, by });
2067
2214
  };
2068
- const discovered = [];
2215
+ const discovered = [...resumed?.discovered ?? []];
2216
+ const userUpdates = (resumed?.userUpdates ?? []).map(
2217
+ (u) => ({ ...u })
2218
+ );
2069
2219
  let currentStep;
2070
- const counter = createCallCounter(cfg.maxToolCalls);
2220
+ const counter = createCallCounter(cfg.maxToolCalls, resumed?.toolCalls);
2071
2221
  const builtins = {};
2072
2222
  if (skills.length) {
2073
2223
  Object.assign(
@@ -2099,9 +2249,21 @@ var createAgent = async (config) => {
2099
2249
  signal: opts.signal,
2100
2250
  addUsage: (u) => bumpUsage(u, "subagent"),
2101
2251
  countCall: counter.count,
2102
- maxToolOutputChars: cfg.compaction.maxToolOutputChars
2252
+ maxToolOutputChars: cfg.compaction.maxToolOutputChars,
2253
+ control: port
2103
2254
  }
2104
2255
  );
2256
+ const deliver = (at) => {
2257
+ if (!port) return [];
2258
+ const taken = port.drain();
2259
+ for (const m of taken) {
2260
+ userUpdates.push({ text: m.text, reconciled: false });
2261
+ emit({ type: "message.delivered", id: m.id, text: m.text, at });
2262
+ log.info(`message from the user (delivered at ${at}):`, m.text);
2263
+ void remember({ role: "user", content: m.text });
2264
+ }
2265
+ return taken.map((m) => m.text);
2266
+ };
2105
2267
  let budgetExceeded;
2106
2268
  const breach = (extra) => {
2107
2269
  const b = checkLimits(extra ? addUsage(usage, extra) : usage, cfg.limits);
@@ -2110,7 +2272,18 @@ var createAgent = async (config) => {
2110
2272
  return { kind: "tool-calls", tokens: counter.calls, cap: cfg.maxToolCalls };
2111
2273
  return void 0;
2112
2274
  };
2113
- emit({ type: "run.start", goal: text });
2275
+ emit({
2276
+ type: "run.start",
2277
+ goal: text,
2278
+ runId,
2279
+ ...resumed ? {
2280
+ resumed: {
2281
+ completedSteps: resumed.trace.length,
2282
+ remainingSteps: resumed.remaining.length
2283
+ }
2284
+ } : {}
2285
+ });
2286
+ port?.attach(emit);
2114
2287
  const images = [...opts.images ?? [], ...opts.files ?? []];
2115
2288
  const refused = images.map(attachmentKind).find((kind) => accepts[kind] === false);
2116
2289
  if (refused) {
@@ -2125,7 +2298,7 @@ var createAgent = async (config) => {
2125
2298
  return result;
2126
2299
  }
2127
2300
  let history = [];
2128
- if (config.memory) {
2301
+ if (config.memory && !resumed) {
2129
2302
  try {
2130
2303
  history = await config.memory.load(sessionId);
2131
2304
  } catch {
@@ -2183,13 +2356,16 @@ var createAgent = async (config) => {
2183
2356
  setCurrentStep: (step) => {
2184
2357
  currentStep = step;
2185
2358
  },
2186
- images: images.length ? images : void 0
2359
+ images: images.length ? images : void 0,
2360
+ userUpdates: () => userUpdates.map((u) => u.text),
2361
+ ...port ? { takeRoundUpdates: () => deliver("round") } : {}
2187
2362
  };
2188
- await remember({
2189
- role: "user",
2190
- content: images.length ? `${text}
2363
+ if (!resumed)
2364
+ await remember({
2365
+ role: "user",
2366
+ content: images.length ? `${text}
2191
2367
  [attached: ${images.map((f, i) => f.name ?? `${attachmentKind(f)} ${i + 1}`).join(", ")}]` : text
2192
- });
2368
+ });
2193
2369
  log.info("run:", text, images.length ? `(+${images.length} image(s))` : "");
2194
2370
  const stop = () => {
2195
2371
  emit({ type: "stopped" });
@@ -2197,8 +2373,8 @@ var createAgent = async (config) => {
2197
2373
  return result;
2198
2374
  };
2199
2375
  try {
2200
- let planned = await createPlan(ctx, text);
2201
- bumpUsage(planned.usage, "plan");
2376
+ let planned = resumed ? { plan: resumed.plan, usage: emptyUsage(), skills: [] } : await createPlan(ctx, text);
2377
+ if (!resumed) bumpUsage(planned.usage, "plan");
2202
2378
  if (isAborted()) return stop();
2203
2379
  if (planned.plan.steps.length === 0 && text.split(/\s+/).length > 2) {
2204
2380
  log.warn(
@@ -2227,14 +2403,65 @@ var createAgent = async (config) => {
2227
2403
  `plan (${planned.plan.steps.length} steps):`,
2228
2404
  planned.plan.steps.map((s) => s.description)
2229
2405
  );
2230
- emit({ type: "plan.created", plan: planned.plan });
2231
- planned.plan.steps.forEach((step, index) => emit({ type: "plan.step-added", step, index }));
2406
+ const announced = resumed ? {
2407
+ thought: planned.plan.thought,
2408
+ steps: [...resumed.trace.map((r) => r.step), ...resumed.remaining]
2409
+ } : planned.plan;
2410
+ emit({ type: "plan.created", plan: announced });
2411
+ announced.steps.forEach((step, index) => emit({ type: "plan.step-added", step, index }));
2232
2412
  for (const name of planned.skills) activateSkill(name, "plan");
2233
- let done = [];
2234
- const findings = [];
2235
- let remaining = [...planned.plan.steps];
2236
- let iter = 0;
2237
- let revisions = 0;
2413
+ let done = resumed ? [...resumed.done] : [];
2414
+ const findings = resumed ? [...resumed.findings] : [];
2415
+ let remaining = resumed ? [...resumed.remaining] : [...planned.plan.steps];
2416
+ let iter = resumed?.iterations ?? 0;
2417
+ let revisions = resumed?.revisions ?? 0;
2418
+ const buildSnapshot = (status, extra = {}) => ({
2419
+ runId,
2420
+ startedAt,
2421
+ status,
2422
+ goal: text,
2423
+ sessionId,
2424
+ plan: planned.plan,
2425
+ // Copies: a store that keeps the object must not watch the loop mutate it.
2426
+ remaining: [...remaining],
2427
+ trace: [...result.trace],
2428
+ done: [...done],
2429
+ findings: [...findings],
2430
+ usage: { ...usage },
2431
+ iterations: iter,
2432
+ revisions,
2433
+ toolCalls: counter.calls,
2434
+ applied: result.applied,
2435
+ skills: [...activeSkillNames],
2436
+ discovered: [...discovered],
2437
+ attachments: images.length,
2438
+ ...userUpdates.length ? { userUpdates: userUpdates.map((u) => ({ ...u })) } : {},
2439
+ ...extra
2440
+ });
2441
+ const persist = async (hook, snapshot) => {
2442
+ const fn = config.persistence?.[hook];
2443
+ if (!fn) return;
2444
+ try {
2445
+ await fn.call(config.persistence, snapshot);
2446
+ } catch (err) {
2447
+ log.warn(`persistence.${hook} threw \u2014 the run carries on`, err);
2448
+ }
2449
+ };
2450
+ if (config.persistence) {
2451
+ track.complete = async (res) => {
2452
+ const error = track.error;
2453
+ const status = error ? "failed" : res?.stopped ? "cancelled" : "complete";
2454
+ await persist(
2455
+ "onRunComplete",
2456
+ buildSnapshot(status, {
2457
+ ...res ? { text: res.final } : {},
2458
+ ...error ? { error } : {},
2459
+ completedAt: Date.now()
2460
+ })
2461
+ );
2462
+ };
2463
+ if (!resumed) await persist("onRunStart", buildSnapshot("executing"));
2464
+ }
2238
2465
  while (remaining.length > 0 && iter < cfg.maxIterations) {
2239
2466
  if (isAborted()) return stop();
2240
2467
  const hit = breach();
@@ -2308,7 +2535,10 @@ var createAgent = async (config) => {
2308
2535
  }
2309
2536
  }
2310
2537
  }
2311
- const wantReplan = cfg.replan && iter < cfg.maxIterations && revisions < cfg.maxRevisions && !isAborted() && !breach() && await replanWanted(cfg.replanAfter, stepResult, {
2538
+ deliver("step");
2539
+ const fresh = userUpdates.filter((u) => !u.reconciled).length;
2540
+ const byUser = fresh > 0 && iter < cfg.maxIterations && !isAborted() && !breach();
2541
+ const wantReplan = byUser || cfg.replan && iter < cfg.maxIterations && revisions < cfg.maxRevisions && !isAborted() && !breach() && await replanWanted(cfg.replanAfter, stepResult, {
2312
2542
  signal: ctx.signal,
2313
2543
  timeoutMs: cfg.chatTimeoutMs,
2314
2544
  onError: (err) => log.warn("replanAfter predicate threw \u2014 using the failure rule", err)
@@ -2318,13 +2548,20 @@ var createAgent = async (config) => {
2318
2548
  ctx,
2319
2549
  text,
2320
2550
  done,
2321
- remaining.map((s) => s.description)
2551
+ remaining.map((s) => s.description),
2552
+ fresh
2322
2553
  );
2323
2554
  bumpUsage(decision.usage, "replan");
2324
- emit({ type: "replan.decision", mode: decision.decision, reason: decision.reason });
2555
+ emit({
2556
+ type: "replan.decision",
2557
+ mode: decision.decision,
2558
+ reason: decision.reason,
2559
+ ...byUser ? { byUser: true } : {}
2560
+ });
2561
+ for (const u of userUpdates) u.reconciled = true;
2325
2562
  if (decision.decision === "finish") break;
2326
2563
  if (decision.decision === "revise" && decision.plan.length > 0) {
2327
- revisions += 1;
2564
+ if (!byUser) revisions += 1;
2328
2565
  remaining = decision.plan.slice(0, Math.min(cfg.maxPlanSteps, cfg.maxIterations - iter)).map((description, i) => ({ id: `r${iter}-${i + 1}`, description }));
2329
2566
  emit({
2330
2567
  type: "plan.revised",
@@ -2333,6 +2570,7 @@ var createAgent = async (config) => {
2333
2570
  });
2334
2571
  }
2335
2572
  }
2573
+ if (config.persistence) await persist("onStepComplete", buildSnapshot("executing"));
2336
2574
  }
2337
2575
  if (!budgetExceeded && remaining.length > 0) {
2338
2576
  const hit = breach();
@@ -2346,6 +2584,7 @@ var createAgent = async (config) => {
2346
2584
  const stepWords = result.trace.map((r) => r.summary.trim()).filter((t) => t && !/^(Executed \d+ tool call\(s\)\.|Step produced no output\.)$/.test(t));
2347
2585
  let summary = stepWords.length ? stepWords.join("\n\n") : "Done \u2014 the changes have been applied.";
2348
2586
  if (cfg.synthesize) {
2587
+ deliver("final");
2349
2588
  try {
2350
2589
  const synth = await synthesizeAnswer(ctx, text, done, findings);
2351
2590
  bumpUsage(synth.usage, "synthesize");
@@ -2390,9 +2629,26 @@ var createAgent = async (config) => {
2390
2629
  if (isAborted()) return stop();
2391
2630
  emit({ type: "error", phase: "run", error: errMessage(err) });
2392
2631
  result.final = errMessage(err);
2632
+ track.error = errMessage(err);
2393
2633
  return result;
2394
2634
  }
2395
2635
  };
2636
+ const run = async (goal, opts = {}) => {
2637
+ const port = portOf(opts.control);
2638
+ const track = {};
2639
+ let result;
2640
+ try {
2641
+ result = await runCore(goal, opts, track, port);
2642
+ } catch (err) {
2643
+ port?.detach();
2644
+ track.error = err instanceof Error ? err.message : String(err);
2645
+ await track.complete?.(void 0);
2646
+ throw err;
2647
+ }
2648
+ if (port) result.undelivered = port.detach();
2649
+ await track.complete?.(result);
2650
+ return result;
2651
+ };
2396
2652
  const compact = async (o = {}) => {
2397
2653
  const empty = {
2398
2654
  compacted: false,
@@ -2509,6 +2765,35 @@ var createSubagentTool = (opts) => {
2509
2765
  if (opts.worker && !opts.workerConfig) {
2510
2766
  throw new Error(`subagent "${opts.name}": a worker subagent needs \`workerConfig\``);
2511
2767
  }
2768
+ const profiles = opts.profiles ?? {};
2769
+ const profileNames = Object.keys(profiles);
2770
+ for (const [pname, p] of Object.entries(profiles)) {
2771
+ if (!pname.trim()) throw new Error(`subagent "${opts.name}": a profile needs a non-empty name`);
2772
+ if (!p || typeof p.description !== "string" || !p.description.trim()) {
2773
+ throw new Error(
2774
+ `subagent "${opts.name}": profile "${pname}" needs a description \u2014 the parent model chooses by it`
2775
+ );
2776
+ }
2777
+ if (opts.worker && p.config) {
2778
+ throw new Error(
2779
+ `subagent "${opts.name}": profile "${pname}" sets \`config\`, which does not apply to a worker subagent \u2014 use \`workerConfig\``
2780
+ );
2781
+ }
2782
+ if (!opts.worker && p.workerConfig) {
2783
+ throw new Error(
2784
+ `subagent "${opts.name}": profile "${pname}" sets \`workerConfig\`, which does not apply to an in-process subagent \u2014 use \`config\``
2785
+ );
2786
+ }
2787
+ }
2788
+ const pickProfile = (name) => {
2789
+ if (!name) return void 0;
2790
+ if (!Object.hasOwn(profiles, name)) {
2791
+ throw new Error(
2792
+ `subagent "${opts.name}": unknown profile "${name}" \u2014 choose one of: ${profileNames.join(", ")}`
2793
+ );
2794
+ }
2795
+ return profiles[name];
2796
+ };
2512
2797
  const acquire = createSemaphore(Math.max(1, opts.maxConcurrent ?? 4));
2513
2798
  const outputMax = opts.outputMaxChars ?? 8e3;
2514
2799
  const gatedHostTools = (approve) => Object.fromEntries(
@@ -2527,8 +2812,8 @@ var createSubagentTool = (opts) => {
2527
2812
  ];
2528
2813
  })
2529
2814
  );
2530
- const runInProcess = async (task, signal, forward, hostTools) => {
2531
- const config = opts.config;
2815
+ const runInProcess = async (task, signal, forward, hostTools, profile) => {
2816
+ const config = { ...opts.config, ...profile?.config };
2532
2817
  const agent = await createAgent({ ...config, tools: { ...config.tools, ...hostTools } });
2533
2818
  let runError;
2534
2819
  const result = await agent.run(task, {
@@ -2550,8 +2835,8 @@ var createSubagentTool = (opts) => {
2550
2835
  readOnly: isReadOnlyTool(t2)
2551
2836
  }))
2552
2837
  );
2553
- const workerConfigFor = async () => {
2554
- const cfg = opts.workerConfig;
2838
+ const workerConfigFor = async (profile) => {
2839
+ const cfg = { ...opts.workerConfig, ...profile?.workerConfig };
2555
2840
  let model = { ...cfg.model };
2556
2841
  if (model.credentialRef && !model.apiKey && opts.credentials) {
2557
2842
  const apiKey = await opts.credentials.getApiKey(model.credentialRef);
@@ -2561,9 +2846,10 @@ var createSubagentTool = (opts) => {
2561
2846
  }
2562
2847
  return toCloneable({ ...cfg, model });
2563
2848
  };
2564
- const runInWorker = async (task, signal, forward, hostTools) => {
2849
+ const runInWorker = async (task, signal, forward, hostTools, profile) => {
2850
+ if (signal?.aborted) throw abortError();
2851
+ const [config, proxied] = await Promise.all([workerConfigFor(profile), proxiedSpecs()]);
2565
2852
  if (signal?.aborted) throw abortError();
2566
- const [config, proxied] = await Promise.all([workerConfigFor(), proxiedSpecs()]);
2567
2853
  const worker = opts.worker();
2568
2854
  return new Promise((resolve, reject) => {
2569
2855
  let settled = false;
@@ -2619,20 +2905,32 @@ var createSubagentTool = (opts) => {
2619
2905
  safePost(worker, { type: "run", task, config, proxied });
2620
2906
  });
2621
2907
  };
2908
+ const description = profileNames.length ? `${opts.description}
2909
+
2910
+ Optional \`profile\` (omit it for the default):
2911
+ ${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
2622
2912
  const t = tool3({
2623
- description: opts.description,
2913
+ description,
2624
2914
  inputSchema: jsonSchema3({
2625
2915
  type: "object",
2626
2916
  properties: {
2627
2917
  task: {
2628
2918
  type: "string",
2629
2919
  description: "A complete, self-contained task: the subagent sees nothing of your context except this text."
2630
- }
2920
+ },
2921
+ ...profileNames.length ? {
2922
+ profile: {
2923
+ type: "string",
2924
+ enum: profileNames,
2925
+ description: "One of this tool's profiles, described above. Omit it for the default."
2926
+ }
2927
+ } : {}
2631
2928
  },
2632
2929
  required: ["task"],
2633
2930
  additionalProperties: false
2634
2931
  }),
2635
- execute: async ({ task }, options) => {
2932
+ execute: async ({ task, profile: profileName }, options) => {
2933
+ const profile = pickProfile(profileName);
2636
2934
  const runCtx = toolRunContextOf(options);
2637
2935
  const parentSignal = options?.abortSignal ?? runCtx?.signal;
2638
2936
  const id = `${opts.name}-${seq2 += 1}`;
@@ -2643,20 +2941,46 @@ var createSubagentTool = (opts) => {
2643
2941
  parentSignal?.addEventListener("abort", onParentAbort, { once: true });
2644
2942
  if (parentSignal?.aborted) controller.abort();
2645
2943
  let timedOut = false;
2944
+ let stoppedByUser = false;
2646
2945
  const timer = opts.timeoutMs && opts.timeoutMs > 0 ? setTimeout(() => {
2647
2946
  timedOut = true;
2648
2947
  controller.abort();
2649
2948
  }, opts.timeoutMs) : void 0;
2650
- emit({ type: "subagent.start", id, name: opts.name, task });
2949
+ emit({
2950
+ type: "subagent.start",
2951
+ id,
2952
+ name: opts.name,
2953
+ task,
2954
+ ...profile ? { profile: profileName } : {}
2955
+ });
2956
+ const unregister = runCtx?.control?.registerSubagent(
2957
+ {
2958
+ id,
2959
+ name: opts.name,
2960
+ task,
2961
+ ...profile ? { profile: profileName } : {},
2962
+ startedAt: Date.now()
2963
+ },
2964
+ () => {
2965
+ stoppedByUser = true;
2966
+ controller.abort();
2967
+ }
2968
+ );
2651
2969
  try {
2652
2970
  const forward = (event) => emit({ type: "subagent.event", id, name: opts.name, event });
2653
2971
  const hostTools = gatedHostTools(runCtx?.approve);
2654
2972
  const run = opts.worker ? runInWorker : runInProcess;
2655
- const out = await run(task, controller.signal, forward, hostTools).catch((err) => {
2656
- if (timedOut)
2657
- throw new Error(`subagent "${opts.name}" timed out after ${opts.timeoutMs} ms`);
2658
- throw err;
2659
- });
2973
+ const out = await run(task, controller.signal, forward, hostTools, profile).catch(
2974
+ (err) => {
2975
+ if (stoppedByUser)
2976
+ throw new Error(
2977
+ `subagent "${opts.name}" was stopped by the user before it finished \u2014 carry on without its result, or take another approach`
2978
+ );
2979
+ if (timedOut)
2980
+ throw new Error(`subagent "${opts.name}" timed out after ${opts.timeoutMs} ms`);
2981
+ throw err;
2982
+ }
2983
+ );
2660
2984
  runCtx?.addUsage(out.usage);
2661
2985
  emit({ type: "subagent.complete", id, name: opts.name, text: out.text, usage: out.usage });
2662
2986
  return clip(out.text, outputMax);
@@ -2665,17 +2989,19 @@ var createSubagentTool = (opts) => {
2665
2989
  type: "subagent.error",
2666
2990
  id,
2667
2991
  name: opts.name,
2668
- error: err instanceof Error ? err.message : String(err)
2992
+ error: err instanceof Error ? err.message : String(err),
2993
+ ...stoppedByUser ? { stopped: true } : {}
2669
2994
  });
2670
2995
  throw err;
2671
2996
  } finally {
2997
+ unregister?.();
2672
2998
  if (timer !== void 0) clearTimeout(timer);
2673
2999
  parentSignal?.removeEventListener("abort", onParentAbort);
2674
3000
  release();
2675
3001
  }
2676
3002
  }
2677
3003
  });
2678
- t.promptHint = "{ task: string }";
3004
+ t.promptHint = profileNames.length ? `{ task: string, profile?: ${profileNames.map((n) => JSON.stringify(n)).join(" | ")} }` : "{ task: string }";
2679
3005
  if (opts.readOnly) t.readOnly = true;
2680
3006
  return t;
2681
3007
  };
@@ -3094,19 +3420,118 @@ var IndexedDBStore = class {
3094
3420
  return (await db.getAllKeys(SESSIONS_STORE)).map(String);
3095
3421
  }
3096
3422
  };
3423
+
3424
+ // src/memory/runs.ts
3425
+ var resumableOf = (all, sessionId) => all.filter(
3426
+ (s) => s.status !== "complete" && (sessionId === void 0 || s.sessionId === sessionId)
3427
+ ).sort((a, b) => b.startedAt - a.startedAt);
3428
+ var MemoryRunStore = class {
3429
+ runs = /* @__PURE__ */ new Map();
3430
+ keepCompleted;
3431
+ constructor(opts = {}) {
3432
+ this.keepCompleted = opts.keepCompleted ?? false;
3433
+ }
3434
+ onRunStart(snapshot) {
3435
+ this.runs.set(snapshot.runId, snapshot);
3436
+ }
3437
+ onStepComplete(snapshot) {
3438
+ this.runs.set(snapshot.runId, snapshot);
3439
+ }
3440
+ onRunComplete(snapshot) {
3441
+ if (snapshot.status === "complete" && !this.keepCompleted) this.runs.delete(snapshot.runId);
3442
+ else this.runs.set(snapshot.runId, snapshot);
3443
+ }
3444
+ loadRun(runId) {
3445
+ return this.runs.get(runId) ?? null;
3446
+ }
3447
+ /** Runs that can still be resumed (executing, stopped or failed), newest first. */
3448
+ resumable(sessionId) {
3449
+ return resumableOf([...this.runs.values()], sessionId);
3450
+ }
3451
+ /** The most recent run that can be resumed — what to offer after a reload. */
3452
+ latestResumable(sessionId) {
3453
+ return this.resumable(sessionId)[0];
3454
+ }
3455
+ delete(runId) {
3456
+ this.runs.delete(runId);
3457
+ }
3458
+ clear() {
3459
+ this.runs.clear();
3460
+ }
3461
+ };
3462
+ var jsonSafe = (value) => JSON.parse(
3463
+ JSON.stringify(
3464
+ value,
3465
+ (_k, v) => v instanceof Error ? v.message : typeof v === "bigint" ? v.toString() : v
3466
+ )
3467
+ );
3468
+ var IndexedDBRunStore = class {
3469
+ dbName;
3470
+ keepCompleted;
3471
+ constructor(opts = {}) {
3472
+ this.dbName = opts.dbName;
3473
+ this.keepCompleted = opts.keepCompleted ?? false;
3474
+ }
3475
+ async put(snapshot) {
3476
+ const db = await openAgentWebDB({ dbName: this.dbName });
3477
+ try {
3478
+ await db.put(RUNS_STORE, snapshot, snapshot.runId);
3479
+ } catch (err) {
3480
+ if (err?.name !== "DataCloneError") throw err;
3481
+ await db.put(RUNS_STORE, jsonSafe(snapshot), snapshot.runId);
3482
+ }
3483
+ }
3484
+ onRunStart(snapshot) {
3485
+ return this.put(snapshot);
3486
+ }
3487
+ onStepComplete(snapshot) {
3488
+ return this.put(snapshot);
3489
+ }
3490
+ async onRunComplete(snapshot) {
3491
+ if (snapshot.status === "complete" && !this.keepCompleted) {
3492
+ await this.delete(snapshot.runId);
3493
+ return;
3494
+ }
3495
+ await this.put(snapshot);
3496
+ }
3497
+ async loadRun(runId) {
3498
+ const db = await openAgentWebDB({ dbName: this.dbName });
3499
+ return await db.get(RUNS_STORE, runId) ?? null;
3500
+ }
3501
+ /** Runs that can still be resumed (executing, stopped or failed), newest first. */
3502
+ async resumable(sessionId) {
3503
+ const db = await openAgentWebDB({ dbName: this.dbName });
3504
+ return resumableOf(await db.getAll(RUNS_STORE), sessionId);
3505
+ }
3506
+ /** The most recent run that can be resumed — what to offer after a reload. */
3507
+ async latestResumable(sessionId) {
3508
+ return (await this.resumable(sessionId))[0];
3509
+ }
3510
+ async delete(runId) {
3511
+ const db = await openAgentWebDB({ dbName: this.dbName });
3512
+ await db.delete(RUNS_STORE, runId);
3513
+ }
3514
+ async clear() {
3515
+ const db = await openAgentWebDB({ dbName: this.dbName });
3516
+ await db.clear(RUNS_STORE);
3517
+ }
3518
+ };
3097
3519
  export {
3098
3520
  AttachmentsNotSupportedError,
3099
3521
  ContextWindowExceededError,
3100
3522
  FILES_STORE,
3101
3523
  FIND_TOOLS_NAME,
3102
3524
  ImagesNotSupportedError,
3525
+ IndexedDBRunStore,
3103
3526
  IndexedDBStore,
3104
3527
  IndexedDBVault,
3105
3528
  KEYS_STORE,
3106
3529
  MemoryCredentialStore,
3530
+ MemoryRunStore,
3107
3531
  MemoryStore,
3108
3532
  PlanSchema,
3109
3533
  PlanStepSchema,
3534
+ RUNS_STORE,
3110
3535
  ReplanSchema,
3111
3536
  SECRETS_STORE,
3112
3537
  SESSIONS_STORE,
@@ -3132,6 +3557,7 @@ export {
3132
3557
  createFindToolsTool,
3133
3558
  createLogger,
3134
3559
  createPlan,
3560
+ createRunControl,
3135
3561
  createSkillTools,
3136
3562
  createSubagentTool,
3137
3563
  createToolResultClearer,
@@ -3187,6 +3613,7 @@ export {
3187
3613
  resolveCompaction,
3188
3614
  resolveConfig,
3189
3615
  resolveModel,
3616
+ resolveResume,
3190
3617
  resolveStage,
3191
3618
  resolveThinking,
3192
3619
  runToolLoop,