@geminixiang/mikan 1.0.0-beta.51 → 1.0.0-beta.52
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/CHANGELOG.md +12 -0
- package/dist/harness/subagent-profiles.d.ts.map +1 -1
- package/dist/harness/subagent-profiles.js +0 -19
- package/dist/harness/subagent-profiles.js.map +1 -1
- package/dist/harness/subagent-runner.d.ts.map +1 -1
- package/dist/harness/subagent-runner.js +2 -41
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/harness/types.d.ts +0 -3
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,11 +9,23 @@ any release.
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [1.0.0-beta.52]
|
|
13
|
+
|
|
14
|
+
### Removed
|
|
15
|
+
|
|
16
|
+
- Remove the subagent `requiredTools` / `required_tools` mechanism: the post-run "every listed tool was invoked" check was a proxy for evidence that never held and failed only after the budget was spent. Callers that want evidence can read `toolCallCounts`.
|
|
17
|
+
|
|
12
18
|
## [1.0.0-beta.51]
|
|
13
19
|
|
|
14
20
|
### Fixed
|
|
15
21
|
|
|
16
22
|
- Drop `requiredTools` from built-in subagent profiles; requiring both `read` and `bash` discarded finished answers from tasks that needed only one of them.
|
|
23
|
+
- Keep a caller's `requiredTools` when the request also names a profile.
|
|
24
|
+
- Stop dropping the retained assistant message when an overflow retry rebuilds context from the store.
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- Read mikan session metadata through Pi's `session.getValue` in `open`/`inspect`; compare `fstat` fields instead of hashing the file for pending-session materialization.
|
|
17
29
|
|
|
18
30
|
## [1.0.0-beta.50]
|
|
19
31
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-profiles.d.ts","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EACV,0BAA0B,EAI3B,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"subagent-profiles.d.ts","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EACV,0BAA0B,EAI3B,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AA8PxF;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,0BAA0B,CAiCrF"}
|
|
@@ -20,10 +20,6 @@
|
|
|
20
20
|
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
21
21
|
import { basename, join } from "node:path";
|
|
22
22
|
import { parseFrontmatter } from "./skills.js";
|
|
23
|
-
// Built-ins carry no requiredTools. The check is a per-task evidence demand
|
|
24
|
-
// ("prove you actually inspected X") that only the caller can judge; as a
|
|
25
|
-
// profile default it fails every task that legitimately needs a subset of the
|
|
26
|
-
// granted tools, discarding a finished answer after the budget is spent.
|
|
27
23
|
const BUILTIN_PROFILES = [
|
|
28
24
|
{
|
|
29
25
|
name: "worker",
|
|
@@ -36,7 +32,6 @@ const BUILTIN_PROFILES = [
|
|
|
36
32
|
"Keep verbose discovery and command output in this isolated run. Return the completed result, files or artifacts changed, verification performed, and any unresolved blocker.",
|
|
37
33
|
].join("\n"),
|
|
38
34
|
tools: ["read", "bash", "edit", "write"],
|
|
39
|
-
requiredTools: [],
|
|
40
35
|
thinkingLevel: "high",
|
|
41
36
|
maxTurns: 30,
|
|
42
37
|
maxTokens: 100_000,
|
|
@@ -52,7 +47,6 @@ const BUILTIN_PROFILES = [
|
|
|
52
47
|
"Keep source discovery, build logs, browser traces, and repetitive diagnostics in this isolated run. Return the implemented or diagnosed outcome, decisive technical evidence, changed artifact paths when applicable, verification results, and remaining engineering risk.",
|
|
53
48
|
].join("\n"),
|
|
54
49
|
tools: ["read", "bash", "edit", "write"],
|
|
55
|
-
requiredTools: [],
|
|
56
50
|
thinkingLevel: "high",
|
|
57
51
|
maxTurns: 35,
|
|
58
52
|
maxTokens: 100_000,
|
|
@@ -68,7 +62,6 @@ const BUILTIN_PROFILES = [
|
|
|
68
62
|
"Keep verbose CLI, API, and job logs in this isolated run. Return the resulting state, affected resources or job identifiers, verification performed, and concrete follow-up or rollback information.",
|
|
69
63
|
].join("\n"),
|
|
70
64
|
tools: ["read", "bash", "edit", "write", "event", "sandbox"],
|
|
71
|
-
requiredTools: [],
|
|
72
65
|
thinkingLevel: "high",
|
|
73
66
|
maxTurns: 40,
|
|
74
67
|
maxTokens: 100_000,
|
|
@@ -84,7 +77,6 @@ const BUILTIN_PROFILES = [
|
|
|
84
77
|
"Keep verbose rows and query output in this isolated run. Return the conclusion, key figures with units and scope, methodology and checks, and limitations that affect confidence.",
|
|
85
78
|
].join("\n"),
|
|
86
79
|
tools: ["read", "bash", "write"],
|
|
87
|
-
requiredTools: [],
|
|
88
80
|
thinkingLevel: "high",
|
|
89
81
|
maxTurns: 35,
|
|
90
82
|
maxTokens: 100_000,
|
|
@@ -100,7 +92,6 @@ const BUILTIN_PROFILES = [
|
|
|
100
92
|
"Keep verbose records and operational output in this isolated run. Return the customer-facing outcome, account or artifact identifiers, decisions and blockers, and the next owner and action where follow-through remains.",
|
|
101
93
|
].join("\n"),
|
|
102
94
|
tools: ["read", "bash", "write", "event"],
|
|
103
|
-
requiredTools: [],
|
|
104
95
|
thinkingLevel: "high",
|
|
105
96
|
maxTurns: 30,
|
|
106
97
|
maxTokens: 100_000,
|
|
@@ -116,7 +107,6 @@ const BUILTIN_PROFILES = [
|
|
|
116
107
|
"Keep raw pages, candidate lists, and repetitive validation output in this isolated run. Return qualified opportunities, supporting evidence, confidence and disqualifiers, and a concise recommended next action.",
|
|
117
108
|
].join("\n"),
|
|
118
109
|
tools: ["read", "bash", "write"],
|
|
119
|
-
requiredTools: [],
|
|
120
110
|
thinkingLevel: "high",
|
|
121
111
|
maxTurns: 30,
|
|
122
112
|
maxTokens: 100_000,
|
|
@@ -132,7 +122,6 @@ const BUILTIN_PROFILES = [
|
|
|
132
122
|
"Keep generation logs, intermediate assets, and provider polling in this isolated run. Return deliverable paths or external identifiers, a concise production summary, verification results, and unresolved creative, quality, or rights constraints.",
|
|
133
123
|
].join("\n"),
|
|
134
124
|
tools: ["read", "bash", "write"],
|
|
135
|
-
requiredTools: [],
|
|
136
125
|
thinkingLevel: "high",
|
|
137
126
|
maxTurns: 40,
|
|
138
127
|
maxTokens: 100_000,
|
|
@@ -148,7 +137,6 @@ const BUILTIN_PROFILES = [
|
|
|
148
137
|
"Keep browser traces, HAR data, report rows, and repetitive diagnostics in this isolated run. Return the operational conclusion, decisive delivery evidence, affected inventory, remediation or escalation owner, and uncertainty that could change the diagnosis.",
|
|
149
138
|
].join("\n"),
|
|
150
139
|
tools: ["read", "bash", "write"],
|
|
151
|
-
requiredTools: [],
|
|
152
140
|
thinkingLevel: "high",
|
|
153
141
|
maxTurns: 35,
|
|
154
142
|
maxTokens: 100_000,
|
|
@@ -162,7 +150,6 @@ const BUILTIN_PROFILES = [
|
|
|
162
150
|
"Do not claim to have inspected files, executed commands, accessed URLs, or verified external state. Clearly distinguish dependency-provided facts from your own analysis. If the supplied evidence is insufficient, state the limitation instead of inventing details.",
|
|
163
151
|
].join("\n"),
|
|
164
152
|
tools: [],
|
|
165
|
-
requiredTools: [],
|
|
166
153
|
thinkingLevel: "high",
|
|
167
154
|
maxTurns: 20,
|
|
168
155
|
maxTokens: 100_000,
|
|
@@ -231,7 +218,6 @@ function parseProfilePatch(filePath, base) {
|
|
|
231
218
|
const patch = {};
|
|
232
219
|
applyField(patch, values, "description", "description", (value) => value.trim());
|
|
233
220
|
applyField(patch, values, "tools", "tools", csv);
|
|
234
|
-
applyField(patch, values, "required_tools", "requiredTools", csv);
|
|
235
221
|
applyField(patch, values, "model", "model", parseModel);
|
|
236
222
|
applyField(patch, values, "thinking", "thinkingLevel", parseThinking);
|
|
237
223
|
applyField(patch, values, "max_turns", "maxTurns", (v) => parsePositiveInteger(v, "max_turns"));
|
|
@@ -252,12 +238,7 @@ function parseProfilePatch(filePath, base) {
|
|
|
252
238
|
description: patch.description || base?.description || name,
|
|
253
239
|
systemPrompt,
|
|
254
240
|
tools: patch.tools ?? base?.tools ?? [],
|
|
255
|
-
requiredTools: patch.requiredTools ?? base?.requiredTools ?? [],
|
|
256
241
|
};
|
|
257
|
-
const ungranted = merged.requiredTools.filter((tool) => !merged.tools.includes(tool));
|
|
258
|
-
if (ungranted.length > 0) {
|
|
259
|
-
throw new Error(`required_tools must be included in tools: ${ungranted.join(", ")}`);
|
|
260
|
-
}
|
|
261
242
|
return merged;
|
|
262
243
|
}
|
|
263
244
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-profiles.js","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAU3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,4EAA4E;AAC5E,0EAA0E;AAC1E,8EAA8E;AAC9E,yEAAyE;AACzE,MAAM,gBAAgB,GAAsB;IAC1C;QACE,IAAI,EAAE,QAAQ;QACd,WAAW,EAAE,4EAA4E;QACzF,YAAY,EAAE;YACZ,sFAAsF;YACtF,EAAE;YACF,maAAma;YACna,EAAE;YACF,8KAA8K;SAC/K,CAAC,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC;QACxC,aAAa,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C,MAAM,CAAC,KAAK,CAAC;gBAC/D,IAAI,EAAE,QAAQ;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Subagent profiles: the curated capability sets a subagent may be launched\n * with.\n *\n * Profiles exist because the two halves of a subagent definition have\n * different owners. What a profile *does* — its tools, required evidence,\n * prompt and budget — is portable, so it ships as a built-in below and is\n * versioned with the code. Which model runs it is per-installation, so it is\n * overridden by `<workspaceDir>/agents/<name>.md`.\n *\n * A workspace file therefore *patches* the built-in of the same name rather\n * than replacing it: overriding only `model:` must not force an operator to\n * restate the tools and prompt, because a restated copy silently drifts from\n * the built-in it was cloned from. A file whose name matches no built-in\n * defines a new profile and must supply `tools` itself.\n *\n * A malformed file is reported as a diagnostic and skipped, never thrown:\n * these are hand-edited, and one typo must not take the whole workspace down.\n */\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type {\n LoadSubagentProfilesResult,\n SubagentModelSpec,\n SubagentProfile,\n SubagentProfileDiagnostic,\n} from \"./types.js\";\n\nexport type { LoadSubagentProfilesResult, SubagentProfileDiagnostic } from \"./types.js\";\nimport { parseFrontmatter } from \"./skills.js\";\n\n// Built-ins carry no requiredTools. The check is a per-task evidence demand\n// (\"prove you actually inspected X\") that only the caller can judge; as a\n// profile default it fails every task that legitimately needs a subset of the\n// granted tools, discarding a finished answer after the budget is spent.\nconst BUILTIN_PROFILES: SubagentProfile[] = [\n {\n name: \"worker\",\n description: \"Completes a bounded general-purpose task without adding domain assumptions\",\n systemPrompt: [\n \"You are a general-purpose worker responsible for one clearly bounded delegated task.\",\n \"\",\n \"Use `read` and `bash` to inspect the actual workspace state, and use `edit` or `write` only when the assignment requires changes. Follow applicable skill instructions, preserve behavior outside the stated scope, and do not invent requirements or broaden the task. Verify concrete outputs before reporting success; if the assignment lacks information or a required capability, state the limitation instead of guessing.\",\n \"\",\n \"Keep verbose discovery and command output in this isolated run. Return the completed result, files or artifacts changed, verification performed, and any unresolved blocker.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 100_000,\n },\n {\n name: \"software-engineer\",\n description:\n \"Owns software investigation, implementation, integration, and technical verification\",\n systemPrompt: [\n \"You are the software engineer responsible for one delegated technical outcome.\",\n \"\",\n \"Apply the relevant engineering and vendor skill instructions. Use `bash` to inspect repositories, run development tools, diagnose browser or integration behavior, and make only changes explicitly included in the assignment. Trace failures to their technical cause, preserve existing contracts outside scope, and verify work with the narrowest meaningful checks. Do not treat plausible output as evidence of success.\",\n \"\",\n \"Keep source discovery, build logs, browser traces, and repetitive diagnostics in this isolated run. Return the implemented or diagnosed outcome, decisive technical evidence, changed artifact paths when applicable, verification results, and remaining engineering risk.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 100_000,\n },\n {\n name: \"devops-engineer\",\n description:\n \"Owns cloud access, environments, deployments, and production workflow reliability\",\n systemPrompt: [\n \"You are the DevOps engineer responsible for one delegated infrastructure or production-operations outcome.\",\n \"\",\n \"Apply the relevant setup, GCP, repository-access, service-status, and production workflow skill instructions. Use `bash` to inspect current state before acting. Respect the named project, environment, principal, and resource scope; protect credentials; prefer least privilege; and check idempotency before writes, retries, or provisioning. Do not broaden access or repeat a non-idempotent operation without explicit authorization and evidence that it is needed.\",\n \"\",\n \"Keep verbose CLI, API, and job logs in this isolated run. Return the resulting state, affected resources or job identifiers, verification performed, and concrete follow-up or rollback information.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\", \"event\", \"sandbox\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 40,\n maxTokens: 100_000,\n },\n {\n name: \"data-scientist\",\n description:\n \"Owns metric definition, data analysis, reconciliation, and defensible conclusions\",\n systemPrompt: [\n \"You are the data scientist responsible for answering one delegated quantitative question.\",\n \"\",\n \"Apply the relevant Metabase, GAM, accounting, billing, reporting, and parser skill instructions. Use `bash` to run the prescribed queries and analysis tools. Establish the time range, timezone, filters, dimensions, population, and metric definitions before interpreting results. Reconcile totals and cross-check consequential figures when practical. Separate source values, derived calculations, and inference; never fill missing data with guesses.\",\n \"\",\n \"Keep verbose rows and query output in this isolated run. Return the conclusion, key figures with units and scope, methodology and checks, and limitations that affect confidence.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 100_000,\n },\n {\n name: \"account-manager\",\n description:\n \"Owns existing-client onboarding, account coordination, and delivery follow-through\",\n systemPrompt: [\n \"You are the account manager responsible for one delegated existing-client outcome.\",\n \"\",\n \"Apply the relevant onboarding, publisher account, slot, workspace, meeting, and communication skill instructions. Use `bash` to inspect the current customer and account state before acting. Preserve supplied commercial and technical requirements, coordinate dependencies, avoid duplicate account changes, and clearly distinguish completed work from items awaiting another owner. Do not invent customer approval or make an external commitment beyond the assignment.\",\n \"\",\n \"Keep verbose records and operational output in this isolated run. Return the customer-facing outcome, account or artifact identifiers, decisions and blockers, and the next owner and action where follow-through remains.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\", \"event\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 100_000,\n },\n {\n name: \"business-development\",\n description:\n \"Owns prospect research, qualification, contact discovery, and outreach preparation\",\n systemPrompt: [\n \"You are the business development specialist responsible for one delegated growth opportunity.\",\n \"\",\n \"Apply the relevant prospecting, website sampling, contact-finding, email-validation, and client-approach skill instructions. Use `bash` to gather and verify public evidence. Evaluate fit against the supplied criteria, distinguish verified contacts from inferred ones, and preserve source URLs. Do not contact prospects, submit forms, or represent that outreach occurred unless the assignment explicitly authorizes it.\",\n \"\",\n \"Keep raw pages, candidate lists, and repetitive validation output in this isolated run. Return qualified opportunities, supporting evidence, confidence and disqualifiers, and a concise recommended next action.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 100_000,\n },\n {\n name: \"creative-producer\",\n description: \"Owns media deliverables from creative brief through verified production output\",\n systemPrompt: [\n \"You are the creative producer responsible for one delegated media deliverable.\",\n \"\",\n \"Apply the relevant source acquisition, storyboard, video, image, speech, lipsync, and generation-provider skill instructions. Use `bash` to run the prescribed production tools. Confirm the brief, audience, format, dimensions, duration, language, and source inputs; use discovery commands rather than guessing provider or model identifiers. Preserve provenance and generation parameters, and verify that claimed outputs exist and match the requested technical properties.\",\n \"\",\n \"Keep generation logs, intermediate assets, and provider polling in this isolated run. Return deliverable paths or external identifiers, a concise production summary, verification results, and unresolved creative, quality, or rights constraints.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 40,\n maxTokens: 100_000,\n },\n {\n name: \"ad-operations-specialist\",\n description:\n \"Owns ad serving setup, delivery diagnostics, policy checks, and operational health\",\n systemPrompt: [\n \"You are the ad operations specialist responsible for one delegated advertising-delivery outcome.\",\n \"\",\n \"Apply the relevant GAM, ads.txt, player detection, targeting, behavior, monitoring, and policy skill instructions. Use `bash` to run the prescribed browser and reporting tools. Establish the site, account, slot, time window, geography, device, and consent conditions; distinguish configuration, eligibility, request, impression, and playback evidence. Reproduce dynamic behavior when practical, and do not change live serving configuration unless explicitly authorized.\",\n \"\",\n \"Keep browser traces, HAR data, report rows, and repetitive diagnostics in this isolated run. Return the operational conclusion, decisive delivery evidence, affected inventory, remediation or escalation owner, and uncertainty that could change the diagnosis.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 100_000,\n },\n {\n name: \"analysis-only\",\n description: \"Analyzes supplied task input without claiming external verification\",\n systemPrompt: [\n \"You analyze only the task text and structured dependency input supplied to this run.\",\n \"\",\n \"Do not claim to have inspected files, executed commands, accessed URLs, or verified external state. Clearly distinguish dependency-provided facts from your own analysis. If the supplied evidence is insufficient, state the limitation instead of inventing details.\",\n ].join(\"\\n\"),\n tools: [],\n requiredTools: [],\n thinkingLevel: \"high\",\n maxTurns: 20,\n maxTokens: 100_000,\n },\n];\n\nconst THINKING_LEVELS = new Set<ThinkingLevel>([\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n]);\n\n/** Parse a comma-separated tool list. The literal `none` is an empty grant. */\nfunction csv(value: string): string[] {\n if (value.trim() === \"none\") return [];\n return [\n ...new Set(\n value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ),\n ];\n}\n\nfunction parseModel(value: string): SubagentModelSpec {\n const separator = value.indexOf(\"/\");\n if (separator <= 0 || separator === value.length - 1) {\n throw new Error(`model must be provider/id, got ${value}`);\n }\n return { provider: value.slice(0, separator), id: value.slice(separator + 1) };\n}\n\nfunction parseThinking(value: string): ThinkingLevel {\n if (!THINKING_LEVELS.has(value as ThinkingLevel)) {\n throw new Error(`unknown thinking level: ${value}`);\n }\n return value as ThinkingLevel;\n}\n\nfunction parsePositiveInteger(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${field} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeNumber(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new Error(`${field} must be a non-negative number`);\n }\n return parsed;\n}\n\n/** Apply `field` from frontmatter onto `patch` only when the file sets it. */\nfunction applyField<K extends keyof SubagentProfile>(\n patch: Partial<SubagentProfile>,\n values: Record<string, string>,\n key: string,\n field: K,\n parse: (value: string) => SubagentProfile[K],\n): void {\n const raw = values[key];\n if (raw === undefined) return;\n patch[field] = parse(raw);\n}\n\n/**\n * Build the overlay a single file contributes. Throws with a human-readable\n * message on malformed input; the caller turns that into a diagnostic.\n */\nfunction parseProfilePatch(filePath: string, base: SubagentProfile | undefined): SubagentProfile {\n const { values, body } = parseFrontmatter(readFileSync(filePath, \"utf-8\"));\n const name = basename(filePath, \".md\");\n const patch: Partial<SubagentProfile> = {};\n\n applyField(patch, values, \"description\", \"description\", (value) => value.trim());\n applyField(patch, values, \"tools\", \"tools\", csv);\n applyField(patch, values, \"required_tools\", \"requiredTools\", csv);\n applyField(patch, values, \"model\", \"model\", parseModel);\n applyField(patch, values, \"thinking\", \"thinkingLevel\", parseThinking);\n applyField(patch, values, \"max_turns\", \"maxTurns\", (v) => parsePositiveInteger(v, \"max_turns\"));\n applyField(patch, values, \"max_tokens\", \"maxTokens\", (v) =>\n parsePositiveInteger(v, \"max_tokens\"),\n );\n applyField(patch, values, \"max_cost_usd\", \"maxCostUsd\", (v) =>\n parseNonNegativeNumber(v, \"max_cost_usd\"),\n );\n applyField(patch, values, \"max_duration_ms\", \"maxDurationMs\", (v) =>\n parsePositiveInteger(v, \"max_duration_ms\"),\n );\n\n const systemPrompt = body.trim() || base?.systemPrompt;\n if (!base && patch.tools === undefined) {\n throw new Error(`tools is required for a new profile (no built-in named ${name})`);\n }\n if (!systemPrompt) {\n throw new Error(`a new profile needs prompt text in the file body`);\n }\n\n const merged: SubagentProfile = {\n ...base,\n ...patch,\n name,\n description: patch.description || base?.description || name,\n systemPrompt,\n tools: patch.tools ?? base?.tools ?? [],\n requiredTools: patch.requiredTools ?? base?.requiredTools ?? [],\n };\n\n const ungranted = merged.requiredTools.filter((tool) => !merged.tools.includes(tool));\n if (ungranted.length > 0) {\n throw new Error(`required_tools must be included in tools: ${ungranted.join(\", \")}`);\n }\n return merged;\n}\n\n/**\n * Load the built-in profiles, then patch them with `<workspaceDir>/agents/*.md`.\n * Malformed files are reported and skipped, leaving the built-in in place.\n */\nexport function loadSubagentProfiles(workspaceDir: string): LoadSubagentProfilesResult {\n const dir = join(workspaceDir, \"agents\");\n const profiles = new Map(BUILTIN_PROFILES.map((profile) => [profile.name, profile]));\n const diagnostics: SubagentProfileDiagnostic[] = [];\n if (!existsSync(dir)) return { profiles, diagnostics };\n\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: dir,\n });\n return { profiles, diagnostics };\n }\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const filePath = join(dir, entry.name);\n try {\n const profile = parseProfilePatch(filePath, profiles.get(basename(entry.name, \".md\")));\n profiles.set(profile.name, profile);\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: filePath,\n });\n }\n }\n return { profiles, diagnostics };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subagent-profiles.js","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAU3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,gBAAgB,GAAsB;IAC1C;QACE,IAAI,EAAE,QAAQ;QACd,WAAW,EAAE,4EAA4E;QACzF,YAAY,EAAE;YACZ,sFAAsF;YACtF,EAAE;YACF,maAAma;YACna,EAAE;YACF,8KAA8K;SAC/K,CAAC,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC;QACxC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAA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,SAAS;QAC7D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;YACvF,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,WAAW,CAAC,IAAI,CAAC;gBACf,IAAI,EAAE,SAAS;gBACf,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;gBAC/D,IAAI,EAAE,QAAQ;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Subagent profiles: the curated capability sets a subagent may be launched\n * with.\n *\n * Profiles exist because the two halves of a subagent definition have\n * different owners. What a profile *does* — its tools, required evidence,\n * prompt and budget — is portable, so it ships as a built-in below and is\n * versioned with the code. Which model runs it is per-installation, so it is\n * overridden by `<workspaceDir>/agents/<name>.md`.\n *\n * A workspace file therefore *patches* the built-in of the same name rather\n * than replacing it: overriding only `model:` must not force an operator to\n * restate the tools and prompt, because a restated copy silently drifts from\n * the built-in it was cloned from. A file whose name matches no built-in\n * defines a new profile and must supply `tools` itself.\n *\n * A malformed file is reported as a diagnostic and skipped, never thrown:\n * these are hand-edited, and one typo must not take the whole workspace down.\n */\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type {\n LoadSubagentProfilesResult,\n SubagentModelSpec,\n SubagentProfile,\n SubagentProfileDiagnostic,\n} from \"./types.js\";\n\nexport type { LoadSubagentProfilesResult, SubagentProfileDiagnostic } from \"./types.js\";\nimport { parseFrontmatter } from \"./skills.js\";\n\nconst BUILTIN_PROFILES: SubagentProfile[] = [\n {\n name: \"worker\",\n description: \"Completes a bounded general-purpose task without adding domain assumptions\",\n systemPrompt: [\n \"You are a general-purpose worker responsible for one clearly bounded delegated task.\",\n \"\",\n \"Use `read` and `bash` to inspect the actual workspace state, and use `edit` or `write` only when the assignment requires changes. Follow applicable skill instructions, preserve behavior outside the stated scope, and do not invent requirements or broaden the task. Verify concrete outputs before reporting success; if the assignment lacks information or a required capability, state the limitation instead of guessing.\",\n \"\",\n \"Keep verbose discovery and command output in this isolated run. Return the completed result, files or artifacts changed, verification performed, and any unresolved blocker.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 100_000,\n },\n {\n name: \"software-engineer\",\n description:\n \"Owns software investigation, implementation, integration, and technical verification\",\n systemPrompt: [\n \"You are the software engineer responsible for one delegated technical outcome.\",\n \"\",\n \"Apply the relevant engineering and vendor skill instructions. Use `bash` to inspect repositories, run development tools, diagnose browser or integration behavior, and make only changes explicitly included in the assignment. Trace failures to their technical cause, preserve existing contracts outside scope, and verify work with the narrowest meaningful checks. Do not treat plausible output as evidence of success.\",\n \"\",\n \"Keep source discovery, build logs, browser traces, and repetitive diagnostics in this isolated run. Return the implemented or diagnosed outcome, decisive technical evidence, changed artifact paths when applicable, verification results, and remaining engineering risk.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 100_000,\n },\n {\n name: \"devops-engineer\",\n description:\n \"Owns cloud access, environments, deployments, and production workflow reliability\",\n systemPrompt: [\n \"You are the DevOps engineer responsible for one delegated infrastructure or production-operations outcome.\",\n \"\",\n \"Apply the relevant setup, GCP, repository-access, service-status, and production workflow skill instructions. Use `bash` to inspect current state before acting. Respect the named project, environment, principal, and resource scope; protect credentials; prefer least privilege; and check idempotency before writes, retries, or provisioning. Do not broaden access or repeat a non-idempotent operation without explicit authorization and evidence that it is needed.\",\n \"\",\n \"Keep verbose CLI, API, and job logs in this isolated run. Return the resulting state, affected resources or job identifiers, verification performed, and concrete follow-up or rollback information.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\", \"event\", \"sandbox\"],\n thinkingLevel: \"high\",\n maxTurns: 40,\n maxTokens: 100_000,\n },\n {\n name: \"data-scientist\",\n description:\n \"Owns metric definition, data analysis, reconciliation, and defensible conclusions\",\n systemPrompt: [\n \"You are the data scientist responsible for answering one delegated quantitative question.\",\n \"\",\n \"Apply the relevant Metabase, GAM, accounting, billing, reporting, and parser skill instructions. Use `bash` to run the prescribed queries and analysis tools. Establish the time range, timezone, filters, dimensions, population, and metric definitions before interpreting results. Reconcile totals and cross-check consequential figures when practical. Separate source values, derived calculations, and inference; never fill missing data with guesses.\",\n \"\",\n \"Keep verbose rows and query output in this isolated run. Return the conclusion, key figures with units and scope, methodology and checks, and limitations that affect confidence.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 100_000,\n },\n {\n name: \"account-manager\",\n description:\n \"Owns existing-client onboarding, account coordination, and delivery follow-through\",\n systemPrompt: [\n \"You are the account manager responsible for one delegated existing-client outcome.\",\n \"\",\n \"Apply the relevant onboarding, publisher account, slot, workspace, meeting, and communication skill instructions. Use `bash` to inspect the current customer and account state before acting. Preserve supplied commercial and technical requirements, coordinate dependencies, avoid duplicate account changes, and clearly distinguish completed work from items awaiting another owner. Do not invent customer approval or make an external commitment beyond the assignment.\",\n \"\",\n \"Keep verbose records and operational output in this isolated run. Return the customer-facing outcome, account or artifact identifiers, decisions and blockers, and the next owner and action where follow-through remains.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\", \"event\"],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 100_000,\n },\n {\n name: \"business-development\",\n description:\n \"Owns prospect research, qualification, contact discovery, and outreach preparation\",\n systemPrompt: [\n \"You are the business development specialist responsible for one delegated growth opportunity.\",\n \"\",\n \"Apply the relevant prospecting, website sampling, contact-finding, email-validation, and client-approach skill instructions. Use `bash` to gather and verify public evidence. Evaluate fit against the supplied criteria, distinguish verified contacts from inferred ones, and preserve source URLs. Do not contact prospects, submit forms, or represent that outreach occurred unless the assignment explicitly authorizes it.\",\n \"\",\n \"Keep raw pages, candidate lists, and repetitive validation output in this isolated run. Return qualified opportunities, supporting evidence, confidence and disqualifiers, and a concise recommended next action.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 100_000,\n },\n {\n name: \"creative-producer\",\n description: \"Owns media deliverables from creative brief through verified production output\",\n systemPrompt: [\n \"You are the creative producer responsible for one delegated media deliverable.\",\n \"\",\n \"Apply the relevant source acquisition, storyboard, video, image, speech, lipsync, and generation-provider skill instructions. Use `bash` to run the prescribed production tools. Confirm the brief, audience, format, dimensions, duration, language, and source inputs; use discovery commands rather than guessing provider or model identifiers. Preserve provenance and generation parameters, and verify that claimed outputs exist and match the requested technical properties.\",\n \"\",\n \"Keep generation logs, intermediate assets, and provider polling in this isolated run. Return deliverable paths or external identifiers, a concise production summary, verification results, and unresolved creative, quality, or rights constraints.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 40,\n maxTokens: 100_000,\n },\n {\n name: \"ad-operations-specialist\",\n description:\n \"Owns ad serving setup, delivery diagnostics, policy checks, and operational health\",\n systemPrompt: [\n \"You are the ad operations specialist responsible for one delegated advertising-delivery outcome.\",\n \"\",\n \"Apply the relevant GAM, ads.txt, player detection, targeting, behavior, monitoring, and policy skill instructions. Use `bash` to run the prescribed browser and reporting tools. Establish the site, account, slot, time window, geography, device, and consent conditions; distinguish configuration, eligibility, request, impression, and playback evidence. Reproduce dynamic behavior when practical, and do not change live serving configuration unless explicitly authorized.\",\n \"\",\n \"Keep browser traces, HAR data, report rows, and repetitive diagnostics in this isolated run. Return the operational conclusion, decisive delivery evidence, affected inventory, remediation or escalation owner, and uncertainty that could change the diagnosis.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 100_000,\n },\n {\n name: \"analysis-only\",\n description: \"Analyzes supplied task input without claiming external verification\",\n systemPrompt: [\n \"You analyze only the task text and structured dependency input supplied to this run.\",\n \"\",\n \"Do not claim to have inspected files, executed commands, accessed URLs, or verified external state. Clearly distinguish dependency-provided facts from your own analysis. If the supplied evidence is insufficient, state the limitation instead of inventing details.\",\n ].join(\"\\n\"),\n tools: [],\n thinkingLevel: \"high\",\n maxTurns: 20,\n maxTokens: 100_000,\n },\n];\n\nconst THINKING_LEVELS = new Set<ThinkingLevel>([\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n]);\n\n/** Parse a comma-separated tool list. The literal `none` is an empty grant. */\nfunction csv(value: string): string[] {\n if (value.trim() === \"none\") return [];\n return [\n ...new Set(\n value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ),\n ];\n}\n\nfunction parseModel(value: string): SubagentModelSpec {\n const separator = value.indexOf(\"/\");\n if (separator <= 0 || separator === value.length - 1) {\n throw new Error(`model must be provider/id, got ${value}`);\n }\n return { provider: value.slice(0, separator), id: value.slice(separator + 1) };\n}\n\nfunction parseThinking(value: string): ThinkingLevel {\n if (!THINKING_LEVELS.has(value as ThinkingLevel)) {\n throw new Error(`unknown thinking level: ${value}`);\n }\n return value as ThinkingLevel;\n}\n\nfunction parsePositiveInteger(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${field} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeNumber(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new Error(`${field} must be a non-negative number`);\n }\n return parsed;\n}\n\n/** Apply `field` from frontmatter onto `patch` only when the file sets it. */\nfunction applyField<K extends keyof SubagentProfile>(\n patch: Partial<SubagentProfile>,\n values: Record<string, string>,\n key: string,\n field: K,\n parse: (value: string) => SubagentProfile[K],\n): void {\n const raw = values[key];\n if (raw === undefined) return;\n patch[field] = parse(raw);\n}\n\n/**\n * Build the overlay a single file contributes. Throws with a human-readable\n * message on malformed input; the caller turns that into a diagnostic.\n */\nfunction parseProfilePatch(filePath: string, base: SubagentProfile | undefined): SubagentProfile {\n const { values, body } = parseFrontmatter(readFileSync(filePath, \"utf-8\"));\n const name = basename(filePath, \".md\");\n const patch: Partial<SubagentProfile> = {};\n\n applyField(patch, values, \"description\", \"description\", (value) => value.trim());\n applyField(patch, values, \"tools\", \"tools\", csv);\n applyField(patch, values, \"model\", \"model\", parseModel);\n applyField(patch, values, \"thinking\", \"thinkingLevel\", parseThinking);\n applyField(patch, values, \"max_turns\", \"maxTurns\", (v) => parsePositiveInteger(v, \"max_turns\"));\n applyField(patch, values, \"max_tokens\", \"maxTokens\", (v) =>\n parsePositiveInteger(v, \"max_tokens\"),\n );\n applyField(patch, values, \"max_cost_usd\", \"maxCostUsd\", (v) =>\n parseNonNegativeNumber(v, \"max_cost_usd\"),\n );\n applyField(patch, values, \"max_duration_ms\", \"maxDurationMs\", (v) =>\n parsePositiveInteger(v, \"max_duration_ms\"),\n );\n\n const systemPrompt = body.trim() || base?.systemPrompt;\n if (!base && patch.tools === undefined) {\n throw new Error(`tools is required for a new profile (no built-in named ${name})`);\n }\n if (!systemPrompt) {\n throw new Error(`a new profile needs prompt text in the file body`);\n }\n\n const merged: SubagentProfile = {\n ...base,\n ...patch,\n name,\n description: patch.description || base?.description || name,\n systemPrompt,\n tools: patch.tools ?? base?.tools ?? [],\n };\n return merged;\n}\n\n/**\n * Load the built-in profiles, then patch them with `<workspaceDir>/agents/*.md`.\n * Malformed files are reported and skipped, leaving the built-in in place.\n */\nexport function loadSubagentProfiles(workspaceDir: string): LoadSubagentProfilesResult {\n const dir = join(workspaceDir, \"agents\");\n const profiles = new Map(BUILTIN_PROFILES.map((profile) => [profile.name, profile]));\n const diagnostics: SubagentProfileDiagnostic[] = [];\n if (!existsSync(dir)) return { profiles, diagnostics };\n\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: dir,\n });\n return { profiles, diagnostics };\n }\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const filePath = join(dir, entry.name);\n try {\n const profile = parseProfilePatch(filePath, profiles.get(basename(entry.name, \".md\")));\n profiles.set(profile.name, profile);\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: filePath,\n });\n }\n }\n return { profiles, diagnostics };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-runner.d.ts","sourceRoot":"","sources":["../../src/harness/subagent-runner.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAe,KAAK,GAAG,EAAyB,KAAK,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACjG,OAAO,EAAc,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG7D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGlD,OAAO,KAAK,EAEV,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EAEjB,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAEp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|
|
208
208
|
}
|
|
209
|
-
/**
|
|
210
|
-
* Wrap a tool so the run can prove it was actually reached. Fields are listed
|
|
211
|
-
* explicitly rather than spread: `AgentTool` is a plain interface, and a
|
|
212
|
-
* structural copy would silently drop anything added to it later.
|
|
213
|
-
*/
|
|
214
|
-
function witnessToolUse(tool, invoked) {
|
|
215
|
-
return {
|
|
216
|
-
name: tool.name,
|
|
217
|
-
label: tool.label,
|
|
218
|
-
description: tool.description,
|
|
219
|
-
parameters: tool.parameters,
|
|
220
|
-
...(tool.constrainedSampling !== undefined
|
|
221
|
-
? { constrainedSampling: tool.constrainedSampling }
|
|
222
|
-
: {}),
|
|
223
|
-
...(tool.prepareArguments ? { prepareArguments: tool.prepareArguments.bind(tool) } : {}),
|
|
224
|
-
...(tool.executionMode ? { executionMode: tool.executionMode } : {}),
|
|
225
|
-
execute: (...args) => {
|
|
226
|
-
invoked.add(tool.name);
|
|
227
|
-
return tool.execute(...args);
|
|
228
|
-
},
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
209
|
function formatTask(task, input, parentContext) {
|
|
232
210
|
const trimmed = task.trim();
|
|
233
211
|
if (!trimmed)
|
|
@@ -468,9 +446,6 @@ function resolveProfile(request, options) {
|
|
|
468
446
|
...request,
|
|
469
447
|
systemPrompt: profile.systemPrompt,
|
|
470
448
|
tools: profile.tools,
|
|
471
|
-
// The guard above allows requiredTools to combine with a profile, so the
|
|
472
|
-
// caller's evidence requirements must survive alongside the profile's.
|
|
473
|
-
requiredTools: [...new Set([...(request.requiredTools ?? []), ...profile.requiredTools])],
|
|
474
449
|
...(profile.model ? { model: profile.model } : {}),
|
|
475
450
|
...(profile.thinkingLevel ? { thinkingLevel: profile.thinkingLevel } : {}),
|
|
476
451
|
...(Object.keys(budget).length > 0 ? { budget } : {}),
|
|
@@ -480,18 +455,13 @@ function prepareSubagentRun(options, request, runId, startedAt) {
|
|
|
480
455
|
const model = request.model
|
|
481
456
|
? options.models.resolve(request.model.provider, request.model.id)
|
|
482
457
|
: options.defaultModel;
|
|
483
|
-
const invokedTools = new Set();
|
|
484
458
|
const granted = selectTools(request.tools, options.availableTools);
|
|
485
|
-
const missingRequiredTools = (request.requiredTools ?? []).filter((name) => !granted.some((tool) => tool.name === name));
|
|
486
|
-
if (missingRequiredTools.length > 0) {
|
|
487
|
-
throw new Error(`Required subagent tools were not granted: ${missingRequiredTools.join(", ")}`);
|
|
488
|
-
}
|
|
489
459
|
const task = formatTask(request.task, request.input, normalizedParentContext(request, options.parentMessages));
|
|
490
460
|
const session = new MikanAgentSession({
|
|
491
461
|
systemPrompt: buildSystemPrompt(request.systemPrompt, request.outputSchema, granted.map((tool) => tool.name)),
|
|
492
462
|
model,
|
|
493
463
|
thinkingLevel: request.thinkingLevel ?? options.thinkingLevel,
|
|
494
|
-
tools: granted
|
|
464
|
+
tools: granted,
|
|
495
465
|
models: options.models,
|
|
496
466
|
sessionStore: SessionStore.inMemory(options.workspaceDir),
|
|
497
467
|
settings: { compaction: { enabled: false } },
|
|
@@ -505,12 +475,11 @@ function prepareSubagentRun(options, request, runId, startedAt) {
|
|
|
505
475
|
modelSpec: { provider: model.provider, id: model.id },
|
|
506
476
|
session,
|
|
507
477
|
budget: resolveBudget(request.budget),
|
|
508
|
-
invokedTools,
|
|
509
478
|
task,
|
|
510
479
|
};
|
|
511
480
|
}
|
|
512
481
|
function buildSubagentResult(run, terminalSignal, cleanupPending = false) {
|
|
513
|
-
const { session, request,
|
|
482
|
+
const { session, request, budget } = run;
|
|
514
483
|
const stats = session.getLastRunStats();
|
|
515
484
|
const assistant = finalAssistant(session.messages);
|
|
516
485
|
const text = assistant ? contentText(assistant.content, "") : "";
|
|
@@ -531,14 +500,6 @@ function buildSubagentResult(run, terminalSignal, cleanupPending = false) {
|
|
|
531
500
|
if (stats.budgetExceededReason) {
|
|
532
501
|
return { ...base, status: "budget_exceeded", error: stats.budgetExceededReason };
|
|
533
502
|
}
|
|
534
|
-
const unusedRequiredTools = (request.requiredTools ?? []).filter((name) => !invokedTools.has(name));
|
|
535
|
-
if (unusedRequiredTools.length > 0) {
|
|
536
|
-
return {
|
|
537
|
-
...base,
|
|
538
|
-
status: "failed",
|
|
539
|
-
error: `Required tool not used: ${unusedRequiredTools.join(", ")}`,
|
|
540
|
-
};
|
|
541
|
-
}
|
|
542
503
|
if (assistant?.stopReason === "error") {
|
|
543
504
|
return { ...base, status: "failed", error: assistant.errorMessage || "Subagent failed" };
|
|
544
505
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-runner.js","sourceRoot":"","sources":["../../src/harness/subagent-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,WAAW,EAA+C,MAAM,uBAAuB,CAAC;AACjG,OAAO,EAAE,IAAI,EAAE,IAAI,EAAgB,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAChD,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AASlD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAyB,MAAM,qBAAqB,CAAC;AAE/E,MAAM,gBAAgB,GAAG,IAAI,iBAAiB,EAAU,CAAC;AACzD,MAAM,qBAAqB,GACzB,6FAA6F,CAAC;AAChG,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,QAAQ,EAAE,GAAG;IACb,UAAU,EAAE,EAAE;IACd,aAAa,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;CACrB,CAAC;AAEX,8EAA8E;AAC9E,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAE3C,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,EAAE,CAAC;QACb,OAAO;YACL,MAAM,EAAE,GAAG;gBACT,CAAC,CAAC,oBAAoB,CAAC,GAAG,EAAE,cAAc,EAAE,GAAG,CAAC;gBAChD,CAAC,CAAC;oBACE,GAAG,aAAa,CAAC,KAAK,EAAE,gBAAgB,EAAE,SAAS,CAAC;oBACpD,MAAM,EAAE,cAAc,IAAI,QAAQ;oBAClC,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;iBACxD;SACN,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,IAAI,OAAO;YAAE,YAAY,CAAC,OAAO,CAAC,CAAC;QACnC,OAAO,CAAC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;AACH,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentMessage, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { contentText, type Api, type AssistantMessage, type Model } from \"@earendil-works/pi-ai\";\nimport { Kind, Type, type TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport * as log from \"../log.js\";\nimport type { MikanModels } from \"./models.js\";\nimport type { SubagentProfile } from \"./types.js\";\nimport { MikanAgentSession } from \"./runner.js\";\nimport { SessionStore } from \"./session-store.js\";\nimport type {\n SubagentModelSpec,\n SubagentRunOutput,\n SubagentRunRequest,\n SubagentRunResult,\n SubagentUsage,\n SubagentUsageSink,\n} from \"./types.js\";\nimport { copyUsage, createEmptyUsage } from \"./usage.js\";\nimport { unboundedSlotPool, type SubagentSlotPool } from \"./subagent-slots.js\";\n\nconst subagentRunDepth = new AsyncLocalStorage<number>();\nconst DEFAULT_SYSTEM_PROMPT =\n \"You are a focused subagent. Complete only the assigned task and return the result directly.\";\nexport const DEFAULT_SUBAGENT_BUDGET = {\n maxTurns: 100,\n maxCostUsd: 10,\n maxDurationMs: 10 * 60 * 1000,\n} as const;\n\n/** Time allowed for an aborted subagent to settle before detached cleanup. */\nexport const SUBAGENT_ABORT_GRACE_MS = 100;\n\nconst SCHEMA_STRUCTURAL_KEYS = new Set([\n \"type\",\n \"properties\",\n \"required\",\n \"items\",\n \"enum\",\n \"const\",\n \"anyOf\",\n \"oneOf\",\n \"allOf\",\n]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaOptions(node: Record<string, unknown>): Record<string, unknown> {\n const options: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node)) {\n if (!SCHEMA_STRUCTURAL_KEYS.has(key)) options[key] = value;\n }\n if (isRecord(options.additionalProperties)) {\n options.additionalProperties = hydrateSchema(options.additionalProperties);\n }\n return options;\n}\n\n/**\n * outputSchema arrives over the subagent tool as plain JSON (tool-call\n * arguments never carry TypeBox's Kind symbol), but Value.Check dispatches\n * purely on schema[Kind] and throws ValueCheckUnknownTypeError for anything\n * without it. Hydrate plain JSON Schema into real TypeBox schema nodes so\n * validation runs instead of throwing; schemas built with TypeBox already\n * carry Kind and pass through untouched.\n *\n * Unsupported keywords ($ref, not, patternProperties, if/then/else) degrade to\n * a permissive Unknown — fail-open by design: outputSchema is advisory output\n * validation, not a security boundary.\n */\nfunction hydrateSchema(schema: unknown): TSchema {\n if (isRecord(schema) && Kind in schema) return schema as TSchema;\n if (!isRecord(schema)) return Type.Unknown();\n\n if (Array.isArray(schema.enum)) {\n const literals = schema.enum.filter(\n (value): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\",\n );\n return literals.length > 0\n ? Type.Union(literals.map((value) => Type.Literal(value)))\n : Type.Unknown();\n }\n if (\"const\" in schema) {\n const value = schema.const;\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n ? Type.Literal(value)\n : Type.Unknown();\n }\n if (Array.isArray(schema.anyOf)) return Type.Union(schema.anyOf.map(hydrateSchema));\n if (Array.isArray(schema.oneOf)) return Type.Union(schema.oneOf.map(hydrateSchema));\n if (Array.isArray(schema.allOf)) return Type.Intersect(schema.allOf.map(hydrateSchema));\n\n const type = Array.isArray(schema.type)\n ? schema.type\n : (schema.type ?? (schema.properties ? \"object\" : schema.items ? \"array\" : undefined));\n if (Array.isArray(type)) {\n return Type.Union(type.map((variant) => hydrateSchema({ ...schema, type: variant })));\n }\n\n const options = schemaOptions(schema);\n switch (type) {\n case \"object\": {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const required = new Set(Array.isArray(schema.required) ? schema.required : []);\n const props: Record<string, TSchema> = {};\n for (const [key, value] of Object.entries(properties)) {\n const hydrated = hydrateSchema(value);\n props[key] = required.has(key) ? hydrated : Type.Optional(hydrated);\n }\n return Type.Object(props, options);\n }\n case \"array\":\n return Type.Array(\n schema.items !== undefined ? hydrateSchema(schema.items) : Type.Unknown(),\n options,\n );\n case \"string\":\n return Type.String(options);\n case \"number\":\n return Type.Number(options);\n case \"integer\":\n return Type.Integer(options);\n case \"boolean\":\n return Type.Boolean(options);\n case \"null\":\n return Type.Null(options);\n default:\n return Type.Unknown(options);\n }\n}\n\ninterface RunSubagentOptions<TOutputSchema extends TSchema | undefined = undefined> {\n request: SubagentRunRequest<TOutputSchema>;\n defaultModel: Model<Api>;\n thinkingLevel: ThinkingLevel;\n models: MikanModels;\n workspaceDir: string;\n availableTools: AgentTool[];\n profiles?: ReadonlyMap<string, SubagentProfile>;\n /** Process-wide launch pool shared by all parent runs. */\n slots?: SubagentSlotPool;\n /** Host-snapshotted parent transcript; never sourced from the public request. */\n parentMessages?: AgentMessage[];\n /** Usage attribution sink snapshotted when this invocation begins. */\n onUsage?: SubagentUsageSink;\n /**\n * Called as the run's visible activity changes, so a caller can show what\n * this subagent is doing rather than only that it started. Best-effort: a\n * throwing sink is logged and the run continues.\n */\n onActivity?: (activity: string) => void;\n}\n\n/**\n * Translate a subagent session's event stream into short activity lines.\n *\n * The stream was always there — nothing subscribed to it, so every subagent\n * was silent for its whole run and a slow step looked identical to a hung one.\n *\n * Text is reported as a growing character count rather than its content: it\n * proves liveness during a long single-turn generation, which is the case with\n * nothing else to show, without putting a half-written answer on screen.\n */\nfunction reportSubagentActivity(\n session: MikanAgentSession,\n onActivity: (activity: string) => void,\n): void {\n let characters = 0;\n let reportedAt = 0;\n const report = (activity: string): void => {\n try {\n onActivity(activity);\n } catch (err) {\n log.logWarning(\"Subagent onActivity listener failed\", String(err));\n }\n };\n\n session.subscribe(async (event: { type: string; [key: string]: unknown }) => {\n if (event.type === \"tool_execution_start\") {\n const args = (event.args ?? {}) as { label?: string };\n const name = String(event.toolName ?? \"tool\");\n report(args.label ? `${name}: ${args.label}` : name);\n return;\n }\n if (event.type === \"tool_execution_end\") {\n report(\"thinking\");\n return;\n }\n if (event.type === \"message_start\") {\n characters = 0;\n reportedAt = 0;\n report(\"thinking\");\n return;\n }\n if (event.type === \"message_update\") {\n const delta = (event as { assistantMessageEvent?: { type?: string; delta?: string } })\n .assistantMessageEvent;\n if (delta?.type !== \"text_delta\" || !delta.delta) return;\n characters += delta.delta.length;\n // Coarse steps: deltas arrive per token, and one report each would churn\n // the dashboard for no added information.\n if (characters - reportedAt < ACTIVITY_CHARS_STEP) return;\n reportedAt = characters;\n report(`writing · ${characters} chars`);\n return;\n }\n if (event.type === \"auto_retry_start\") {\n // The most valuable line here: a retry is the usual reason a run goes\n // quiet for minutes, and it was completely invisible.\n report(\"retrying after an error\");\n }\n });\n}\n\n/** How much new text earns a fresh activity line during a long generation. */\nconst ACTIVITY_CHARS_STEP = 250;\n\nfunction resolveBudget(budget: RunSubagentOptions[\"request\"][\"budget\"]) {\n const resolved = { ...DEFAULT_SUBAGENT_BUDGET, ...budget };\n const positiveIntegerFields = [\n [\"maxTurns\", resolved.maxTurns],\n [\"maxTokens\", resolved.maxTokens],\n [\"maxDurationMs\", resolved.maxDurationMs],\n ] as const;\n for (const [name, value] of positiveIntegerFields) {\n if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {\n throw new Error(`api.subagent.run budget.${name} must be a positive integer`);\n }\n }\n if (!Number.isFinite(resolved.maxCostUsd) || resolved.maxCostUsd < 0) {\n throw new Error(\"api.subagent.run budget.maxCostUsd must be a non-negative number\");\n }\n return resolved;\n}\n\nfunction selectTools(requested: string[] | undefined, available: AgentTool[]): AgentTool[] {\n if (!requested || requested.length === 0) return [];\n const byName = new Map<string, AgentTool>();\n for (const tool of available) {\n if (!byName.has(tool.name)) byName.set(tool.name, tool);\n }\n const selected: AgentTool[] = [];\n for (const name of new Set(requested)) {\n const tool = byName.get(name);\n if (!tool) throw new Error(`Unknown or unavailable subagent tool: ${name}`);\n selected.push(tool);\n }\n return selected;\n}\n\n/**\n * Wrap a tool so the run can prove it was actually reached. Fields are listed\n * explicitly rather than spread: `AgentTool` is a plain interface, and a\n * structural copy would silently drop anything added to it later.\n */\nfunction witnessToolUse(tool: AgentTool, invoked: Set<string>): AgentTool {\n return {\n name: tool.name,\n label: tool.label,\n description: tool.description,\n parameters: tool.parameters,\n ...(tool.constrainedSampling !== undefined\n ? { constrainedSampling: tool.constrainedSampling }\n : {}),\n ...(tool.prepareArguments ? { prepareArguments: tool.prepareArguments.bind(tool) } : {}),\n ...(tool.executionMode ? { executionMode: tool.executionMode } : {}),\n execute: (...args: Parameters<AgentTool[\"execute\"]>) => {\n invoked.add(tool.name);\n return tool.execute(...args);\n },\n };\n}\n\nfunction formatTask(task: string, input: unknown, parentContext?: string): string {\n const trimmed = task.trim();\n if (!trimmed) throw new Error(\"api.subagent.run requires a non-empty task\");\n let formatted = trimmed;\n if (input !== undefined) {\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(input, null, 2);\n } catch (err) {\n throw new Error(\n `api.subagent.run input must be JSON-serializable: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n if (serialized === undefined)\n throw new Error(\"api.subagent.run input must be JSON-serializable\");\n formatted = `${trimmed}\\n\\nInput:\\n${serialized}`;\n }\n return parentContext ? `${parentContext}\\n\\n${formatted}` : formatted;\n}\n\nfunction messageText(message: AgentMessage): string {\n if (message.role === \"compactionSummary\" || message.role === \"branchSummary\") {\n return message.summary;\n }\n if (!(\"content\" in message)) return \"\";\n return contentText(message.content, \"\");\n}\n\nfunction normalizedParentContext(\n request: SubagentRunRequest<TSchema | undefined>,\n messages: AgentMessage[] | undefined,\n): string | undefined {\n if (!request.parentContext || !messages) return undefined;\n const recentTurns = request.parentContext.recentTurns ?? 3;\n if (!Number.isInteger(recentTurns) || recentTurns < 1 || recentTurns > 8) {\n throw new Error(\"api.subagent.run parentContext.recentTurns must be an integer from 1 to 8\");\n }\n const conversation = messages.filter(\n (message) => (message.role === \"user\" || message.role === \"assistant\") && messageText(message),\n );\n let first = conversation.length;\n let users = 0;\n while (first > 0 && users < recentTurns) {\n first -= 1;\n if (conversation[first]?.role === \"user\") users += 1;\n }\n const recent = conversation.slice(first);\n const recentStart = recent[0] ? messages.indexOf(recent[0]) : messages.length;\n let summary: AgentMessage | undefined;\n for (let index = recentStart - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"compactionSummary\" || message?.role === \"branchSummary\") {\n summary = message;\n break;\n }\n }\n return [\n \"<parent_reference_context>\",\n summary ? `Earlier summary: ${messageText(summary)}` : \"[Earlier parent context omitted]\",\n ...recent.map(\n (message) => `${message.role === \"user\" ? \"User\" : \"Assistant\"}: ${messageText(message)}`,\n ),\n \"</parent_reference_context>\",\n ].join(\"\\n\");\n}\n\n/**\n * The evidence policy has to name the actual grant. Told to \"use granted\n * tools\" while holding none, a model will write a tool call as prose and\n * hand that text back as its answer — which then flows to dependent DAG\n * nodes as if it were a finding.\n */\nfunction groundingPolicy(toolNames: string[]): string {\n if (toolNames.length === 0) {\n return [\n \"Evidence policy:\",\n \"- You have NO tools in this run. Do not emit tool calls or tool-call syntax; they will not execute.\",\n \"- Answer only from the task text and any structured input supplied to you.\",\n \"- Never claim to have read a file, run a command, or reached a repository or URL.\",\n \"- If the task cannot be done without a tool, say so plainly and stop.\",\n ].join(\"\\n\");\n }\n return [\n \"Evidence policy:\",\n `- Your tools this run: ${toolNames.join(\", \")}. Nothing else will execute.`,\n \"- Use them for any claim about files, commands, repositories, or external state.\",\n \"- Never simulate tool output or claim a tool was used when it was not.\",\n \"- If the task requires a tool you were not granted, state that you cannot verify it instead of guessing.\",\n ].join(\"\\n\");\n}\n\nfunction buildSystemPrompt(\n base: string | undefined,\n outputSchema: TSchema | undefined,\n toolNames: string[],\n): string {\n const prompt = [base?.trim() || DEFAULT_SYSTEM_PROMPT, groundingPolicy(toolNames)].join(\"\\n\\n\");\n if (!outputSchema) return prompt;\n return [\n prompt,\n \"\",\n \"Return only one JSON value matching this JSON Schema. Do not use Markdown or code fences.\",\n JSON.stringify(outputSchema),\n ].join(\"\\n\");\n}\n\ntype SubagentRunStats = ReturnType<MikanAgentSession[\"getLastRunStats\"]>;\n\n/**\n * Every SubagentRunResult's metric fields are born here — one derivation from\n * the session's run stats, so adding a metric is one edit and no terminal\n * site can drift (the abort branch once shipped without toolCallCounts). The\n * terminal sites state only what differs: status, error, text.\n */\nfunction baseRunResult(\n runId: string,\n model: SubagentModelSpec,\n startedAt: number,\n stats?: SubagentRunStats,\n) {\n const usage = stats?.usage ?? createEmptyUsage();\n return {\n runId,\n model,\n turns: stats?.llmCalls ?? 0,\n toolCalls: stats?.toolCalls ?? 0,\n toolCallCounts: stats?.toolCallCounts ?? {},\n usage,\n tokens: usage.totalTokens,\n costUsd: usage.cost.total,\n durationMs: Date.now() - startedAt,\n };\n}\n\nfunction finalAssistant(messages: AgentMessage[]): AssistantMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"assistant\") return message;\n }\n return undefined;\n}\n\n/**\n * Execute one non-recursive, fresh subagent run. Never rejects: every\n * failure — including request validation — is a result with a terminal\n * status, so batch callers (`tasks` / `dag`) can never orphan in-flight\n * sibling runs on one bad request. Usage is reported once, after the\n * underlying run settles; an aborted run may report it from detached cleanup.\n */\nexport async function runSubagent<TOutputSchema extends TSchema | undefined = undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n): Promise<SubagentRunResult<SubagentRunOutput<TOutputSchema>>> {\n const execution = await executeBoundedSubagentRun(options);\n if (execution.cleanup) {\n void execution.cleanup\n .then(async (result) => {\n await reportSubagentUsage(options.onUsage, result.usage);\n })\n .catch((err) => {\n log.logWarning(\"Subagent detached cleanup failed\", String(err));\n });\n return execution.result;\n }\n await reportSubagentUsage(options.onUsage, execution.result.usage);\n return execution.result;\n}\n\nasync function reportSubagentUsage(\n onUsage: SubagentUsageSink | undefined,\n usage: SubagentUsage,\n): Promise<void> {\n try {\n await onUsage?.(copyUsage(usage));\n } catch (err) {\n log.logWarning(\"Subagent onUsage listener failed\", String(err));\n }\n}\n\ntype BoundedSubagentExecution<TOutput> = {\n result: SubagentRunResult<TOutput>;\n /** Resolves after an aborted prompt settles and returns its final result. */\n cleanup?: Promise<SubagentRunResult<TOutput>>;\n};\n\nasync function executeBoundedSubagentRun<TOutputSchema extends TSchema | undefined = undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n): Promise<BoundedSubagentExecution<SubagentRunOutput<TOutputSchema>>> {\n const startedAt = Date.now();\n let release: (() => void) | undefined;\n try {\n release = await (options.slots ?? unboundedSlotPool()).acquire(options.request.signal);\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n const model = options.request.model ?? {\n provider: options.defaultModel.provider,\n id: options.defaultModel.id,\n };\n return {\n result: { ...baseRunResult(randomUUID(), model, startedAt), status: \"cancelled\" },\n };\n }\n throw err;\n }\n if (!release) throw new Error(\"Subagent slot acquisition returned no release handle\");\n\n try {\n const execution = await executeSubagentRun(options);\n if (!execution.cleanup) {\n release();\n release = undefined;\n return execution;\n }\n\n const cleanup = execution.cleanup;\n const heldRelease = release;\n void cleanup\n .then(\n () => heldRelease(),\n (err) => {\n log.logWarning(\"Subagent detached cleanup failed\", String(err));\n heldRelease();\n },\n )\n .catch((err) => {\n log.logWarning(\"Subagent detached release failed\", String(err));\n heldRelease();\n });\n release = undefined;\n return execution;\n } catch (err) {\n release?.();\n release = undefined;\n throw err;\n }\n}\n\nfunction noop(): void {}\n\n/**\n * Expand `request.profile` into the concrete capability set it names. Most\n * profile budgets are caps that callers may only tighten. Token budgets are\n * different: the effective allowance is the larger of the profile default and\n * the caller's request.\n */\nfunction resolveProfile<TOutputSchema extends TSchema | undefined>(\n request: SubagentRunRequest<TOutputSchema>,\n options: RunSubagentOptions<TOutputSchema>,\n): SubagentRunRequest<TOutputSchema> {\n if (!request.profile) return request;\n const profile = options.profiles?.get(request.profile);\n if (!profile) {\n const known = [...(options.profiles?.keys() ?? [])].join(\", \");\n throw new Error(\n `Unknown subagent profile: ${request.profile}${known ? ` (available: ${known})` : \"\"}`,\n );\n }\n if (request.tools || request.model || request.systemPrompt || request.thinkingLevel) {\n throw new Error(\n `Subagent profile ${request.profile} cannot be combined with tools, model, systemPrompt, or thinkingLevel`,\n );\n }\n const budget = {\n ...request.budget,\n ...(profile.maxTurns !== undefined\n ? { maxTurns: Math.min(profile.maxTurns, request.budget?.maxTurns ?? profile.maxTurns) }\n : {}),\n ...(profile.maxTokens !== undefined || request.budget?.maxTokens !== undefined\n ? { maxTokens: Math.max(profile.maxTokens ?? 0, request.budget?.maxTokens ?? 0) }\n : {}),\n ...(profile.maxCostUsd !== undefined\n ? {\n maxCostUsd: Math.min(\n profile.maxCostUsd,\n request.budget?.maxCostUsd ?? profile.maxCostUsd,\n ),\n }\n : {}),\n ...(profile.maxDurationMs !== undefined\n ? {\n maxDurationMs: Math.min(\n profile.maxDurationMs,\n request.budget?.maxDurationMs ?? profile.maxDurationMs,\n ),\n }\n : {}),\n };\n return {\n ...request,\n systemPrompt: profile.systemPrompt,\n tools: profile.tools,\n // The guard above allows requiredTools to combine with a profile, so the\n // caller's evidence requirements must survive alongside the profile's.\n requiredTools: [...new Set([...(request.requiredTools ?? []), ...profile.requiredTools])],\n ...(profile.model ? { model: profile.model } : {}),\n ...(profile.thinkingLevel ? { thinkingLevel: profile.thinkingLevel } : {}),\n ...(Object.keys(budget).length > 0 ? { budget } : {}),\n };\n}\n\ntype TerminalSignal = \"cancelled\" | \"timeout\";\n\ntype PreparedSubagentRun<TOutputSchema extends TSchema | undefined> = {\n request: SubagentRunRequest<TOutputSchema>;\n runId: string;\n startedAt: number;\n modelSpec: SubagentModelSpec;\n session: MikanAgentSession;\n budget: ReturnType<typeof resolveBudget>;\n invokedTools: Set<string>;\n task: string;\n};\n\nfunction prepareSubagentRun<TOutputSchema extends TSchema | undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n request: SubagentRunRequest<TOutputSchema>,\n runId: string,\n startedAt: number,\n): PreparedSubagentRun<TOutputSchema> {\n const model = request.model\n ? options.models.resolve(request.model.provider, request.model.id)\n : options.defaultModel;\n const invokedTools = new Set<string>();\n const granted = selectTools(request.tools, options.availableTools);\n const missingRequiredTools = (request.requiredTools ?? []).filter(\n (name) => !granted.some((tool) => tool.name === name),\n );\n if (missingRequiredTools.length > 0) {\n throw new Error(`Required subagent tools were not granted: ${missingRequiredTools.join(\", \")}`);\n }\n const task = formatTask(\n request.task,\n request.input,\n normalizedParentContext(request, options.parentMessages),\n );\n const session = new MikanAgentSession({\n systemPrompt: buildSystemPrompt(\n request.systemPrompt,\n request.outputSchema,\n granted.map((tool) => tool.name),\n ),\n model,\n thinkingLevel: request.thinkingLevel ?? options.thinkingLevel,\n tools: granted.map((tool) => witnessToolUse(tool, invokedTools)),\n models: options.models,\n sessionStore: SessionStore.inMemory(options.workspaceDir),\n settings: { compaction: { enabled: false } },\n });\n if (options.onActivity) reportSubagentActivity(session, options.onActivity);\n return {\n request,\n runId,\n startedAt,\n modelSpec: { provider: model.provider, id: model.id },\n session,\n budget: resolveBudget(request.budget),\n invokedTools,\n task,\n };\n}\n\nfunction buildSubagentResult<TOutputSchema extends TSchema | undefined>(\n run: PreparedSubagentRun<TOutputSchema>,\n terminalSignal: TerminalSignal | undefined,\n cleanupPending = false,\n): SubagentRunResult<SubagentRunOutput<TOutputSchema>> {\n const { session, request, invokedTools, budget } = run;\n const stats = session.getLastRunStats();\n const assistant = finalAssistant(session.messages);\n const text = assistant ? contentText(assistant.content, \"\") : \"\";\n const base = {\n ...baseRunResult(run.runId, run.modelSpec, run.startedAt, stats),\n ...(text ? { text } : {}),\n ...(cleanupPending ? { cleanupPending: true as const } : {}),\n };\n\n if (terminalSignal) {\n return {\n ...base,\n status: terminalSignal,\n ...(terminalSignal === \"timeout\"\n ? { error: `Subagent exceeded its ${budget.maxDurationMs}ms duration limit` }\n : {}),\n };\n }\n if (stats.budgetExceededReason) {\n return { ...base, status: \"budget_exceeded\", error: stats.budgetExceededReason };\n }\n const unusedRequiredTools = (request.requiredTools ?? []).filter(\n (name) => !invokedTools.has(name),\n );\n if (unusedRequiredTools.length > 0) {\n return {\n ...base,\n status: \"failed\",\n error: `Required tool not used: ${unusedRequiredTools.join(\", \")}`,\n };\n }\n if (assistant?.stopReason === \"error\") {\n return { ...base, status: \"failed\", error: assistant.errorMessage || \"Subagent failed\" };\n }\n if (!assistant) {\n return { ...base, status: \"failed\", error: \"Subagent produced no assistant response\" };\n }\n if (!request.outputSchema) {\n return text\n ? { ...base, status: \"completed\", output: text as SubagentRunOutput<TOutputSchema> }\n : { ...base, status: \"failed\", error: \"Subagent produced no text output\" };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ...base, status: \"invalid_output\", error: \"Subagent output is not valid JSON\" };\n }\n if (!Value.Check(hydrateSchema(request.outputSchema), parsed)) {\n return {\n ...base,\n status: \"invalid_output\",\n error: \"Subagent output does not match the requested schema\",\n };\n }\n return {\n ...base,\n status: \"completed\",\n output: parsed as SubagentRunOutput<TOutputSchema>,\n };\n}\n\nfunction buildSubagentFailure<TOutputSchema extends TSchema | undefined>(\n run: PreparedSubagentRun<TOutputSchema>,\n terminalSignal: TerminalSignal | undefined,\n err: unknown,\n): SubagentRunResult<SubagentRunOutput<TOutputSchema>> {\n return {\n ...baseRunResult(run.runId, run.modelSpec, run.startedAt, run.session.getLastRunStats()),\n status: terminalSignal ?? \"failed\",\n error: err instanceof Error ? err.message : String(err),\n };\n}\n\nasync function executeSubagentPrompt<TOutputSchema extends TSchema | undefined>(\n run: PreparedSubagentRun<TOutputSchema>,\n abortRequested: Promise<void>,\n terminalSignal: () => TerminalSignal | undefined,\n): Promise<BoundedSubagentExecution<SubagentRunOutput<TOutputSchema>> | undefined> {\n if (terminalSignal()) return undefined;\n const promptOutcome = subagentRunDepth\n .run(1, () =>\n run.session.prompt(run.task, {\n budget: {\n maxLlmCalls: run.budget.maxTurns,\n maxTokens: run.budget.maxTokens,\n maxCostUsd: run.budget.maxCostUsd,\n },\n }),\n )\n .then(\n () => ({ ok: true as const }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n const winner = await Promise.race([\n promptOutcome.then((outcome) => ({ type: \"settled\" as const, outcome })),\n abortRequested.then(async () => {\n let graceTimer: NodeJS.Timeout | undefined;\n const graceExpired = new Promise<\"expired\">((resolve) => {\n graceTimer = setTimeout(() => resolve(\"expired\"), SUBAGENT_ABORT_GRACE_MS);\n });\n const outcome = await Promise.race([\n promptOutcome.then((settledOutcome) => ({\n type: \"settled\" as const,\n outcome: settledOutcome,\n })),\n graceExpired.then((value) => ({ type: value as \"expired\" })),\n ]);\n if (graceTimer) clearTimeout(graceTimer);\n return outcome;\n }),\n ]);\n if (winner.type === \"expired\") {\n const cleanup = promptOutcome.then((outcome) =>\n outcome.ok\n ? buildSubagentResult(run, terminalSignal())\n : buildSubagentFailure(run, terminalSignal(), outcome.error),\n );\n return { result: buildSubagentResult(run, terminalSignal(), true), cleanup };\n }\n if (!winner.outcome.ok) throw winner.outcome.error;\n return undefined;\n}\n\nasync function executeSubagentRun<TOutputSchema extends TSchema | undefined = undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n): Promise<BoundedSubagentExecution<SubagentRunOutput<TOutputSchema>>> {\n const request = resolveProfile(options.request, options);\n const runId = randomUUID();\n const startedAt = Date.now();\n const initialModelSpec = request.model ?? {\n provider: options.defaultModel.provider,\n id: options.defaultModel.id,\n };\n let run: PreparedSubagentRun<TOutputSchema> | undefined;\n let terminalSignal: TerminalSignal | undefined;\n let timeout: NodeJS.Timeout | undefined;\n let notifyAbort: () => void = noop;\n const abortRequested = new Promise<void>((resolve) => {\n notifyAbort = resolve;\n });\n const abort = (reason: TerminalSignal) => {\n if (terminalSignal) return;\n terminalSignal = reason;\n run?.session.abort();\n notifyAbort();\n };\n const onAbort = () => abort(\"cancelled\");\n\n try {\n if ((subagentRunDepth.getStore() ?? 0) >= 1) {\n throw new Error(\"Nested api.subagent.run calls are not allowed\");\n }\n run = prepareSubagentRun(options, request, runId, startedAt);\n request.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (request.signal?.aborted) abort(\"cancelled\");\n timeout = setTimeout(() => abort(\"timeout\"), run.budget.maxDurationMs);\n timeout.unref();\n\n const earlyResult = await executeSubagentPrompt(run, abortRequested, () => terminalSignal);\n return earlyResult ?? { result: buildSubagentResult(run, terminalSignal) };\n } catch (err) {\n return {\n result: run\n ? buildSubagentFailure(run, terminalSignal, err)\n : {\n ...baseRunResult(runId, initialModelSpec, startedAt),\n status: terminalSignal ?? \"failed\",\n error: err instanceof Error ? err.message : String(err),\n },\n };\n } finally {\n if (timeout) clearTimeout(timeout);\n request.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subagent-runner.js","sourceRoot":"","sources":["../../src/harness/subagent-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,WAAW,EAA+C,MAAM,uBAAuB,CAAC;AACjG,OAAO,EAAE,IAAI,EAAE,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BAAoB,CAAC,GAAG,EAAE,cAAc,EAAE,GAAG,CAAC;gBAChD,CAAC,CAAC;oBACE,GAAG,aAAa,CAAC,KAAK,EAAE,gBAAgB,EAAE,SAAS,CAAC;oBACpD,MAAM,EAAE,cAAc,IAAI,QAAQ;oBAClC,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;iBACxD;SACN,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,IAAI,OAAO;YAAE,YAAY,CAAC,OAAO,CAAC,CAAC;QACnC,OAAO,CAAC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;AACH,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentMessage, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { contentText, type Api, type AssistantMessage, type Model } from \"@earendil-works/pi-ai\";\nimport { Kind, Type, type TSchema } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport * as log from \"../log.js\";\nimport type { MikanModels } from \"./models.js\";\nimport type { SubagentProfile } from \"./types.js\";\nimport { MikanAgentSession } from \"./runner.js\";\nimport { SessionStore } from \"./session-store.js\";\nimport type {\n SubagentModelSpec,\n SubagentRunOutput,\n SubagentRunRequest,\n SubagentRunResult,\n SubagentUsage,\n SubagentUsageSink,\n} from \"./types.js\";\nimport { copyUsage, createEmptyUsage } from \"./usage.js\";\nimport { unboundedSlotPool, type SubagentSlotPool } from \"./subagent-slots.js\";\n\nconst subagentRunDepth = new AsyncLocalStorage<number>();\nconst DEFAULT_SYSTEM_PROMPT =\n \"You are a focused subagent. Complete only the assigned task and return the result directly.\";\nexport const DEFAULT_SUBAGENT_BUDGET = {\n maxTurns: 100,\n maxCostUsd: 10,\n maxDurationMs: 10 * 60 * 1000,\n} as const;\n\n/** Time allowed for an aborted subagent to settle before detached cleanup. */\nexport const SUBAGENT_ABORT_GRACE_MS = 100;\n\nconst SCHEMA_STRUCTURAL_KEYS = new Set([\n \"type\",\n \"properties\",\n \"required\",\n \"items\",\n \"enum\",\n \"const\",\n \"anyOf\",\n \"oneOf\",\n \"allOf\",\n]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction schemaOptions(node: Record<string, unknown>): Record<string, unknown> {\n const options: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node)) {\n if (!SCHEMA_STRUCTURAL_KEYS.has(key)) options[key] = value;\n }\n if (isRecord(options.additionalProperties)) {\n options.additionalProperties = hydrateSchema(options.additionalProperties);\n }\n return options;\n}\n\n/**\n * outputSchema arrives over the subagent tool as plain JSON (tool-call\n * arguments never carry TypeBox's Kind symbol), but Value.Check dispatches\n * purely on schema[Kind] and throws ValueCheckUnknownTypeError for anything\n * without it. Hydrate plain JSON Schema into real TypeBox schema nodes so\n * validation runs instead of throwing; schemas built with TypeBox already\n * carry Kind and pass through untouched.\n *\n * Unsupported keywords ($ref, not, patternProperties, if/then/else) degrade to\n * a permissive Unknown — fail-open by design: outputSchema is advisory output\n * validation, not a security boundary.\n */\nfunction hydrateSchema(schema: unknown): TSchema {\n if (isRecord(schema) && Kind in schema) return schema as TSchema;\n if (!isRecord(schema)) return Type.Unknown();\n\n if (Array.isArray(schema.enum)) {\n const literals = schema.enum.filter(\n (value): value is string | number | boolean =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\",\n );\n return literals.length > 0\n ? Type.Union(literals.map((value) => Type.Literal(value)))\n : Type.Unknown();\n }\n if (\"const\" in schema) {\n const value = schema.const;\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n ? Type.Literal(value)\n : Type.Unknown();\n }\n if (Array.isArray(schema.anyOf)) return Type.Union(schema.anyOf.map(hydrateSchema));\n if (Array.isArray(schema.oneOf)) return Type.Union(schema.oneOf.map(hydrateSchema));\n if (Array.isArray(schema.allOf)) return Type.Intersect(schema.allOf.map(hydrateSchema));\n\n const type = Array.isArray(schema.type)\n ? schema.type\n : (schema.type ?? (schema.properties ? \"object\" : schema.items ? \"array\" : undefined));\n if (Array.isArray(type)) {\n return Type.Union(type.map((variant) => hydrateSchema({ ...schema, type: variant })));\n }\n\n const options = schemaOptions(schema);\n switch (type) {\n case \"object\": {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const required = new Set(Array.isArray(schema.required) ? schema.required : []);\n const props: Record<string, TSchema> = {};\n for (const [key, value] of Object.entries(properties)) {\n const hydrated = hydrateSchema(value);\n props[key] = required.has(key) ? hydrated : Type.Optional(hydrated);\n }\n return Type.Object(props, options);\n }\n case \"array\":\n return Type.Array(\n schema.items !== undefined ? hydrateSchema(schema.items) : Type.Unknown(),\n options,\n );\n case \"string\":\n return Type.String(options);\n case \"number\":\n return Type.Number(options);\n case \"integer\":\n return Type.Integer(options);\n case \"boolean\":\n return Type.Boolean(options);\n case \"null\":\n return Type.Null(options);\n default:\n return Type.Unknown(options);\n }\n}\n\ninterface RunSubagentOptions<TOutputSchema extends TSchema | undefined = undefined> {\n request: SubagentRunRequest<TOutputSchema>;\n defaultModel: Model<Api>;\n thinkingLevel: ThinkingLevel;\n models: MikanModels;\n workspaceDir: string;\n availableTools: AgentTool[];\n profiles?: ReadonlyMap<string, SubagentProfile>;\n /** Process-wide launch pool shared by all parent runs. */\n slots?: SubagentSlotPool;\n /** Host-snapshotted parent transcript; never sourced from the public request. */\n parentMessages?: AgentMessage[];\n /** Usage attribution sink snapshotted when this invocation begins. */\n onUsage?: SubagentUsageSink;\n /**\n * Called as the run's visible activity changes, so a caller can show what\n * this subagent is doing rather than only that it started. Best-effort: a\n * throwing sink is logged and the run continues.\n */\n onActivity?: (activity: string) => void;\n}\n\n/**\n * Translate a subagent session's event stream into short activity lines.\n *\n * The stream was always there — nothing subscribed to it, so every subagent\n * was silent for its whole run and a slow step looked identical to a hung one.\n *\n * Text is reported as a growing character count rather than its content: it\n * proves liveness during a long single-turn generation, which is the case with\n * nothing else to show, without putting a half-written answer on screen.\n */\nfunction reportSubagentActivity(\n session: MikanAgentSession,\n onActivity: (activity: string) => void,\n): void {\n let characters = 0;\n let reportedAt = 0;\n const report = (activity: string): void => {\n try {\n onActivity(activity);\n } catch (err) {\n log.logWarning(\"Subagent onActivity listener failed\", String(err));\n }\n };\n\n session.subscribe(async (event: { type: string; [key: string]: unknown }) => {\n if (event.type === \"tool_execution_start\") {\n const args = (event.args ?? {}) as { label?: string };\n const name = String(event.toolName ?? \"tool\");\n report(args.label ? `${name}: ${args.label}` : name);\n return;\n }\n if (event.type === \"tool_execution_end\") {\n report(\"thinking\");\n return;\n }\n if (event.type === \"message_start\") {\n characters = 0;\n reportedAt = 0;\n report(\"thinking\");\n return;\n }\n if (event.type === \"message_update\") {\n const delta = (event as { assistantMessageEvent?: { type?: string; delta?: string } })\n .assistantMessageEvent;\n if (delta?.type !== \"text_delta\" || !delta.delta) return;\n characters += delta.delta.length;\n // Coarse steps: deltas arrive per token, and one report each would churn\n // the dashboard for no added information.\n if (characters - reportedAt < ACTIVITY_CHARS_STEP) return;\n reportedAt = characters;\n report(`writing · ${characters} chars`);\n return;\n }\n if (event.type === \"auto_retry_start\") {\n // The most valuable line here: a retry is the usual reason a run goes\n // quiet for minutes, and it was completely invisible.\n report(\"retrying after an error\");\n }\n });\n}\n\n/** How much new text earns a fresh activity line during a long generation. */\nconst ACTIVITY_CHARS_STEP = 250;\n\nfunction resolveBudget(budget: RunSubagentOptions[\"request\"][\"budget\"]) {\n const resolved = { ...DEFAULT_SUBAGENT_BUDGET, ...budget };\n const positiveIntegerFields = [\n [\"maxTurns\", resolved.maxTurns],\n [\"maxTokens\", resolved.maxTokens],\n [\"maxDurationMs\", resolved.maxDurationMs],\n ] as const;\n for (const [name, value] of positiveIntegerFields) {\n if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {\n throw new Error(`api.subagent.run budget.${name} must be a positive integer`);\n }\n }\n if (!Number.isFinite(resolved.maxCostUsd) || resolved.maxCostUsd < 0) {\n throw new Error(\"api.subagent.run budget.maxCostUsd must be a non-negative number\");\n }\n return resolved;\n}\n\nfunction selectTools(requested: string[] | undefined, available: AgentTool[]): AgentTool[] {\n if (!requested || requested.length === 0) return [];\n const byName = new Map<string, AgentTool>();\n for (const tool of available) {\n if (!byName.has(tool.name)) byName.set(tool.name, tool);\n }\n const selected: AgentTool[] = [];\n for (const name of new Set(requested)) {\n const tool = byName.get(name);\n if (!tool) throw new Error(`Unknown or unavailable subagent tool: ${name}`);\n selected.push(tool);\n }\n return selected;\n}\n\nfunction formatTask(task: string, input: unknown, parentContext?: string): string {\n const trimmed = task.trim();\n if (!trimmed) throw new Error(\"api.subagent.run requires a non-empty task\");\n let formatted = trimmed;\n if (input !== undefined) {\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(input, null, 2);\n } catch (err) {\n throw new Error(\n `api.subagent.run input must be JSON-serializable: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n if (serialized === undefined)\n throw new Error(\"api.subagent.run input must be JSON-serializable\");\n formatted = `${trimmed}\\n\\nInput:\\n${serialized}`;\n }\n return parentContext ? `${parentContext}\\n\\n${formatted}` : formatted;\n}\n\nfunction messageText(message: AgentMessage): string {\n if (message.role === \"compactionSummary\" || message.role === \"branchSummary\") {\n return message.summary;\n }\n if (!(\"content\" in message)) return \"\";\n return contentText(message.content, \"\");\n}\n\nfunction normalizedParentContext(\n request: SubagentRunRequest<TSchema | undefined>,\n messages: AgentMessage[] | undefined,\n): string | undefined {\n if (!request.parentContext || !messages) return undefined;\n const recentTurns = request.parentContext.recentTurns ?? 3;\n if (!Number.isInteger(recentTurns) || recentTurns < 1 || recentTurns > 8) {\n throw new Error(\"api.subagent.run parentContext.recentTurns must be an integer from 1 to 8\");\n }\n const conversation = messages.filter(\n (message) => (message.role === \"user\" || message.role === \"assistant\") && messageText(message),\n );\n let first = conversation.length;\n let users = 0;\n while (first > 0 && users < recentTurns) {\n first -= 1;\n if (conversation[first]?.role === \"user\") users += 1;\n }\n const recent = conversation.slice(first);\n const recentStart = recent[0] ? messages.indexOf(recent[0]) : messages.length;\n let summary: AgentMessage | undefined;\n for (let index = recentStart - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"compactionSummary\" || message?.role === \"branchSummary\") {\n summary = message;\n break;\n }\n }\n return [\n \"<parent_reference_context>\",\n summary ? `Earlier summary: ${messageText(summary)}` : \"[Earlier parent context omitted]\",\n ...recent.map(\n (message) => `${message.role === \"user\" ? \"User\" : \"Assistant\"}: ${messageText(message)}`,\n ),\n \"</parent_reference_context>\",\n ].join(\"\\n\");\n}\n\n/**\n * The evidence policy has to name the actual grant. Told to \"use granted\n * tools\" while holding none, a model will write a tool call as prose and\n * hand that text back as its answer — which then flows to dependent DAG\n * nodes as if it were a finding.\n */\nfunction groundingPolicy(toolNames: string[]): string {\n if (toolNames.length === 0) {\n return [\n \"Evidence policy:\",\n \"- You have NO tools in this run. Do not emit tool calls or tool-call syntax; they will not execute.\",\n \"- Answer only from the task text and any structured input supplied to you.\",\n \"- Never claim to have read a file, run a command, or reached a repository or URL.\",\n \"- If the task cannot be done without a tool, say so plainly and stop.\",\n ].join(\"\\n\");\n }\n return [\n \"Evidence policy:\",\n `- Your tools this run: ${toolNames.join(\", \")}. Nothing else will execute.`,\n \"- Use them for any claim about files, commands, repositories, or external state.\",\n \"- Never simulate tool output or claim a tool was used when it was not.\",\n \"- If the task requires a tool you were not granted, state that you cannot verify it instead of guessing.\",\n ].join(\"\\n\");\n}\n\nfunction buildSystemPrompt(\n base: string | undefined,\n outputSchema: TSchema | undefined,\n toolNames: string[],\n): string {\n const prompt = [base?.trim() || DEFAULT_SYSTEM_PROMPT, groundingPolicy(toolNames)].join(\"\\n\\n\");\n if (!outputSchema) return prompt;\n return [\n prompt,\n \"\",\n \"Return only one JSON value matching this JSON Schema. Do not use Markdown or code fences.\",\n JSON.stringify(outputSchema),\n ].join(\"\\n\");\n}\n\ntype SubagentRunStats = ReturnType<MikanAgentSession[\"getLastRunStats\"]>;\n\n/**\n * Every SubagentRunResult's metric fields are born here — one derivation from\n * the session's run stats, so adding a metric is one edit and no terminal\n * site can drift (the abort branch once shipped without toolCallCounts). The\n * terminal sites state only what differs: status, error, text.\n */\nfunction baseRunResult(\n runId: string,\n model: SubagentModelSpec,\n startedAt: number,\n stats?: SubagentRunStats,\n) {\n const usage = stats?.usage ?? createEmptyUsage();\n return {\n runId,\n model,\n turns: stats?.llmCalls ?? 0,\n toolCalls: stats?.toolCalls ?? 0,\n toolCallCounts: stats?.toolCallCounts ?? {},\n usage,\n tokens: usage.totalTokens,\n costUsd: usage.cost.total,\n durationMs: Date.now() - startedAt,\n };\n}\n\nfunction finalAssistant(messages: AgentMessage[]): AssistantMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"assistant\") return message;\n }\n return undefined;\n}\n\n/**\n * Execute one non-recursive, fresh subagent run. Never rejects: every\n * failure — including request validation — is a result with a terminal\n * status, so batch callers (`tasks` / `dag`) can never orphan in-flight\n * sibling runs on one bad request. Usage is reported once, after the\n * underlying run settles; an aborted run may report it from detached cleanup.\n */\nexport async function runSubagent<TOutputSchema extends TSchema | undefined = undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n): Promise<SubagentRunResult<SubagentRunOutput<TOutputSchema>>> {\n const execution = await executeBoundedSubagentRun(options);\n if (execution.cleanup) {\n void execution.cleanup\n .then(async (result) => {\n await reportSubagentUsage(options.onUsage, result.usage);\n })\n .catch((err) => {\n log.logWarning(\"Subagent detached cleanup failed\", String(err));\n });\n return execution.result;\n }\n await reportSubagentUsage(options.onUsage, execution.result.usage);\n return execution.result;\n}\n\nasync function reportSubagentUsage(\n onUsage: SubagentUsageSink | undefined,\n usage: SubagentUsage,\n): Promise<void> {\n try {\n await onUsage?.(copyUsage(usage));\n } catch (err) {\n log.logWarning(\"Subagent onUsage listener failed\", String(err));\n }\n}\n\ntype BoundedSubagentExecution<TOutput> = {\n result: SubagentRunResult<TOutput>;\n /** Resolves after an aborted prompt settles and returns its final result. */\n cleanup?: Promise<SubagentRunResult<TOutput>>;\n};\n\nasync function executeBoundedSubagentRun<TOutputSchema extends TSchema | undefined = undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n): Promise<BoundedSubagentExecution<SubagentRunOutput<TOutputSchema>>> {\n const startedAt = Date.now();\n let release: (() => void) | undefined;\n try {\n release = await (options.slots ?? unboundedSlotPool()).acquire(options.request.signal);\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n const model = options.request.model ?? {\n provider: options.defaultModel.provider,\n id: options.defaultModel.id,\n };\n return {\n result: { ...baseRunResult(randomUUID(), model, startedAt), status: \"cancelled\" },\n };\n }\n throw err;\n }\n if (!release) throw new Error(\"Subagent slot acquisition returned no release handle\");\n\n try {\n const execution = await executeSubagentRun(options);\n if (!execution.cleanup) {\n release();\n release = undefined;\n return execution;\n }\n\n const cleanup = execution.cleanup;\n const heldRelease = release;\n void cleanup\n .then(\n () => heldRelease(),\n (err) => {\n log.logWarning(\"Subagent detached cleanup failed\", String(err));\n heldRelease();\n },\n )\n .catch((err) => {\n log.logWarning(\"Subagent detached release failed\", String(err));\n heldRelease();\n });\n release = undefined;\n return execution;\n } catch (err) {\n release?.();\n release = undefined;\n throw err;\n }\n}\n\nfunction noop(): void {}\n\n/**\n * Expand `request.profile` into the concrete capability set it names. Most\n * profile budgets are caps that callers may only tighten. Token budgets are\n * different: the effective allowance is the larger of the profile default and\n * the caller's request.\n */\nfunction resolveProfile<TOutputSchema extends TSchema | undefined>(\n request: SubagentRunRequest<TOutputSchema>,\n options: RunSubagentOptions<TOutputSchema>,\n): SubagentRunRequest<TOutputSchema> {\n if (!request.profile) return request;\n const profile = options.profiles?.get(request.profile);\n if (!profile) {\n const known = [...(options.profiles?.keys() ?? [])].join(\", \");\n throw new Error(\n `Unknown subagent profile: ${request.profile}${known ? ` (available: ${known})` : \"\"}`,\n );\n }\n if (request.tools || request.model || request.systemPrompt || request.thinkingLevel) {\n throw new Error(\n `Subagent profile ${request.profile} cannot be combined with tools, model, systemPrompt, or thinkingLevel`,\n );\n }\n const budget = {\n ...request.budget,\n ...(profile.maxTurns !== undefined\n ? { maxTurns: Math.min(profile.maxTurns, request.budget?.maxTurns ?? profile.maxTurns) }\n : {}),\n ...(profile.maxTokens !== undefined || request.budget?.maxTokens !== undefined\n ? { maxTokens: Math.max(profile.maxTokens ?? 0, request.budget?.maxTokens ?? 0) }\n : {}),\n ...(profile.maxCostUsd !== undefined\n ? {\n maxCostUsd: Math.min(\n profile.maxCostUsd,\n request.budget?.maxCostUsd ?? profile.maxCostUsd,\n ),\n }\n : {}),\n ...(profile.maxDurationMs !== undefined\n ? {\n maxDurationMs: Math.min(\n profile.maxDurationMs,\n request.budget?.maxDurationMs ?? profile.maxDurationMs,\n ),\n }\n : {}),\n };\n return {\n ...request,\n systemPrompt: profile.systemPrompt,\n tools: profile.tools,\n ...(profile.model ? { model: profile.model } : {}),\n ...(profile.thinkingLevel ? { thinkingLevel: profile.thinkingLevel } : {}),\n ...(Object.keys(budget).length > 0 ? { budget } : {}),\n };\n}\n\ntype TerminalSignal = \"cancelled\" | \"timeout\";\n\ntype PreparedSubagentRun<TOutputSchema extends TSchema | undefined> = {\n request: SubagentRunRequest<TOutputSchema>;\n runId: string;\n startedAt: number;\n modelSpec: SubagentModelSpec;\n session: MikanAgentSession;\n budget: ReturnType<typeof resolveBudget>;\n task: string;\n};\n\nfunction prepareSubagentRun<TOutputSchema extends TSchema | undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n request: SubagentRunRequest<TOutputSchema>,\n runId: string,\n startedAt: number,\n): PreparedSubagentRun<TOutputSchema> {\n const model = request.model\n ? options.models.resolve(request.model.provider, request.model.id)\n : options.defaultModel;\n const granted = selectTools(request.tools, options.availableTools);\n const task = formatTask(\n request.task,\n request.input,\n normalizedParentContext(request, options.parentMessages),\n );\n const session = new MikanAgentSession({\n systemPrompt: buildSystemPrompt(\n request.systemPrompt,\n request.outputSchema,\n granted.map((tool) => tool.name),\n ),\n model,\n thinkingLevel: request.thinkingLevel ?? options.thinkingLevel,\n tools: granted,\n models: options.models,\n sessionStore: SessionStore.inMemory(options.workspaceDir),\n settings: { compaction: { enabled: false } },\n });\n if (options.onActivity) reportSubagentActivity(session, options.onActivity);\n return {\n request,\n runId,\n startedAt,\n modelSpec: { provider: model.provider, id: model.id },\n session,\n budget: resolveBudget(request.budget),\n task,\n };\n}\n\nfunction buildSubagentResult<TOutputSchema extends TSchema | undefined>(\n run: PreparedSubagentRun<TOutputSchema>,\n terminalSignal: TerminalSignal | undefined,\n cleanupPending = false,\n): SubagentRunResult<SubagentRunOutput<TOutputSchema>> {\n const { session, request, budget } = run;\n const stats = session.getLastRunStats();\n const assistant = finalAssistant(session.messages);\n const text = assistant ? contentText(assistant.content, \"\") : \"\";\n const base = {\n ...baseRunResult(run.runId, run.modelSpec, run.startedAt, stats),\n ...(text ? { text } : {}),\n ...(cleanupPending ? { cleanupPending: true as const } : {}),\n };\n\n if (terminalSignal) {\n return {\n ...base,\n status: terminalSignal,\n ...(terminalSignal === \"timeout\"\n ? { error: `Subagent exceeded its ${budget.maxDurationMs}ms duration limit` }\n : {}),\n };\n }\n if (stats.budgetExceededReason) {\n return { ...base, status: \"budget_exceeded\", error: stats.budgetExceededReason };\n }\n if (assistant?.stopReason === \"error\") {\n return { ...base, status: \"failed\", error: assistant.errorMessage || \"Subagent failed\" };\n }\n if (!assistant) {\n return { ...base, status: \"failed\", error: \"Subagent produced no assistant response\" };\n }\n if (!request.outputSchema) {\n return text\n ? { ...base, status: \"completed\", output: text as SubagentRunOutput<TOutputSchema> }\n : { ...base, status: \"failed\", error: \"Subagent produced no text output\" };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { ...base, status: \"invalid_output\", error: \"Subagent output is not valid JSON\" };\n }\n if (!Value.Check(hydrateSchema(request.outputSchema), parsed)) {\n return {\n ...base,\n status: \"invalid_output\",\n error: \"Subagent output does not match the requested schema\",\n };\n }\n return {\n ...base,\n status: \"completed\",\n output: parsed as SubagentRunOutput<TOutputSchema>,\n };\n}\n\nfunction buildSubagentFailure<TOutputSchema extends TSchema | undefined>(\n run: PreparedSubagentRun<TOutputSchema>,\n terminalSignal: TerminalSignal | undefined,\n err: unknown,\n): SubagentRunResult<SubagentRunOutput<TOutputSchema>> {\n return {\n ...baseRunResult(run.runId, run.modelSpec, run.startedAt, run.session.getLastRunStats()),\n status: terminalSignal ?? \"failed\",\n error: err instanceof Error ? err.message : String(err),\n };\n}\n\nasync function executeSubagentPrompt<TOutputSchema extends TSchema | undefined>(\n run: PreparedSubagentRun<TOutputSchema>,\n abortRequested: Promise<void>,\n terminalSignal: () => TerminalSignal | undefined,\n): Promise<BoundedSubagentExecution<SubagentRunOutput<TOutputSchema>> | undefined> {\n if (terminalSignal()) return undefined;\n const promptOutcome = subagentRunDepth\n .run(1, () =>\n run.session.prompt(run.task, {\n budget: {\n maxLlmCalls: run.budget.maxTurns,\n maxTokens: run.budget.maxTokens,\n maxCostUsd: run.budget.maxCostUsd,\n },\n }),\n )\n .then(\n () => ({ ok: true as const }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n const winner = await Promise.race([\n promptOutcome.then((outcome) => ({ type: \"settled\" as const, outcome })),\n abortRequested.then(async () => {\n let graceTimer: NodeJS.Timeout | undefined;\n const graceExpired = new Promise<\"expired\">((resolve) => {\n graceTimer = setTimeout(() => resolve(\"expired\"), SUBAGENT_ABORT_GRACE_MS);\n });\n const outcome = await Promise.race([\n promptOutcome.then((settledOutcome) => ({\n type: \"settled\" as const,\n outcome: settledOutcome,\n })),\n graceExpired.then((value) => ({ type: value as \"expired\" })),\n ]);\n if (graceTimer) clearTimeout(graceTimer);\n return outcome;\n }),\n ]);\n if (winner.type === \"expired\") {\n const cleanup = promptOutcome.then((outcome) =>\n outcome.ok\n ? buildSubagentResult(run, terminalSignal())\n : buildSubagentFailure(run, terminalSignal(), outcome.error),\n );\n return { result: buildSubagentResult(run, terminalSignal(), true), cleanup };\n }\n if (!winner.outcome.ok) throw winner.outcome.error;\n return undefined;\n}\n\nasync function executeSubagentRun<TOutputSchema extends TSchema | undefined = undefined>(\n options: RunSubagentOptions<TOutputSchema>,\n): Promise<BoundedSubagentExecution<SubagentRunOutput<TOutputSchema>>> {\n const request = resolveProfile(options.request, options);\n const runId = randomUUID();\n const startedAt = Date.now();\n const initialModelSpec = request.model ?? {\n provider: options.defaultModel.provider,\n id: options.defaultModel.id,\n };\n let run: PreparedSubagentRun<TOutputSchema> | undefined;\n let terminalSignal: TerminalSignal | undefined;\n let timeout: NodeJS.Timeout | undefined;\n let notifyAbort: () => void = noop;\n const abortRequested = new Promise<void>((resolve) => {\n notifyAbort = resolve;\n });\n const abort = (reason: TerminalSignal) => {\n if (terminalSignal) return;\n terminalSignal = reason;\n run?.session.abort();\n notifyAbort();\n };\n const onAbort = () => abort(\"cancelled\");\n\n try {\n if ((subagentRunDepth.getStore() ?? 0) >= 1) {\n throw new Error(\"Nested api.subagent.run calls are not allowed\");\n }\n run = prepareSubagentRun(options, request, runId, startedAt);\n request.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (request.signal?.aborted) abort(\"cancelled\");\n timeout = setTimeout(() => abort(\"timeout\"), run.budget.maxDurationMs);\n timeout.unref();\n\n const earlyResult = await executeSubagentPrompt(run, abortRequested, () => terminalSignal);\n return earlyResult ?? { result: buildSubagentResult(run, terminalSignal) };\n } catch (err) {\n return {\n result: run\n ? buildSubagentFailure(run, terminalSignal, err)\n : {\n ...baseRunResult(runId, initialModelSpec, startedAt),\n status: terminalSignal ?? \"failed\",\n error: err instanceof Error ? err.message : String(err),\n },\n };\n } finally {\n if (timeout) clearTimeout(timeout);\n request.signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n"]}
|
package/dist/harness/types.d.ts
CHANGED
|
@@ -50,7 +50,6 @@ export interface SubagentProfile {
|
|
|
50
50
|
description: string;
|
|
51
51
|
systemPrompt: string;
|
|
52
52
|
tools: string[];
|
|
53
|
-
requiredTools: string[];
|
|
54
53
|
model?: SubagentModelSpec;
|
|
55
54
|
thinkingLevel?: ThinkingLevel;
|
|
56
55
|
maxTurns?: number;
|
|
@@ -92,8 +91,6 @@ export interface SubagentRunRequest<TOutputSchema extends TSchema | undefined =
|
|
|
92
91
|
model?: SubagentModelSpec;
|
|
93
92
|
/** Tool names explicitly granted to the subagent. Defaults to no tools. */
|
|
94
93
|
tools?: string[];
|
|
95
|
-
/** Tool names that must each be invoked at least once before completion. */
|
|
96
|
-
requiredTools?: string[];
|
|
97
94
|
/** Per-profile thinking override. */
|
|
98
95
|
thinkingLevel?: ThinkingLevel;
|
|
99
96
|
/** When present, the final response must be JSON matching this schema. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EACV,UAAU,EACV,YAAY,EACZ,SAAS,EACT,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,KAAK,EACL,YAAY,EACZ,aAAa,EACb,kBAAkB,EACnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEzD,YAAY,EAAE,kBAAkB,EAAE,eAAe,EAAE,WAAW,EAAE,CAAC;AAEjE,2EAA2E;AAC3E,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,YAA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MAAM,CAAA;CAAE,GAClF;IACE,IAAI,EAAE,iBAAiB,CAAC;IACxB,6DAA6D;IAC7D,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEN,MAAM,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAEjF,MAAM,WAAW,wBAAwB;IACvC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,aAAa,EAAE,aAAa,CAAC;IAC7B,KAAK,EAAE,SAAS,EAAE,CAAC;IACnB,MAAM,EAAE,WAAW,CAAC;IACpB,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,CAAC,EAAE;QACT,UAAU,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;QACzC,KAAK,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;QAC/B,MAAM,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;KAClC,CAAC;CACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAsCA,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC","sourcesContent":["/**\n * Core types for the mikan agent harness.\n *\n * The harness is built directly on pi-agent-core and pi-ai. Sessions use\n * pi's current v4 entry model and JSONL storage format. mikan-owned\n * metadata uses a namespaced durable value; legacy v3 and Pi 0.84 v4 files\n * are handled exclusively by the offline session migrations.\n */\nimport type {\n AgentEvent,\n AgentMessage,\n AgentTool,\n BranchSummaryEntry,\n CompactionEntry,\n CustomEntry,\n Entry,\n MessageEntry,\n ThinkingLevel,\n CompactionSettings,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model, RetryPolicy, Usage } from \"@earendil-works/pi-ai\";\nimport type { MikanModels } from \"./models.js\";\nimport type { SessionStore } from \"./session-store.js\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\nexport type { BranchSummaryEntry, CompactionEntry, CustomEntry };\n\n/** Model-visible messages reconstructed from the active session branch. */\nexport interface SessionContext {\n messages: AgentMessage[];\n}\n\n/** Message entry as stored in mikan session files (pi v4). */\nexport type SessionMessageEntry = MessageEntry;\n\n/** Union of entry types mikan reads and writes. Alias of pi's v4 entry. */\nexport type SessionEntry = Entry;\n\nexport const CURRENT_SESSION_VERSION = 4;\n\nexport interface SessionCreateInfo {\n id?: string;\n parentSession?: string;\n parentSessionId?: string;\n}\n\n/** Immutable session queries available to portals, admin, and migration code. */\nexport interface SessionInspection {\n getHeader(): SessionHeader;\n getEntries(): Promise<Entry[]>;\n getSessionName(): Promise<string | undefined>;\n getBranch(fromId?: string): Promise<Entry[]>;\n buildSessionContext(): Promise<SessionContext>;\n}\n\nexport interface SubagentModelSpec {\n provider: string;\n id: string;\n}\n\n/**\n * A curated capability set a subagent can be launched with. Built-ins ship\n * with the harness; `<workspaceDir>/agents/<name>.md` patches them per\n * installation. Turn, cost, and duration fields are caps — an explicit\n * `request.budget` may tighten them but never raise them. Token budgets use the\n * larger of the profile default and the request value.\n */\nexport interface SubagentProfile {\n name: string;\n description: string;\n systemPrompt: string;\n tools: string[];\n requiredTools: string[];\n model?: SubagentModelSpec;\n thinkingLevel?: ThinkingLevel;\n maxTurns?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n maxDurationMs?: number;\n}\n\nexport interface SubagentRunBudget {\n /** Maximum assistant/model calls in the subagent run. */\n maxTurns?: number;\n /** Maximum cumulative input/output/cache tokens. */\n maxTokens?: number;\n /** Maximum provider cost in USD. */\n maxCostUsd?: number;\n /** Maximum wall-clock duration. */\n maxDurationMs?: number;\n}\n\nexport type SubagentRunStatus =\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"timeout\"\n | \"budget_exceeded\"\n | \"invalid_output\";\n\nexport interface SubagentParentContext {\n mode: \"normalized\";\n /** Number of recent user/assistant turns to include. Defaults to 3. */\n recentTurns?: number;\n}\n\n/** Aggregated model usage across every assistant turn in a subagent run. */\nexport type SubagentUsage = Usage;\n\n/** Receives usage from a subagent run, including after detached cleanup settles. */\nexport type SubagentUsageSink = (usage: SubagentUsage) => void | Promise<void>;\n\n/** A fresh, isolated subagent run. */\nexport interface SubagentRunRequest<TOutputSchema extends TSchema | undefined = undefined> {\n task: string;\n /** Named profile: a harness built-in, patched by `<workspaceDir>/agents/<name>.md`. */\n profile?: string;\n /** Opt in to a normalized textual snapshot of the active parent run. Defaults to fresh. */\n parentContext?: SubagentParentContext;\n systemPrompt?: string;\n /** JSON-serializable input appended to the task. */\n input?: unknown;\n /** Defaults to the parent runner's configured model. */\n model?: SubagentModelSpec;\n /** Tool names explicitly granted to the subagent. Defaults to no tools. */\n tools?: string[];\n /** Tool names that must each be invoked at least once before completion. */\n requiredTools?: string[];\n /** Per-profile thinking override. */\n thinkingLevel?: ThinkingLevel;\n /** When present, the final response must be JSON matching this schema. */\n outputSchema?: TOutputSchema;\n budget?: SubagentRunBudget;\n signal?: AbortSignal;\n}\n\nexport type SubagentRunOutput<TSchemaOrUndefined extends TSchema | undefined> =\n TSchemaOrUndefined extends TSchema ? Static<TSchemaOrUndefined> : string;\n\ninterface SubagentRunMetadata {\n runId: string;\n /** Raw final assistant text, including when structured validation failed. */\n text?: string;\n model: SubagentModelSpec;\n turns: number;\n toolCalls: number;\n toolCallCounts: Record<string, number>;\n /** Full token and cost breakdown across the run. */\n usage: SubagentUsage;\n /** Aggregate token count; equivalent to `usage.totalTokens`. */\n tokens: number;\n /** Aggregate provider cost; equivalent to `usage.cost.total`. */\n costUsd: number;\n durationMs: number;\n /**\n * The caller received a terminal result before the underlying run settled.\n * When true, `usage`, `tokens`, and `costUsd` are provisional snapshots;\n * final usage is delivered later through the run's bound usage sink. The\n * global slot remains held until cleanup settles because in-process work\n * cannot be safely reclaimed without a killable execution boundary.\n */\n cleanupPending?: boolean;\n}\n\ninterface SubagentRunCompletedResult<TOutput> extends SubagentRunMetadata {\n status: \"completed\";\n output: TOutput;\n error?: never;\n}\n\ninterface SubagentRunIncompleteResult extends SubagentRunMetadata {\n status: Exclude<SubagentRunStatus, \"completed\">;\n output?: never;\n error?: string;\n}\n\nexport type SubagentRunResult<TOutput = string> =\n | SubagentRunCompletedResult<TOutput>\n | SubagentRunIncompleteResult;\n\n/**\n * Compatibility header view synthesized from the v4 file header for callers\n * that read mikan session lineage. `metadata` carries mikan header extras (for\n * example `parentSessionPath` and the legacy `source` marker preserved by\n * the v3 migration).\n */\nexport interface SessionHeader {\n type: \"session\";\n version?: number;\n id: string;\n timestamp: string;\n cwd: string;\n parentSession?: string;\n parentSessionId?: string;\n [extra: string]: unknown;\n}\n\nexport interface CreateMikanModelsOptions {\n modelsJsonPath?: string;\n}\n\nexport type EventConversationKind = \"direct\" | \"shared\";\n\nexport type EventType = \"immediate\" | \"one-shot\" | \"periodic\";\n\ninterface EventPayloadBase {\n /** Target platform; may be omitted when only one platform is running. */\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n /** Self-contained task text; event runs do not inherit conversation history. */\n text: string;\n}\n\nexport interface ImmediateEventPayload extends EventPayloadBase {\n type: \"immediate\";\n}\n\nexport interface OneShotEventPayload extends EventPayloadBase {\n type: \"one-shot\";\n /** ISO 8601 timestamp with offset. */\n at: string;\n}\n\nexport interface PeriodicEventPayload extends EventPayloadBase {\n type: \"periodic\";\n /** Cron expression (croner syntax). */\n schedule: string;\n /** IANA timezone, e.g. \"Asia/Taipei\". */\n timezone: string;\n}\n\n/** Wire shape of one event file. */\nexport type EventFilePayload = ImmediateEventPayload | OneShotEventPayload | PeriodicEventPayload;\n\nexport interface EventPayloadInput {\n type: EventType;\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n text: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n}\n\n/** A loaded skill. `baseDir` is the directory containing the skill file. */\nexport interface MikanSkill {\n name: string;\n description: string;\n /** Full skill instructions (file content without frontmatter). */\n content: string;\n filePath: string;\n baseDir: string;\n /** Where the skill was loaded from (e.g. \"workspace\", \"channel\"). */\n source: string;\n /** Exclude from model-visible skill lists. */\n disableModelInvocation?: boolean;\n /** Embed the skill body in the prompt instead of referencing its file path. */\n inline?: boolean;\n}\n\nexport interface SkillDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n /** Set when the entry was skipped because it is a symlink on a rejecting load. */\n code?: \"symlink\";\n}\n\nexport interface LoadSkillsResult {\n skills: MikanSkill[];\n diagnostics: SkillDiagnostic[];\n}\n\nexport type RetrySettings = RetryPolicy;\n\nexport interface BudgetSettings {\n /** Max cumulative tokens processed this run (input + output + cache read/write). */\n maxTokens?: number;\n /** Max cumulative provider cost (USD) this run. Requires a populated model cost table. */\n maxCostUsd?: number;\n /** Max wall-clock duration for the run, in milliseconds. */\n maxDurationMs?: number;\n /** Max number of LLM calls (assistant turns) this run. */\n maxLlmCalls?: number;\n}\n\nexport interface HarnessSettings {\n compaction: CompactionSettings;\n retry: RetrySettings;\n budget: BudgetSettings;\n}\n\nexport interface SubagentProfileDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n}\n\nexport interface LoadSubagentProfilesResult {\n profiles: Map<string, SubagentProfile>;\n diagnostics: SubagentProfileDiagnostic[];\n}\n\nexport type CompactionReason = \"threshold\" | \"overflow\" | \"manual\";\n\ninterface CompactionResultSummary {\n summary: string;\n /** Number of recent messages retained inline on the compaction entry. */\n retainedMessages: number;\n tokensBefore: number;\n}\n\nexport type HarnessEvent =\n | AgentEvent\n | { type: \"compaction_start\"; reason: CompactionReason }\n | {\n type: \"compaction_end\";\n reason: CompactionReason;\n result?: CompactionResultSummary;\n aborted: boolean;\n errorMessage?: string;\n }\n | {\n type: \"auto_retry_start\";\n attempt: number;\n maxAttempts: number;\n delayMs: number;\n errorMessage: string;\n }\n | { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n | {\n type: \"budget_exceeded\";\n /** Which cap was hit, e.g. \"cost 2.01 USD > 2 USD limit\". */\n reason: string;\n tokens: number;\n costUsd: number;\n llmCalls: number;\n durationMs: number;\n };\n\nexport type HarnessEventListener = (event: HarnessEvent) => void | Promise<void>;\n\nexport interface MikanAgentSessionOptions {\n systemPrompt: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: AgentTool[];\n models: MikanModels;\n sessionStore: SessionStore;\n settings?: {\n compaction?: Partial<CompactionSettings>;\n retry?: Partial<RetrySettings>;\n budget?: Partial<BudgetSettings>;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAsCA,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC","sourcesContent":["/**\n * Core types for the mikan agent harness.\n *\n * The harness is built directly on pi-agent-core and pi-ai. Sessions use\n * pi's current v4 entry model and JSONL storage format. mikan-owned\n * metadata uses a namespaced durable value; legacy v3 and Pi 0.84 v4 files\n * are handled exclusively by the offline session migrations.\n */\nimport type {\n AgentEvent,\n AgentMessage,\n AgentTool,\n BranchSummaryEntry,\n CompactionEntry,\n CustomEntry,\n Entry,\n MessageEntry,\n ThinkingLevel,\n CompactionSettings,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model, RetryPolicy, Usage } from \"@earendil-works/pi-ai\";\nimport type { MikanModels } from \"./models.js\";\nimport type { SessionStore } from \"./session-store.js\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\nexport type { BranchSummaryEntry, CompactionEntry, CustomEntry };\n\n/** Model-visible messages reconstructed from the active session branch. */\nexport interface SessionContext {\n messages: AgentMessage[];\n}\n\n/** Message entry as stored in mikan session files (pi v4). */\nexport type SessionMessageEntry = MessageEntry;\n\n/** Union of entry types mikan reads and writes. Alias of pi's v4 entry. */\nexport type SessionEntry = Entry;\n\nexport const CURRENT_SESSION_VERSION = 4;\n\nexport interface SessionCreateInfo {\n id?: string;\n parentSession?: string;\n parentSessionId?: string;\n}\n\n/** Immutable session queries available to portals, admin, and migration code. */\nexport interface SessionInspection {\n getHeader(): SessionHeader;\n getEntries(): Promise<Entry[]>;\n getSessionName(): Promise<string | undefined>;\n getBranch(fromId?: string): Promise<Entry[]>;\n buildSessionContext(): Promise<SessionContext>;\n}\n\nexport interface SubagentModelSpec {\n provider: string;\n id: string;\n}\n\n/**\n * A curated capability set a subagent can be launched with. Built-ins ship\n * with the harness; `<workspaceDir>/agents/<name>.md` patches them per\n * installation. Turn, cost, and duration fields are caps — an explicit\n * `request.budget` may tighten them but never raise them. Token budgets use the\n * larger of the profile default and the request value.\n */\nexport interface SubagentProfile {\n name: string;\n description: string;\n systemPrompt: string;\n tools: string[];\n model?: SubagentModelSpec;\n thinkingLevel?: ThinkingLevel;\n maxTurns?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n maxDurationMs?: number;\n}\n\nexport interface SubagentRunBudget {\n /** Maximum assistant/model calls in the subagent run. */\n maxTurns?: number;\n /** Maximum cumulative input/output/cache tokens. */\n maxTokens?: number;\n /** Maximum provider cost in USD. */\n maxCostUsd?: number;\n /** Maximum wall-clock duration. */\n maxDurationMs?: number;\n}\n\nexport type SubagentRunStatus =\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"timeout\"\n | \"budget_exceeded\"\n | \"invalid_output\";\n\nexport interface SubagentParentContext {\n mode: \"normalized\";\n /** Number of recent user/assistant turns to include. Defaults to 3. */\n recentTurns?: number;\n}\n\n/** Aggregated model usage across every assistant turn in a subagent run. */\nexport type SubagentUsage = Usage;\n\n/** Receives usage from a subagent run, including after detached cleanup settles. */\nexport type SubagentUsageSink = (usage: SubagentUsage) => void | Promise<void>;\n\n/** A fresh, isolated subagent run. */\nexport interface SubagentRunRequest<TOutputSchema extends TSchema | undefined = undefined> {\n task: string;\n /** Named profile: a harness built-in, patched by `<workspaceDir>/agents/<name>.md`. */\n profile?: string;\n /** Opt in to a normalized textual snapshot of the active parent run. Defaults to fresh. */\n parentContext?: SubagentParentContext;\n systemPrompt?: string;\n /** JSON-serializable input appended to the task. */\n input?: unknown;\n /** Defaults to the parent runner's configured model. */\n model?: SubagentModelSpec;\n /** Tool names explicitly granted to the subagent. Defaults to no tools. */\n tools?: string[];\n /** Per-profile thinking override. */\n thinkingLevel?: ThinkingLevel;\n /** When present, the final response must be JSON matching this schema. */\n outputSchema?: TOutputSchema;\n budget?: SubagentRunBudget;\n signal?: AbortSignal;\n}\n\nexport type SubagentRunOutput<TSchemaOrUndefined extends TSchema | undefined> =\n TSchemaOrUndefined extends TSchema ? Static<TSchemaOrUndefined> : string;\n\ninterface SubagentRunMetadata {\n runId: string;\n /** Raw final assistant text, including when structured validation failed. */\n text?: string;\n model: SubagentModelSpec;\n turns: number;\n toolCalls: number;\n toolCallCounts: Record<string, number>;\n /** Full token and cost breakdown across the run. */\n usage: SubagentUsage;\n /** Aggregate token count; equivalent to `usage.totalTokens`. */\n tokens: number;\n /** Aggregate provider cost; equivalent to `usage.cost.total`. */\n costUsd: number;\n durationMs: number;\n /**\n * The caller received a terminal result before the underlying run settled.\n * When true, `usage`, `tokens`, and `costUsd` are provisional snapshots;\n * final usage is delivered later through the run's bound usage sink. The\n * global slot remains held until cleanup settles because in-process work\n * cannot be safely reclaimed without a killable execution boundary.\n */\n cleanupPending?: boolean;\n}\n\ninterface SubagentRunCompletedResult<TOutput> extends SubagentRunMetadata {\n status: \"completed\";\n output: TOutput;\n error?: never;\n}\n\ninterface SubagentRunIncompleteResult extends SubagentRunMetadata {\n status: Exclude<SubagentRunStatus, \"completed\">;\n output?: never;\n error?: string;\n}\n\nexport type SubagentRunResult<TOutput = string> =\n | SubagentRunCompletedResult<TOutput>\n | SubagentRunIncompleteResult;\n\n/**\n * Compatibility header view synthesized from the v4 file header for callers\n * that read mikan session lineage. `metadata` carries mikan header extras (for\n * example `parentSessionPath` and the legacy `source` marker preserved by\n * the v3 migration).\n */\nexport interface SessionHeader {\n type: \"session\";\n version?: number;\n id: string;\n timestamp: string;\n cwd: string;\n parentSession?: string;\n parentSessionId?: string;\n [extra: string]: unknown;\n}\n\nexport interface CreateMikanModelsOptions {\n modelsJsonPath?: string;\n}\n\nexport type EventConversationKind = \"direct\" | \"shared\";\n\nexport type EventType = \"immediate\" | \"one-shot\" | \"periodic\";\n\ninterface EventPayloadBase {\n /** Target platform; may be omitted when only one platform is running. */\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n /** Self-contained task text; event runs do not inherit conversation history. */\n text: string;\n}\n\nexport interface ImmediateEventPayload extends EventPayloadBase {\n type: \"immediate\";\n}\n\nexport interface OneShotEventPayload extends EventPayloadBase {\n type: \"one-shot\";\n /** ISO 8601 timestamp with offset. */\n at: string;\n}\n\nexport interface PeriodicEventPayload extends EventPayloadBase {\n type: \"periodic\";\n /** Cron expression (croner syntax). */\n schedule: string;\n /** IANA timezone, e.g. \"Asia/Taipei\". */\n timezone: string;\n}\n\n/** Wire shape of one event file. */\nexport type EventFilePayload = ImmediateEventPayload | OneShotEventPayload | PeriodicEventPayload;\n\nexport interface EventPayloadInput {\n type: EventType;\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n text: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n}\n\n/** A loaded skill. `baseDir` is the directory containing the skill file. */\nexport interface MikanSkill {\n name: string;\n description: string;\n /** Full skill instructions (file content without frontmatter). */\n content: string;\n filePath: string;\n baseDir: string;\n /** Where the skill was loaded from (e.g. \"workspace\", \"channel\"). */\n source: string;\n /** Exclude from model-visible skill lists. */\n disableModelInvocation?: boolean;\n /** Embed the skill body in the prompt instead of referencing its file path. */\n inline?: boolean;\n}\n\nexport interface SkillDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n /** Set when the entry was skipped because it is a symlink on a rejecting load. */\n code?: \"symlink\";\n}\n\nexport interface LoadSkillsResult {\n skills: MikanSkill[];\n diagnostics: SkillDiagnostic[];\n}\n\nexport type RetrySettings = RetryPolicy;\n\nexport interface BudgetSettings {\n /** Max cumulative tokens processed this run (input + output + cache read/write). */\n maxTokens?: number;\n /** Max cumulative provider cost (USD) this run. Requires a populated model cost table. */\n maxCostUsd?: number;\n /** Max wall-clock duration for the run, in milliseconds. */\n maxDurationMs?: number;\n /** Max number of LLM calls (assistant turns) this run. */\n maxLlmCalls?: number;\n}\n\nexport interface HarnessSettings {\n compaction: CompactionSettings;\n retry: RetrySettings;\n budget: BudgetSettings;\n}\n\nexport interface SubagentProfileDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n}\n\nexport interface LoadSubagentProfilesResult {\n profiles: Map<string, SubagentProfile>;\n diagnostics: SubagentProfileDiagnostic[];\n}\n\nexport type CompactionReason = \"threshold\" | \"overflow\" | \"manual\";\n\ninterface CompactionResultSummary {\n summary: string;\n /** Number of recent messages retained inline on the compaction entry. */\n retainedMessages: number;\n tokensBefore: number;\n}\n\nexport type HarnessEvent =\n | AgentEvent\n | { type: \"compaction_start\"; reason: CompactionReason }\n | {\n type: \"compaction_end\";\n reason: CompactionReason;\n result?: CompactionResultSummary;\n aborted: boolean;\n errorMessage?: string;\n }\n | {\n type: \"auto_retry_start\";\n attempt: number;\n maxAttempts: number;\n delayMs: number;\n errorMessage: string;\n }\n | { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n | {\n type: \"budget_exceeded\";\n /** Which cap was hit, e.g. \"cost 2.01 USD > 2 USD limit\". */\n reason: string;\n tokens: number;\n costUsd: number;\n llmCalls: number;\n durationMs: number;\n };\n\nexport type HarnessEventListener = (event: HarnessEvent) => void | Promise<void>;\n\nexport interface MikanAgentSessionOptions {\n systemPrompt: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: AgentTool[];\n models: MikanModels;\n sessionStore: SessionStore;\n settings?: {\n compaction?: Partial<CompactionSettings>;\n retry?: Partial<RetrySettings>;\n budget?: Partial<BudgetSettings>;\n };\n}\n"]}
|