@dudko.dev/agent-web 0.0.27 → 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/README.md +39 -1
- package/dist/agent-web.js +111 -98
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-V7COB2EA.js → chunk-CPSDKXO6.js} +5 -2
- package/dist/chunk-CPSDKXO6.js.map +1 -0
- package/dist/index.cjs +496 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +349 -24
- package/dist/index.d.ts +349 -24
- package/dist/index.js +490 -63
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +3 -1
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/types-DwSMj_Xs.d.cts +21 -0
- package/dist/types-DwSMj_Xs.d.ts +21 -0
- package/dist/webmcp.cjs +208 -0
- package/dist/webmcp.cjs.map +1 -0
- package/dist/webmcp.d.cts +131 -0
- package/dist/webmcp.d.ts +131 -0
- package/dist/webmcp.js +179 -0
- package/dist/webmcp.js.map +1 -0
- package/package.json +19 -9
- package/dist/chunk-V7COB2EA.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -468,13 +468,16 @@ __export(src_exports, {
|
|
|
468
468
|
FILES_STORE: () => FILES_STORE,
|
|
469
469
|
FIND_TOOLS_NAME: () => FIND_TOOLS_NAME,
|
|
470
470
|
ImagesNotSupportedError: () => ImagesNotSupportedError,
|
|
471
|
+
IndexedDBRunStore: () => IndexedDBRunStore,
|
|
471
472
|
IndexedDBStore: () => IndexedDBStore,
|
|
472
473
|
IndexedDBVault: () => IndexedDBVault,
|
|
473
474
|
KEYS_STORE: () => KEYS_STORE,
|
|
474
475
|
MemoryCredentialStore: () => MemoryCredentialStore,
|
|
476
|
+
MemoryRunStore: () => MemoryRunStore,
|
|
475
477
|
MemoryStore: () => MemoryStore,
|
|
476
478
|
PlanSchema: () => PlanSchema,
|
|
477
479
|
PlanStepSchema: () => PlanStepSchema,
|
|
480
|
+
RUNS_STORE: () => RUNS_STORE,
|
|
478
481
|
ReplanSchema: () => ReplanSchema,
|
|
479
482
|
SECRETS_STORE: () => SECRETS_STORE,
|
|
480
483
|
SESSIONS_STORE: () => SESSIONS_STORE,
|
|
@@ -500,6 +503,7 @@ __export(src_exports, {
|
|
|
500
503
|
createFindToolsTool: () => createFindToolsTool,
|
|
501
504
|
createLogger: () => createLogger,
|
|
502
505
|
createPlan: () => createPlan,
|
|
506
|
+
createRunControl: () => createRunControl,
|
|
503
507
|
createSkillTools: () => createSkillTools,
|
|
504
508
|
createSubagentTool: () => createSubagentTool,
|
|
505
509
|
createToolResultClearer: () => createToolResultClearer,
|
|
@@ -555,6 +559,7 @@ __export(src_exports, {
|
|
|
555
559
|
resolveCompaction: () => resolveCompaction,
|
|
556
560
|
resolveConfig: () => resolveConfig,
|
|
557
561
|
resolveModel: () => resolveModel,
|
|
562
|
+
resolveResume: () => resolveResume,
|
|
558
563
|
resolveStage: () => resolveStage,
|
|
559
564
|
resolveThinking: () => resolveThinking,
|
|
560
565
|
runToolLoop: () => runToolLoop,
|
|
@@ -904,6 +909,23 @@ var section = (title, body) => body && body.trim() ? `
|
|
|
904
909
|
|
|
905
910
|
${title}:
|
|
906
911
|
${body.trim()}` : "";
|
|
912
|
+
var quoted = (text) => text.trim().replace(/\n/g, "\n ");
|
|
913
|
+
var updatesBlock = (updates, fresh = 0, advice = "") => {
|
|
914
|
+
if (!updates || updates.length === 0) return "";
|
|
915
|
+
const firstNew = fresh > 0 ? updates.length - fresh : updates.length;
|
|
916
|
+
const lines = updates.map(
|
|
917
|
+
(u, i) => `${i + 1}. ${quoted(u)}${i >= firstNew ? " [NEW \u2014 not yet reflected in the plan]" : ""}`
|
|
918
|
+
);
|
|
919
|
+
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):
|
|
920
|
+
${lines.join("\n")}`;
|
|
921
|
+
return advice ? `${head}
|
|
922
|
+
${advice}` : head;
|
|
923
|
+
};
|
|
924
|
+
var renderUserMessages = (texts) => `NEW MESSAGE FROM THE USER, sent while you were working:
|
|
925
|
+
${texts.map((t) => `- ${quoted(t)}`).join(
|
|
926
|
+
"\n"
|
|
927
|
+
)}
|
|
928
|
+
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.`;
|
|
907
929
|
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.
|
|
908
930
|
- 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.
|
|
909
931
|
- Plan realistic steps the available TOOLS can perform, grounded in the current STATE.
|
|
@@ -956,6 +978,8 @@ Reply with a single JSON object, nothing else:
|
|
|
956
978
|
- "revise": replace the REMAINING steps with a better list in "plan"; never repeat done work.
|
|
957
979
|
- "finish": the goal is already met \u2014 stop (omit "plan").
|
|
958
980
|
${REPLANNER_RULES}`;
|
|
981
|
+
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.`;
|
|
982
|
+
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.`;
|
|
959
983
|
var SYNTHESIZER_SYSTEM = `You are the SYNTHESIZER. Answer the user's goal from what the agent did and found.
|
|
960
984
|
- Lead with the result: the concrete data, from the FINDINGS verbatim when accuracy matters (names, numbers, ids), then \u2014 briefly \u2014 what was changed.
|
|
961
985
|
- Mention any assumption the agent made. If something could not be done, say so plainly and why.
|
|
@@ -976,6 +1000,7 @@ ${ctx.toolCatalog}`,
|
|
|
976
1000
|
stateBlock(ctx.state).trimStart(),
|
|
977
1001
|
ctx.mode === "prompted" ? `TOOLS:
|
|
978
1002
|
${ctx.toolCatalog}` : "",
|
|
1003
|
+
updatesBlock(ctx.updates),
|
|
979
1004
|
ctx.done.length ? `Already done:
|
|
980
1005
|
${numbered(ctx.done, "")}` : "",
|
|
981
1006
|
`STEP ${ctx.index}/${ctx.total}: ${ctx.step}`
|
|
@@ -986,6 +1011,7 @@ ${numbered(ctx.done, "")}` : "",
|
|
|
986
1011
|
prompt: [
|
|
987
1012
|
`GOAL: ${ctx.goal}`,
|
|
988
1013
|
stateBlock(ctx.state).trimStart(),
|
|
1014
|
+
updatesBlock(ctx.updates, ctx.newUpdates, REPLANNER_UPDATES_ADVICE),
|
|
989
1015
|
`Already done:
|
|
990
1016
|
${numbered(ctx.done, "(nothing yet)")}`,
|
|
991
1017
|
`Remaining plan:
|
|
@@ -998,6 +1024,7 @@ ${numbered(ctx.remaining, "(none)")}`,
|
|
|
998
1024
|
prompt: [
|
|
999
1025
|
`GOAL: ${ctx.goal}`,
|
|
1000
1026
|
stateBlock(ctx.state).trimStart(),
|
|
1027
|
+
updatesBlock(ctx.updates, 0, SYNTHESIZER_UPDATES_ADVICE),
|
|
1001
1028
|
`What was done:
|
|
1002
1029
|
${numbered(ctx.done, "(no changes)")}`,
|
|
1003
1030
|
ctx.findings?.length ? `FINDINGS (tool results):
|
|
@@ -1535,7 +1562,8 @@ var wrapToolsForRun = (tools, o) => {
|
|
|
1535
1562
|
step: o.step(),
|
|
1536
1563
|
signal: o.signal,
|
|
1537
1564
|
addUsage: o.addUsage,
|
|
1538
|
-
approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro)
|
|
1565
|
+
approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),
|
|
1566
|
+
...o.control ? { control: o.control } : {}
|
|
1539
1567
|
};
|
|
1540
1568
|
return execute.call(t, input, { ...options, agentRun });
|
|
1541
1569
|
};
|
|
@@ -1560,8 +1588,8 @@ var wrapToolsForRun = (tools, o) => {
|
|
|
1560
1588
|
}
|
|
1561
1589
|
return out;
|
|
1562
1590
|
};
|
|
1563
|
-
var createCallCounter = (cap) => {
|
|
1564
|
-
let calls = 0;
|
|
1591
|
+
var createCallCounter = (cap, initial = 0) => {
|
|
1592
|
+
let calls = Math.max(0, Math.floor(initial));
|
|
1565
1593
|
return {
|
|
1566
1594
|
count: () => {
|
|
1567
1595
|
if (cap && cap > 0 && calls >= cap) throw new ToolBudgetError(cap);
|
|
@@ -1605,6 +1633,69 @@ var schemaHintOf = async (t) => {
|
|
|
1605
1633
|
}
|
|
1606
1634
|
};
|
|
1607
1635
|
|
|
1636
|
+
// src/agent/control.ts
|
|
1637
|
+
var ports = /* @__PURE__ */ new WeakMap();
|
|
1638
|
+
var portOf = (control) => {
|
|
1639
|
+
if (!control) return void 0;
|
|
1640
|
+
const port = ports.get(control);
|
|
1641
|
+
if (!port) throw new TypeError("`control` must be created with createRunControl()");
|
|
1642
|
+
return port;
|
|
1643
|
+
};
|
|
1644
|
+
var createRunControl = () => {
|
|
1645
|
+
let seq3 = 0;
|
|
1646
|
+
let queue = [];
|
|
1647
|
+
let emit;
|
|
1648
|
+
let ended = false;
|
|
1649
|
+
const children = /* @__PURE__ */ new Map();
|
|
1650
|
+
const control = {
|
|
1651
|
+
send(text) {
|
|
1652
|
+
const clean = typeof text === "string" ? text.trim() : "";
|
|
1653
|
+
if (!clean || ended) return false;
|
|
1654
|
+
const message = { id: `msg-${seq3 += 1}`, text: clean };
|
|
1655
|
+
queue.push(message);
|
|
1656
|
+
emit?.({ type: "message.queued", id: message.id, text: message.text });
|
|
1657
|
+
return true;
|
|
1658
|
+
},
|
|
1659
|
+
pending: () => queue.map((m) => m.text),
|
|
1660
|
+
subagents: () => [...children.values()].map((c) => c.info).sort((a, b) => a.startedAt - b.startedAt),
|
|
1661
|
+
stopSubagent(id) {
|
|
1662
|
+
const child = children.get(id);
|
|
1663
|
+
if (!child) return false;
|
|
1664
|
+
child.stop();
|
|
1665
|
+
return true;
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
ports.set(control, {
|
|
1669
|
+
attach(next) {
|
|
1670
|
+
if (ended) {
|
|
1671
|
+
queue = [];
|
|
1672
|
+
children.clear();
|
|
1673
|
+
}
|
|
1674
|
+
emit = next;
|
|
1675
|
+
ended = false;
|
|
1676
|
+
for (const m of queue) next({ type: "message.queued", id: m.id, text: m.text });
|
|
1677
|
+
},
|
|
1678
|
+
detach() {
|
|
1679
|
+
emit = void 0;
|
|
1680
|
+
ended = true;
|
|
1681
|
+
children.clear();
|
|
1682
|
+
return queue.map((m) => m.text);
|
|
1683
|
+
},
|
|
1684
|
+
drain() {
|
|
1685
|
+
const out = queue;
|
|
1686
|
+
queue = [];
|
|
1687
|
+
return out;
|
|
1688
|
+
},
|
|
1689
|
+
registerSubagent(info, stop) {
|
|
1690
|
+
children.set(info.id, { info, stop });
|
|
1691
|
+
return () => {
|
|
1692
|
+
children.delete(info.id);
|
|
1693
|
+
};
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
return control;
|
|
1697
|
+
};
|
|
1698
|
+
|
|
1608
1699
|
// src/agent/executor.ts
|
|
1609
1700
|
init_context_window();
|
|
1610
1701
|
|
|
@@ -1849,6 +1940,7 @@ var runNative = async (model, opts) => {
|
|
|
1849
1940
|
const caching = opts.caching?.enabled ? opts.caching : void 0;
|
|
1850
1941
|
const clear = opts.clearToolResults ? createToolResultClearer(opts.clearToolResults, opts.callbacks?.onToolResultsCleared) : void 0;
|
|
1851
1942
|
const editMessages = caching || clear;
|
|
1943
|
+
const steered = opts.takeUpdates;
|
|
1852
1944
|
const result = (0, import_ai7.streamText)({
|
|
1853
1945
|
model,
|
|
1854
1946
|
tools: opts.tools,
|
|
@@ -1856,13 +1948,18 @@ var runNative = async (model, opts) => {
|
|
|
1856
1948
|
// Before every round: re-read the active set so tools activated mid-call
|
|
1857
1949
|
// (find_tools) become callable; clear stale tool results; move the cache
|
|
1858
1950
|
// breakpoint to the newest message.
|
|
1859
|
-
...dynamic || editMessages ? {
|
|
1860
|
-
prepareStep: ({
|
|
1861
|
-
|
|
1951
|
+
...dynamic || editMessages || steered ? {
|
|
1952
|
+
prepareStep: ({
|
|
1953
|
+
messages,
|
|
1954
|
+
stepNumber
|
|
1955
|
+
}) => {
|
|
1956
|
+
const said = steered && stepNumber > 0 ? steered() : [];
|
|
1957
|
+
let next = said.length ? [...messages, { role: "user", content: renderUserMessages(said) }] : messages;
|
|
1958
|
+
if (clear) next = clear(next);
|
|
1862
1959
|
if (caching) next = withRollingBreakpoint(next, caching);
|
|
1863
1960
|
return {
|
|
1864
1961
|
...dynamic ? { activeTools: activeOf(opts) } : {},
|
|
1865
|
-
...editMessages ? { messages: next } : {}
|
|
1962
|
+
...editMessages || said.length ? { messages: next } : {}
|
|
1866
1963
|
};
|
|
1867
1964
|
}
|
|
1868
1965
|
} : {},
|
|
@@ -1921,7 +2018,7 @@ var asJson = (value) => {
|
|
|
1921
2018
|
return String(value);
|
|
1922
2019
|
}
|
|
1923
2020
|
};
|
|
1924
|
-
var toolResultsPrompt = (results, newTools) => {
|
|
2021
|
+
var toolResultsPrompt = (results, newTools, said) => {
|
|
1925
2022
|
const lines = results.map(
|
|
1926
2023
|
(r) => `- ${r.name} ${clip(asJson(r.input), 160)} \u2192 ${r.ok ? "ok" : "FAILED"}: ${clip(asJson(r.output), 400)}`
|
|
1927
2024
|
);
|
|
@@ -1930,6 +2027,8 @@ ${lines.join("\n")}
|
|
|
1930
2027
|
${newTools ? `
|
|
1931
2028
|
TOOLS NOW AVAILABLE (call them by these exact names):
|
|
1932
2029
|
${newTools}
|
|
2030
|
+
` : ""}${said.length ? `
|
|
2031
|
+
${renderUserMessages(said)}
|
|
1933
2032
|
` : ""}
|
|
1934
2033
|
Continue THIS step using the results above. Reply with a single JSON object, nothing else:
|
|
1935
2034
|
{ "reply": string, "actions": [ { "tool": string, "args": object } ] }
|
|
@@ -1986,7 +2085,8 @@ var runPrompted = async (model, opts) => {
|
|
|
1986
2085
|
role: "user",
|
|
1987
2086
|
content: toolResultsPrompt(
|
|
1988
2087
|
results,
|
|
1989
|
-
added.length && opts.describeTools ? opts.describeTools(added) : ""
|
|
2088
|
+
added.length && opts.describeTools ? opts.describeTools(added) : "",
|
|
2089
|
+
opts.takeUpdates?.() ?? []
|
|
1990
2090
|
)
|
|
1991
2091
|
});
|
|
1992
2092
|
}
|
|
@@ -2129,7 +2229,8 @@ var executeStep = async (ctx, goal, step, index, total, done) => {
|
|
|
2129
2229
|
mode: ctx.executorMode,
|
|
2130
2230
|
skills: ctx.skills?.length ? renderSkillIndex(ctx.skills) : void 0,
|
|
2131
2231
|
activeSkills: active.length ? renderActiveSkills(active) : void 0,
|
|
2132
|
-
searchMode: searchMode && Boolean(ctx.tools[FIND_TOOLS_NAME])
|
|
2232
|
+
searchMode: searchMode && Boolean(ctx.tools[FIND_TOOLS_NAME]),
|
|
2233
|
+
updates: ctx.userUpdates?.()
|
|
2133
2234
|
});
|
|
2134
2235
|
const loop = await runToolLoop(ctx.executorModel, {
|
|
2135
2236
|
mode: ctx.executorMode,
|
|
@@ -2141,6 +2242,7 @@ var executeStep = async (ctx, goal, step, index, total, done) => {
|
|
|
2141
2242
|
describeTools: (names) => catalogFor(ctx, names),
|
|
2142
2243
|
maxSteps: ctx.config.maxStepsPerTask,
|
|
2143
2244
|
shouldStop: ctx.overBudget,
|
|
2245
|
+
...ctx.takeRoundUpdates ? { takeUpdates: ctx.takeRoundUpdates } : {},
|
|
2144
2246
|
maxOutputTokens: ctx.config.budgets.executor,
|
|
2145
2247
|
temperature: ctx.config.temperature,
|
|
2146
2248
|
abortSignal: ctx.signal,
|
|
@@ -2219,6 +2321,44 @@ var replanWanted = async (trigger, result, opts = {}) => {
|
|
|
2219
2321
|
]);
|
|
2220
2322
|
};
|
|
2221
2323
|
|
|
2324
|
+
// src/agent/persistence.ts
|
|
2325
|
+
var SAFE_RUN_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
2326
|
+
var assertSafeRunId = (runId, label = "runId") => {
|
|
2327
|
+
if (typeof runId !== "string" || !SAFE_RUN_ID.test(runId)) {
|
|
2328
|
+
throw new Error(`${label} must be 1-128 characters of letters, digits, "_" or "-"`);
|
|
2329
|
+
}
|
|
2330
|
+
return runId;
|
|
2331
|
+
};
|
|
2332
|
+
var resolveResume = async (persistence, resumeFromRunId) => {
|
|
2333
|
+
if (resumeFromRunId === void 0) return void 0;
|
|
2334
|
+
assertSafeRunId(resumeFromRunId, "resumeFromRunId");
|
|
2335
|
+
if (!persistence?.loadRun) {
|
|
2336
|
+
throw new Error("resumeFromRunId requires `persistence.loadRun` to be implemented");
|
|
2337
|
+
}
|
|
2338
|
+
const snapshot = await persistence.loadRun(resumeFromRunId);
|
|
2339
|
+
if (!snapshot) throw new Error(`No persisted run found for runId "${resumeFromRunId}"`);
|
|
2340
|
+
assertSafeRunId(snapshot.runId, "snapshot.runId");
|
|
2341
|
+
if (snapshot.runId !== resumeFromRunId) {
|
|
2342
|
+
throw new Error(
|
|
2343
|
+
`Persistence returned runId "${snapshot.runId}" for resumeFromRunId "${resumeFromRunId}"; refusing to resume on mismatch`
|
|
2344
|
+
);
|
|
2345
|
+
}
|
|
2346
|
+
if (snapshot.status === "complete") {
|
|
2347
|
+
throw new Error(`Run "${resumeFromRunId}" is already complete; nothing to resume`);
|
|
2348
|
+
}
|
|
2349
|
+
if (!snapshot.plan || !Array.isArray(snapshot.remaining) || !Array.isArray(snapshot.trace)) {
|
|
2350
|
+
throw new Error(
|
|
2351
|
+
`Run "${resumeFromRunId}" has no usable checkpoint (status="${snapshot.status}"); cannot resume`
|
|
2352
|
+
);
|
|
2353
|
+
}
|
|
2354
|
+
if (snapshot.remaining.length === 0) {
|
|
2355
|
+
throw new Error(
|
|
2356
|
+
`Run "${resumeFromRunId}" has no steps left to run (status="${snapshot.status}"); nothing to resume`
|
|
2357
|
+
);
|
|
2358
|
+
}
|
|
2359
|
+
return snapshot;
|
|
2360
|
+
};
|
|
2361
|
+
|
|
2222
2362
|
// src/agent/planner.ts
|
|
2223
2363
|
init_context_window();
|
|
2224
2364
|
init_generate();
|
|
@@ -2332,8 +2472,9 @@ var asMessage = (err) => err instanceof Error ? err.message : String(err);
|
|
|
2332
2472
|
// src/agent/replanner.ts
|
|
2333
2473
|
init_generate();
|
|
2334
2474
|
init_util();
|
|
2335
|
-
var decideReplan = async (ctx, goal, done, remaining) => {
|
|
2475
|
+
var decideReplan = async (ctx, goal, done, remaining, newUpdates = 0) => {
|
|
2336
2476
|
const state = await ctx.state();
|
|
2477
|
+
const updates = ctx.userUpdates?.();
|
|
2337
2478
|
const active = ctx.activeSkills?.() ?? [];
|
|
2338
2479
|
const commonFor = (mode) => {
|
|
2339
2480
|
const parts = ctx.prompts.replanner({
|
|
@@ -2342,7 +2483,8 @@ var decideReplan = async (ctx, goal, done, remaining) => {
|
|
|
2342
2483
|
done,
|
|
2343
2484
|
remaining,
|
|
2344
2485
|
mode,
|
|
2345
|
-
activeSkills: active.length ? renderActiveSkills(active) : void 0
|
|
2486
|
+
activeSkills: active.length ? renderActiveSkills(active) : void 0,
|
|
2487
|
+
...updates?.length ? { updates, newUpdates } : {}
|
|
2346
2488
|
});
|
|
2347
2489
|
return {
|
|
2348
2490
|
...stageCall(ctx, "replanner", parts.system),
|
|
@@ -2391,7 +2533,8 @@ var synthesizeAnswer = async (ctx, goal, done, findings = []) => {
|
|
|
2391
2533
|
state,
|
|
2392
2534
|
done,
|
|
2393
2535
|
findings,
|
|
2394
|
-
activeSkills: active.length ? renderActiveSkills(active) : void 0
|
|
2536
|
+
activeSkills: active.length ? renderActiveSkills(active) : void 0,
|
|
2537
|
+
updates: ctx.userUpdates?.()
|
|
2395
2538
|
});
|
|
2396
2539
|
const result = stream(ctx.synthesizerModel, {
|
|
2397
2540
|
...stageCall(ctx, "synthesizer", parts.system),
|
|
@@ -2500,6 +2643,7 @@ var supportsPdf = (model) => {
|
|
|
2500
2643
|
};
|
|
2501
2644
|
|
|
2502
2645
|
// src/agent/runner.ts
|
|
2646
|
+
var newRunId = () => globalThis.crypto?.randomUUID?.() ?? `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
2503
2647
|
var errMessage = (err) => err instanceof Error ? err.message : String(err);
|
|
2504
2648
|
var filterTools = (all, available, excluded) => {
|
|
2505
2649
|
let entries = Object.entries(all);
|
|
@@ -2585,23 +2729,27 @@ var createAgent = async (config) => {
|
|
|
2585
2729
|
log.info(
|
|
2586
2730
|
`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}`
|
|
2587
2731
|
);
|
|
2588
|
-
const
|
|
2732
|
+
const runCore = async (goal, opts, track, port) => {
|
|
2733
|
+
const resumed = await resolveResume(config.persistence, opts.resumeFromRunId);
|
|
2589
2734
|
const emit = (event) => {
|
|
2590
2735
|
try {
|
|
2591
2736
|
opts.onEvent?.(event);
|
|
2592
2737
|
} catch {
|
|
2593
2738
|
}
|
|
2594
2739
|
};
|
|
2595
|
-
const text = goal.trim();
|
|
2596
|
-
const sessionId = opts.sessionId ?? cfg.sessionId;
|
|
2597
|
-
|
|
2740
|
+
const text = (resumed?.goal ?? goal).trim();
|
|
2741
|
+
const sessionId = resumed?.sessionId ?? opts.sessionId ?? cfg.sessionId;
|
|
2742
|
+
const runId = resumed?.runId ?? newRunId();
|
|
2743
|
+
const startedAt = resumed?.startedAt ?? Date.now();
|
|
2744
|
+
let usage = resumed ? { ...resumed.usage } : emptyUsage();
|
|
2598
2745
|
const result = {
|
|
2746
|
+
runId,
|
|
2599
2747
|
goal: text,
|
|
2600
2748
|
final: "",
|
|
2601
|
-
plan: { thought: "", steps: [] },
|
|
2602
|
-
trace: [],
|
|
2603
|
-
steps: 0,
|
|
2604
|
-
applied: 0,
|
|
2749
|
+
plan: resumed ? resumed.plan : { thought: "", steps: [] },
|
|
2750
|
+
trace: resumed ? [...resumed.trace] : [],
|
|
2751
|
+
steps: resumed ? resumed.trace.length : 0,
|
|
2752
|
+
applied: resumed?.applied ?? 0,
|
|
2605
2753
|
stopped: false,
|
|
2606
2754
|
usage,
|
|
2607
2755
|
skills: []
|
|
@@ -2621,16 +2769,22 @@ var createAgent = async (config) => {
|
|
|
2621
2769
|
} catch {
|
|
2622
2770
|
}
|
|
2623
2771
|
};
|
|
2624
|
-
const activeSkillNames =
|
|
2772
|
+
const activeSkillNames = new Set(
|
|
2773
|
+
(resumed?.skills ?? []).filter((n) => skillNames.has(n))
|
|
2774
|
+
);
|
|
2775
|
+
result.skills = [...activeSkillNames];
|
|
2625
2776
|
const activateSkill = (name, by) => {
|
|
2626
2777
|
if (activeSkillNames.has(name) || !skillNames.has(name)) return;
|
|
2627
2778
|
activeSkillNames.add(name);
|
|
2628
2779
|
result.skills = [...activeSkillNames];
|
|
2629
2780
|
emit({ type: "skill.activated", name, by });
|
|
2630
2781
|
};
|
|
2631
|
-
const discovered = [];
|
|
2782
|
+
const discovered = [...resumed?.discovered ?? []];
|
|
2783
|
+
const userUpdates = (resumed?.userUpdates ?? []).map(
|
|
2784
|
+
(u) => ({ ...u })
|
|
2785
|
+
);
|
|
2632
2786
|
let currentStep;
|
|
2633
|
-
const counter = createCallCounter(cfg.maxToolCalls);
|
|
2787
|
+
const counter = createCallCounter(cfg.maxToolCalls, resumed?.toolCalls);
|
|
2634
2788
|
const builtins = {};
|
|
2635
2789
|
if (skills.length) {
|
|
2636
2790
|
Object.assign(
|
|
@@ -2662,9 +2816,21 @@ var createAgent = async (config) => {
|
|
|
2662
2816
|
signal: opts.signal,
|
|
2663
2817
|
addUsage: (u) => bumpUsage(u, "subagent"),
|
|
2664
2818
|
countCall: counter.count,
|
|
2665
|
-
maxToolOutputChars: cfg.compaction.maxToolOutputChars
|
|
2819
|
+
maxToolOutputChars: cfg.compaction.maxToolOutputChars,
|
|
2820
|
+
control: port
|
|
2666
2821
|
}
|
|
2667
2822
|
);
|
|
2823
|
+
const deliver = (at) => {
|
|
2824
|
+
if (!port) return [];
|
|
2825
|
+
const taken = port.drain();
|
|
2826
|
+
for (const m of taken) {
|
|
2827
|
+
userUpdates.push({ text: m.text, reconciled: false });
|
|
2828
|
+
emit({ type: "message.delivered", id: m.id, text: m.text, at });
|
|
2829
|
+
log.info(`message from the user (delivered at ${at}):`, m.text);
|
|
2830
|
+
void remember({ role: "user", content: m.text });
|
|
2831
|
+
}
|
|
2832
|
+
return taken.map((m) => m.text);
|
|
2833
|
+
};
|
|
2668
2834
|
let budgetExceeded;
|
|
2669
2835
|
const breach = (extra) => {
|
|
2670
2836
|
const b = checkLimits(extra ? addUsage(usage, extra) : usage, cfg.limits);
|
|
@@ -2673,7 +2839,18 @@ var createAgent = async (config) => {
|
|
|
2673
2839
|
return { kind: "tool-calls", tokens: counter.calls, cap: cfg.maxToolCalls };
|
|
2674
2840
|
return void 0;
|
|
2675
2841
|
};
|
|
2676
|
-
emit({
|
|
2842
|
+
emit({
|
|
2843
|
+
type: "run.start",
|
|
2844
|
+
goal: text,
|
|
2845
|
+
runId,
|
|
2846
|
+
...resumed ? {
|
|
2847
|
+
resumed: {
|
|
2848
|
+
completedSteps: resumed.trace.length,
|
|
2849
|
+
remainingSteps: resumed.remaining.length
|
|
2850
|
+
}
|
|
2851
|
+
} : {}
|
|
2852
|
+
});
|
|
2853
|
+
port?.attach(emit);
|
|
2677
2854
|
const images = [...opts.images ?? [], ...opts.files ?? []];
|
|
2678
2855
|
const refused = images.map(attachmentKind).find((kind) => accepts[kind] === false);
|
|
2679
2856
|
if (refused) {
|
|
@@ -2688,7 +2865,7 @@ var createAgent = async (config) => {
|
|
|
2688
2865
|
return result;
|
|
2689
2866
|
}
|
|
2690
2867
|
let history = [];
|
|
2691
|
-
if (config.memory) {
|
|
2868
|
+
if (config.memory && !resumed) {
|
|
2692
2869
|
try {
|
|
2693
2870
|
history = await config.memory.load(sessionId);
|
|
2694
2871
|
} catch {
|
|
@@ -2746,13 +2923,16 @@ var createAgent = async (config) => {
|
|
|
2746
2923
|
setCurrentStep: (step) => {
|
|
2747
2924
|
currentStep = step;
|
|
2748
2925
|
},
|
|
2749
|
-
images: images.length ? images : void 0
|
|
2926
|
+
images: images.length ? images : void 0,
|
|
2927
|
+
userUpdates: () => userUpdates.map((u) => u.text),
|
|
2928
|
+
...port ? { takeRoundUpdates: () => deliver("round") } : {}
|
|
2750
2929
|
};
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2930
|
+
if (!resumed)
|
|
2931
|
+
await remember({
|
|
2932
|
+
role: "user",
|
|
2933
|
+
content: images.length ? `${text}
|
|
2754
2934
|
[attached: ${images.map((f, i) => f.name ?? `${attachmentKind(f)} ${i + 1}`).join(", ")}]` : text
|
|
2755
|
-
|
|
2935
|
+
});
|
|
2756
2936
|
log.info("run:", text, images.length ? `(+${images.length} image(s))` : "");
|
|
2757
2937
|
const stop = () => {
|
|
2758
2938
|
emit({ type: "stopped" });
|
|
@@ -2760,8 +2940,8 @@ var createAgent = async (config) => {
|
|
|
2760
2940
|
return result;
|
|
2761
2941
|
};
|
|
2762
2942
|
try {
|
|
2763
|
-
let planned = await createPlan(ctx, text);
|
|
2764
|
-
bumpUsage(planned.usage, "plan");
|
|
2943
|
+
let planned = resumed ? { plan: resumed.plan, usage: emptyUsage(), skills: [] } : await createPlan(ctx, text);
|
|
2944
|
+
if (!resumed) bumpUsage(planned.usage, "plan");
|
|
2765
2945
|
if (isAborted()) return stop();
|
|
2766
2946
|
if (planned.plan.steps.length === 0 && text.split(/\s+/).length > 2) {
|
|
2767
2947
|
log.warn(
|
|
@@ -2790,14 +2970,65 @@ var createAgent = async (config) => {
|
|
|
2790
2970
|
`plan (${planned.plan.steps.length} steps):`,
|
|
2791
2971
|
planned.plan.steps.map((s) => s.description)
|
|
2792
2972
|
);
|
|
2793
|
-
|
|
2794
|
-
|
|
2973
|
+
const announced = resumed ? {
|
|
2974
|
+
thought: planned.plan.thought,
|
|
2975
|
+
steps: [...resumed.trace.map((r) => r.step), ...resumed.remaining]
|
|
2976
|
+
} : planned.plan;
|
|
2977
|
+
emit({ type: "plan.created", plan: announced });
|
|
2978
|
+
announced.steps.forEach((step, index) => emit({ type: "plan.step-added", step, index }));
|
|
2795
2979
|
for (const name of planned.skills) activateSkill(name, "plan");
|
|
2796
|
-
let done = [];
|
|
2797
|
-
const findings = [];
|
|
2798
|
-
let remaining = [...planned.plan.steps];
|
|
2799
|
-
let iter = 0;
|
|
2800
|
-
let revisions = 0;
|
|
2980
|
+
let done = resumed ? [...resumed.done] : [];
|
|
2981
|
+
const findings = resumed ? [...resumed.findings] : [];
|
|
2982
|
+
let remaining = resumed ? [...resumed.remaining] : [...planned.plan.steps];
|
|
2983
|
+
let iter = resumed?.iterations ?? 0;
|
|
2984
|
+
let revisions = resumed?.revisions ?? 0;
|
|
2985
|
+
const buildSnapshot = (status, extra = {}) => ({
|
|
2986
|
+
runId,
|
|
2987
|
+
startedAt,
|
|
2988
|
+
status,
|
|
2989
|
+
goal: text,
|
|
2990
|
+
sessionId,
|
|
2991
|
+
plan: planned.plan,
|
|
2992
|
+
// Copies: a store that keeps the object must not watch the loop mutate it.
|
|
2993
|
+
remaining: [...remaining],
|
|
2994
|
+
trace: [...result.trace],
|
|
2995
|
+
done: [...done],
|
|
2996
|
+
findings: [...findings],
|
|
2997
|
+
usage: { ...usage },
|
|
2998
|
+
iterations: iter,
|
|
2999
|
+
revisions,
|
|
3000
|
+
toolCalls: counter.calls,
|
|
3001
|
+
applied: result.applied,
|
|
3002
|
+
skills: [...activeSkillNames],
|
|
3003
|
+
discovered: [...discovered],
|
|
3004
|
+
attachments: images.length,
|
|
3005
|
+
...userUpdates.length ? { userUpdates: userUpdates.map((u) => ({ ...u })) } : {},
|
|
3006
|
+
...extra
|
|
3007
|
+
});
|
|
3008
|
+
const persist = async (hook, snapshot) => {
|
|
3009
|
+
const fn = config.persistence?.[hook];
|
|
3010
|
+
if (!fn) return;
|
|
3011
|
+
try {
|
|
3012
|
+
await fn.call(config.persistence, snapshot);
|
|
3013
|
+
} catch (err) {
|
|
3014
|
+
log.warn(`persistence.${hook} threw \u2014 the run carries on`, err);
|
|
3015
|
+
}
|
|
3016
|
+
};
|
|
3017
|
+
if (config.persistence) {
|
|
3018
|
+
track.complete = async (res) => {
|
|
3019
|
+
const error = track.error;
|
|
3020
|
+
const status = error ? "failed" : res?.stopped ? "cancelled" : "complete";
|
|
3021
|
+
await persist(
|
|
3022
|
+
"onRunComplete",
|
|
3023
|
+
buildSnapshot(status, {
|
|
3024
|
+
...res ? { text: res.final } : {},
|
|
3025
|
+
...error ? { error } : {},
|
|
3026
|
+
completedAt: Date.now()
|
|
3027
|
+
})
|
|
3028
|
+
);
|
|
3029
|
+
};
|
|
3030
|
+
if (!resumed) await persist("onRunStart", buildSnapshot("executing"));
|
|
3031
|
+
}
|
|
2801
3032
|
while (remaining.length > 0 && iter < cfg.maxIterations) {
|
|
2802
3033
|
if (isAborted()) return stop();
|
|
2803
3034
|
const hit = breach();
|
|
@@ -2871,7 +3102,10 @@ var createAgent = async (config) => {
|
|
|
2871
3102
|
}
|
|
2872
3103
|
}
|
|
2873
3104
|
}
|
|
2874
|
-
|
|
3105
|
+
deliver("step");
|
|
3106
|
+
const fresh = userUpdates.filter((u) => !u.reconciled).length;
|
|
3107
|
+
const byUser = fresh > 0 && iter < cfg.maxIterations && !isAborted() && !breach();
|
|
3108
|
+
const wantReplan = byUser || cfg.replan && iter < cfg.maxIterations && revisions < cfg.maxRevisions && !isAborted() && !breach() && await replanWanted(cfg.replanAfter, stepResult, {
|
|
2875
3109
|
signal: ctx.signal,
|
|
2876
3110
|
timeoutMs: cfg.chatTimeoutMs,
|
|
2877
3111
|
onError: (err) => log.warn("replanAfter predicate threw \u2014 using the failure rule", err)
|
|
@@ -2881,13 +3115,20 @@ var createAgent = async (config) => {
|
|
|
2881
3115
|
ctx,
|
|
2882
3116
|
text,
|
|
2883
3117
|
done,
|
|
2884
|
-
remaining.map((s) => s.description)
|
|
3118
|
+
remaining.map((s) => s.description),
|
|
3119
|
+
fresh
|
|
2885
3120
|
);
|
|
2886
3121
|
bumpUsage(decision.usage, "replan");
|
|
2887
|
-
emit({
|
|
3122
|
+
emit({
|
|
3123
|
+
type: "replan.decision",
|
|
3124
|
+
mode: decision.decision,
|
|
3125
|
+
reason: decision.reason,
|
|
3126
|
+
...byUser ? { byUser: true } : {}
|
|
3127
|
+
});
|
|
3128
|
+
for (const u of userUpdates) u.reconciled = true;
|
|
2888
3129
|
if (decision.decision === "finish") break;
|
|
2889
3130
|
if (decision.decision === "revise" && decision.plan.length > 0) {
|
|
2890
|
-
revisions += 1;
|
|
3131
|
+
if (!byUser) revisions += 1;
|
|
2891
3132
|
remaining = decision.plan.slice(0, Math.min(cfg.maxPlanSteps, cfg.maxIterations - iter)).map((description, i) => ({ id: `r${iter}-${i + 1}`, description }));
|
|
2892
3133
|
emit({
|
|
2893
3134
|
type: "plan.revised",
|
|
@@ -2896,6 +3137,7 @@ var createAgent = async (config) => {
|
|
|
2896
3137
|
});
|
|
2897
3138
|
}
|
|
2898
3139
|
}
|
|
3140
|
+
if (config.persistence) await persist("onStepComplete", buildSnapshot("executing"));
|
|
2899
3141
|
}
|
|
2900
3142
|
if (!budgetExceeded && remaining.length > 0) {
|
|
2901
3143
|
const hit = breach();
|
|
@@ -2909,6 +3151,7 @@ var createAgent = async (config) => {
|
|
|
2909
3151
|
const stepWords = result.trace.map((r) => r.summary.trim()).filter((t) => t && !/^(Executed \d+ tool call\(s\)\.|Step produced no output\.)$/.test(t));
|
|
2910
3152
|
let summary = stepWords.length ? stepWords.join("\n\n") : "Done \u2014 the changes have been applied.";
|
|
2911
3153
|
if (cfg.synthesize) {
|
|
3154
|
+
deliver("final");
|
|
2912
3155
|
try {
|
|
2913
3156
|
const synth = await synthesizeAnswer(ctx, text, done, findings);
|
|
2914
3157
|
bumpUsage(synth.usage, "synthesize");
|
|
@@ -2953,9 +3196,26 @@ var createAgent = async (config) => {
|
|
|
2953
3196
|
if (isAborted()) return stop();
|
|
2954
3197
|
emit({ type: "error", phase: "run", error: errMessage(err) });
|
|
2955
3198
|
result.final = errMessage(err);
|
|
3199
|
+
track.error = errMessage(err);
|
|
2956
3200
|
return result;
|
|
2957
3201
|
}
|
|
2958
3202
|
};
|
|
3203
|
+
const run = async (goal, opts = {}) => {
|
|
3204
|
+
const port = portOf(opts.control);
|
|
3205
|
+
const track = {};
|
|
3206
|
+
let result;
|
|
3207
|
+
try {
|
|
3208
|
+
result = await runCore(goal, opts, track, port);
|
|
3209
|
+
} catch (err) {
|
|
3210
|
+
port?.detach();
|
|
3211
|
+
track.error = err instanceof Error ? err.message : String(err);
|
|
3212
|
+
await track.complete?.(void 0);
|
|
3213
|
+
throw err;
|
|
3214
|
+
}
|
|
3215
|
+
if (port) result.undelivered = port.detach();
|
|
3216
|
+
await track.complete?.(result);
|
|
3217
|
+
return result;
|
|
3218
|
+
};
|
|
2959
3219
|
const compact = async (o = {}) => {
|
|
2960
3220
|
const empty = {
|
|
2961
3221
|
compacted: false,
|
|
@@ -3073,6 +3333,35 @@ var createSubagentTool = (opts) => {
|
|
|
3073
3333
|
if (opts.worker && !opts.workerConfig) {
|
|
3074
3334
|
throw new Error(`subagent "${opts.name}": a worker subagent needs \`workerConfig\``);
|
|
3075
3335
|
}
|
|
3336
|
+
const profiles = opts.profiles ?? {};
|
|
3337
|
+
const profileNames = Object.keys(profiles);
|
|
3338
|
+
for (const [pname, p] of Object.entries(profiles)) {
|
|
3339
|
+
if (!pname.trim()) throw new Error(`subagent "${opts.name}": a profile needs a non-empty name`);
|
|
3340
|
+
if (!p || typeof p.description !== "string" || !p.description.trim()) {
|
|
3341
|
+
throw new Error(
|
|
3342
|
+
`subagent "${opts.name}": profile "${pname}" needs a description \u2014 the parent model chooses by it`
|
|
3343
|
+
);
|
|
3344
|
+
}
|
|
3345
|
+
if (opts.worker && p.config) {
|
|
3346
|
+
throw new Error(
|
|
3347
|
+
`subagent "${opts.name}": profile "${pname}" sets \`config\`, which does not apply to a worker subagent \u2014 use \`workerConfig\``
|
|
3348
|
+
);
|
|
3349
|
+
}
|
|
3350
|
+
if (!opts.worker && p.workerConfig) {
|
|
3351
|
+
throw new Error(
|
|
3352
|
+
`subagent "${opts.name}": profile "${pname}" sets \`workerConfig\`, which does not apply to an in-process subagent \u2014 use \`config\``
|
|
3353
|
+
);
|
|
3354
|
+
}
|
|
3355
|
+
}
|
|
3356
|
+
const pickProfile = (name) => {
|
|
3357
|
+
if (!name) return void 0;
|
|
3358
|
+
if (!Object.hasOwn(profiles, name)) {
|
|
3359
|
+
throw new Error(
|
|
3360
|
+
`subagent "${opts.name}": unknown profile "${name}" \u2014 choose one of: ${profileNames.join(", ")}`
|
|
3361
|
+
);
|
|
3362
|
+
}
|
|
3363
|
+
return profiles[name];
|
|
3364
|
+
};
|
|
3076
3365
|
const acquire = createSemaphore(Math.max(1, opts.maxConcurrent ?? 4));
|
|
3077
3366
|
const outputMax = opts.outputMaxChars ?? 8e3;
|
|
3078
3367
|
const gatedHostTools = (approve) => Object.fromEntries(
|
|
@@ -3091,8 +3380,8 @@ var createSubagentTool = (opts) => {
|
|
|
3091
3380
|
];
|
|
3092
3381
|
})
|
|
3093
3382
|
);
|
|
3094
|
-
const runInProcess = async (task, signal, forward, hostTools) => {
|
|
3095
|
-
const config = opts.config;
|
|
3383
|
+
const runInProcess = async (task, signal, forward, hostTools, profile) => {
|
|
3384
|
+
const config = { ...opts.config, ...profile?.config };
|
|
3096
3385
|
const agent = await createAgent({ ...config, tools: { ...config.tools, ...hostTools } });
|
|
3097
3386
|
let runError;
|
|
3098
3387
|
const result = await agent.run(task, {
|
|
@@ -3114,8 +3403,8 @@ var createSubagentTool = (opts) => {
|
|
|
3114
3403
|
readOnly: isReadOnlyTool(t2)
|
|
3115
3404
|
}))
|
|
3116
3405
|
);
|
|
3117
|
-
const workerConfigFor = async () => {
|
|
3118
|
-
const cfg = opts.workerConfig;
|
|
3406
|
+
const workerConfigFor = async (profile) => {
|
|
3407
|
+
const cfg = { ...opts.workerConfig, ...profile?.workerConfig };
|
|
3119
3408
|
let model = { ...cfg.model };
|
|
3120
3409
|
if (model.credentialRef && !model.apiKey && opts.credentials) {
|
|
3121
3410
|
const apiKey = await opts.credentials.getApiKey(model.credentialRef);
|
|
@@ -3125,9 +3414,10 @@ var createSubagentTool = (opts) => {
|
|
|
3125
3414
|
}
|
|
3126
3415
|
return toCloneable({ ...cfg, model });
|
|
3127
3416
|
};
|
|
3128
|
-
const runInWorker = async (task, signal, forward, hostTools) => {
|
|
3417
|
+
const runInWorker = async (task, signal, forward, hostTools, profile) => {
|
|
3418
|
+
if (signal?.aborted) throw abortError();
|
|
3419
|
+
const [config, proxied] = await Promise.all([workerConfigFor(profile), proxiedSpecs()]);
|
|
3129
3420
|
if (signal?.aborted) throw abortError();
|
|
3130
|
-
const [config, proxied] = await Promise.all([workerConfigFor(), proxiedSpecs()]);
|
|
3131
3421
|
const worker = opts.worker();
|
|
3132
3422
|
return new Promise((resolve, reject) => {
|
|
3133
3423
|
let settled = false;
|
|
@@ -3183,20 +3473,32 @@ var createSubagentTool = (opts) => {
|
|
|
3183
3473
|
safePost(worker, { type: "run", task, config, proxied });
|
|
3184
3474
|
});
|
|
3185
3475
|
};
|
|
3476
|
+
const description = profileNames.length ? `${opts.description}
|
|
3477
|
+
|
|
3478
|
+
Optional \`profile\` (omit it for the default):
|
|
3479
|
+
${profileNames.map((n) => `- ${n}: ${profiles[n].description}`).join("\n")}` : opts.description;
|
|
3186
3480
|
const t = (0, import_ai8.tool)({
|
|
3187
|
-
description
|
|
3481
|
+
description,
|
|
3188
3482
|
inputSchema: (0, import_ai8.jsonSchema)({
|
|
3189
3483
|
type: "object",
|
|
3190
3484
|
properties: {
|
|
3191
3485
|
task: {
|
|
3192
3486
|
type: "string",
|
|
3193
3487
|
description: "A complete, self-contained task: the subagent sees nothing of your context except this text."
|
|
3194
|
-
}
|
|
3488
|
+
},
|
|
3489
|
+
...profileNames.length ? {
|
|
3490
|
+
profile: {
|
|
3491
|
+
type: "string",
|
|
3492
|
+
enum: profileNames,
|
|
3493
|
+
description: "One of this tool's profiles, described above. Omit it for the default."
|
|
3494
|
+
}
|
|
3495
|
+
} : {}
|
|
3195
3496
|
},
|
|
3196
3497
|
required: ["task"],
|
|
3197
3498
|
additionalProperties: false
|
|
3198
3499
|
}),
|
|
3199
|
-
execute: async ({ task }, options) => {
|
|
3500
|
+
execute: async ({ task, profile: profileName }, options) => {
|
|
3501
|
+
const profile = pickProfile(profileName);
|
|
3200
3502
|
const runCtx = toolRunContextOf(options);
|
|
3201
3503
|
const parentSignal = options?.abortSignal ?? runCtx?.signal;
|
|
3202
3504
|
const id = `${opts.name}-${seq2 += 1}`;
|
|
@@ -3207,20 +3509,46 @@ var createSubagentTool = (opts) => {
|
|
|
3207
3509
|
parentSignal?.addEventListener("abort", onParentAbort, { once: true });
|
|
3208
3510
|
if (parentSignal?.aborted) controller.abort();
|
|
3209
3511
|
let timedOut = false;
|
|
3512
|
+
let stoppedByUser = false;
|
|
3210
3513
|
const timer = opts.timeoutMs && opts.timeoutMs > 0 ? setTimeout(() => {
|
|
3211
3514
|
timedOut = true;
|
|
3212
3515
|
controller.abort();
|
|
3213
3516
|
}, opts.timeoutMs) : void 0;
|
|
3214
|
-
emit({
|
|
3517
|
+
emit({
|
|
3518
|
+
type: "subagent.start",
|
|
3519
|
+
id,
|
|
3520
|
+
name: opts.name,
|
|
3521
|
+
task,
|
|
3522
|
+
...profile ? { profile: profileName } : {}
|
|
3523
|
+
});
|
|
3524
|
+
const unregister = runCtx?.control?.registerSubagent(
|
|
3525
|
+
{
|
|
3526
|
+
id,
|
|
3527
|
+
name: opts.name,
|
|
3528
|
+
task,
|
|
3529
|
+
...profile ? { profile: profileName } : {},
|
|
3530
|
+
startedAt: Date.now()
|
|
3531
|
+
},
|
|
3532
|
+
() => {
|
|
3533
|
+
stoppedByUser = true;
|
|
3534
|
+
controller.abort();
|
|
3535
|
+
}
|
|
3536
|
+
);
|
|
3215
3537
|
try {
|
|
3216
3538
|
const forward = (event) => emit({ type: "subagent.event", id, name: opts.name, event });
|
|
3217
3539
|
const hostTools = gatedHostTools(runCtx?.approve);
|
|
3218
3540
|
const run = opts.worker ? runInWorker : runInProcess;
|
|
3219
|
-
const out = await run(task, controller.signal, forward, hostTools).catch(
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3541
|
+
const out = await run(task, controller.signal, forward, hostTools, profile).catch(
|
|
3542
|
+
(err) => {
|
|
3543
|
+
if (stoppedByUser)
|
|
3544
|
+
throw new Error(
|
|
3545
|
+
`subagent "${opts.name}" was stopped by the user before it finished \u2014 carry on without its result, or take another approach`
|
|
3546
|
+
);
|
|
3547
|
+
if (timedOut)
|
|
3548
|
+
throw new Error(`subagent "${opts.name}" timed out after ${opts.timeoutMs} ms`);
|
|
3549
|
+
throw err;
|
|
3550
|
+
}
|
|
3551
|
+
);
|
|
3224
3552
|
runCtx?.addUsage(out.usage);
|
|
3225
3553
|
emit({ type: "subagent.complete", id, name: opts.name, text: out.text, usage: out.usage });
|
|
3226
3554
|
return clip(out.text, outputMax);
|
|
@@ -3229,17 +3557,19 @@ var createSubagentTool = (opts) => {
|
|
|
3229
3557
|
type: "subagent.error",
|
|
3230
3558
|
id,
|
|
3231
3559
|
name: opts.name,
|
|
3232
|
-
error: err instanceof Error ? err.message : String(err)
|
|
3560
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3561
|
+
...stoppedByUser ? { stopped: true } : {}
|
|
3233
3562
|
});
|
|
3234
3563
|
throw err;
|
|
3235
3564
|
} finally {
|
|
3565
|
+
unregister?.();
|
|
3236
3566
|
if (timer !== void 0) clearTimeout(timer);
|
|
3237
3567
|
parentSignal?.removeEventListener("abort", onParentAbort);
|
|
3238
3568
|
release();
|
|
3239
3569
|
}
|
|
3240
3570
|
}
|
|
3241
3571
|
});
|
|
3242
|
-
t.promptHint = "{ task: string }";
|
|
3572
|
+
t.promptHint = profileNames.length ? `{ task: string, profile?: ${profileNames.map((n) => JSON.stringify(n)).join(" | ")} }` : "{ task: string }";
|
|
3243
3573
|
if (opts.readOnly) t.readOnly = true;
|
|
3244
3574
|
return t;
|
|
3245
3575
|
};
|
|
@@ -3253,7 +3583,8 @@ var KEYS_STORE = "keys";
|
|
|
3253
3583
|
var SECRETS_STORE = "secrets";
|
|
3254
3584
|
var SESSIONS_STORE = "sessions";
|
|
3255
3585
|
var FILES_STORE = "files";
|
|
3256
|
-
var
|
|
3586
|
+
var RUNS_STORE = "runs";
|
|
3587
|
+
var DB_VERSION = 3;
|
|
3257
3588
|
var cache = /* @__PURE__ */ new Map();
|
|
3258
3589
|
var openAgentWebDB = (opts = {}) => {
|
|
3259
3590
|
const name = opts.dbName ?? "agent-web";
|
|
@@ -3265,6 +3596,7 @@ var openAgentWebDB = (opts = {}) => {
|
|
|
3265
3596
|
if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE);
|
|
3266
3597
|
if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE);
|
|
3267
3598
|
if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE);
|
|
3599
|
+
if (!db.objectStoreNames.contains(RUNS_STORE)) db.createObjectStore(RUNS_STORE);
|
|
3268
3600
|
}
|
|
3269
3601
|
});
|
|
3270
3602
|
cache.set(name, p);
|
|
@@ -3785,6 +4117,102 @@ var IndexedDBStore = class {
|
|
|
3785
4117
|
}
|
|
3786
4118
|
};
|
|
3787
4119
|
|
|
4120
|
+
// src/memory/runs.ts
|
|
4121
|
+
var resumableOf = (all, sessionId) => all.filter(
|
|
4122
|
+
(s) => s.status !== "complete" && (sessionId === void 0 || s.sessionId === sessionId)
|
|
4123
|
+
).sort((a, b) => b.startedAt - a.startedAt);
|
|
4124
|
+
var MemoryRunStore = class {
|
|
4125
|
+
runs = /* @__PURE__ */ new Map();
|
|
4126
|
+
keepCompleted;
|
|
4127
|
+
constructor(opts = {}) {
|
|
4128
|
+
this.keepCompleted = opts.keepCompleted ?? false;
|
|
4129
|
+
}
|
|
4130
|
+
onRunStart(snapshot) {
|
|
4131
|
+
this.runs.set(snapshot.runId, snapshot);
|
|
4132
|
+
}
|
|
4133
|
+
onStepComplete(snapshot) {
|
|
4134
|
+
this.runs.set(snapshot.runId, snapshot);
|
|
4135
|
+
}
|
|
4136
|
+
onRunComplete(snapshot) {
|
|
4137
|
+
if (snapshot.status === "complete" && !this.keepCompleted) this.runs.delete(snapshot.runId);
|
|
4138
|
+
else this.runs.set(snapshot.runId, snapshot);
|
|
4139
|
+
}
|
|
4140
|
+
loadRun(runId) {
|
|
4141
|
+
return this.runs.get(runId) ?? null;
|
|
4142
|
+
}
|
|
4143
|
+
/** Runs that can still be resumed (executing, stopped or failed), newest first. */
|
|
4144
|
+
resumable(sessionId) {
|
|
4145
|
+
return resumableOf([...this.runs.values()], sessionId);
|
|
4146
|
+
}
|
|
4147
|
+
/** The most recent run that can be resumed — what to offer after a reload. */
|
|
4148
|
+
latestResumable(sessionId) {
|
|
4149
|
+
return this.resumable(sessionId)[0];
|
|
4150
|
+
}
|
|
4151
|
+
delete(runId) {
|
|
4152
|
+
this.runs.delete(runId);
|
|
4153
|
+
}
|
|
4154
|
+
clear() {
|
|
4155
|
+
this.runs.clear();
|
|
4156
|
+
}
|
|
4157
|
+
};
|
|
4158
|
+
var jsonSafe = (value) => JSON.parse(
|
|
4159
|
+
JSON.stringify(
|
|
4160
|
+
value,
|
|
4161
|
+
(_k, v) => v instanceof Error ? v.message : typeof v === "bigint" ? v.toString() : v
|
|
4162
|
+
)
|
|
4163
|
+
);
|
|
4164
|
+
var IndexedDBRunStore = class {
|
|
4165
|
+
dbName;
|
|
4166
|
+
keepCompleted;
|
|
4167
|
+
constructor(opts = {}) {
|
|
4168
|
+
this.dbName = opts.dbName;
|
|
4169
|
+
this.keepCompleted = opts.keepCompleted ?? false;
|
|
4170
|
+
}
|
|
4171
|
+
async put(snapshot) {
|
|
4172
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4173
|
+
try {
|
|
4174
|
+
await db.put(RUNS_STORE, snapshot, snapshot.runId);
|
|
4175
|
+
} catch (err) {
|
|
4176
|
+
if (err?.name !== "DataCloneError") throw err;
|
|
4177
|
+
await db.put(RUNS_STORE, jsonSafe(snapshot), snapshot.runId);
|
|
4178
|
+
}
|
|
4179
|
+
}
|
|
4180
|
+
onRunStart(snapshot) {
|
|
4181
|
+
return this.put(snapshot);
|
|
4182
|
+
}
|
|
4183
|
+
onStepComplete(snapshot) {
|
|
4184
|
+
return this.put(snapshot);
|
|
4185
|
+
}
|
|
4186
|
+
async onRunComplete(snapshot) {
|
|
4187
|
+
if (snapshot.status === "complete" && !this.keepCompleted) {
|
|
4188
|
+
await this.delete(snapshot.runId);
|
|
4189
|
+
return;
|
|
4190
|
+
}
|
|
4191
|
+
await this.put(snapshot);
|
|
4192
|
+
}
|
|
4193
|
+
async loadRun(runId) {
|
|
4194
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4195
|
+
return await db.get(RUNS_STORE, runId) ?? null;
|
|
4196
|
+
}
|
|
4197
|
+
/** Runs that can still be resumed (executing, stopped or failed), newest first. */
|
|
4198
|
+
async resumable(sessionId) {
|
|
4199
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4200
|
+
return resumableOf(await db.getAll(RUNS_STORE), sessionId);
|
|
4201
|
+
}
|
|
4202
|
+
/** The most recent run that can be resumed — what to offer after a reload. */
|
|
4203
|
+
async latestResumable(sessionId) {
|
|
4204
|
+
return (await this.resumable(sessionId))[0];
|
|
4205
|
+
}
|
|
4206
|
+
async delete(runId) {
|
|
4207
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4208
|
+
await db.delete(RUNS_STORE, runId);
|
|
4209
|
+
}
|
|
4210
|
+
async clear() {
|
|
4211
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
4212
|
+
await db.clear(RUNS_STORE);
|
|
4213
|
+
}
|
|
4214
|
+
};
|
|
4215
|
+
|
|
3788
4216
|
// src/index.ts
|
|
3789
4217
|
init_compress();
|
|
3790
4218
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -3794,13 +4222,16 @@ init_compress();
|
|
|
3794
4222
|
FILES_STORE,
|
|
3795
4223
|
FIND_TOOLS_NAME,
|
|
3796
4224
|
ImagesNotSupportedError,
|
|
4225
|
+
IndexedDBRunStore,
|
|
3797
4226
|
IndexedDBStore,
|
|
3798
4227
|
IndexedDBVault,
|
|
3799
4228
|
KEYS_STORE,
|
|
3800
4229
|
MemoryCredentialStore,
|
|
4230
|
+
MemoryRunStore,
|
|
3801
4231
|
MemoryStore,
|
|
3802
4232
|
PlanSchema,
|
|
3803
4233
|
PlanStepSchema,
|
|
4234
|
+
RUNS_STORE,
|
|
3804
4235
|
ReplanSchema,
|
|
3805
4236
|
SECRETS_STORE,
|
|
3806
4237
|
SESSIONS_STORE,
|
|
@@ -3826,6 +4257,7 @@ init_compress();
|
|
|
3826
4257
|
createFindToolsTool,
|
|
3827
4258
|
createLogger,
|
|
3828
4259
|
createPlan,
|
|
4260
|
+
createRunControl,
|
|
3829
4261
|
createSkillTools,
|
|
3830
4262
|
createSubagentTool,
|
|
3831
4263
|
createToolResultClearer,
|
|
@@ -3881,6 +4313,7 @@ init_compress();
|
|
|
3881
4313
|
resolveCompaction,
|
|
3882
4314
|
resolveConfig,
|
|
3883
4315
|
resolveModel,
|
|
4316
|
+
resolveResume,
|
|
3884
4317
|
resolveStage,
|
|
3885
4318
|
resolveThinking,
|
|
3886
4319
|
runToolLoop,
|