@geminixiang/mikan 1.0.0-beta.50 → 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 +18 -0
- package/dist/harness/runner.d.ts.map +1 -1
- package/dist/harness/runner.js +3 -3
- package/dist/harness/runner.js.map +1 -1
- package/dist/harness/session-store.d.ts.map +1 -1
- package/dist/harness/session-store.js +10 -7
- package/dist/harness/session-store.js.map +1 -1
- package/dist/harness/subagent-profiles.d.ts.map +1 -1
- package/dist/harness/subagent-profiles.js +0 -15
- 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 -39
- 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
|
@@ -32,7 +32,6 @@ const BUILTIN_PROFILES = [
|
|
|
32
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.",
|
|
33
33
|
].join("\n"),
|
|
34
34
|
tools: ["read", "bash", "edit", "write"],
|
|
35
|
-
requiredTools: ["read", "bash"],
|
|
36
35
|
thinkingLevel: "high",
|
|
37
36
|
maxTurns: 30,
|
|
38
37
|
maxTokens: 100_000,
|
|
@@ -48,7 +47,6 @@ const BUILTIN_PROFILES = [
|
|
|
48
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.",
|
|
49
48
|
].join("\n"),
|
|
50
49
|
tools: ["read", "bash", "edit", "write"],
|
|
51
|
-
requiredTools: ["read", "bash"],
|
|
52
50
|
thinkingLevel: "high",
|
|
53
51
|
maxTurns: 35,
|
|
54
52
|
maxTokens: 100_000,
|
|
@@ -64,7 +62,6 @@ const BUILTIN_PROFILES = [
|
|
|
64
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.",
|
|
65
63
|
].join("\n"),
|
|
66
64
|
tools: ["read", "bash", "edit", "write", "event", "sandbox"],
|
|
67
|
-
requiredTools: ["read", "bash", "sandbox"],
|
|
68
65
|
thinkingLevel: "high",
|
|
69
66
|
maxTurns: 40,
|
|
70
67
|
maxTokens: 100_000,
|
|
@@ -80,7 +77,6 @@ const BUILTIN_PROFILES = [
|
|
|
80
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.",
|
|
81
78
|
].join("\n"),
|
|
82
79
|
tools: ["read", "bash", "write"],
|
|
83
|
-
requiredTools: ["read", "bash"],
|
|
84
80
|
thinkingLevel: "high",
|
|
85
81
|
maxTurns: 35,
|
|
86
82
|
maxTokens: 100_000,
|
|
@@ -96,7 +92,6 @@ const BUILTIN_PROFILES = [
|
|
|
96
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.",
|
|
97
93
|
].join("\n"),
|
|
98
94
|
tools: ["read", "bash", "write", "event"],
|
|
99
|
-
requiredTools: ["read", "bash"],
|
|
100
95
|
thinkingLevel: "high",
|
|
101
96
|
maxTurns: 30,
|
|
102
97
|
maxTokens: 100_000,
|
|
@@ -112,7 +107,6 @@ const BUILTIN_PROFILES = [
|
|
|
112
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.",
|
|
113
108
|
].join("\n"),
|
|
114
109
|
tools: ["read", "bash", "write"],
|
|
115
|
-
requiredTools: ["read", "bash"],
|
|
116
110
|
thinkingLevel: "high",
|
|
117
111
|
maxTurns: 30,
|
|
118
112
|
maxTokens: 100_000,
|
|
@@ -128,7 +122,6 @@ const BUILTIN_PROFILES = [
|
|
|
128
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.",
|
|
129
123
|
].join("\n"),
|
|
130
124
|
tools: ["read", "bash", "write"],
|
|
131
|
-
requiredTools: ["read", "bash", "write"],
|
|
132
125
|
thinkingLevel: "high",
|
|
133
126
|
maxTurns: 40,
|
|
134
127
|
maxTokens: 100_000,
|
|
@@ -144,7 +137,6 @@ const BUILTIN_PROFILES = [
|
|
|
144
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.",
|
|
145
138
|
].join("\n"),
|
|
146
139
|
tools: ["read", "bash", "write"],
|
|
147
|
-
requiredTools: ["read", "bash"],
|
|
148
140
|
thinkingLevel: "high",
|
|
149
141
|
maxTurns: 35,
|
|
150
142
|
maxTokens: 100_000,
|
|
@@ -158,7 +150,6 @@ const BUILTIN_PROFILES = [
|
|
|
158
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.",
|
|
159
151
|
].join("\n"),
|
|
160
152
|
tools: [],
|
|
161
|
-
requiredTools: [],
|
|
162
153
|
thinkingLevel: "high",
|
|
163
154
|
maxTurns: 20,
|
|
164
155
|
maxTokens: 100_000,
|
|
@@ -227,7 +218,6 @@ function parseProfilePatch(filePath, base) {
|
|
|
227
218
|
const patch = {};
|
|
228
219
|
applyField(patch, values, "description", "description", (value) => value.trim());
|
|
229
220
|
applyField(patch, values, "tools", "tools", csv);
|
|
230
|
-
applyField(patch, values, "required_tools", "requiredTools", csv);
|
|
231
221
|
applyField(patch, values, "model", "model", parseModel);
|
|
232
222
|
applyField(patch, values, "thinking", "thinkingLevel", parseThinking);
|
|
233
223
|
applyField(patch, values, "max_turns", "maxTurns", (v) => parsePositiveInteger(v, "max_turns"));
|
|
@@ -248,12 +238,7 @@ function parseProfilePatch(filePath, base) {
|
|
|
248
238
|
description: patch.description || base?.description || name,
|
|
249
239
|
systemPrompt,
|
|
250
240
|
tools: patch.tools ?? base?.tools ?? [],
|
|
251
|
-
requiredTools: patch.requiredTools ?? base?.requiredTools ?? [],
|
|
252
241
|
};
|
|
253
|
-
const ungranted = merged.requiredTools.filter((tool) => !merged.tools.includes(tool));
|
|
254
|
-
if (ungranted.length > 0) {
|
|
255
|
-
throw new Error(`required_tools must be included in tools: ${ungranted.join(", ")}`);
|
|
256
|
-
}
|
|
257
242
|
return merged;
|
|
258
243
|
}
|
|
259
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,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,CAAC,MAAM,EAAE,MAAM,CAAC;QAC/B,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;QACZ,SAAS,EAAE,OAAO;KACnB;IACD;QACE,IAAI,EAAE,mBAAmB;QACzB,WAAW,EACT,sFAAsF;QACxF,YAAY,EAAE;YACZ,gFAAgF;YAChF,EAAE;YACF,iaA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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\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: [\"read\", \"bash\"],\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: [\"read\", \"bash\"],\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: [\"read\", \"bash\", \"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 requiredTools: [\"read\", \"bash\"],\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: [\"read\", \"bash\"],\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: [\"read\", \"bash\"],\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: [\"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 requiredTools: [\"read\", \"bash\"],\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,EAAE;Q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AS;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;AAEpB,O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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,7 +446,6 @@ function resolveProfile(request, options) {
|
|
|
468
446
|
...request,
|
|
469
447
|
systemPrompt: profile.systemPrompt,
|
|
470
448
|
tools: profile.tools,
|
|
471
|
-
requiredTools: profile.requiredTools,
|
|
472
449
|
...(profile.model ? { model: profile.model } : {}),
|
|
473
450
|
...(profile.thinkingLevel ? { thinkingLevel: profile.thinkingLevel } : {}),
|
|
474
451
|
...(Object.keys(budget).length > 0 ? { budget } : {}),
|
|
@@ -478,18 +455,13 @@ function prepareSubagentRun(options, request, runId, startedAt) {
|
|
|
478
455
|
const model = request.model
|
|
479
456
|
? options.models.resolve(request.model.provider, request.model.id)
|
|
480
457
|
: options.defaultModel;
|
|
481
|
-
const invokedTools = new Set();
|
|
482
458
|
const granted = selectTools(request.tools, options.availableTools);
|
|
483
|
-
const missingRequiredTools = (request.requiredTools ?? []).filter((name) => !granted.some((tool) => tool.name === name));
|
|
484
|
-
if (missingRequiredTools.length > 0) {
|
|
485
|
-
throw new Error(`Required subagent tools were not granted: ${missingRequiredTools.join(", ")}`);
|
|
486
|
-
}
|
|
487
459
|
const task = formatTask(request.task, request.input, normalizedParentContext(request, options.parentMessages));
|
|
488
460
|
const session = new MikanAgentSession({
|
|
489
461
|
systemPrompt: buildSystemPrompt(request.systemPrompt, request.outputSchema, granted.map((tool) => tool.name)),
|
|
490
462
|
model,
|
|
491
463
|
thinkingLevel: request.thinkingLevel ?? options.thinkingLevel,
|
|
492
|
-
tools: granted
|
|
464
|
+
tools: granted,
|
|
493
465
|
models: options.models,
|
|
494
466
|
sessionStore: SessionStore.inMemory(options.workspaceDir),
|
|
495
467
|
settings: { compaction: { enabled: false } },
|
|
@@ -503,12 +475,11 @@ function prepareSubagentRun(options, request, runId, startedAt) {
|
|
|
503
475
|
modelSpec: { provider: model.provider, id: model.id },
|
|
504
476
|
session,
|
|
505
477
|
budget: resolveBudget(request.budget),
|
|
506
|
-
invokedTools,
|
|
507
478
|
task,
|
|
508
479
|
};
|
|
509
480
|
}
|
|
510
481
|
function buildSubagentResult(run, terminalSignal, cleanupPending = false) {
|
|
511
|
-
const { session, request,
|
|
482
|
+
const { session, request, budget } = run;
|
|
512
483
|
const stats = session.getLastRunStats();
|
|
513
484
|
const assistant = finalAssistant(session.messages);
|
|
514
485
|
const text = assistant ? contentText(assistant.content, "") : "";
|
|
@@ -529,14 +500,6 @@ function buildSubagentResult(run, terminalSignal, cleanupPending = false) {
|
|
|
529
500
|
if (stats.budgetExceededReason) {
|
|
530
501
|
return { ...base, status: "budget_exceeded", error: stats.budgetExceededReason };
|
|
531
502
|
}
|
|
532
|
-
const unusedRequiredTools = (request.requiredTools ?? []).filter((name) => !invokedTools.has(name));
|
|
533
|
-
if (unusedRequiredTools.length > 0) {
|
|
534
|
-
return {
|
|
535
|
-
...base,
|
|
536
|
-
status: "failed",
|
|
537
|
-
error: `Required tool not used: ${unusedRequiredTools.join(", ")}`,
|
|
538
|
-
};
|
|
539
|
-
}
|
|
540
503
|
if (assistant?.stopReason === "error") {
|
|
541
504
|
return { ...base, status: "failed", error: assistant.errorMessage || "Subagent failed" };
|
|
542
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,MAAM,sBAAsB,GAAG,IAAI,GAAG,CAAC;IACrC,MAAM;IACN,YAAY;IACZ,UAAU;IACV,OAAO;IACP,MAAM;IACN,OAAO;IACP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E,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 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,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,qBAA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,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. */
|