@geminixiang/mikan 1.0.0-beta.32 → 1.0.0-beta.33
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 +14 -0
- package/dist/harness/subagent-profiles.d.ts.map +1 -1
- package/dist/harness/subagent-profiles.js +9 -0
- package/dist/harness/subagent-profiles.js.map +1 -1
- package/dist/harness/subagent-runner.js +6 -4
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/harness/types.d.ts +3 -2
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/observability/sentry.d.ts +2 -0
- package/dist/observability/sentry.d.ts.map +1 -1
- package/dist/observability/sentry.js +7 -0
- package/dist/observability/sentry.js.map +1 -1
- package/dist/tools/subagent.d.ts.map +1 -1
- package/dist/tools/subagent.js +6 -3
- package/dist/tools/subagent.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,20 @@ any release.
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [1.0.0-beta.33]
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- Give every built-in subagent profile a 100,000-token allowance and honor larger token budgets requested by the parent model.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- Disable Sentry's faulty OpenAI integration to prevent instrumentation failures in model-provider requests.
|
|
21
|
+
|
|
22
|
+
### Tests
|
|
23
|
+
|
|
24
|
+
- Add regression coverage for subagent profile token defaults, model-requested increases, tool schema behavior, and disabled OpenAI instrumentation.
|
|
25
|
+
|
|
12
26
|
## [1.0.0-beta.32]
|
|
13
27
|
|
|
14
28
|
### Changed
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-profiles.d.ts","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EACV,0BAA0B,EAI3B,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"subagent-profiles.d.ts","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EACV,0BAA0B,EAI3B,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AA8QxF;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,0BAA0B,CAiCrF"}
|
|
@@ -35,6 +35,7 @@ const BUILTIN_PROFILES = [
|
|
|
35
35
|
requiredTools: ["read", "bash"],
|
|
36
36
|
thinkingLevel: "high",
|
|
37
37
|
maxTurns: 30,
|
|
38
|
+
maxTokens: 100_000,
|
|
38
39
|
},
|
|
39
40
|
{
|
|
40
41
|
name: "software-engineer",
|
|
@@ -50,6 +51,7 @@ const BUILTIN_PROFILES = [
|
|
|
50
51
|
requiredTools: ["read", "bash"],
|
|
51
52
|
thinkingLevel: "high",
|
|
52
53
|
maxTurns: 35,
|
|
54
|
+
maxTokens: 100_000,
|
|
53
55
|
},
|
|
54
56
|
{
|
|
55
57
|
name: "devops-engineer",
|
|
@@ -65,6 +67,7 @@ const BUILTIN_PROFILES = [
|
|
|
65
67
|
requiredTools: ["read", "bash", "sandbox"],
|
|
66
68
|
thinkingLevel: "high",
|
|
67
69
|
maxTurns: 40,
|
|
70
|
+
maxTokens: 100_000,
|
|
68
71
|
},
|
|
69
72
|
{
|
|
70
73
|
name: "data-scientist",
|
|
@@ -80,6 +83,7 @@ const BUILTIN_PROFILES = [
|
|
|
80
83
|
requiredTools: ["read", "bash"],
|
|
81
84
|
thinkingLevel: "high",
|
|
82
85
|
maxTurns: 35,
|
|
86
|
+
maxTokens: 100_000,
|
|
83
87
|
},
|
|
84
88
|
{
|
|
85
89
|
name: "account-manager",
|
|
@@ -95,6 +99,7 @@ const BUILTIN_PROFILES = [
|
|
|
95
99
|
requiredTools: ["read", "bash"],
|
|
96
100
|
thinkingLevel: "high",
|
|
97
101
|
maxTurns: 30,
|
|
102
|
+
maxTokens: 100_000,
|
|
98
103
|
},
|
|
99
104
|
{
|
|
100
105
|
name: "business-development",
|
|
@@ -110,6 +115,7 @@ const BUILTIN_PROFILES = [
|
|
|
110
115
|
requiredTools: ["read", "bash"],
|
|
111
116
|
thinkingLevel: "high",
|
|
112
117
|
maxTurns: 30,
|
|
118
|
+
maxTokens: 100_000,
|
|
113
119
|
},
|
|
114
120
|
{
|
|
115
121
|
name: "creative-producer",
|
|
@@ -125,6 +131,7 @@ const BUILTIN_PROFILES = [
|
|
|
125
131
|
requiredTools: ["read", "bash", "write"],
|
|
126
132
|
thinkingLevel: "high",
|
|
127
133
|
maxTurns: 40,
|
|
134
|
+
maxTokens: 100_000,
|
|
128
135
|
},
|
|
129
136
|
{
|
|
130
137
|
name: "ad-operations-specialist",
|
|
@@ -140,6 +147,7 @@ const BUILTIN_PROFILES = [
|
|
|
140
147
|
requiredTools: ["read", "bash"],
|
|
141
148
|
thinkingLevel: "high",
|
|
142
149
|
maxTurns: 35,
|
|
150
|
+
maxTokens: 100_000,
|
|
143
151
|
},
|
|
144
152
|
{
|
|
145
153
|
name: "analysis-only",
|
|
@@ -153,6 +161,7 @@ const BUILTIN_PROFILES = [
|
|
|
153
161
|
requiredTools: [],
|
|
154
162
|
thinkingLevel: "high",
|
|
155
163
|
maxTurns: 20,
|
|
164
|
+
maxTokens: 100_000,
|
|
156
165
|
},
|
|
157
166
|
];
|
|
158
167
|
const THINKING_LEVELS = new Set([
|
|
@@ -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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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 \"fs\";\nimport { basename, join } from \"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 },\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 },\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 },\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 },\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 },\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 },\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 },\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 },\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 },\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,IAAI,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAUtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,gBAAgB,GAAsB;IAC1C;QACE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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 \"fs\";\nimport { basename, join } from \"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"]}
|
|
@@ -382,8 +382,10 @@ async function executeBoundedSubagentRun(options) {
|
|
|
382
382
|
}
|
|
383
383
|
function noop() { }
|
|
384
384
|
/**
|
|
385
|
-
* Expand `request.profile` into the concrete capability set it names.
|
|
386
|
-
* budgets are caps
|
|
385
|
+
* Expand `request.profile` into the concrete capability set it names. Most
|
|
386
|
+
* profile budgets are caps that callers may only tighten. Token budgets are
|
|
387
|
+
* different: the effective allowance is the larger of the profile default and
|
|
388
|
+
* the caller's request.
|
|
387
389
|
*/
|
|
388
390
|
function resolveProfile(request, options) {
|
|
389
391
|
if (!request.profile)
|
|
@@ -401,8 +403,8 @@ function resolveProfile(request, options) {
|
|
|
401
403
|
...(profile.maxTurns !== undefined
|
|
402
404
|
? { maxTurns: Math.min(profile.maxTurns, request.budget?.maxTurns ?? profile.maxTurns) }
|
|
403
405
|
: {}),
|
|
404
|
-
...(profile.maxTokens !== undefined
|
|
405
|
-
? { maxTokens: Math.
|
|
406
|
+
...(profile.maxTokens !== undefined || request.budget?.maxTokens !== undefined
|
|
407
|
+
? { maxTokens: Math.max(profile.maxTokens ?? 0, request.budget?.maxTokens ?? 0) }
|
|
406
408
|
: {}),
|
|
407
409
|
...(profile.maxCostUsd !== undefined
|
|
408
410
|
? {
|
|
@@ -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;AAGrD,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,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAyB,MAAM,4BAA4B,CAAC;AAEtF,MAAM,gBAAgB,GAAG,IAAI,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,YAAY,CAAC,UAAU,CAAC,CAAC;oBACzC,OAAO,YAAY,CAAC;gBACtB,CAAC,CAAC;aACH,CAAC,CAAC;YACH,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC9B,MAAM,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,EAAE,CACpD,cAAc,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,kBAAkB,CAAC,cAAc,CAAC,KAAK,CAAC,CAC7E,CAAC;gBACF,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC;YAChD,CAAC;YACD,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE;gBAAE,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC;QACrD,CAAC;QAED,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,CAAC;IACnC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO;YACL,MAAM,EAAE;gBACN,GAAG,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,CAAC;gBAC5E,MAAM,EAAE,cAAc,IAAI,QAAQ;gBAClC,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;aACxD;SACF,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 type { Api, AssistantMessage, 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 { copySubagentUsage, createEmptySubagentUsage } from \"./usage.js\";\nimport { unboundedSlotPool, type SubagentSlotPool } from \"../tools/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 tool and extension invocations. */\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\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 if (typeof message.content === \"string\") return message.content;\n if (!Array.isArray(message.content)) return \"\";\n return message.content\n .filter(\n (part): part is { type: \"text\"; text: string } =>\n typeof part === \"object\" && part !== null && part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\");\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 ?? createEmptySubagentUsage();\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\nfunction assistantText(message: AssistantMessage | undefined): string {\n if (!message) return \"\";\n return message.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\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?.(copySubagentUsage(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. Profile\n * budgets are caps: a caller can tighten them but never raise them.\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\n ? { maxTokens: Math.min(profile.maxTokens, request.budget?.maxTokens ?? profile.maxTokens) }\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\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 let modelSpec: SubagentModelSpec = request.model ?? {\n provider: options.defaultModel.provider,\n id: options.defaultModel.id,\n };\n let sessionRef: MikanAgentSession | undefined;\n let terminalSignal: \"cancelled\" | \"timeout\" | 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: \"cancelled\" | \"timeout\") => {\n if (terminalSignal) return;\n terminalSignal = reason;\n sessionRef?.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 const model = request.model\n ? options.models.resolve(request.model.provider, request.model.id)\n : options.defaultModel;\n modelSpec = { provider: model.provider, id: model.id };\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(\n `Required subagent tools were not granted: ${missingRequiredTools.join(\", \")}`,\n );\n }\n const tools = granted.map((tool) => witnessToolUse(tool, invokedTools));\n const task = formatTask(\n request.task,\n request.input,\n normalizedParentContext(request, options.parentMessages),\n );\n const budget = resolveBudget(request.budget);\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,\n models: options.models,\n sessionStore: SessionStore.inMemory(options.workspaceDir),\n settings: { compaction: { enabled: false } },\n });\n sessionRef = session;\n\n request.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (request.signal?.aborted) abort(\"cancelled\");\n timeout = setTimeout(() => abort(\"timeout\"), budget.maxDurationMs);\n timeout.unref();\n\n const buildResult = (\n cleanupPending = false,\n ): SubagentRunResult<SubagentRunOutput<TOutputSchema>> => {\n const stats = session.getLastRunStats();\n const assistant = finalAssistant(session.messages);\n const text = assistantText(assistant);\n const base = {\n ...baseRunResult(runId, modelSpec, 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 {\n ...base,\n status: \"budget_exceeded\",\n error: stats.budgetExceededReason,\n };\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 {\n ...base,\n status: \"failed\",\n error: assistant.errorMessage || \"Subagent failed\",\n };\n }\n if (!assistant) {\n return { ...base, status: \"failed\", error: \"Subagent produced no assistant response\" };\n }\n\n if (request.outputSchema) {\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\n if (!text) {\n return { ...base, status: \"failed\", error: \"Subagent produced no text output\" };\n }\n return {\n ...base,\n status: \"completed\",\n output: text as SubagentRunOutput<TOutputSchema>,\n };\n };\n const buildFailureResult = (\n err: unknown,\n ): SubagentRunResult<SubagentRunOutput<TOutputSchema>> => ({\n ...baseRunResult(runId, modelSpec, startedAt, session.getLastRunStats()),\n status: terminalSignal ?? \"failed\",\n error: err instanceof Error ? err.message : String(err),\n });\n\n if (!terminalSignal) {\n const promptOutcome = subagentRunDepth\n .run(1, () =>\n session.prompt(task, {\n budget: {\n maxLlmCalls: budget.maxTurns,\n maxTokens: budget.maxTokens,\n maxCostUsd: budget.maxCostUsd,\n maxDurationMs: budget.maxDurationMs,\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 graceOutcome = 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 graceOutcome;\n }),\n ]);\n if (winner.type === \"expired\") {\n const cleanup = promptOutcome.then((settledOutcome) =>\n settledOutcome.ok ? buildResult() : buildFailureResult(settledOutcome.error),\n );\n return { result: buildResult(true), cleanup };\n }\n if (!winner.outcome.ok) throw winner.outcome.error;\n }\n\n return { result: buildResult() };\n } catch (err) {\n return {\n result: {\n ...baseRunResult(runId, modelSpec, startedAt, sessionRef?.getLastRunStats()),\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;AAGrD,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,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C,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 type { Api, AssistantMessage, 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 { copySubagentUsage, createEmptySubagentUsage } from \"./usage.js\";\nimport { unboundedSlotPool, type SubagentSlotPool } from \"../tools/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 tool and extension invocations. */\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\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 if (typeof message.content === \"string\") return message.content;\n if (!Array.isArray(message.content)) return \"\";\n return message.content\n .filter(\n (part): part is { type: \"text\"; text: string } =>\n typeof part === \"object\" && part !== null && part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\");\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 ?? createEmptySubagentUsage();\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\nfunction assistantText(message: AssistantMessage | undefined): string {\n if (!message) return \"\";\n return message.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\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?.(copySubagentUsage(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\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 let modelSpec: SubagentModelSpec = request.model ?? {\n provider: options.defaultModel.provider,\n id: options.defaultModel.id,\n };\n let sessionRef: MikanAgentSession | undefined;\n let terminalSignal: \"cancelled\" | \"timeout\" | 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: \"cancelled\" | \"timeout\") => {\n if (terminalSignal) return;\n terminalSignal = reason;\n sessionRef?.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 const model = request.model\n ? options.models.resolve(request.model.provider, request.model.id)\n : options.defaultModel;\n modelSpec = { provider: model.provider, id: model.id };\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(\n `Required subagent tools were not granted: ${missingRequiredTools.join(\", \")}`,\n );\n }\n const tools = granted.map((tool) => witnessToolUse(tool, invokedTools));\n const task = formatTask(\n request.task,\n request.input,\n normalizedParentContext(request, options.parentMessages),\n );\n const budget = resolveBudget(request.budget);\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,\n models: options.models,\n sessionStore: SessionStore.inMemory(options.workspaceDir),\n settings: { compaction: { enabled: false } },\n });\n sessionRef = session;\n\n request.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (request.signal?.aborted) abort(\"cancelled\");\n timeout = setTimeout(() => abort(\"timeout\"), budget.maxDurationMs);\n timeout.unref();\n\n const buildResult = (\n cleanupPending = false,\n ): SubagentRunResult<SubagentRunOutput<TOutputSchema>> => {\n const stats = session.getLastRunStats();\n const assistant = finalAssistant(session.messages);\n const text = assistantText(assistant);\n const base = {\n ...baseRunResult(runId, modelSpec, 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 {\n ...base,\n status: \"budget_exceeded\",\n error: stats.budgetExceededReason,\n };\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 {\n ...base,\n status: \"failed\",\n error: assistant.errorMessage || \"Subagent failed\",\n };\n }\n if (!assistant) {\n return { ...base, status: \"failed\", error: \"Subagent produced no assistant response\" };\n }\n\n if (request.outputSchema) {\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\n if (!text) {\n return { ...base, status: \"failed\", error: \"Subagent produced no text output\" };\n }\n return {\n ...base,\n status: \"completed\",\n output: text as SubagentRunOutput<TOutputSchema>,\n };\n };\n const buildFailureResult = (\n err: unknown,\n ): SubagentRunResult<SubagentRunOutput<TOutputSchema>> => ({\n ...baseRunResult(runId, modelSpec, startedAt, session.getLastRunStats()),\n status: terminalSignal ?? \"failed\",\n error: err instanceof Error ? err.message : String(err),\n });\n\n if (!terminalSignal) {\n const promptOutcome = subagentRunDepth\n .run(1, () =>\n session.prompt(task, {\n budget: {\n maxLlmCalls: budget.maxTurns,\n maxTokens: budget.maxTokens,\n maxCostUsd: budget.maxCostUsd,\n maxDurationMs: budget.maxDurationMs,\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 graceOutcome = 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 graceOutcome;\n }),\n ]);\n if (winner.type === \"expired\") {\n const cleanup = promptOutcome.then((settledOutcome) =>\n settledOutcome.ok ? buildResult() : buildFailureResult(settledOutcome.error),\n );\n return { result: buildResult(true), cleanup };\n }\n if (!winner.outcome.ok) throw winner.outcome.error;\n }\n\n return { result: buildResult() };\n } catch (err) {\n return {\n result: {\n ...baseRunResult(runId, modelSpec, startedAt, sessionRef?.getLastRunStats()),\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
|
@@ -25,8 +25,9 @@ export interface SubagentModelSpec {
|
|
|
25
25
|
/**
|
|
26
26
|
* A curated capability set a subagent can be launched with. Built-ins ship
|
|
27
27
|
* with the harness; `<workspaceDir>/agents/<name>.md` patches them per
|
|
28
|
-
* installation.
|
|
29
|
-
* tighten them but never raise them.
|
|
28
|
+
* installation. Turn, cost, and duration fields are caps — an explicit
|
|
29
|
+
* `request.budget` may tighten them but never raise them. Token budgets use the
|
|
30
|
+
* larger of the profile default and the request value.
|
|
30
31
|
*/
|
|
31
32
|
export interface SubagentProfile {
|
|
32
33
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EACV,UAAU,EACV,SAAS,EACT,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EACb,kBAAkB,EACnB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEzD,YAAY,EACV,kBAAkB,EAClB,eAAe,EACf,WAAW,EACX,kBAAkB,EAClB,cAAc,EACd,gBAAgB,GACjB,CAAC;AAEF,sDAAsD;AACtD,MAAM,MAAM,mBAAmB,GAAG,YAAY,CAAC;AAE/C,wFAAwF;AACxF,MAAM,MAAM,YAAY,GAAG,gBAAgB,CAAC;AAE5C,eAAO,MAAM,uBAAuB,IAAI,CAAC;AAEzC,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;CACZ;A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IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,GAClF;IACE,IAAI,EAAE,iBAAiB,CAAC;IACxB,6DAA6D;IAC7D,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEN,MAAM,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAEjF,mFAAmF;AACnF,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,IAAI,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,wBAAwB;IACvC,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,aAAa,EAAE,aAAa,CAAC;IAC7B,KAAK,EAAE,SAAS,EAAE,CAAC;IACnB,MAAM,EAAE,WAAW,CAAC;IACpB,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,CAAC,EAAE;QACT,UAAU,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;QACzC,KAAK,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;QAC/B,MAAM,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;KAClC,CAAC;IACF,UAAU,CAAC,EAAE,iBAAiB,CAAC;CAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AA2CA,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC","sourcesContent":["/**\n * Core types for the mikan agent harness.\n *\n * The harness is built directly on pi-agent-core and pi-ai. Session entries\n * are structurally identical to pi-agent-core's `SessionTreeEntry`, and the\n * on-disk JSONL format stays compatible with the v3 session files mikan has\n * always written, so existing conversation history keeps working unchanged.\n */\nimport type {\n AgentEvent,\n AgentTool,\n BranchSummaryEntry,\n CompactionEntry,\n CustomEntry,\n CustomMessageEntry,\n MessageEntry,\n SessionContext,\n SessionInfoEntry,\n SessionTreeEntry,\n ThinkingLevel,\n CompactionSettings,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model, Usage } from \"@earendil-works/pi-ai\";\nimport type { ExtensionRegistry } from \"./extensions/registry.js\";\nimport type { MikanModels } from \"./models.js\";\nimport type { SessionStore } from \"./session-store.js\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\nexport type {\n BranchSummaryEntry,\n CompactionEntry,\n CustomEntry,\n CustomMessageEntry,\n SessionContext,\n SessionInfoEntry,\n};\n\n/** Message entry as stored in mikan session files. */\nexport type SessionMessageEntry = MessageEntry;\n\n/** Union of entry types mikan reads and writes. Alias of pi-agent-core's tree entry. */\nexport type SessionEntry = SessionTreeEntry;\n\nexport const CURRENT_SESSION_VERSION = 3;\n\nexport interface SubagentModelSpec {\n provider: string;\n id: string;\n}\n\n/**\n * A curated capability set a subagent can be launched with. Built-ins ship\n * with the harness; `<workspaceDir>/agents/<name>.md` patches them per\n * installation. Budget fields are caps — an explicit `request.budget` may\n * tighten them but never raise them.\n */\nexport interface SubagentProfile {\n name: string;\n description: string;\n systemPrompt: string;\n tools: string[];\n requiredTools: string[];\n model?: SubagentModelSpec;\n thinkingLevel?: ThinkingLevel;\n maxTurns?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n maxDurationMs?: number;\n}\n\nexport interface SubagentRunBudget {\n /** Maximum assistant/model calls in the subagent run. */\n maxTurns?: number;\n /** Maximum cumulative input/output/cache tokens. */\n maxTokens?: number;\n /** Maximum provider cost in USD. */\n maxCostUsd?: number;\n /** Maximum wall-clock duration. */\n maxDurationMs?: number;\n}\n\nexport type SubagentRunStatus =\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"timeout\"\n | \"budget_exceeded\"\n | \"invalid_output\";\n\nexport interface SubagentParentContext {\n mode: \"normalized\";\n /** Number of recent user/assistant turns to include. Defaults to 3. */\n recentTurns?: number;\n}\n\n/** Aggregated model usage across every assistant turn in a subagent run. */\nexport type SubagentUsage = Usage;\n\n/** Receives usage from a subagent run, including after detached cleanup settles. */\nexport type SubagentUsageSink = (usage: SubagentUsage) => void | Promise<void>;\n\n/** A fresh, isolated subagent run. */\nexport interface SubagentRunRequest<TOutputSchema extends TSchema | undefined = undefined> {\n task: string;\n /** Named profile: a harness built-in, patched by `<workspaceDir>/agents/<name>.md`. */\n profile?: string;\n /** Opt in to a normalized textual snapshot of the active parent run. Defaults to fresh. */\n parentContext?: SubagentParentContext;\n systemPrompt?: string;\n /** JSON-serializable input appended to the task. */\n input?: unknown;\n /** Defaults to the parent runner's configured model. */\n model?: SubagentModelSpec;\n /** Tool names explicitly granted to the subagent. Defaults to no tools. */\n tools?: string[];\n /** Tool names that must each be invoked at least once before completion. */\n requiredTools?: string[];\n /** Per-profile thinking override. */\n thinkingLevel?: ThinkingLevel;\n /** When present, the final response must be JSON matching this schema. */\n outputSchema?: TOutputSchema;\n budget?: SubagentRunBudget;\n signal?: AbortSignal;\n}\n\nexport type SubagentRunOutput<TSchemaOrUndefined extends TSchema | undefined> =\n TSchemaOrUndefined extends TSchema ? Static<TSchemaOrUndefined> : string;\n\ninterface SubagentRunMetadata {\n runId: string;\n /** Raw final assistant text, including when structured validation failed. */\n text?: string;\n model: SubagentModelSpec;\n turns: number;\n toolCalls: number;\n toolCallCounts: Record<string, number>;\n /** Full token and cost breakdown across the run. */\n usage: SubagentUsage;\n /** Aggregate token count; equivalent to `usage.totalTokens`. */\n tokens: number;\n /** Aggregate provider cost; equivalent to `usage.cost.total`. */\n costUsd: number;\n durationMs: number;\n /**\n * The caller received a terminal result before the underlying run settled.\n * When true, `usage`, `tokens`, and `costUsd` are provisional snapshots;\n * final usage is delivered later through the run's bound usage sink. The\n * global slot remains held until cleanup settles because in-process work\n * cannot be safely reclaimed without a killable execution boundary.\n */\n cleanupPending?: boolean;\n}\n\ninterface SubagentRunCompletedResult<TOutput> extends SubagentRunMetadata {\n status: \"completed\";\n output: TOutput;\n error?: never;\n}\n\ninterface SubagentRunIncompleteResult extends SubagentRunMetadata {\n status: Exclude<SubagentRunStatus, \"completed\">;\n output?: never;\n error?: string;\n}\n\nexport type SubagentRunResult<TOutput = string> =\n | SubagentRunCompletedResult<TOutput>\n | SubagentRunIncompleteResult;\n\n/**\n * First line of every session file. `cwd` records where the session was\n * started; extra fields (for example mikan's `source` marker) are preserved\n * verbatim on read and rewrite.\n */\nexport interface SessionHeader {\n type: \"session\";\n version?: number;\n id: string;\n timestamp: string;\n cwd: string;\n parentSession?: string;\n [extra: string]: unknown;\n}\n\n/** Raw file line: the header or one session entry. */\nexport type SessionFileEntry = SessionHeader | SessionEntry;\n\nexport interface CreateMikanModelsOptions {\n authPath?: string;\n modelsJsonPath?: string;\n}\n\nexport type EventConversationKind = \"direct\" | \"shared\";\n\nexport type EventType = \"immediate\" | \"one-shot\" | \"periodic\";\n\ninterface EventPayloadBase {\n /** Target platform; may be omitted when only one platform is running. */\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n /** Self-contained task text; event runs do not inherit conversation history. */\n text: string;\n}\n\nexport interface ImmediateEventPayload extends EventPayloadBase {\n type: \"immediate\";\n}\n\nexport interface OneShotEventPayload extends EventPayloadBase {\n type: \"one-shot\";\n /** ISO 8601 timestamp with offset. */\n at: string;\n}\n\nexport interface PeriodicEventPayload extends EventPayloadBase {\n type: \"periodic\";\n /** Cron expression (croner syntax). */\n schedule: string;\n /** IANA timezone, e.g. \"Asia/Taipei\". */\n timezone: string;\n}\n\n/** Wire shape of one event file. */\nexport type EventFilePayload = ImmediateEventPayload | OneShotEventPayload | PeriodicEventPayload;\n\nexport interface EventPayloadInput {\n type: EventType;\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n text: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n}\n\n/** A loaded skill. `baseDir` is the directory containing the skill file. */\nexport interface MikanSkill {\n name: string;\n description: string;\n /** Full skill instructions (file content without frontmatter). */\n content: string;\n filePath: string;\n baseDir: string;\n /** Where the skill was loaded from (e.g. \"workspace\", \"channel\"). */\n source: string;\n /** Exclude from model-visible skill lists. */\n disableModelInvocation?: boolean;\n /**\n * Embed the skill body in the prompt instead of referencing its file path.\n * Used for skills whose files the agent cannot read at runtime (e.g.\n * extension skills under the host-only state dir in sandbox modes).\n */\n inline?: boolean;\n}\n\nexport interface SkillDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n}\n\nexport interface LoadSkillsResult {\n skills: MikanSkill[];\n diagnostics: SkillDiagnostic[];\n}\n\nexport interface RetrySettings {\n enabled: boolean;\n maxRetries: number;\n baseDelayMs: number;\n}\n\nexport interface BudgetSettings {\n /** Max cumulative tokens processed this run (input + output + cache read/write). */\n maxTokens?: number;\n /** Max cumulative provider cost (USD) this run. Requires a populated model cost table. */\n maxCostUsd?: number;\n /** Max wall-clock duration for the run, in milliseconds. */\n maxDurationMs?: number;\n /** Max number of LLM calls (assistant turns) this run. */\n maxLlmCalls?: number;\n}\n\nexport interface HarnessSettings {\n compaction: CompactionSettings;\n retry: RetrySettings;\n budget: BudgetSettings;\n}\n\nexport interface SubagentProfileDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n}\n\nexport interface LoadSubagentProfilesResult {\n profiles: Map<string, SubagentProfile>;\n diagnostics: SubagentProfileDiagnostic[];\n}\n\nexport type CompactionReason = \"threshold\" | \"overflow\" | \"manual\";\n\ninterface CompactionResultSummary {\n summary: string;\n firstKeptEntryId: string;\n tokensBefore: number;\n}\n\nexport type HarnessEvent =\n | AgentEvent\n | { type: \"compaction_start\"; reason: CompactionReason }\n | {\n type: \"compaction_end\";\n reason: CompactionReason;\n result?: CompactionResultSummary;\n aborted: boolean;\n errorMessage?: string;\n }\n | {\n type: \"auto_retry_start\";\n attempt: number;\n maxAttempts: number;\n delayMs: number;\n errorMessage: string;\n }\n | { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n | {\n type: \"budget_exceeded\";\n /** Which cap was hit, e.g. \"cost 2.01 USD > 2 USD limit\". */\n reason: string;\n tokens: number;\n costUsd: number;\n llmCalls: number;\n durationMs: number;\n };\n\nexport type HarnessEventListener = (event: HarnessEvent) => void | Promise<void>;\n\n/** Outcome of a `prompt()` call that an extension blocked before the model ran. */\nexport interface PromptBlockedOutcome {\n blocked: true;\n reason?: string;\n}\n\nexport interface MikanAgentSessionOptions {\n systemPrompt: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: AgentTool[];\n models: MikanModels;\n sessionStore: SessionStore;\n settings?: {\n compaction?: Partial<CompactionSettings>;\n retry?: Partial<RetrySettings>;\n budget?: Partial<BudgetSettings>;\n };\n extensions?: ExtensionRegistry;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/harness/types.ts"],"names":[],"mappings":"AA2CA,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC","sourcesContent":["/**\n * Core types for the mikan agent harness.\n *\n * The harness is built directly on pi-agent-core and pi-ai. Session entries\n * are structurally identical to pi-agent-core's `SessionTreeEntry`, and the\n * on-disk JSONL format stays compatible with the v3 session files mikan has\n * always written, so existing conversation history keeps working unchanged.\n */\nimport type {\n AgentEvent,\n AgentTool,\n BranchSummaryEntry,\n CompactionEntry,\n CustomEntry,\n CustomMessageEntry,\n MessageEntry,\n SessionContext,\n SessionInfoEntry,\n SessionTreeEntry,\n ThinkingLevel,\n CompactionSettings,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model, Usage } from \"@earendil-works/pi-ai\";\nimport type { ExtensionRegistry } from \"./extensions/registry.js\";\nimport type { MikanModels } from \"./models.js\";\nimport type { SessionStore } from \"./session-store.js\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\nexport type {\n BranchSummaryEntry,\n CompactionEntry,\n CustomEntry,\n CustomMessageEntry,\n SessionContext,\n SessionInfoEntry,\n};\n\n/** Message entry as stored in mikan session files. */\nexport type SessionMessageEntry = MessageEntry;\n\n/** Union of entry types mikan reads and writes. Alias of pi-agent-core's tree entry. */\nexport type SessionEntry = SessionTreeEntry;\n\nexport const CURRENT_SESSION_VERSION = 3;\n\nexport interface SubagentModelSpec {\n provider: string;\n id: string;\n}\n\n/**\n * A curated capability set a subagent can be launched with. Built-ins ship\n * with the harness; `<workspaceDir>/agents/<name>.md` patches them per\n * installation. Turn, cost, and duration fields are caps — an explicit\n * `request.budget` may tighten them but never raise them. Token budgets use the\n * larger of the profile default and the request value.\n */\nexport interface SubagentProfile {\n name: string;\n description: string;\n systemPrompt: string;\n tools: string[];\n requiredTools: string[];\n model?: SubagentModelSpec;\n thinkingLevel?: ThinkingLevel;\n maxTurns?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n maxDurationMs?: number;\n}\n\nexport interface SubagentRunBudget {\n /** Maximum assistant/model calls in the subagent run. */\n maxTurns?: number;\n /** Maximum cumulative input/output/cache tokens. */\n maxTokens?: number;\n /** Maximum provider cost in USD. */\n maxCostUsd?: number;\n /** Maximum wall-clock duration. */\n maxDurationMs?: number;\n}\n\nexport type SubagentRunStatus =\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"timeout\"\n | \"budget_exceeded\"\n | \"invalid_output\";\n\nexport interface SubagentParentContext {\n mode: \"normalized\";\n /** Number of recent user/assistant turns to include. Defaults to 3. */\n recentTurns?: number;\n}\n\n/** Aggregated model usage across every assistant turn in a subagent run. */\nexport type SubagentUsage = Usage;\n\n/** Receives usage from a subagent run, including after detached cleanup settles. */\nexport type SubagentUsageSink = (usage: SubagentUsage) => void | Promise<void>;\n\n/** A fresh, isolated subagent run. */\nexport interface SubagentRunRequest<TOutputSchema extends TSchema | undefined = undefined> {\n task: string;\n /** Named profile: a harness built-in, patched by `<workspaceDir>/agents/<name>.md`. */\n profile?: string;\n /** Opt in to a normalized textual snapshot of the active parent run. Defaults to fresh. */\n parentContext?: SubagentParentContext;\n systemPrompt?: string;\n /** JSON-serializable input appended to the task. */\n input?: unknown;\n /** Defaults to the parent runner's configured model. */\n model?: SubagentModelSpec;\n /** Tool names explicitly granted to the subagent. Defaults to no tools. */\n tools?: string[];\n /** Tool names that must each be invoked at least once before completion. */\n requiredTools?: string[];\n /** Per-profile thinking override. */\n thinkingLevel?: ThinkingLevel;\n /** When present, the final response must be JSON matching this schema. */\n outputSchema?: TOutputSchema;\n budget?: SubagentRunBudget;\n signal?: AbortSignal;\n}\n\nexport type SubagentRunOutput<TSchemaOrUndefined extends TSchema | undefined> =\n TSchemaOrUndefined extends TSchema ? Static<TSchemaOrUndefined> : string;\n\ninterface SubagentRunMetadata {\n runId: string;\n /** Raw final assistant text, including when structured validation failed. */\n text?: string;\n model: SubagentModelSpec;\n turns: number;\n toolCalls: number;\n toolCallCounts: Record<string, number>;\n /** Full token and cost breakdown across the run. */\n usage: SubagentUsage;\n /** Aggregate token count; equivalent to `usage.totalTokens`. */\n tokens: number;\n /** Aggregate provider cost; equivalent to `usage.cost.total`. */\n costUsd: number;\n durationMs: number;\n /**\n * The caller received a terminal result before the underlying run settled.\n * When true, `usage`, `tokens`, and `costUsd` are provisional snapshots;\n * final usage is delivered later through the run's bound usage sink. The\n * global slot remains held until cleanup settles because in-process work\n * cannot be safely reclaimed without a killable execution boundary.\n */\n cleanupPending?: boolean;\n}\n\ninterface SubagentRunCompletedResult<TOutput> extends SubagentRunMetadata {\n status: \"completed\";\n output: TOutput;\n error?: never;\n}\n\ninterface SubagentRunIncompleteResult extends SubagentRunMetadata {\n status: Exclude<SubagentRunStatus, \"completed\">;\n output?: never;\n error?: string;\n}\n\nexport type SubagentRunResult<TOutput = string> =\n | SubagentRunCompletedResult<TOutput>\n | SubagentRunIncompleteResult;\n\n/**\n * First line of every session file. `cwd` records where the session was\n * started; extra fields (for example mikan's `source` marker) are preserved\n * verbatim on read and rewrite.\n */\nexport interface SessionHeader {\n type: \"session\";\n version?: number;\n id: string;\n timestamp: string;\n cwd: string;\n parentSession?: string;\n [extra: string]: unknown;\n}\n\n/** Raw file line: the header or one session entry. */\nexport type SessionFileEntry = SessionHeader | SessionEntry;\n\nexport interface CreateMikanModelsOptions {\n authPath?: string;\n modelsJsonPath?: string;\n}\n\nexport type EventConversationKind = \"direct\" | \"shared\";\n\nexport type EventType = \"immediate\" | \"one-shot\" | \"periodic\";\n\ninterface EventPayloadBase {\n /** Target platform; may be omitted when only one platform is running. */\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n /** Self-contained task text; event runs do not inherit conversation history. */\n text: string;\n}\n\nexport interface ImmediateEventPayload extends EventPayloadBase {\n type: \"immediate\";\n}\n\nexport interface OneShotEventPayload extends EventPayloadBase {\n type: \"one-shot\";\n /** ISO 8601 timestamp with offset. */\n at: string;\n}\n\nexport interface PeriodicEventPayload extends EventPayloadBase {\n type: \"periodic\";\n /** Cron expression (croner syntax). */\n schedule: string;\n /** IANA timezone, e.g. \"Asia/Taipei\". */\n timezone: string;\n}\n\n/** Wire shape of one event file. */\nexport type EventFilePayload = ImmediateEventPayload | OneShotEventPayload | PeriodicEventPayload;\n\nexport interface EventPayloadInput {\n type: EventType;\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n text: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n}\n\n/** A loaded skill. `baseDir` is the directory containing the skill file. */\nexport interface MikanSkill {\n name: string;\n description: string;\n /** Full skill instructions (file content without frontmatter). */\n content: string;\n filePath: string;\n baseDir: string;\n /** Where the skill was loaded from (e.g. \"workspace\", \"channel\"). */\n source: string;\n /** Exclude from model-visible skill lists. */\n disableModelInvocation?: boolean;\n /**\n * Embed the skill body in the prompt instead of referencing its file path.\n * Used for skills whose files the agent cannot read at runtime (e.g.\n * extension skills under the host-only state dir in sandbox modes).\n */\n inline?: boolean;\n}\n\nexport interface SkillDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n}\n\nexport interface LoadSkillsResult {\n skills: MikanSkill[];\n diagnostics: SkillDiagnostic[];\n}\n\nexport interface RetrySettings {\n enabled: boolean;\n maxRetries: number;\n baseDelayMs: number;\n}\n\nexport interface BudgetSettings {\n /** Max cumulative tokens processed this run (input + output + cache read/write). */\n maxTokens?: number;\n /** Max cumulative provider cost (USD) this run. Requires a populated model cost table. */\n maxCostUsd?: number;\n /** Max wall-clock duration for the run, in milliseconds. */\n maxDurationMs?: number;\n /** Max number of LLM calls (assistant turns) this run. */\n maxLlmCalls?: number;\n}\n\nexport interface HarnessSettings {\n compaction: CompactionSettings;\n retry: RetrySettings;\n budget: BudgetSettings;\n}\n\nexport interface SubagentProfileDiagnostic {\n type: \"warning\";\n message: string;\n path: string;\n}\n\nexport interface LoadSubagentProfilesResult {\n profiles: Map<string, SubagentProfile>;\n diagnostics: SubagentProfileDiagnostic[];\n}\n\nexport type CompactionReason = \"threshold\" | \"overflow\" | \"manual\";\n\ninterface CompactionResultSummary {\n summary: string;\n firstKeptEntryId: string;\n tokensBefore: number;\n}\n\nexport type HarnessEvent =\n | AgentEvent\n | { type: \"compaction_start\"; reason: CompactionReason }\n | {\n type: \"compaction_end\";\n reason: CompactionReason;\n result?: CompactionResultSummary;\n aborted: boolean;\n errorMessage?: string;\n }\n | {\n type: \"auto_retry_start\";\n attempt: number;\n maxAttempts: number;\n delayMs: number;\n errorMessage: string;\n }\n | { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n | {\n type: \"budget_exceeded\";\n /** Which cap was hit, e.g. \"cost 2.01 USD > 2 USD limit\". */\n reason: string;\n tokens: number;\n costUsd: number;\n llmCalls: number;\n durationMs: number;\n };\n\nexport type HarnessEventListener = (event: HarnessEvent) => void | Promise<void>;\n\n/** Outcome of a `prompt()` call that an extension blocked before the model ran. */\nexport interface PromptBlockedOutcome {\n blocked: true;\n reason?: string;\n}\n\nexport interface MikanAgentSessionOptions {\n systemPrompt: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: AgentTool[];\n models: MikanModels;\n sessionStore: SessionStore;\n settings?: {\n compaction?: Partial<CompactionSettings>;\n retry?: Partial<RetrySettings>;\n budget?: Partial<BudgetSettings>;\n };\n extensions?: ExtensionRegistry;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Breadcrumb, ErrorEvent, Event, EventHint, Scope } from "@sentry/node";
|
|
2
|
+
import * as Sentry from "@sentry/node";
|
|
2
3
|
export type { ReportUserFacingErrorOptions, SentryAttributionAttributes, SentryRunScopeContext, SentrySpanPayload, SentryTransactionPayload, } from "./types.js";
|
|
3
4
|
import type { ReportUserFacingErrorOptions, SentryAttributionAttributes, SentryRunScopeContext, SentrySpanPayload, SentryTransactionPayload } from "./types.js";
|
|
4
5
|
export declare function createSentryInitOptions(dsn?: string): {
|
|
@@ -9,6 +10,7 @@ export declare function createSentryInitOptions(dsn?: string): {
|
|
|
9
10
|
tracesSampleRate: number;
|
|
10
11
|
includeLocalVariables: boolean;
|
|
11
12
|
enableLogs: boolean;
|
|
13
|
+
integrations(defaultIntegrations: ReturnType<typeof Sentry.getDefaultIntegrations>): import("@sentry/core").Integration[];
|
|
12
14
|
beforeSend(event: ErrorEvent, hint: EventHint): ErrorEvent | null;
|
|
13
15
|
beforeSendSpan(span: SentrySpanPayload): SentrySpanPayload;
|
|
14
16
|
beforeSendTransaction(event: SentryTransactionPayload): SentryTransactionPayload | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../../src/observability/sentry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../../src/observability/sentry.ts"],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,GAAG,OAAO,GAAG,SAAS,CAAC,GAChE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAO3C;AAED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC,GAC3D,IAAI,CAON;AAED,wBAAgB,aAAa,CAAC,CAAC,SAAS,KAAK,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,SAAS,GAAG,CAAC,GAAG,IAAI,CA2CpF;AAED,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,iBAAiB,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,CAU5E;AAsBD,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,GAAG,IAAI,CAU5E;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,KAAK,SAAI,GAAG,OAAO,CAwB9E"}
|
|
@@ -61,6 +61,13 @@ export function createSentryInitOptions(dsn) {
|
|
|
61
61
|
tracesSampleRate: 1.0,
|
|
62
62
|
includeLocalVariables: false,
|
|
63
63
|
enableLogs: true,
|
|
64
|
+
// Sentry's OpenAI APIPromise wrapper leaks a second rejection when an
|
|
65
|
+
// in-flight request is aborted (for example by an agent budget limit).
|
|
66
|
+
// Keep all other default integrations until the upstream wrapper handles
|
|
67
|
+
// both withResponse() branches without an unhandled rejection.
|
|
68
|
+
integrations(defaultIntegrations) {
|
|
69
|
+
return defaultIntegrations.filter((integration) => integration.name !== "OpenAI");
|
|
70
|
+
},
|
|
64
71
|
beforeSend(event, hint) {
|
|
65
72
|
return sanitizeEvent(event, hint);
|
|
66
73
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sentry.js","sourceRoot":"","sources":["../../src/observability/sentry.ts"],"names":[],"m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AAM,GAAG,CAAC;IAC7F,CAAC;IACD,OAAO,aAAa,KAAK,GAAG,CAAC;AAC/B,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,IAAI,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,qBAAqB,EAAE,GAAG,CAAC,EAAE,aAAa,CAAC,CAAC;IACrF,KAAK,MAAM,OAAO,IAAI,cAAc,EAAE,CAAC;QACrC,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;IACpE,CAAC;IACD,IAAI,SAAS,CAAC,MAAM,GAAG,iBAAiB,EAAE,CAAC;QACzC,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,iBAAiB,CAAC,gBAAgB,SAAS,CAAC,MAAM,GAAG,iBAAiB,SAAS,CAAC;IAC/G,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { Breadcrumb, ErrorEvent, Event, EventHint, Scope } from \"@sentry/node\";\nimport * as Sentry from \"@sentry/node\";\nimport { readEnv } from \"../utils/env.js\";\n\nconst REDACTED = \"[REDACTED]\";\nconst REDACTED_PATH = \"[REDACTED_PATH]\";\nconst MAX_STRING_LENGTH = 256;\nconst MAX_DEPTH = 4;\nconst TRACE_ATTRIBUTION_TTL_MS = 5 * 60 * 1000;\n\nconst SENSITIVE_KEYS = new Set([\n \"accesstoken\",\n \"apikey\",\n \"args\",\n \"attachment\",\n \"attachments\",\n \"authorization\",\n \"body\",\n \"clientsecret\",\n \"code\",\n \"content\",\n \"contents\",\n \"cookie\",\n \"cookies\",\n \"credential\",\n \"filepath\",\n \"headers\",\n \"image\",\n \"imageattachments\",\n \"images\",\n \"localpath\",\n \"messages\",\n \"newusermessage\",\n \"password\",\n \"path\",\n \"paths\",\n \"prompt\",\n \"refreshtoken\",\n \"response\",\n \"result\",\n \"secret\",\n \"systemprompt\",\n \"text\",\n \"thinking\",\n \"token\",\n \"url\",\n \"uri\",\n \"workspacepath\",\n]);\n\nconst ABSOLUTE_PATH_PATTERN =\n /(?:\\/Users\\/[^\\s\"'`]+|\\/workspace\\/[^\\s\"'`]+|\\/tmp\\/[^\\s\"'`]+|\\/var\\/folders\\/[^\\s\"'`]+|[A-Za-z]:\\\\[^\\s\"'`]+)/;\nconst TOKEN_PATTERNS = [\n /\\bsk-[A-Za-z0-9_-]{12,}\\b/,\n /\\bxox[a-z]-[A-Za-z0-9-]{10,}\\b/,\n /\\bAIza[0-9A-Za-z_-]{20,}\\b/,\n /\\bgh[pousr]_[A-Za-z0-9]{20,}\\b/,\n];\n\nexport type {\n ReportUserFacingErrorOptions,\n SentryAttributionAttributes,\n SentryRunScopeContext,\n SentrySpanPayload,\n SentryTransactionPayload,\n} from \"./types.js\";\nimport type {\n ReportUserFacingErrorOptions,\n SentryAttributionAttributes,\n SentryRunScopeContext,\n SentrySpanPayload,\n SentryTransactionPayload,\n} from \"./types.js\";\n\ntype TraceAttributionEntry = {\n attributes: SentryAttributionAttributes;\n expiresAt: number;\n};\n\nconst traceAttribution = new Map<string, TraceAttributionEntry>();\n\nexport function createSentryInitOptions(dsn?: string) {\n return {\n dsn,\n environment: readEnv(\"SENTRY_ENVIRONMENT\") ?? \"production\",\n enabled: Boolean(dsn) && readEnv(\"SENTRY_ENABLED\") !== \"false\",\n sendDefaultPii: false,\n tracesSampleRate: 1.0,\n includeLocalVariables: false,\n enableLogs: true,\n beforeSend(event: ErrorEvent, hint: EventHint): ErrorEvent | null {\n return sanitizeEvent(event, hint);\n },\n beforeSendSpan(span: SentrySpanPayload): SentrySpanPayload {\n return applySpanAttribution(span);\n },\n beforeSendTransaction(event: SentryTransactionPayload): SentryTransactionPayload | null {\n return sanitizeTransactionEvent(event);\n },\n beforeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {\n return sanitizeBreadcrumb(breadcrumb);\n },\n };\n}\n\nexport function reportUserFacingError(\n error: unknown,\n options: ReportUserFacingErrorOptions,\n): string | undefined {\n if (options.expected) return undefined;\n\n const exception = error instanceof Error ? error : new Error(String(error));\n return Sentry.withScope((scope) => {\n scope.setLevel(options.severity ?? \"error\");\n scope.setTag(\"user_facing\", \"true\");\n scope.setTag(\"expected\", \"false\");\n scope.setTag(\"error_domain\", options.domain);\n scope.setTag(\"error_surface\", options.surface);\n scope.setTag(\"operation\", options.operation);\n setOptionalTag(scope, \"platform\", options.platform);\n setOptionalTag(scope, \"provider\", options.provider);\n setOptionalTag(scope, \"model\", options.model);\n setOptionalTag(scope, \"tool\", options.toolName);\n setOptionalTag(scope, \"stop_reason\", options.stopReason);\n for (const [key, value] of Object.entries(options.tags ?? {})) {\n if (value !== undefined) scope.setTag(key, String(value));\n }\n if (options.fingerprint) scope.setFingerprint(options.fingerprint);\n scope.setContext(\"user_facing_error\", {\n domain: options.domain,\n surface: options.surface,\n operation: options.operation,\n severity: options.severity ?? \"error\",\n platform: options.platform,\n provider: options.provider,\n model: options.model,\n toolName: options.toolName,\n stopReason: options.stopReason,\n ...(sanitizeValue(options.context ?? {}) as Record<string, unknown>),\n });\n return Sentry.captureException(exception);\n });\n}\n\nfunction setOptionalTag(scope: Scope, key: string, value: string | undefined): void {\n if (value !== undefined) scope.setTag(key, value);\n}\n\nexport function createRunAttributionAttributes(\n context: SentryRunScopeContext,\n): SentryAttributionAttributes {\n return metricAttributes({\n conversation_id: context.conversationId,\n channel_id: context.conversationId,\n session_key: context.sessionKey,\n message_id: context.messageId,\n platform: context.platform,\n user_id: context.userId,\n thread_ts: context.threadTs,\n provider: context.provider,\n model: context.model,\n });\n}\n\nexport function registerTraceAttribution(\n span: { setAttributes(attributes: SentryAttributionAttributes): unknown },\n attributes: SentryAttributionAttributes,\n): void {\n span.setAttributes(attributes);\n const traceId = Sentry.spanToJSON(span as Parameters<typeof Sentry.spanToJSON>[0]).trace_id;\n if (!traceId) return;\n\n const now = Date.now();\n pruneExpiredTraceAttributions(now);\n traceAttribution.set(traceId, {\n attributes: { ...traceAttribution.get(traceId)?.attributes, ...attributes },\n expiresAt: now + TRACE_ATTRIBUTION_TTL_MS,\n });\n}\n\nexport function updateActiveSpanAttribution(attributes: SentryAttributionAttributes): void {\n const span = Sentry.getActiveSpan();\n if (!span) return;\n registerTraceAttribution(span, attributes);\n}\n\nexport function applyRunScope(scope: Scope, context: SentryRunScopeContext): void {\n const attributes = createRunAttributionAttributes(context);\n\n for (const [key, value] of Object.entries(attributes)) {\n scope.setTag(key, value);\n }\n scope.setAttributes(attributes);\n scope.setUser({\n id: context.userId,\n username: context.userName,\n });\n scope.setContext(\"agent_run\", {\n conversationId: context.conversationId,\n channelId: context.conversationId,\n sessionKey: context.sessionKey,\n messageId: context.messageId,\n threadTs: context.threadTs,\n platform: context.platform,\n provider: context.provider,\n model: context.model,\n });\n}\n\nexport function metricAttributes(\n attributes: Record<string, string | number | boolean | undefined>,\n): Record<string, string | number | boolean> {\n return Object.fromEntries(\n Object.entries(attributes).filter((entry): entry is [string, string | number | boolean] => {\n const [, value] = entry;\n return value !== undefined;\n }),\n );\n}\n\nexport function addLifecycleBreadcrumb(\n message: string,\n data?: Record<string, string | number | boolean | undefined>,\n): void {\n Sentry.addBreadcrumb({\n category: \"agent.lifecycle\",\n message,\n level: \"info\",\n data: data ? metricAttributes(data) : undefined,\n });\n}\n\nexport function sanitizeEvent<T extends Event>(event: T, _hint?: EventHint): T | null {\n const sanitized: T = {\n ...event,\n breadcrumbs: event.breadcrumbs\n ?.map((breadcrumb) => sanitizeBreadcrumb(breadcrumb))\n .filter((breadcrumb): breadcrumb is Breadcrumb => breadcrumb !== null),\n extra: sanitizeValue(event.extra) as T[\"extra\"],\n contexts: sanitizeValue(event.contexts) as T[\"contexts\"],\n request: sanitizeRequest(event.request),\n user: undefined,\n server_name: undefined,\n };\n\n if (sanitized.message) {\n sanitized.message = sanitizeString(sanitized.message);\n }\n\n if (sanitized.logentry) {\n sanitized.logentry = {\n ...sanitized.logentry,\n message: sanitized.logentry.message ? sanitizeString(sanitized.logentry.message) : undefined,\n };\n }\n\n if (sanitized.exception?.values) {\n sanitized.exception.values = sanitized.exception.values.map((value) => ({\n ...value,\n value: value.value ? sanitizeString(value.value) : value.value,\n stacktrace: value.stacktrace\n ? {\n ...value.stacktrace,\n frames: value.stacktrace.frames?.map((frame) => ({\n ...frame,\n filename: frame.filename ? sanitizeString(frame.filename) : frame.filename,\n abs_path: frame.abs_path ? sanitizeString(frame.abs_path) : frame.abs_path,\n vars: undefined,\n })),\n }\n : value.stacktrace,\n }));\n }\n\n return sanitized;\n}\n\nexport function applySpanAttribution<T extends SentrySpanPayload>(span: T): T {\n const attributes = getTraceAttribution(span.trace_id);\n if (!attributes) return span;\n return {\n ...span,\n data: {\n ...span.data,\n ...attributes,\n },\n };\n}\n\nfunction sanitizeTransactionEvent<T extends SentryTransactionPayload>(event: T): T | null {\n const sanitized = sanitizeEvent(event);\n if (!sanitized) return null;\n\n const traceContext = sanitized.contexts?.trace;\n const traceId = traceContext?.trace_id;\n if (typeof traceId !== \"string\") return sanitized;\n const attributes = getTraceAttribution(traceId);\n if (!attributes) return sanitized;\n\n const entries = (sanitized as { entries?: Array<{ type?: string; data?: unknown }> }).entries;\n for (const entry of entries ?? []) {\n if (entry.type !== \"spans\" || !Array.isArray(entry.data)) continue;\n entry.data = entry.data.map((span: SentrySpanPayload) => applySpanAttribution(span));\n }\n\n traceAttribution.delete(traceId);\n return sanitized;\n}\n\nexport function sanitizeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {\n if (breadcrumb.category === \"console\") {\n return null;\n }\n\n return {\n ...breadcrumb,\n message: breadcrumb.message ? sanitizeString(breadcrumb.message) : breadcrumb.message,\n data: sanitizeValue(breadcrumb.data) as Breadcrumb[\"data\"],\n };\n}\n\nexport function sanitizeValue(value: unknown, key?: string, depth = 0): unknown {\n if (value == null) return value;\n if (depth > MAX_DEPTH) return \"[Truncated]\";\n\n if (isSensitiveKey(key)) {\n return summarizeValue(value, key);\n }\n\n if (typeof value === \"string\") {\n return sanitizeString(value);\n }\n\n if (Array.isArray(value)) {\n return value.slice(0, 20).map((entry) => sanitizeValue(entry, key, depth + 1));\n }\n\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).map(\n ([entryKey, entryValue]) => [entryKey, sanitizeValue(entryValue, entryKey, depth + 1)],\n );\n return Object.fromEntries(entries);\n }\n\n return value;\n}\n\nfunction sanitizeRequest(request: Event[\"request\"]): Event[\"request\"] {\n if (!request) return request;\n\n return {\n ...request,\n data: request.data ? summarizeValue(request.data, \"body\") : undefined,\n headers: undefined,\n cookies: undefined,\n };\n}\n\nfunction getTraceAttribution(traceId: string): SentryAttributionAttributes | undefined {\n const entry = traceAttribution.get(traceId);\n if (!entry) return undefined;\n if (entry.expiresAt > Date.now()) return entry.attributes;\n traceAttribution.delete(traceId);\n return undefined;\n}\n\nfunction pruneExpiredTraceAttributions(now: number): void {\n for (const [traceId, entry] of traceAttribution) {\n if (entry.expiresAt <= now) traceAttribution.delete(traceId);\n }\n}\n\nfunction isSensitiveKey(key?: string): boolean {\n if (!key) return false;\n return SENSITIVE_KEYS.has(key.toLowerCase().replace(/[^a-z0-9]/g, \"\"));\n}\n\nfunction summarizeValue(value: unknown, key?: string): string {\n const label = key ?? \"field\";\n if (typeof value === \"string\") {\n return `[Redacted ${label}; length=${value.length}]`;\n }\n if (Array.isArray(value)) {\n return `[Redacted ${label}; items=${value.length}]`;\n }\n if (value && typeof value === \"object\") {\n return `[Redacted ${label}; keys=${Object.keys(value as Record<string, unknown>).length}]`;\n }\n return `[Redacted ${label}]`;\n}\n\nfunction sanitizeString(value: string): string {\n let sanitized = value.replace(new RegExp(ABSOLUTE_PATH_PATTERN, \"g\"), REDACTED_PATH);\n for (const pattern of TOKEN_PATTERNS) {\n sanitized = sanitized.replace(new RegExp(pattern, \"g\"), REDACTED);\n }\n if (sanitized.length > MAX_STRING_LENGTH) {\n return `${sanitized.slice(0, MAX_STRING_LENGTH)}… [truncated ${sanitized.length - MAX_STRING_LENGTH} chars]`;\n }\n return sanitized;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sentry.js","sourceRoot":"","sources":["../../src/observability/sentry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE1C,MAAM,QAAQ,GAAG,YAAY,CAAC;AAC9B,MAAM,aAAa,GAAG,iBAAiB,CAAC;AACxC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAE/C,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC;IAC7B,aAAa;IACb,QAAQ;IACR,MAAM;IACN,YAAY;IACZ,aAAa;IACb,eAAe;IACf,MAAM;IACN,cAAc;IACd,MAAM;IACN,SAAS;IACT,UAAU;IACV,QAAQ;IACR,SAAS;IACT,YAAY;IACZ,UAAU;IACV,SAAS;IACT,OAAO;IACP,kBAAkB;IAClB,QAAQ;IACR,WAAW;IACX,UAAU;IACV,gBAAgB;IAChB,UAAU;IACV,MAAM;IACN,OAAO;IACP,QAAQ;IACR,cAAc;IACd,UAAU;IACV,QAAQ;IACR,QAAQ;IACR,cAAc;IACd,MAAM;IACN,UAAU;IACV,OAAO;IACP,KAAK;IACL,KAAK;IACL,eAAe;CAChB,CAAC,CAAC;AAEH,MAAM,qBAAqB,GACzB,+GAA+G,CAAC;AAClH,MAAM,cAAc,GAAG;IACrB,2BAA2B;IAC3B,gCAAgC;IAChC,4BAA4B;IAC5B,gCAAgC;CACjC,CAAC;AAsBF,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAiC,CAAC;AAElE,MAAM,UAAU,uBAAuB,CAAC,GAAY;IAClD,OAAO;QACL,GAAG;QACH,WAAW,EAAE,OAAO,CAAC,oBAAoB,CAAC,IA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AE,CAAC;QAC9B,OAAO,aAAa,KAAK,YAAY,KAAK,CAAC,MAAM,GAAG,CAAC;IACvD,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,aAAa,KAAK,WAAW,KAAK,CAAC,MAAM,GAAG,CAAC;IACtD,CAAC;IACD,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvC,OAAO,aAAa,KAAK,UAAU,MAAM,CAAC,IAAI,CAAC,KAAgC,CAAC,CAAC,MAAM,GAAG,CAAC;IAC7F,CAAC;IACD,OAAO,aAAa,KAAK,GAAG,CAAC;AAC/B,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,IAAI,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,qBAAqB,EAAE,GAAG,CAAC,EAAE,aAAa,CAAC,CAAC;IACrF,KAAK,MAAM,OAAO,IAAI,cAAc,EAAE,CAAC;QACrC,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;IACpE,CAAC;IACD,IAAI,SAAS,CAAC,MAAM,GAAG,iBAAiB,EAAE,CAAC;QACzC,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,iBAAiB,CAAC,gBAAgB,SAAS,CAAC,MAAM,GAAG,iBAAiB,SAAS,CAAC;IAC/G,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { Breadcrumb, ErrorEvent, Event, EventHint, Scope } from \"@sentry/node\";\nimport * as Sentry from \"@sentry/node\";\nimport { readEnv } from \"../utils/env.js\";\n\nconst REDACTED = \"[REDACTED]\";\nconst REDACTED_PATH = \"[REDACTED_PATH]\";\nconst MAX_STRING_LENGTH = 256;\nconst MAX_DEPTH = 4;\nconst TRACE_ATTRIBUTION_TTL_MS = 5 * 60 * 1000;\n\nconst SENSITIVE_KEYS = new Set([\n \"accesstoken\",\n \"apikey\",\n \"args\",\n \"attachment\",\n \"attachments\",\n \"authorization\",\n \"body\",\n \"clientsecret\",\n \"code\",\n \"content\",\n \"contents\",\n \"cookie\",\n \"cookies\",\n \"credential\",\n \"filepath\",\n \"headers\",\n \"image\",\n \"imageattachments\",\n \"images\",\n \"localpath\",\n \"messages\",\n \"newusermessage\",\n \"password\",\n \"path\",\n \"paths\",\n \"prompt\",\n \"refreshtoken\",\n \"response\",\n \"result\",\n \"secret\",\n \"systemprompt\",\n \"text\",\n \"thinking\",\n \"token\",\n \"url\",\n \"uri\",\n \"workspacepath\",\n]);\n\nconst ABSOLUTE_PATH_PATTERN =\n /(?:\\/Users\\/[^\\s\"'`]+|\\/workspace\\/[^\\s\"'`]+|\\/tmp\\/[^\\s\"'`]+|\\/var\\/folders\\/[^\\s\"'`]+|[A-Za-z]:\\\\[^\\s\"'`]+)/;\nconst TOKEN_PATTERNS = [\n /\\bsk-[A-Za-z0-9_-]{12,}\\b/,\n /\\bxox[a-z]-[A-Za-z0-9-]{10,}\\b/,\n /\\bAIza[0-9A-Za-z_-]{20,}\\b/,\n /\\bgh[pousr]_[A-Za-z0-9]{20,}\\b/,\n];\n\nexport type {\n ReportUserFacingErrorOptions,\n SentryAttributionAttributes,\n SentryRunScopeContext,\n SentrySpanPayload,\n SentryTransactionPayload,\n} from \"./types.js\";\nimport type {\n ReportUserFacingErrorOptions,\n SentryAttributionAttributes,\n SentryRunScopeContext,\n SentrySpanPayload,\n SentryTransactionPayload,\n} from \"./types.js\";\n\ntype TraceAttributionEntry = {\n attributes: SentryAttributionAttributes;\n expiresAt: number;\n};\n\nconst traceAttribution = new Map<string, TraceAttributionEntry>();\n\nexport function createSentryInitOptions(dsn?: string) {\n return {\n dsn,\n environment: readEnv(\"SENTRY_ENVIRONMENT\") ?? \"production\",\n enabled: Boolean(dsn) && readEnv(\"SENTRY_ENABLED\") !== \"false\",\n sendDefaultPii: false,\n tracesSampleRate: 1.0,\n includeLocalVariables: false,\n enableLogs: true,\n // Sentry's OpenAI APIPromise wrapper leaks a second rejection when an\n // in-flight request is aborted (for example by an agent budget limit).\n // Keep all other default integrations until the upstream wrapper handles\n // both withResponse() branches without an unhandled rejection.\n integrations(defaultIntegrations: ReturnType<typeof Sentry.getDefaultIntegrations>) {\n return defaultIntegrations.filter((integration) => integration.name !== \"OpenAI\");\n },\n beforeSend(event: ErrorEvent, hint: EventHint): ErrorEvent | null {\n return sanitizeEvent(event, hint);\n },\n beforeSendSpan(span: SentrySpanPayload): SentrySpanPayload {\n return applySpanAttribution(span);\n },\n beforeSendTransaction(event: SentryTransactionPayload): SentryTransactionPayload | null {\n return sanitizeTransactionEvent(event);\n },\n beforeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {\n return sanitizeBreadcrumb(breadcrumb);\n },\n };\n}\n\nexport function reportUserFacingError(\n error: unknown,\n options: ReportUserFacingErrorOptions,\n): string | undefined {\n if (options.expected) return undefined;\n\n const exception = error instanceof Error ? error : new Error(String(error));\n return Sentry.withScope((scope) => {\n scope.setLevel(options.severity ?? \"error\");\n scope.setTag(\"user_facing\", \"true\");\n scope.setTag(\"expected\", \"false\");\n scope.setTag(\"error_domain\", options.domain);\n scope.setTag(\"error_surface\", options.surface);\n scope.setTag(\"operation\", options.operation);\n setOptionalTag(scope, \"platform\", options.platform);\n setOptionalTag(scope, \"provider\", options.provider);\n setOptionalTag(scope, \"model\", options.model);\n setOptionalTag(scope, \"tool\", options.toolName);\n setOptionalTag(scope, \"stop_reason\", options.stopReason);\n for (const [key, value] of Object.entries(options.tags ?? {})) {\n if (value !== undefined) scope.setTag(key, String(value));\n }\n if (options.fingerprint) scope.setFingerprint(options.fingerprint);\n scope.setContext(\"user_facing_error\", {\n domain: options.domain,\n surface: options.surface,\n operation: options.operation,\n severity: options.severity ?? \"error\",\n platform: options.platform,\n provider: options.provider,\n model: options.model,\n toolName: options.toolName,\n stopReason: options.stopReason,\n ...(sanitizeValue(options.context ?? {}) as Record<string, unknown>),\n });\n return Sentry.captureException(exception);\n });\n}\n\nfunction setOptionalTag(scope: Scope, key: string, value: string | undefined): void {\n if (value !== undefined) scope.setTag(key, value);\n}\n\nexport function createRunAttributionAttributes(\n context: SentryRunScopeContext,\n): SentryAttributionAttributes {\n return metricAttributes({\n conversation_id: context.conversationId,\n channel_id: context.conversationId,\n session_key: context.sessionKey,\n message_id: context.messageId,\n platform: context.platform,\n user_id: context.userId,\n thread_ts: context.threadTs,\n provider: context.provider,\n model: context.model,\n });\n}\n\nexport function registerTraceAttribution(\n span: { setAttributes(attributes: SentryAttributionAttributes): unknown },\n attributes: SentryAttributionAttributes,\n): void {\n span.setAttributes(attributes);\n const traceId = Sentry.spanToJSON(span as Parameters<typeof Sentry.spanToJSON>[0]).trace_id;\n if (!traceId) return;\n\n const now = Date.now();\n pruneExpiredTraceAttributions(now);\n traceAttribution.set(traceId, {\n attributes: { ...traceAttribution.get(traceId)?.attributes, ...attributes },\n expiresAt: now + TRACE_ATTRIBUTION_TTL_MS,\n });\n}\n\nexport function updateActiveSpanAttribution(attributes: SentryAttributionAttributes): void {\n const span = Sentry.getActiveSpan();\n if (!span) return;\n registerTraceAttribution(span, attributes);\n}\n\nexport function applyRunScope(scope: Scope, context: SentryRunScopeContext): void {\n const attributes = createRunAttributionAttributes(context);\n\n for (const [key, value] of Object.entries(attributes)) {\n scope.setTag(key, value);\n }\n scope.setAttributes(attributes);\n scope.setUser({\n id: context.userId,\n username: context.userName,\n });\n scope.setContext(\"agent_run\", {\n conversationId: context.conversationId,\n channelId: context.conversationId,\n sessionKey: context.sessionKey,\n messageId: context.messageId,\n threadTs: context.threadTs,\n platform: context.platform,\n provider: context.provider,\n model: context.model,\n });\n}\n\nexport function metricAttributes(\n attributes: Record<string, string | number | boolean | undefined>,\n): Record<string, string | number | boolean> {\n return Object.fromEntries(\n Object.entries(attributes).filter((entry): entry is [string, string | number | boolean] => {\n const [, value] = entry;\n return value !== undefined;\n }),\n );\n}\n\nexport function addLifecycleBreadcrumb(\n message: string,\n data?: Record<string, string | number | boolean | undefined>,\n): void {\n Sentry.addBreadcrumb({\n category: \"agent.lifecycle\",\n message,\n level: \"info\",\n data: data ? metricAttributes(data) : undefined,\n });\n}\n\nexport function sanitizeEvent<T extends Event>(event: T, _hint?: EventHint): T | null {\n const sanitized: T = {\n ...event,\n breadcrumbs: event.breadcrumbs\n ?.map((breadcrumb) => sanitizeBreadcrumb(breadcrumb))\n .filter((breadcrumb): breadcrumb is Breadcrumb => breadcrumb !== null),\n extra: sanitizeValue(event.extra) as T[\"extra\"],\n contexts: sanitizeValue(event.contexts) as T[\"contexts\"],\n request: sanitizeRequest(event.request),\n user: undefined,\n server_name: undefined,\n };\n\n if (sanitized.message) {\n sanitized.message = sanitizeString(sanitized.message);\n }\n\n if (sanitized.logentry) {\n sanitized.logentry = {\n ...sanitized.logentry,\n message: sanitized.logentry.message ? sanitizeString(sanitized.logentry.message) : undefined,\n };\n }\n\n if (sanitized.exception?.values) {\n sanitized.exception.values = sanitized.exception.values.map((value) => ({\n ...value,\n value: value.value ? sanitizeString(value.value) : value.value,\n stacktrace: value.stacktrace\n ? {\n ...value.stacktrace,\n frames: value.stacktrace.frames?.map((frame) => ({\n ...frame,\n filename: frame.filename ? sanitizeString(frame.filename) : frame.filename,\n abs_path: frame.abs_path ? sanitizeString(frame.abs_path) : frame.abs_path,\n vars: undefined,\n })),\n }\n : value.stacktrace,\n }));\n }\n\n return sanitized;\n}\n\nexport function applySpanAttribution<T extends SentrySpanPayload>(span: T): T {\n const attributes = getTraceAttribution(span.trace_id);\n if (!attributes) return span;\n return {\n ...span,\n data: {\n ...span.data,\n ...attributes,\n },\n };\n}\n\nfunction sanitizeTransactionEvent<T extends SentryTransactionPayload>(event: T): T | null {\n const sanitized = sanitizeEvent(event);\n if (!sanitized) return null;\n\n const traceContext = sanitized.contexts?.trace;\n const traceId = traceContext?.trace_id;\n if (typeof traceId !== \"string\") return sanitized;\n const attributes = getTraceAttribution(traceId);\n if (!attributes) return sanitized;\n\n const entries = (sanitized as { entries?: Array<{ type?: string; data?: unknown }> }).entries;\n for (const entry of entries ?? []) {\n if (entry.type !== \"spans\" || !Array.isArray(entry.data)) continue;\n entry.data = entry.data.map((span: SentrySpanPayload) => applySpanAttribution(span));\n }\n\n traceAttribution.delete(traceId);\n return sanitized;\n}\n\nexport function sanitizeBreadcrumb(breadcrumb: Breadcrumb): Breadcrumb | null {\n if (breadcrumb.category === \"console\") {\n return null;\n }\n\n return {\n ...breadcrumb,\n message: breadcrumb.message ? sanitizeString(breadcrumb.message) : breadcrumb.message,\n data: sanitizeValue(breadcrumb.data) as Breadcrumb[\"data\"],\n };\n}\n\nexport function sanitizeValue(value: unknown, key?: string, depth = 0): unknown {\n if (value == null) return value;\n if (depth > MAX_DEPTH) return \"[Truncated]\";\n\n if (isSensitiveKey(key)) {\n return summarizeValue(value, key);\n }\n\n if (typeof value === \"string\") {\n return sanitizeString(value);\n }\n\n if (Array.isArray(value)) {\n return value.slice(0, 20).map((entry) => sanitizeValue(entry, key, depth + 1));\n }\n\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).map(\n ([entryKey, entryValue]) => [entryKey, sanitizeValue(entryValue, entryKey, depth + 1)],\n );\n return Object.fromEntries(entries);\n }\n\n return value;\n}\n\nfunction sanitizeRequest(request: Event[\"request\"]): Event[\"request\"] {\n if (!request) return request;\n\n return {\n ...request,\n data: request.data ? summarizeValue(request.data, \"body\") : undefined,\n headers: undefined,\n cookies: undefined,\n };\n}\n\nfunction getTraceAttribution(traceId: string): SentryAttributionAttributes | undefined {\n const entry = traceAttribution.get(traceId);\n if (!entry) return undefined;\n if (entry.expiresAt > Date.now()) return entry.attributes;\n traceAttribution.delete(traceId);\n return undefined;\n}\n\nfunction pruneExpiredTraceAttributions(now: number): void {\n for (const [traceId, entry] of traceAttribution) {\n if (entry.expiresAt <= now) traceAttribution.delete(traceId);\n }\n}\n\nfunction isSensitiveKey(key?: string): boolean {\n if (!key) return false;\n return SENSITIVE_KEYS.has(key.toLowerCase().replace(/[^a-z0-9]/g, \"\"));\n}\n\nfunction summarizeValue(value: unknown, key?: string): string {\n const label = key ?? \"field\";\n if (typeof value === \"string\") {\n return `[Redacted ${label}; length=${value.length}]`;\n }\n if (Array.isArray(value)) {\n return `[Redacted ${label}; items=${value.length}]`;\n }\n if (value && typeof value === \"object\") {\n return `[Redacted ${label}; keys=${Object.keys(value as Record<string, unknown>).length}]`;\n }\n return `[Redacted ${label}]`;\n}\n\nfunction sanitizeString(value: string): string {\n let sanitized = value.replace(new RegExp(ABSOLUTE_PATH_PATTERN, \"g\"), REDACTED_PATH);\n for (const pattern of TOKEN_PATTERNS) {\n sanitized = sanitized.replace(new RegExp(pattern, \"g\"), REDACTED);\n }\n if (sanitized.length > MAX_STRING_LENGTH) {\n return `${sanitized.slice(0, MAX_STRING_LENGTH)}… [truncated ${sanitized.length - MAX_STRING_LENGTH} chars]`;\n }\n return sanitized;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../src/tools/subagent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAA2B,MAAM,+BAA+B,CAAC;AACxF,OAAO,EAAqB,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../src/tools/subagent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAA2B,MAAM,+BAA+B,CAAC;AACxF,OAAO,EAAqB,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AA2HpG,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAA0B,CAAC;AAM/C,KAAK,WAAW,GAAG,CAAC,aAAa,SAAS,OAAO,GAAG,SAAS,GAAG,SAAS,EACvE,OAAO,EAAE,kBAAkB,CAAC,aAAa,CAAC,KACvC,OAAO,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AAoSlE,gFAAgF;AAChF,UAAU,wBAAwB;IAChC,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB;AAyBD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,WAAW,EACxB,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,wBAAwB,CAAC,GACtD,SAAS,CAAC,OAAO,cAAc,CAAC,CA0ElC"}
|
package/dist/tools/subagent.js
CHANGED
|
@@ -10,8 +10,9 @@ const MAX_DEPENDENCY_OUTPUT_CHARS = 4000;
|
|
|
10
10
|
* tool grant, model and budget defaults. Letting the model assemble those
|
|
11
11
|
* per call proved unstable, so the schema deliberately exposes no
|
|
12
12
|
* `systemPrompt`, `tools` or `model` escape hatch — narrowing what the model
|
|
13
|
-
* can get wrong is the point. `budget` survives
|
|
14
|
-
* the profile
|
|
13
|
+
* can get wrong is the point. `budget` survives so the model can propose
|
|
14
|
+
* limits. Token requests may raise the profile allowance; the other fields can
|
|
15
|
+
* only tighten profile defaults.
|
|
15
16
|
*
|
|
16
17
|
* `profileNames` is baked into the schema as an enum to steer the model's
|
|
17
18
|
* choice. TypeBox does not check `enum` on a string, so an unknown name still
|
|
@@ -44,7 +45,9 @@ const sharedProperties = {
|
|
|
44
45
|
maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
45
46
|
maxCostUsd: Type.Optional(Type.Number({ minimum: 0 })),
|
|
46
47
|
maxDurationMs: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
47
|
-
}, {
|
|
48
|
+
}, {
|
|
49
|
+
description: "Sets run budget preferences. maxTokens may raise the profile allowance; other fields can only tighten profile defaults.",
|
|
50
|
+
})),
|
|
48
51
|
};
|
|
49
52
|
/**
|
|
50
53
|
* The runtime schema varies only in the `profile` enum, so every instance
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../src/tools/subagent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAA6B,MAAM,mBAAmB,CAAC;AAMpE,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAExF,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,wBAAwB,GAAG,CAAC,CAAC;AACnC,MAAM,2BAA2B,GAAG,IAAI,CAAC;AAEzC;;;;;;;;;;;GAWG;AACH,SAAS,mBAAmB,CAAC,YAAsB;IACjD,OAAO;QACL,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,WAAW,EAAE,2CAA2C,EAAE,CAAC;QAC7F,OAAO,EAAE,IAAI,CAAC,QAAQ,CACpB,IAAI,CAAC,MAAM,CAAC;YACV,IAAI,EAAE,YAAY;YAClB,WAAW,EACT,+HAA+H;SAClI,CAAC,CACH;QACD,2EAA2E;QAC3E,2EAA2E;QAC3E,kEAAkE;QAClE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC,CAAC;QAC7F,KAAK,EAAE,IAAI,CAAC,QAAQ,CAClB,IAAI,CAAC,OAAO,CAAC,EAAE,WAAW,EAAE,2DAA2D,EAAE,CAAC,CAC3F;KACF,CAAC;AACJ,CAAC;AAED,MAAM,gBAAgB,GAAG;IACvB,aAAa,EAAE,IAAI,CAAC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ACZ,IAAI,EAAE,OAAO;qCACV,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,KAAK,GAAG,CAAC,KAAK,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC;qCACjE,IAAI,CAAC,MAAM,CAAC;6BAChB;yBACF;wBACD,OAAO,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE;qBACvC,CAAC;gBACJ,CAAC;gBACD,KAAK,QAAQ,EAAE,CAAC;oBACd,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;oBAC1C,OAAO;wBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC;wBACxD,OAAO,EAAE,MAAM;qBAChB,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool, AgentToolUpdateCallback } from \"@earendil-works/pi-agent-core\";\nimport { Type, type Static, type TSchema } from \"@sinclair/typebox\";\nimport type { SubagentRunOutput, SubagentRunRequest, SubagentRunResult } from \"../harness/types.js\";\n// Progress statuses extend run statuses with the pre- and non-run states. The\n// dashboard renders the same union, so it is defined once alongside the\n// snapshot the tool emits rather than restated here.\nimport type { SubagentProgressNode, SubagentProgressStatus } from \"../types.js\";\nimport { boundSubagentProgressNode, clampSubagentLabel } from \"../subagent-progress.js\";\n\nconst MAX_DAG_NODES = 8;\nconst MAX_DAG_EDGES = 16;\nconst MAX_DAG_DEPTH = 4;\nconst MAX_CONCURRENT_SUBAGENTS = 4;\nconst MAX_DEPENDENCY_OUTPUT_CHARS = 4000;\n\n/**\n * Every subagent runs under a named profile: the profile owns the prompt,\n * tool grant, model and budget defaults. Letting the model assemble those\n * per call proved unstable, so the schema deliberately exposes no\n * `systemPrompt`, `tools` or `model` escape hatch — narrowing what the model\n * can get wrong is the point. `budget` survives because it can only tighten\n * the profile's defaults, never widen them.\n *\n * `profileNames` is baked into the schema as an enum to steer the model's\n * choice. TypeBox does not check `enum` on a string, so an unknown name still\n * reaches `validatePlanProfiles`, which names the available profiles.\n */\nfunction buildTaskProperties(profileNames: string[]) {\n return {\n task: Type.String({ minLength: 1, description: \"Self-contained task for a fresh subagent.\" }),\n profile: Type.Optional(\n Type.String({\n enum: profileNames,\n description:\n \"Profile this subagent runs under. Required, but a top-level profile covers every task and DAG node that does not set its own.\",\n }),\n ),\n // No length bound: a label is a display string, and `taskLabel` clamps it.\n // Bounding it in the schema only lets a cosmetic field reject a whole DAG,\n // and validation reports that failure by echoing every node back.\n label: Type.Optional(Type.String({ description: \"Short progress label for this subagent.\" })),\n input: Type.Optional(\n Type.Unknown({ description: \"Optional JSON-serializable structured input for the task.\" }),\n ),\n };\n}\n\nconst sharedProperties = {\n parentContext: Type.Optional(\n Type.Object({\n mode: Type.Literal(\"normalized\"),\n recentTurns: Type.Optional(Type.Integer({ minimum: 1, maximum: 8, default: 3 })),\n }),\n ),\n outputSchema: Type.Optional(\n Type.Record(Type.String(), Type.Unknown(), {\n description: \"Optional TypeBox/JSON Schema applied to every subagent result.\",\n }),\n ),\n budget: Type.Optional(\n Type.Object(\n {\n maxTurns: Type.Optional(Type.Integer({ minimum: 1 })),\n maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),\n maxCostUsd: Type.Optional(Type.Number({ minimum: 0 })),\n maxDurationMs: Type.Optional(Type.Integer({ minimum: 1 })),\n },\n { description: \"Tightens the profile's budget defaults; cannot raise them.\" },\n ),\n ),\n};\n\n/**\n * The runtime schema varies only in the `profile` enum, so every instance\n * shares one static type and `subagentSchema` below can stand in for it.\n */\nfunction buildSubagentSchema(profileNames: string[]) {\n const taskProperties = buildTaskProperties(profileNames);\n return Type.Object(\n {\n task: Type.Optional(taskProperties.task),\n profile: taskProperties.profile,\n label: taskProperties.label,\n input: taskProperties.input,\n tasks: Type.Optional(\n Type.Array(Type.Object(taskProperties), {\n minItems: 1,\n maxItems: MAX_DAG_NODES,\n description:\n \"Independent subagent tasks executed concurrently; results preserve input order.\",\n }),\n ),\n dag: Type.Optional(\n Type.Object({\n nodes: Type.Array(\n Type.Object({\n id: Type.String({\n pattern: \"^[A-Za-z0-9_-]+$\",\n maxLength: 64,\n description: \"Unique stable node id used by dependsOn.\",\n }),\n ...taskProperties,\n dependsOn: Type.Optional(Type.Array(Type.String(), { maxItems: MAX_DAG_NODES })),\n }),\n { minItems: 1, maxItems: MAX_DAG_NODES },\n ),\n maxConcurrency: Type.Optional(\n Type.Integer({\n minimum: 1,\n maximum: MAX_CONCURRENT_SUBAGENTS,\n default: MAX_CONCURRENT_SUBAGENTS,\n }),\n ),\n }),\n ),\n ...sharedProperties,\n },\n { description: \"Provide task, tasks, or dag.\" },\n );\n}\n\nconst subagentSchema = buildSubagentSchema([]);\n\ntype SubagentParams = Static<typeof subagentSchema>;\ntype SubagentTask = NonNullable<SubagentParams[\"tasks\"]>[number];\ntype DagNode = NonNullable<SubagentParams[\"dag\"]>[\"nodes\"][number];\ntype SharedParams = Pick<SubagentParams, \"parentContext\" | \"outputSchema\" | \"budget\">;\ntype RunSubagent = <TOutputSchema extends TSchema | undefined = undefined>(\n request: SubagentRunRequest<TOutputSchema>,\n) => Promise<SubagentRunResult<SubagentRunOutput<TOutputSchema>>>;\n\ntype PlanMode = \"single\" | \"parallel\" | \"dag\";\n\n/** One planned subagent run; single and tasks modes are plans with no edges. */\ninterface PlanItem {\n id: string;\n label: string;\n task: SubagentTask;\n dependsOn: string[];\n}\n\ninterface Plan {\n mode: PlanMode;\n items: PlanItem[];\n waves: PlanItem[][];\n concurrency: number;\n}\n\ntype PlanOutcome =\n | ({ id: string } & SubagentRunResult<unknown>)\n | { id: string; status: \"skipped\"; error: string };\n\n/** The metrics half of a progress node — derived, not restated. */\ntype SubagentProgressMetrics = Omit<SubagentProgressNode, \"id\" | \"label\" | \"status\" | \"profile\">;\n\nclass SubagentProgressTracker {\n private readonly states = new Map<string, SubagentProgressStatus>();\n private readonly metrics = new Map<string, SubagentProgressMetrics>();\n\n constructor(\n private readonly mode: PlanMode,\n private readonly items: Array<{ id: string; label: string; profile?: string }>,\n private readonly onUpdate?: AgentToolUpdateCallback,\n ) {\n for (const item of items) this.states.set(item.id, \"pending\");\n }\n\n update(id: string, status: SubagentProgressStatus, metrics?: SubagentProgressMetrics): void {\n this.states.set(id, status);\n if (metrics) this.metrics.set(id, metrics);\n this.emit();\n }\n\n emit(): void {\n if (!this.onUpdate) return;\n const nodes = this.items.map((item) =>\n boundSubagentProgressNode({\n ...item,\n status: this.states.get(item.id) ?? (\"pending\" as SubagentProgressStatus),\n ...this.metrics.get(item.id),\n }),\n );\n this.onUpdate({\n content: [],\n details: { progress: { mode: this.mode, nodes } },\n });\n }\n}\n\nfunction taskLabel(task: SubagentTask, fallback: string): string {\n return clampSubagentLabel(task.label?.trim() || task.task.trim().slice(0, 48) || fallback);\n}\n\nfunction formatOutcome(outcome: {\n status: SubagentProgressStatus;\n output?: unknown;\n error?: string;\n}): string {\n if (outcome.status === \"budget_exceeded\") {\n return `Subagent stopped: budget limit exceeded${outcome.error ? ` (${outcome.error})` : \"\"}`;\n }\n if (outcome.status !== \"completed\") {\n return `Subagent ${outcome.status}${outcome.error ? `: ${outcome.error}` : \"\"}`;\n }\n return typeof outcome.output === \"string\"\n ? outcome.output\n : JSON.stringify(outcome.output, null, 2);\n}\n\nfunction buildRequest(\n task: SubagentTask,\n shared: SharedParams,\n signal?: AbortSignal,\n): SubagentRunRequest<TSchema | undefined> {\n const outputSchema = shared.outputSchema as TSchema | undefined;\n return {\n task: task.task,\n ...(task.profile ? { profile: task.profile } : {}),\n ...(task.input !== undefined ? { input: task.input } : {}),\n ...(shared.parentContext ? { parentContext: shared.parentContext } : {}),\n ...(outputSchema ? { outputSchema } : {}),\n ...(shared.budget ? { budget: shared.budget } : {}),\n ...(signal ? { signal } : {}),\n };\n}\n\nfunction buildDagWaves(nodes: DagNode[]): DagNode[][] {\n if (nodes.length === 0 || nodes.length > MAX_DAG_NODES) {\n throw new Error(`Subagent DAG must contain 1-${MAX_DAG_NODES} nodes`);\n }\n const byId = new Map<string, DagNode>();\n let edgeCount = 0;\n for (const node of nodes) {\n if (!/^[A-Za-z0-9_-]{1,64}$/.test(node.id)) {\n throw new Error(`Invalid subagent DAG node id: ${node.id}`);\n }\n if (byId.has(node.id)) throw new Error(`Duplicate subagent DAG node id: ${node.id}`);\n byId.set(node.id, node);\n const dependencies = new Set(node.dependsOn ?? []);\n if (dependencies.size !== (node.dependsOn?.length ?? 0)) {\n throw new Error(`Duplicate dependency on subagent DAG node: ${node.id}`);\n }\n edgeCount += dependencies.size;\n }\n if (edgeCount > MAX_DAG_EDGES) {\n throw new Error(`Subagent DAG exceeds ${MAX_DAG_EDGES} dependency edges`);\n }\n for (const node of nodes) {\n for (const dependency of node.dependsOn ?? []) {\n if (!byId.has(dependency)) {\n throw new Error(`Unknown subagent DAG dependency ${dependency} for node ${node.id}`);\n }\n if (dependency === node.id) throw new Error(`Subagent DAG node ${node.id} depends on itself`);\n }\n }\n\n const remaining = new Set(nodes.map((node) => node.id));\n const completed = new Set<string>();\n const waves: DagNode[][] = [];\n while (remaining.size > 0) {\n const wave = nodes.filter(\n (node) => remaining.has(node.id) && (node.dependsOn ?? []).every((id) => completed.has(id)),\n );\n if (wave.length === 0) throw new Error(\"Subagent DAG contains a cycle\");\n waves.push(wave);\n if (waves.length > MAX_DAG_DEPTH) {\n throw new Error(`Subagent DAG exceeds maximum depth ${MAX_DAG_DEPTH}`);\n }\n for (const node of wave) {\n remaining.delete(node.id);\n completed.add(node.id);\n }\n }\n return waves;\n}\n\n/**\n * A top-level `profile` is the default for every task and DAG node, like the\n * other shared params. A fan-out that runs entirely under one profile then\n * names it once instead of repeating it per node.\n */\nfunction withDefaultProfile<T extends { profile?: string }>(task: T, fallback?: string): T {\n return task.profile || !fallback ? task : { ...task, profile: fallback };\n}\n\nfunction itemForNode(node: DagNode, defaultProfile?: string): PlanItem {\n return {\n id: node.id,\n label: clampSubagentLabel(node.label?.trim() || node.id),\n task: withDefaultProfile(node, defaultProfile),\n dependsOn: node.dependsOn ?? [],\n };\n}\n\n/** Normalize every tool mode into one plan: nodes, waves, concurrency. */\nfunction buildPlan(params: SubagentParams): Plan {\n const modeCount = [params.task, params.tasks, params.dag].filter(\n (mode) => mode !== undefined,\n ).length;\n if (modeCount !== 1) {\n throw new Error(\"Subagent requires exactly one of task, tasks, or dag\");\n }\n\n if (params.dag !== undefined) {\n const toItem = (node: DagNode) => itemForNode(node, params.profile);\n const waves = buildDagWaves(params.dag.nodes).map((wave) => wave.map(toItem));\n const requested = params.dag.maxConcurrency ?? MAX_CONCURRENT_SUBAGENTS;\n return {\n mode: \"dag\",\n items: params.dag.nodes.map(toItem),\n waves,\n concurrency: Math.max(1, Math.min(MAX_CONCURRENT_SUBAGENTS, Math.floor(requested))),\n };\n }\n if (params.tasks !== undefined) {\n const items = params.tasks.map((task, index) => ({\n id: String(index),\n label: taskLabel(task, String(index + 1)),\n task: withDefaultProfile(task, params.profile),\n dependsOn: [],\n }));\n return { mode: \"parallel\", items, waves: [items], concurrency: MAX_CONCURRENT_SUBAGENTS };\n }\n if (!params.task) throw new Error(\"Subagent requires task, tasks, or dag\");\n const task = { ...params, task: params.task };\n const item = { id: \"0\", label: taskLabel(task, \"subagent\"), task, dependsOn: [] };\n return { mode: \"single\", items: [item], waves: [[item]], concurrency: 1 };\n}\n\n/** Run `worker` over every item with at most `limit` in flight. */\nasync function forEachConcurrent<T>(\n items: readonly T[],\n limit: number,\n worker: (item: T, index: number) => Promise<void>,\n): Promise<void> {\n let cursor = 0;\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, async () => {\n while (cursor < items.length) {\n const index = cursor++;\n await worker(items[index], index);\n }\n }),\n );\n}\n\nfunction dependencyOutput(outcome: PlanOutcome): unknown {\n if (outcome.status !== \"completed\") return undefined;\n const value = outcome.output;\n const serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n if (serialized === undefined) return null;\n if (serialized.length <= MAX_DEPENDENCY_OUTPUT_CHARS) return value;\n // Oversized structured output becomes a marked string — the shape is lost,\n // which the tool description warns downstream consumers about.\n return `${serialized.slice(0, MAX_DEPENDENCY_OUTPUT_CHARS)}\\n[truncated]`;\n}\n\nfunction planRequest(\n item: PlanItem,\n shared: SharedParams,\n outcomes: Map<string, PlanOutcome>,\n signal?: AbortSignal,\n): SubagentRunRequest<TSchema | undefined> {\n if (item.dependsOn.length === 0) return buildRequest(item.task, shared, signal);\n const dependencies = Object.fromEntries(\n item.dependsOn.map((id) => [id, dependencyOutput(outcomes.get(id)!)]),\n );\n const input = {\n ...(item.task.input !== undefined ? { input: item.task.input } : {}),\n dependencies,\n };\n return buildRequest({ ...item.task, input }, shared, signal);\n}\n\n/**\n * One executor for every mode: wave barriers and a per-invocation concurrency\n * bound. Process-wide slots are acquired by the shared runner seam.\n */\nasync function runWaves(\n plan: Plan,\n shared: SharedParams,\n runSubagent: RunSubagent,\n progress: SubagentProgressTracker,\n signal?: AbortSignal,\n): Promise<PlanOutcome[]> {\n const outcomes = new Map<string, PlanOutcome>();\n for (const wave of plan.waves) {\n await forEachConcurrent(wave, plan.concurrency, async (item) => {\n const failedDependency = item.dependsOn.find(\n (id) => outcomes.get(id)?.status !== \"completed\",\n );\n if (failedDependency) {\n outcomes.set(item.id, {\n id: item.id,\n status: \"skipped\",\n error: `Dependency ${failedDependency} did not complete`,\n });\n progress.update(item.id, \"skipped\", {\n reason: `Dependency ${failedDependency} did not complete`,\n });\n return;\n }\n let result: SubagentRunResult<unknown>;\n progress.update(item.id, \"running\");\n result = await runSubagent(planRequest(item, shared, outcomes, signal));\n outcomes.set(item.id, { id: item.id, ...result });\n progress.update(item.id, result.status, {\n turns: result.turns,\n toolCalls: result.toolCalls,\n toolCallCounts: result.toolCallCounts,\n tokens: result.tokens,\n costUsd: result.costUsd,\n durationMs: result.durationMs,\n ...(result.error ? { reason: result.error } : {}),\n ...(result.cleanupPending ? { cleanupPending: true } : {}),\n });\n });\n }\n return plan.items.map((item) => outcomes.get(item.id)!);\n}\n\n/** What the model needs to choose a profile: what it is, and what it can do. */\ninterface SubagentProfileMenuEntry {\n description: string;\n tools?: string[];\n}\n\n/**\n * The tool grant belongs in the menu. A description alone reads as a stylistic\n * constraint, so a model will pick a no-tool profile for work that needs tools\n * and then narrate the tool call it could not make.\n */\nfunction formatToolGrant(tools: string[] | undefined): string {\n if (!tools) return \"tools unknown\";\n return tools.length === 0 ? \"no tools\" : `tools: ${tools.join(\", \")}`;\n}\n\nfunction validatePlanProfiles(plan: Plan, availableProfiles: ReadonlySet<string>): void {\n const known = [...availableProfiles].join(\", \");\n for (const item of plan.items) {\n const profile = item.task.profile;\n if (!profile) {\n throw new Error(`Subagent ${item.label} must specify a profile (available: ${known})`);\n }\n if (!availableProfiles.has(profile)) {\n throw new Error(`Unknown subagent profile: ${profile} (available: ${known})`);\n }\n }\n}\n\n/**\n * Create the normal agent's bounded subagent delegation and DAG tool.\n * `globalSlots` is the process-wide fan-out account shared across every\n * conversation's tool instance; omitted, fan-out is bounded per run only.\n *\n * `profiles` must be non-empty: it is both the model-facing menu and the only\n * way to grant a subagent any capability at all.\n */\nexport function createSubagentTool(\n runSubagent: RunSubagent,\n profiles: ReadonlyMap<string, SubagentProfileMenuEntry>,\n): AgentTool<typeof subagentSchema> {\n if (profiles.size === 0) {\n throw new Error(\"createSubagentTool requires at least one subagent profile\");\n }\n const profileDescription = [...profiles.entries()]\n .map(\n ([name, profile]) => `${name} [${formatToolGrant(profile.tools)}] — ${profile.description}`,\n )\n .join(\"; \");\n return {\n name: \"subagent\",\n label: \"Subagent\",\n description:\n `Run fresh isolated subagents. Use task for one subagent, tasks for independent concurrent work, or dag.nodes for a bounded dependency graph. At most ${MAX_CONCURRENT_SUBAGENTS} subagents run concurrently. DAG limits: ${MAX_DAG_NODES} nodes, ${MAX_DAG_EDGES} edges, depth ${MAX_DAG_DEPTH}; failed dependencies skip descendants, and dependency outputs larger than ${MAX_DEPENDENCY_OUTPUT_CHARS} characters reach downstream nodes as a truncated string. ` +\n \"Subagents are fresh by default; parentContext.mode=normalized can include a sanitized reference snapshot of the active parent run. Nested subagents are not allowed. \" +\n `Every task and DAG node must set profile; the profile supplies the prompt, tools, model and budget. Available profiles: ${profileDescription}.`,\n parameters: buildSubagentSchema([...profiles.keys()]),\n execute: async (\n _toolCallId: string,\n params: SubagentParams,\n signal?: AbortSignal,\n onUpdate?: AgentToolUpdateCallback,\n ) => {\n const plan = buildPlan(params);\n validatePlanProfiles(plan, new Set(profiles.keys()));\n const progress = new SubagentProgressTracker(\n plan.mode,\n plan.items.map(({ id, label, task }) => ({ id, label, profile: task.profile })),\n onUpdate,\n );\n progress.emit();\n const ordered = await runWaves(plan, params, runSubagent, progress, signal);\n\n switch (plan.mode) {\n case \"dag\":\n return {\n content: [\n {\n type: \"text\",\n text: ordered\n .map((outcome) => `[${outcome.id}] ${formatOutcome(outcome)}`)\n .join(\"\\n\\n\"),\n },\n ],\n details: {\n mode: \"dag\",\n waves: plan.waves.map((wave) => wave.map((item) => item.id)),\n results: ordered,\n },\n };\n case \"parallel\": {\n const results = ordered.map(({ id: _id, ...result }) => result);\n return {\n content: [\n {\n type: \"text\",\n text: results\n .map((result, index) => `[${index + 1}] ${formatOutcome(result)}`)\n .join(\"\\n\\n\"),\n },\n ],\n details: { mode: \"parallel\", results },\n };\n }\n case \"single\": {\n const { id: _id, ...result } = ordered[0];\n return {\n content: [{ type: \"text\", text: formatOutcome(result) }],\n details: result,\n };\n }\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../src/tools/subagent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAA6B,MAAM,mBAAmB,CAAC;AAMpE,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAExF,MAAM,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;oBAC1C,OAAO;wBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC;wBACxD,OAAO,EAAE,MAAM;qBAChB,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentTool, AgentToolUpdateCallback } from \"@earendil-works/pi-agent-core\";\nimport { Type, type Static, type TSchema } from \"@sinclair/typebox\";\nimport type { SubagentRunOutput, SubagentRunRequest, SubagentRunResult } from \"../harness/types.js\";\n// Progress statuses extend run statuses with the pre- and non-run states. The\n// dashboard renders the same union, so it is defined once alongside the\n// snapshot the tool emits rather than restated here.\nimport type { SubagentProgressNode, SubagentProgressStatus } from \"../types.js\";\nimport { boundSubagentProgressNode, clampSubagentLabel } from \"../subagent-progress.js\";\n\nconst MAX_DAG_NODES = 8;\nconst MAX_DAG_EDGES = 16;\nconst MAX_DAG_DEPTH = 4;\nconst MAX_CONCURRENT_SUBAGENTS = 4;\nconst MAX_DEPENDENCY_OUTPUT_CHARS = 4000;\n\n/**\n * Every subagent runs under a named profile: the profile owns the prompt,\n * tool grant, model and budget defaults. Letting the model assemble those\n * per call proved unstable, so the schema deliberately exposes no\n * `systemPrompt`, `tools` or `model` escape hatch — narrowing what the model\n * can get wrong is the point. `budget` survives so the model can propose\n * limits. Token requests may raise the profile allowance; the other fields can\n * only tighten profile defaults.\n *\n * `profileNames` is baked into the schema as an enum to steer the model's\n * choice. TypeBox does not check `enum` on a string, so an unknown name still\n * reaches `validatePlanProfiles`, which names the available profiles.\n */\nfunction buildTaskProperties(profileNames: string[]) {\n return {\n task: Type.String({ minLength: 1, description: \"Self-contained task for a fresh subagent.\" }),\n profile: Type.Optional(\n Type.String({\n enum: profileNames,\n description:\n \"Profile this subagent runs under. Required, but a top-level profile covers every task and DAG node that does not set its own.\",\n }),\n ),\n // No length bound: a label is a display string, and `taskLabel` clamps it.\n // Bounding it in the schema only lets a cosmetic field reject a whole DAG,\n // and validation reports that failure by echoing every node back.\n label: Type.Optional(Type.String({ description: \"Short progress label for this subagent.\" })),\n input: Type.Optional(\n Type.Unknown({ description: \"Optional JSON-serializable structured input for the task.\" }),\n ),\n };\n}\n\nconst sharedProperties = {\n parentContext: Type.Optional(\n Type.Object({\n mode: Type.Literal(\"normalized\"),\n recentTurns: Type.Optional(Type.Integer({ minimum: 1, maximum: 8, default: 3 })),\n }),\n ),\n outputSchema: Type.Optional(\n Type.Record(Type.String(), Type.Unknown(), {\n description: \"Optional TypeBox/JSON Schema applied to every subagent result.\",\n }),\n ),\n budget: Type.Optional(\n Type.Object(\n {\n maxTurns: Type.Optional(Type.Integer({ minimum: 1 })),\n maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),\n maxCostUsd: Type.Optional(Type.Number({ minimum: 0 })),\n maxDurationMs: Type.Optional(Type.Integer({ minimum: 1 })),\n },\n {\n description:\n \"Sets run budget preferences. maxTokens may raise the profile allowance; other fields can only tighten profile defaults.\",\n },\n ),\n ),\n};\n\n/**\n * The runtime schema varies only in the `profile` enum, so every instance\n * shares one static type and `subagentSchema` below can stand in for it.\n */\nfunction buildSubagentSchema(profileNames: string[]) {\n const taskProperties = buildTaskProperties(profileNames);\n return Type.Object(\n {\n task: Type.Optional(taskProperties.task),\n profile: taskProperties.profile,\n label: taskProperties.label,\n input: taskProperties.input,\n tasks: Type.Optional(\n Type.Array(Type.Object(taskProperties), {\n minItems: 1,\n maxItems: MAX_DAG_NODES,\n description:\n \"Independent subagent tasks executed concurrently; results preserve input order.\",\n }),\n ),\n dag: Type.Optional(\n Type.Object({\n nodes: Type.Array(\n Type.Object({\n id: Type.String({\n pattern: \"^[A-Za-z0-9_-]+$\",\n maxLength: 64,\n description: \"Unique stable node id used by dependsOn.\",\n }),\n ...taskProperties,\n dependsOn: Type.Optional(Type.Array(Type.String(), { maxItems: MAX_DAG_NODES })),\n }),\n { minItems: 1, maxItems: MAX_DAG_NODES },\n ),\n maxConcurrency: Type.Optional(\n Type.Integer({\n minimum: 1,\n maximum: MAX_CONCURRENT_SUBAGENTS,\n default: MAX_CONCURRENT_SUBAGENTS,\n }),\n ),\n }),\n ),\n ...sharedProperties,\n },\n { description: \"Provide task, tasks, or dag.\" },\n );\n}\n\nconst subagentSchema = buildSubagentSchema([]);\n\ntype SubagentParams = Static<typeof subagentSchema>;\ntype SubagentTask = NonNullable<SubagentParams[\"tasks\"]>[number];\ntype DagNode = NonNullable<SubagentParams[\"dag\"]>[\"nodes\"][number];\ntype SharedParams = Pick<SubagentParams, \"parentContext\" | \"outputSchema\" | \"budget\">;\ntype RunSubagent = <TOutputSchema extends TSchema | undefined = undefined>(\n request: SubagentRunRequest<TOutputSchema>,\n) => Promise<SubagentRunResult<SubagentRunOutput<TOutputSchema>>>;\n\ntype PlanMode = \"single\" | \"parallel\" | \"dag\";\n\n/** One planned subagent run; single and tasks modes are plans with no edges. */\ninterface PlanItem {\n id: string;\n label: string;\n task: SubagentTask;\n dependsOn: string[];\n}\n\ninterface Plan {\n mode: PlanMode;\n items: PlanItem[];\n waves: PlanItem[][];\n concurrency: number;\n}\n\ntype PlanOutcome =\n | ({ id: string } & SubagentRunResult<unknown>)\n | { id: string; status: \"skipped\"; error: string };\n\n/** The metrics half of a progress node — derived, not restated. */\ntype SubagentProgressMetrics = Omit<SubagentProgressNode, \"id\" | \"label\" | \"status\" | \"profile\">;\n\nclass SubagentProgressTracker {\n private readonly states = new Map<string, SubagentProgressStatus>();\n private readonly metrics = new Map<string, SubagentProgressMetrics>();\n\n constructor(\n private readonly mode: PlanMode,\n private readonly items: Array<{ id: string; label: string; profile?: string }>,\n private readonly onUpdate?: AgentToolUpdateCallback,\n ) {\n for (const item of items) this.states.set(item.id, \"pending\");\n }\n\n update(id: string, status: SubagentProgressStatus, metrics?: SubagentProgressMetrics): void {\n this.states.set(id, status);\n if (metrics) this.metrics.set(id, metrics);\n this.emit();\n }\n\n emit(): void {\n if (!this.onUpdate) return;\n const nodes = this.items.map((item) =>\n boundSubagentProgressNode({\n ...item,\n status: this.states.get(item.id) ?? (\"pending\" as SubagentProgressStatus),\n ...this.metrics.get(item.id),\n }),\n );\n this.onUpdate({\n content: [],\n details: { progress: { mode: this.mode, nodes } },\n });\n }\n}\n\nfunction taskLabel(task: SubagentTask, fallback: string): string {\n return clampSubagentLabel(task.label?.trim() || task.task.trim().slice(0, 48) || fallback);\n}\n\nfunction formatOutcome(outcome: {\n status: SubagentProgressStatus;\n output?: unknown;\n error?: string;\n}): string {\n if (outcome.status === \"budget_exceeded\") {\n return `Subagent stopped: budget limit exceeded${outcome.error ? ` (${outcome.error})` : \"\"}`;\n }\n if (outcome.status !== \"completed\") {\n return `Subagent ${outcome.status}${outcome.error ? `: ${outcome.error}` : \"\"}`;\n }\n return typeof outcome.output === \"string\"\n ? outcome.output\n : JSON.stringify(outcome.output, null, 2);\n}\n\nfunction buildRequest(\n task: SubagentTask,\n shared: SharedParams,\n signal?: AbortSignal,\n): SubagentRunRequest<TSchema | undefined> {\n const outputSchema = shared.outputSchema as TSchema | undefined;\n return {\n task: task.task,\n ...(task.profile ? { profile: task.profile } : {}),\n ...(task.input !== undefined ? { input: task.input } : {}),\n ...(shared.parentContext ? { parentContext: shared.parentContext } : {}),\n ...(outputSchema ? { outputSchema } : {}),\n ...(shared.budget ? { budget: shared.budget } : {}),\n ...(signal ? { signal } : {}),\n };\n}\n\nfunction buildDagWaves(nodes: DagNode[]): DagNode[][] {\n if (nodes.length === 0 || nodes.length > MAX_DAG_NODES) {\n throw new Error(`Subagent DAG must contain 1-${MAX_DAG_NODES} nodes`);\n }\n const byId = new Map<string, DagNode>();\n let edgeCount = 0;\n for (const node of nodes) {\n if (!/^[A-Za-z0-9_-]{1,64}$/.test(node.id)) {\n throw new Error(`Invalid subagent DAG node id: ${node.id}`);\n }\n if (byId.has(node.id)) throw new Error(`Duplicate subagent DAG node id: ${node.id}`);\n byId.set(node.id, node);\n const dependencies = new Set(node.dependsOn ?? []);\n if (dependencies.size !== (node.dependsOn?.length ?? 0)) {\n throw new Error(`Duplicate dependency on subagent DAG node: ${node.id}`);\n }\n edgeCount += dependencies.size;\n }\n if (edgeCount > MAX_DAG_EDGES) {\n throw new Error(`Subagent DAG exceeds ${MAX_DAG_EDGES} dependency edges`);\n }\n for (const node of nodes) {\n for (const dependency of node.dependsOn ?? []) {\n if (!byId.has(dependency)) {\n throw new Error(`Unknown subagent DAG dependency ${dependency} for node ${node.id}`);\n }\n if (dependency === node.id) throw new Error(`Subagent DAG node ${node.id} depends on itself`);\n }\n }\n\n const remaining = new Set(nodes.map((node) => node.id));\n const completed = new Set<string>();\n const waves: DagNode[][] = [];\n while (remaining.size > 0) {\n const wave = nodes.filter(\n (node) => remaining.has(node.id) && (node.dependsOn ?? []).every((id) => completed.has(id)),\n );\n if (wave.length === 0) throw new Error(\"Subagent DAG contains a cycle\");\n waves.push(wave);\n if (waves.length > MAX_DAG_DEPTH) {\n throw new Error(`Subagent DAG exceeds maximum depth ${MAX_DAG_DEPTH}`);\n }\n for (const node of wave) {\n remaining.delete(node.id);\n completed.add(node.id);\n }\n }\n return waves;\n}\n\n/**\n * A top-level `profile` is the default for every task and DAG node, like the\n * other shared params. A fan-out that runs entirely under one profile then\n * names it once instead of repeating it per node.\n */\nfunction withDefaultProfile<T extends { profile?: string }>(task: T, fallback?: string): T {\n return task.profile || !fallback ? task : { ...task, profile: fallback };\n}\n\nfunction itemForNode(node: DagNode, defaultProfile?: string): PlanItem {\n return {\n id: node.id,\n label: clampSubagentLabel(node.label?.trim() || node.id),\n task: withDefaultProfile(node, defaultProfile),\n dependsOn: node.dependsOn ?? [],\n };\n}\n\n/** Normalize every tool mode into one plan: nodes, waves, concurrency. */\nfunction buildPlan(params: SubagentParams): Plan {\n const modeCount = [params.task, params.tasks, params.dag].filter(\n (mode) => mode !== undefined,\n ).length;\n if (modeCount !== 1) {\n throw new Error(\"Subagent requires exactly one of task, tasks, or dag\");\n }\n\n if (params.dag !== undefined) {\n const toItem = (node: DagNode) => itemForNode(node, params.profile);\n const waves = buildDagWaves(params.dag.nodes).map((wave) => wave.map(toItem));\n const requested = params.dag.maxConcurrency ?? MAX_CONCURRENT_SUBAGENTS;\n return {\n mode: \"dag\",\n items: params.dag.nodes.map(toItem),\n waves,\n concurrency: Math.max(1, Math.min(MAX_CONCURRENT_SUBAGENTS, Math.floor(requested))),\n };\n }\n if (params.tasks !== undefined) {\n const items = params.tasks.map((task, index) => ({\n id: String(index),\n label: taskLabel(task, String(index + 1)),\n task: withDefaultProfile(task, params.profile),\n dependsOn: [],\n }));\n return { mode: \"parallel\", items, waves: [items], concurrency: MAX_CONCURRENT_SUBAGENTS };\n }\n if (!params.task) throw new Error(\"Subagent requires task, tasks, or dag\");\n const task = { ...params, task: params.task };\n const item = { id: \"0\", label: taskLabel(task, \"subagent\"), task, dependsOn: [] };\n return { mode: \"single\", items: [item], waves: [[item]], concurrency: 1 };\n}\n\n/** Run `worker` over every item with at most `limit` in flight. */\nasync function forEachConcurrent<T>(\n items: readonly T[],\n limit: number,\n worker: (item: T, index: number) => Promise<void>,\n): Promise<void> {\n let cursor = 0;\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, async () => {\n while (cursor < items.length) {\n const index = cursor++;\n await worker(items[index], index);\n }\n }),\n );\n}\n\nfunction dependencyOutput(outcome: PlanOutcome): unknown {\n if (outcome.status !== \"completed\") return undefined;\n const value = outcome.output;\n const serialized = typeof value === \"string\" ? value : JSON.stringify(value);\n if (serialized === undefined) return null;\n if (serialized.length <= MAX_DEPENDENCY_OUTPUT_CHARS) return value;\n // Oversized structured output becomes a marked string — the shape is lost,\n // which the tool description warns downstream consumers about.\n return `${serialized.slice(0, MAX_DEPENDENCY_OUTPUT_CHARS)}\\n[truncated]`;\n}\n\nfunction planRequest(\n item: PlanItem,\n shared: SharedParams,\n outcomes: Map<string, PlanOutcome>,\n signal?: AbortSignal,\n): SubagentRunRequest<TSchema | undefined> {\n if (item.dependsOn.length === 0) return buildRequest(item.task, shared, signal);\n const dependencies = Object.fromEntries(\n item.dependsOn.map((id) => [id, dependencyOutput(outcomes.get(id)!)]),\n );\n const input = {\n ...(item.task.input !== undefined ? { input: item.task.input } : {}),\n dependencies,\n };\n return buildRequest({ ...item.task, input }, shared, signal);\n}\n\n/**\n * One executor for every mode: wave barriers and a per-invocation concurrency\n * bound. Process-wide slots are acquired by the shared runner seam.\n */\nasync function runWaves(\n plan: Plan,\n shared: SharedParams,\n runSubagent: RunSubagent,\n progress: SubagentProgressTracker,\n signal?: AbortSignal,\n): Promise<PlanOutcome[]> {\n const outcomes = new Map<string, PlanOutcome>();\n for (const wave of plan.waves) {\n await forEachConcurrent(wave, plan.concurrency, async (item) => {\n const failedDependency = item.dependsOn.find(\n (id) => outcomes.get(id)?.status !== \"completed\",\n );\n if (failedDependency) {\n outcomes.set(item.id, {\n id: item.id,\n status: \"skipped\",\n error: `Dependency ${failedDependency} did not complete`,\n });\n progress.update(item.id, \"skipped\", {\n reason: `Dependency ${failedDependency} did not complete`,\n });\n return;\n }\n let result: SubagentRunResult<unknown>;\n progress.update(item.id, \"running\");\n result = await runSubagent(planRequest(item, shared, outcomes, signal));\n outcomes.set(item.id, { id: item.id, ...result });\n progress.update(item.id, result.status, {\n turns: result.turns,\n toolCalls: result.toolCalls,\n toolCallCounts: result.toolCallCounts,\n tokens: result.tokens,\n costUsd: result.costUsd,\n durationMs: result.durationMs,\n ...(result.error ? { reason: result.error } : {}),\n ...(result.cleanupPending ? { cleanupPending: true } : {}),\n });\n });\n }\n return plan.items.map((item) => outcomes.get(item.id)!);\n}\n\n/** What the model needs to choose a profile: what it is, and what it can do. */\ninterface SubagentProfileMenuEntry {\n description: string;\n tools?: string[];\n}\n\n/**\n * The tool grant belongs in the menu. A description alone reads as a stylistic\n * constraint, so a model will pick a no-tool profile for work that needs tools\n * and then narrate the tool call it could not make.\n */\nfunction formatToolGrant(tools: string[] | undefined): string {\n if (!tools) return \"tools unknown\";\n return tools.length === 0 ? \"no tools\" : `tools: ${tools.join(\", \")}`;\n}\n\nfunction validatePlanProfiles(plan: Plan, availableProfiles: ReadonlySet<string>): void {\n const known = [...availableProfiles].join(\", \");\n for (const item of plan.items) {\n const profile = item.task.profile;\n if (!profile) {\n throw new Error(`Subagent ${item.label} must specify a profile (available: ${known})`);\n }\n if (!availableProfiles.has(profile)) {\n throw new Error(`Unknown subagent profile: ${profile} (available: ${known})`);\n }\n }\n}\n\n/**\n * Create the normal agent's bounded subagent delegation and DAG tool.\n * `globalSlots` is the process-wide fan-out account shared across every\n * conversation's tool instance; omitted, fan-out is bounded per run only.\n *\n * `profiles` must be non-empty: it is both the model-facing menu and the only\n * way to grant a subagent any capability at all.\n */\nexport function createSubagentTool(\n runSubagent: RunSubagent,\n profiles: ReadonlyMap<string, SubagentProfileMenuEntry>,\n): AgentTool<typeof subagentSchema> {\n if (profiles.size === 0) {\n throw new Error(\"createSubagentTool requires at least one subagent profile\");\n }\n const profileDescription = [...profiles.entries()]\n .map(\n ([name, profile]) => `${name} [${formatToolGrant(profile.tools)}] — ${profile.description}`,\n )\n .join(\"; \");\n return {\n name: \"subagent\",\n label: \"Subagent\",\n description:\n `Run fresh isolated subagents. Use task for one subagent, tasks for independent concurrent work, or dag.nodes for a bounded dependency graph. At most ${MAX_CONCURRENT_SUBAGENTS} subagents run concurrently. DAG limits: ${MAX_DAG_NODES} nodes, ${MAX_DAG_EDGES} edges, depth ${MAX_DAG_DEPTH}; failed dependencies skip descendants, and dependency outputs larger than ${MAX_DEPENDENCY_OUTPUT_CHARS} characters reach downstream nodes as a truncated string. ` +\n \"Subagents are fresh by default; parentContext.mode=normalized can include a sanitized reference snapshot of the active parent run. Nested subagents are not allowed. \" +\n `Every task and DAG node must set profile; the profile supplies the prompt, tools, model and budget. Available profiles: ${profileDescription}.`,\n parameters: buildSubagentSchema([...profiles.keys()]),\n execute: async (\n _toolCallId: string,\n params: SubagentParams,\n signal?: AbortSignal,\n onUpdate?: AgentToolUpdateCallback,\n ) => {\n const plan = buildPlan(params);\n validatePlanProfiles(plan, new Set(profiles.keys()));\n const progress = new SubagentProgressTracker(\n plan.mode,\n plan.items.map(({ id, label, task }) => ({ id, label, profile: task.profile })),\n onUpdate,\n );\n progress.emit();\n const ordered = await runWaves(plan, params, runSubagent, progress, signal);\n\n switch (plan.mode) {\n case \"dag\":\n return {\n content: [\n {\n type: \"text\",\n text: ordered\n .map((outcome) => `[${outcome.id}] ${formatOutcome(outcome)}`)\n .join(\"\\n\\n\"),\n },\n ],\n details: {\n mode: \"dag\",\n waves: plan.waves.map((wave) => wave.map((item) => item.id)),\n results: ordered,\n },\n };\n case \"parallel\": {\n const results = ordered.map(({ id: _id, ...result }) => result);\n return {\n content: [\n {\n type: \"text\",\n text: results\n .map((result, index) => `[${index + 1}] ${formatOutcome(result)}`)\n .join(\"\\n\\n\"),\n },\n ],\n details: { mode: \"parallel\", results },\n };\n }\n case \"single\": {\n const { id: _id, ...result } = ordered[0];\n return {\n content: [{ type: \"text\", text: formatOutcome(result) }],\n details: result,\n };\n }\n }\n },\n };\n}\n"]}
|