@geminixiang/mikan 1.0.0-beta.70 → 1.0.0-beta.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/adapters/web/admin/portal.d.ts.map +1 -1
- package/dist/adapters/web/admin/portal.js +279 -47
- package/dist/adapters/web/admin/portal.js.map +1 -1
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/index.d.ts.map +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/prompt.d.ts.map +1 -1
- package/dist/harness/prompt.js +4 -13
- package/dist/harness/prompt.js.map +1 -1
- package/dist/harness/skills.d.ts +2 -0
- package/dist/harness/skills.d.ts.map +1 -1
- package/dist/harness/skills.js +2 -1
- package/dist/harness/skills.js.map +1 -1
- package/dist/harness/subagent-profiles.d.ts.map +1 -1
- package/dist/harness/subagent-profiles.js +18 -9
- package/dist/harness/subagent-profiles.js.map +1 -1
- package/dist/harness/tools/subagent.d.ts +0 -3
- package/dist/harness/tools/subagent.d.ts.map +1 -1
- package/dist/harness/tools/subagent.js +3 -7
- package/dist/harness/tools/subagent.js.map +1 -1
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +4 -1
- package/dist/log.js.map +1 -1
- package/dist/sandbox/provisioner.d.ts.map +1 -1
- package/dist/sandbox/provisioner.js +1 -4
- package/dist/sandbox/provisioner.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-profiles.js","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAU3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa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f,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;YAC/D,IAAI,EAAE,GAAG;SACV,CAAC,CAAC;QACH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACnC,CAAC;IAED,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,SAAS;QAC7D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;YACvF,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,WAAW,CAAC,IAAI,CAAC;gBACf,IAAI,EAAE,SAAS;gBACf,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;gBAC/D,IAAI,EAAE,QAAQ;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Subagent profiles: the curated capability sets a subagent may be launched\n * with.\n *\n * Profiles exist because the two halves of a subagent definition have\n * different owners. What a profile *does* — its tools, required evidence,\n * prompt and budget — is portable, so it ships as a built-in below and is\n * versioned with the code. Which model runs it is per-installation, so it is\n * overridden by `<workspaceDir>/agents/<name>.md`.\n *\n * A workspace file therefore *patches* the built-in of the same name rather\n * than replacing it: overriding only `model:` must not force an operator to\n * restate the tools and prompt, because a restated copy silently drifts from\n * the built-in it was cloned from. A file whose name matches no built-in\n * defines a new profile and must supply `tools` itself.\n *\n * A malformed file is reported as a diagnostic and skipped, never thrown:\n * these are hand-edited, and one typo must not take the whole workspace down.\n */\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type {\n LoadSubagentProfilesResult,\n SubagentModelSpec,\n SubagentProfile,\n SubagentProfileDiagnostic,\n} from \"./types.js\";\n\nexport type { LoadSubagentProfilesResult, SubagentProfileDiagnostic } from \"./types.js\";\nimport { parseFrontmatter } from \"./skills.js\";\n\nconst BUILTIN_PROFILES: SubagentProfile[] = [\n {\n name: \"worker\",\n description: \"Completes a bounded general-purpose task without adding domain assumptions\",\n systemPrompt: [\n \"You are a general-purpose worker responsible for one clearly bounded delegated task.\",\n \"\",\n \"Use `read` and `bash` to inspect the actual workspace state, and use `edit` or `write` only when the assignment requires changes. Follow applicable skill instructions, preserve behavior outside the stated scope, and do not invent requirements or broaden the task. Verify concrete outputs before reporting success; if the assignment lacks information or a required capability, state the limitation instead of guessing.\",\n \"\",\n \"Keep verbose discovery and command output in this isolated run. Return the completed result, files or artifacts changed, verification performed, and any unresolved blocker.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\", \"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 1_000_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\", \"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 1_000_000,\n },\n {\n name: \"devops-engineer\",\n description:\n \"Owns cloud access, environments, deployments, and production workflow reliability\",\n systemPrompt: [\n \"You are the DevOps engineer responsible for one delegated infrastructure or production-operations outcome.\",\n \"\",\n \"Apply the relevant setup, GCP, repository-access, service-status, and production workflow skill instructions. Use `bash` to inspect current state before acting. Respect the named project, environment, principal, and resource scope; protect credentials; prefer least privilege; and check idempotency before writes, retries, or provisioning. Do not broaden access or repeat a non-idempotent operation without explicit authorization and evidence that it is needed.\",\n \"\",\n \"Keep verbose CLI, API, and job logs in this isolated run. Return the resulting state, affected resources or job identifiers, verification performed, and concrete follow-up or rollback information.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\", \"event\", \"sandbox\"],\n thinkingLevel: \"high\",\n maxTurns: 40,\n maxTokens: 1_000_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\", \"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 1_000_000,\n },\n {\n name: \"account-manager\",\n description:\n \"Owns existing-client onboarding, account coordination, and delivery follow-through\",\n systemPrompt: [\n \"You are the account manager responsible for one delegated existing-client outcome.\",\n \"\",\n \"Apply the relevant onboarding, publisher account, slot, workspace, meeting, and communication skill instructions. Use `bash` to inspect the current customer and account state before acting. Preserve supplied commercial and technical requirements, coordinate dependencies, avoid duplicate account changes, and clearly distinguish completed work from items awaiting another owner. Do not invent customer approval or make an external commitment beyond the assignment.\",\n \"\",\n \"Keep verbose records and operational output in this isolated run. Return the customer-facing outcome, account or artifact identifiers, decisions and blockers, and the next owner and action where follow-through remains.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\", \"event\"],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 1_000_000,\n },\n {\n name: \"business-development\",\n description:\n \"Owns prospect research, qualification, contact discovery, and outreach preparation\",\n systemPrompt: [\n \"You are the business development specialist responsible for one delegated growth opportunity.\",\n \"\",\n \"Apply the relevant prospecting, website sampling, contact-finding, email-validation, and client-approach skill instructions. Use `bash` to gather and verify public evidence. Evaluate fit against the supplied criteria, distinguish verified contacts from inferred ones, and preserve source URLs. Do not contact prospects, submit forms, or represent that outreach occurred unless the assignment explicitly authorizes it.\",\n \"\",\n \"Keep raw pages, candidate lists, and repetitive validation output in this isolated run. Return qualified opportunities, supporting evidence, confidence and disqualifiers, and a concise recommended next action.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 30,\n maxTokens: 1_000_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, and `generate_image` for image deliverables. 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\", \"generate_image\"],\n thinkingLevel: \"high\",\n maxTurns: 40,\n maxTokens: 1_000_000,\n },\n {\n name: \"ad-operations-specialist\",\n description:\n \"Owns ad serving setup, delivery diagnostics, policy checks, and operational health\",\n systemPrompt: [\n \"You are the ad operations specialist responsible for one delegated advertising-delivery outcome.\",\n \"\",\n \"Apply the relevant GAM, ads.txt, player detection, targeting, behavior, monitoring, and policy skill instructions. Use `bash` to run the prescribed browser and reporting tools. Establish the site, account, slot, time window, geography, device, and consent conditions; distinguish configuration, eligibility, request, impression, and playback evidence. Reproduce dynamic behavior when practical, and do not change live serving configuration unless explicitly authorized.\",\n \"\",\n \"Keep browser traces, HAR data, report rows, and repetitive diagnostics in this isolated run. Return the operational conclusion, decisive delivery evidence, affected inventory, remediation or escalation owner, and uncertainty that could change the diagnosis.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 35,\n maxTokens: 1_000_000,\n },\n {\n name: \"summarizer\",\n description:\n \"Synthesizes supplied task input and upstream DAG dependency output without claiming external verification\",\n systemPrompt: [\n \"You synthesize only the task text and structured dependency input supplied to this run — typically the combined output of upstream DAG nodes that did their own investigation.\",\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. `jev` is your only tool: use it to classify, rank, or check claims against the supplied input when the volume is large or a calibrated probability helps.\",\n ].join(\"\\n\"),\n tools: [\"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 20,\n maxTokens: 1_000_000,\n },\n];\n\nconst THINKING_LEVELS = new Set<ThinkingLevel>([\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n]);\n\n/** Parse a comma-separated tool list. The literal `none` is an empty grant. */\nfunction csv(value: string): string[] {\n if (value.trim() === \"none\") return [];\n return [\n ...new Set(\n value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ),\n ];\n}\n\nfunction parseModel(value: string): SubagentModelSpec {\n const separator = value.indexOf(\"/\");\n if (separator <= 0 || separator === value.length - 1) {\n throw new Error(`model must be provider/id, got ${value}`);\n }\n return { provider: value.slice(0, separator), id: value.slice(separator + 1) };\n}\n\nfunction parseThinking(value: string): ThinkingLevel {\n if (!THINKING_LEVELS.has(value as ThinkingLevel)) {\n throw new Error(`unknown thinking level: ${value}`);\n }\n return value as ThinkingLevel;\n}\n\nfunction parsePositiveInteger(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${field} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeNumber(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new Error(`${field} must be a non-negative number`);\n }\n return parsed;\n}\n\n/** Apply `field` from frontmatter onto `patch` only when the file sets it. */\nfunction applyField<K extends keyof SubagentProfile>(\n patch: Partial<SubagentProfile>,\n values: Record<string, string>,\n key: string,\n field: K,\n parse: (value: string) => SubagentProfile[K],\n): void {\n const raw = values[key];\n if (raw === undefined) return;\n patch[field] = parse(raw);\n}\n\n/**\n * Build the overlay a single file contributes. Throws with a human-readable\n * message on malformed input; the caller turns that into a diagnostic.\n */\nfunction parseProfilePatch(filePath: string, base: SubagentProfile | undefined): SubagentProfile {\n const { values, body } = parseFrontmatter(readFileSync(filePath, \"utf-8\"));\n const name = basename(filePath, \".md\");\n const patch: Partial<SubagentProfile> = {};\n\n applyField(patch, values, \"description\", \"description\", (value) => value.trim());\n applyField(patch, values, \"tools\", \"tools\", csv);\n applyField(patch, values, \"model\", \"model\", parseModel);\n applyField(patch, values, \"thinking\", \"thinkingLevel\", parseThinking);\n applyField(patch, values, \"max_turns\", \"maxTurns\", (v) => parsePositiveInteger(v, \"max_turns\"));\n applyField(patch, values, \"max_tokens\", \"maxTokens\", (v) =>\n parsePositiveInteger(v, \"max_tokens\"),\n );\n applyField(patch, values, \"max_cost_usd\", \"maxCostUsd\", (v) =>\n parseNonNegativeNumber(v, \"max_cost_usd\"),\n );\n applyField(patch, values, \"max_duration_ms\", \"maxDurationMs\", (v) =>\n parsePositiveInteger(v, \"max_duration_ms\"),\n );\n\n const systemPrompt = body.trim() || base?.systemPrompt;\n if (!base && patch.tools === undefined) {\n throw new Error(`tools is required for a new profile (no built-in named ${name})`);\n }\n if (!systemPrompt) {\n throw new Error(`a new profile needs prompt text in the file body`);\n }\n\n const merged: SubagentProfile = {\n ...base,\n ...patch,\n name,\n description: patch.description || base?.description || name,\n systemPrompt,\n tools: patch.tools ?? base?.tools ?? [],\n };\n return merged;\n}\n\n/**\n * Load the built-in profiles, then patch them with `<workspaceDir>/agents/*.md`.\n * Malformed files are reported and skipped, leaving the built-in in place.\n */\nexport function loadSubagentProfiles(workspaceDir: string): LoadSubagentProfilesResult {\n const dir = join(workspaceDir, \"agents\");\n const profiles = new Map(BUILTIN_PROFILES.map((profile) => [profile.name, profile]));\n const diagnostics: SubagentProfileDiagnostic[] = [];\n if (!existsSync(dir)) return { profiles, diagnostics };\n\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: dir,\n });\n return { profiles, diagnostics };\n }\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const filePath = join(dir, entry.name);\n try {\n const profile = parseProfilePatch(filePath, profiles.get(basename(entry.name, \".md\")));\n profiles.set(profile.name, profile);\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: filePath,\n });\n }\n }\n return { profiles, diagnostics };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subagent-profiles.js","sourceRoot":"","sources":["../../src/harness/subagent-profiles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAU3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,gBAAgB,GAAsB;IAC1C;QACE,IAAI,EAAE,QAAQ;QACd,WAAW,EAAE,4EAA4E;QACzF,YAAY,EAAE;YACZ,sFAAsF;YACtF,EAAE;YACF,maAAma;YACna,EAAE;YACF,8KAA8K;SAC/K,CAAC,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;QAC/C,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,GAAG;QACb,SAAS,EAAE,SAAS;QACpB,UAAU,EAAE,EAAE;KACf;IACD;QACE,IAAI,EAAE,mBAAmB;QACzB,WAAW,EACT,sFAAsF;QACxF,YAAY,EAAE;YACZ,gFAAgF;YAChF,EAAE;YACF,iaAAia;YACja,EAAE;YACF,6QAA6Q;SAC9Q,CAAC,IAAI,CAAC,IAAI,CAAC;QACZ,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;QAC/C,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,GAAG;QACb,SAAS,EAAE,SAAS;QACpB,UAAU,EAAE,EAAE;KACf;IACD;QACE,IAAI,EAAE,iBAAiB;QACvB,WAAW,EACT,mFAAmF;QACrF,YAAY,EAAE;YACZ,4GAA4G;YAC5G,EAAE;YACF,+cAA+c;YAC/c,EAAE;YACF,sMAAsM;SACvM,C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AC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,WAAW,CAAC,IAAI,CAAC;gBACf,IAAI,EAAE,SAAS;gBACf,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;gBAC/D,IAAI,EAAE,QAAQ;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Subagent profiles: the curated capability sets a subagent may be launched\n * with.\n *\n * Profiles exist because the two halves of a subagent definition have\n * different owners. What a profile *does* — its tools, required evidence,\n * prompt and budget — is portable, so it ships as a built-in below and is\n * versioned with the code. Which model runs it is per-installation, so it is\n * overridden by `<workspaceDir>/agents/<name>.md`.\n *\n * A workspace file therefore *patches* the built-in of the same name rather\n * than replacing it: overriding only `model:` must not force an operator to\n * restate the tools and prompt, because a restated copy silently drifts from\n * the built-in it was cloned from. A file whose name matches no built-in\n * defines a new profile and must supply `tools` itself.\n *\n * A malformed file is reported as a diagnostic and skipped, never thrown:\n * these are hand-edited, and one typo must not take the whole workspace down.\n */\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type {\n LoadSubagentProfilesResult,\n SubagentModelSpec,\n SubagentProfile,\n SubagentProfileDiagnostic,\n} from \"./types.js\";\n\nexport type { LoadSubagentProfilesResult, SubagentProfileDiagnostic } from \"./types.js\";\nimport { parseFrontmatter } from \"./skills.js\";\n\nconst BUILTIN_PROFILES: SubagentProfile[] = [\n {\n name: \"worker\",\n description: \"Completes a bounded general-purpose task without adding domain assumptions\",\n systemPrompt: [\n \"You are a general-purpose worker responsible for one clearly bounded delegated task.\",\n \"\",\n \"Use `read` and `bash` to inspect the actual workspace state, and use `edit` or `write` only when the assignment requires changes. Follow applicable skill instructions, preserve behavior outside the stated scope, and do not invent requirements or broaden the task. Verify concrete outputs before reporting success; if the assignment lacks information or a required capability, state the limitation instead of guessing.\",\n \"\",\n \"Keep verbose discovery and command output in this isolated run. Return the completed result, files or artifacts changed, verification performed, and any unresolved blocker.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\", \"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\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\", \"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\n },\n {\n name: \"devops-engineer\",\n description:\n \"Owns cloud access, environments, deployments, and production workflow reliability\",\n systemPrompt: [\n \"You are the DevOps engineer responsible for one delegated infrastructure or production-operations outcome.\",\n \"\",\n \"Apply the relevant setup, GCP, repository-access, service-status, and production workflow skill instructions. Use `bash` to inspect current state before acting. Respect the named project, environment, principal, and resource scope; protect credentials; prefer least privilege; and check idempotency before writes, retries, or provisioning. Do not broaden access or repeat a non-idempotent operation without explicit authorization and evidence that it is needed.\",\n \"\",\n \"Keep verbose CLI, API, and job logs in this isolated run. Return the resulting state, affected resources or job identifiers, verification performed, and concrete follow-up or rollback information.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"edit\", \"write\", \"event\", \"sandbox\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\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\", \"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\n },\n {\n name: \"account-manager\",\n description:\n \"Owns existing-client onboarding, account coordination, and delivery follow-through\",\n systemPrompt: [\n \"You are the account manager responsible for one delegated existing-client outcome.\",\n \"\",\n \"Apply the relevant onboarding, publisher account, slot, workspace, meeting, and communication skill instructions. Use `bash` to inspect the current customer and account state before acting. Preserve supplied commercial and technical requirements, coordinate dependencies, avoid duplicate account changes, and clearly distinguish completed work from items awaiting another owner. Do not invent customer approval or make an external commitment beyond the assignment.\",\n \"\",\n \"Keep verbose records and operational output in this isolated run. Return the customer-facing outcome, account or artifact identifiers, decisions and blockers, and the next owner and action where follow-through remains.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\", \"event\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\n },\n {\n name: \"business-development\",\n description:\n \"Owns prospect research, qualification, contact discovery, and outreach preparation\",\n systemPrompt: [\n \"You are the business development specialist responsible for one delegated growth opportunity.\",\n \"\",\n \"Apply the relevant prospecting, website sampling, contact-finding, email-validation, and client-approach skill instructions. Use `bash` to gather and verify public evidence. Evaluate fit against the supplied criteria, distinguish verified contacts from inferred ones, and preserve source URLs. Do not contact prospects, submit forms, or represent that outreach occurred unless the assignment explicitly authorizes it.\",\n \"\",\n \"Keep raw pages, candidate lists, and repetitive validation output in this isolated run. Return qualified opportunities, supporting evidence, confidence and disqualifiers, and a concise recommended next action.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\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, and `generate_image` for image deliverables. 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\", \"generate_image\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\n },\n {\n name: \"ad-operations-specialist\",\n description:\n \"Owns ad serving setup, delivery diagnostics, policy checks, and operational health\",\n systemPrompt: [\n \"You are the ad operations specialist responsible for one delegated advertising-delivery outcome.\",\n \"\",\n \"Apply the relevant GAM, ads.txt, player detection, targeting, behavior, monitoring, and policy skill instructions. Use `bash` to run the prescribed browser and reporting tools. Establish the site, account, slot, time window, geography, device, and consent conditions; distinguish configuration, eligibility, request, impression, and playback evidence. Reproduce dynamic behavior when practical, and do not change live serving configuration unless explicitly authorized.\",\n \"\",\n \"Keep browser traces, HAR data, report rows, and repetitive diagnostics in this isolated run. Return the operational conclusion, decisive delivery evidence, affected inventory, remediation or escalation owner, and uncertainty that could change the diagnosis.\",\n ].join(\"\\n\"),\n tools: [\"read\", \"bash\", \"write\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\n },\n {\n name: \"summarizer\",\n description:\n \"Synthesizes supplied task input and upstream DAG dependency output without claiming external verification\",\n systemPrompt: [\n \"You synthesize only the task text and structured dependency input supplied to this run — typically the combined output of upstream DAG nodes that did their own investigation.\",\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. `jev` is your only tool: use it to classify, rank, or check claims against the supplied input when the volume is large or a calibrated probability helps.\",\n ].join(\"\\n\"),\n tools: [\"jev\"],\n thinkingLevel: \"high\",\n maxTurns: 100,\n maxTokens: 1_000_000,\n maxCostUsd: 10,\n },\n];\n\nconst THINKING_LEVELS = new Set<ThinkingLevel>([\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n]);\n\n/** Parse a comma-separated tool list. The literal `none` is an empty grant. */\nfunction csv(value: string): string[] {\n if (value.trim() === \"none\") return [];\n return [\n ...new Set(\n value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ),\n ];\n}\n\nfunction parseModel(value: string): SubagentModelSpec {\n const separator = value.indexOf(\"/\");\n if (separator <= 0 || separator === value.length - 1) {\n throw new Error(`model must be provider/id, got ${value}`);\n }\n return { provider: value.slice(0, separator), id: value.slice(separator + 1) };\n}\n\nfunction parseThinking(value: string): ThinkingLevel {\n if (!THINKING_LEVELS.has(value as ThinkingLevel)) {\n throw new Error(`unknown thinking level: ${value}`);\n }\n return value as ThinkingLevel;\n}\n\nfunction parsePositiveInteger(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`${field} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeNumber(value: string, field: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new Error(`${field} must be a non-negative number`);\n }\n return parsed;\n}\n\n/** Apply `field` from frontmatter onto `patch` only when the file sets it. */\nfunction applyField<K extends keyof SubagentProfile>(\n patch: Partial<SubagentProfile>,\n values: Record<string, string>,\n key: string,\n field: K,\n parse: (value: string) => SubagentProfile[K],\n): void {\n const raw = values[key];\n if (raw === undefined) return;\n patch[field] = parse(raw);\n}\n\n/**\n * Build the overlay a single file contributes. Throws with a human-readable\n * message on malformed input; the caller turns that into a diagnostic.\n */\nfunction parseProfilePatch(filePath: string, base: SubagentProfile | undefined): SubagentProfile {\n const { values, body } = parseFrontmatter(readFileSync(filePath, \"utf-8\"));\n const name = basename(filePath, \".md\");\n const patch: Partial<SubagentProfile> = {};\n\n applyField(patch, values, \"description\", \"description\", (value) => value.trim());\n applyField(patch, values, \"tools\", \"tools\", csv);\n applyField(patch, values, \"model\", \"model\", parseModel);\n applyField(patch, values, \"thinking\", \"thinkingLevel\", parseThinking);\n applyField(patch, values, \"max_turns\", \"maxTurns\", (v) => parsePositiveInteger(v, \"max_turns\"));\n applyField(patch, values, \"max_tokens\", \"maxTokens\", (v) =>\n parsePositiveInteger(v, \"max_tokens\"),\n );\n applyField(patch, values, \"max_cost_usd\", \"maxCostUsd\", (v) =>\n parseNonNegativeNumber(v, \"max_cost_usd\"),\n );\n applyField(patch, values, \"max_duration_ms\", \"maxDurationMs\", (v) =>\n parsePositiveInteger(v, \"max_duration_ms\"),\n );\n\n const systemPrompt = body.trim() || base?.systemPrompt;\n if (!base && patch.tools === undefined) {\n throw new Error(`tools is required for a new profile (no built-in named ${name})`);\n }\n if (!systemPrompt) {\n throw new Error(`a new profile needs prompt text in the file body`);\n }\n\n const merged: SubagentProfile = {\n ...base,\n ...patch,\n name,\n description: patch.description || base?.description || name,\n systemPrompt,\n tools: patch.tools ?? base?.tools ?? [],\n };\n return merged;\n}\n\n/**\n * Load the built-in profiles, then patch them with `<workspaceDir>/agents/*.md`.\n * Malformed files are reported and skipped, leaving the built-in in place.\n */\nexport function loadSubagentProfiles(workspaceDir: string): LoadSubagentProfilesResult {\n const dir = join(workspaceDir, \"agents\");\n const profiles = new Map(BUILTIN_PROFILES.map((profile) => [profile.name, profile]));\n const diagnostics: SubagentProfileDiagnostic[] = [];\n if (!existsSync(dir)) return { profiles, diagnostics };\n\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: dir,\n });\n return { profiles, diagnostics };\n }\n\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const filePath = join(dir, entry.name);\n try {\n const profile = parseProfilePatch(filePath, profiles.get(basename(entry.name, \".md\")));\n profiles.set(profile.name, profile);\n } catch (error) {\n diagnostics.push({\n type: \"warning\",\n message: error instanceof Error ? error.message : String(error),\n path: filePath,\n });\n }\n }\n return { profiles, diagnostics };\n}\n"]}
|
|
@@ -9,10 +9,7 @@ declare const subagentSchema: import("@sinclair/typebox").TObject<{
|
|
|
9
9
|
}>>;
|
|
10
10
|
outputSchema: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TRecord<import("@sinclair/typebox").TString, import("@sinclair/typebox").TUnknown>>;
|
|
11
11
|
budget: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TObject<{
|
|
12
|
-
maxTurns: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
|
|
13
12
|
maxTokens: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
|
|
14
|
-
maxCostUsd: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
|
|
15
|
-
maxDurationMs: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
|
|
16
13
|
}>>;
|
|
17
14
|
task: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
18
15
|
profile: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/harness/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,aAAa,CAAC;AAI5F,OAAO,KAAK,EACV,oBAAoB,EACpB,wBAAwB,EAEzB,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/harness/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,aAAa,CAAC;AAI5F,OAAO,KAAK,EACV,oBAAoB,EACpB,wBAAwB,EAEzB,MAAM,gBAAgB,CAAC;AAkHxB,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAA0B,CAAC;AAM/C;;;;GAIG;AACH,KAAK,WAAW,GAAG,CAAC,aAAa,SAAS,OAAO,GAAG,SAAS,GAAG,SAAS,EACvE,OAAO,EAAE,kBAAkB,CAAC,aAAa,CAAC,EAC1C,KAAK,CAAC,EAAE;IAAE,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;CAAE,KAChD,OAAO,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;AA2VlE,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,CA8ElC;AAKD,oFAAoF;AACpF,eAAO,MAAM,wBAAwB,MAAM,CAAC;AA0C5C,2EAA2E;AAC3E,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,oBAAoB,GAAG,oBAAoB,CAU1F;AAsCD;;;;GAIG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,GACb,wBAAwB,GAAG,SAAS,CAgBtC;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,wBAAwB,EAClC,OAAO,EAAE,OAAO,GACf,wBAAwB,CAS1B;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,SAAS,wBAAwB,EAAE,GAC7C,wBAAwB,GAAG,SAAS,CAYtC;AAoFD,8EAA8E;AAC9E,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,wBAAwB,GAAG,MAAM,CAOlF"}
|
|
@@ -10,9 +10,8 @@ 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.
|
|
14
|
-
*
|
|
15
|
-
* only tighten profile defaults.
|
|
13
|
+
* can get wrong is the point. The model may request a larger token allowance,
|
|
14
|
+
* but cannot accidentally shrink the profile's turn, cost, or duration limits.
|
|
16
15
|
*
|
|
17
16
|
* `profileNames` is baked into the schema as an enum to steer the model's
|
|
18
17
|
* choice. TypeBox does not check `enum` on a string, so an unknown name still
|
|
@@ -41,12 +40,9 @@ const sharedProperties = {
|
|
|
41
40
|
description: "Optional TypeBox/JSON Schema applied to every subagent result.",
|
|
42
41
|
})),
|
|
43
42
|
budget: Type.Optional(Type.Object({
|
|
44
|
-
maxTurns: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
45
43
|
maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
46
|
-
maxCostUsd: Type.Optional(Type.Number({ minimum: 0 })),
|
|
47
|
-
maxDurationMs: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
48
44
|
}, {
|
|
49
|
-
description: "
|
|
45
|
+
description: "Optionally requests a larger token allowance than the profile default.",
|
|
50
46
|
})),
|
|
51
47
|
};
|
|
52
48
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/harness/tools/subagent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAA6B,MAAM,mBAAmB,CAAC;AAUpE,OAAO,EAAE,qBAAqB,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAEhG,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;;;;;;;;;;;;GAYG;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;Q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AAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;IAC3F,0EAA0E;IAC1E,2EAA2E;IAC3E,wEAAwE;IACxE,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;IACvE,4EAA4E;IAC5E,qDAAqD;IACrD,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,MAAM,CAAC;SACpF,MAAM,CAAC,OAAO,CAAC;SACf,IAAI,CAAC,KAAK,CAAC,CAAC;AACjB,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,uBAAuB,CAAC,QAAkC;IACxE,MAAM,MAAM,GAAG,KAAK,eAAe,CAAC,QAAQ,CAAC,IAAI,CAAC;IAClD,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC5C,GAAG,sBAAsB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QACtE,KAAK,UAAU,CAAC,IAAI,CAAC,EAAE;KACxB,CAAC,CAAC;IACH,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACtC,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 \"../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 {\n SubagentProgressNode,\n SubagentProgressSnapshot,\n SubagentProgressStatus,\n} from \"../../types.js\";\nimport { recordSubagentOutcome, reportSubagentLaunchError } from \"../../observability/index.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\">;\n/**\n * `hooks` carries host-side callbacks rather than widening the request: the\n * request is the public shape the model asks for, and a\n * progress sink belongs to whoever is displaying the run.\n */\ntype RunSubagent = <TOutputSchema extends TSchema | undefined = undefined>(\n request: SubagentRunRequest<TOutputSchema>,\n hooks?: { onActivity?: (activity: string) => void },\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\n/** Shortest gap between activity-driven redraws of the dashboard. */\nconst ACTIVITY_EMIT_INTERVAL_MS = 2000;\n\nclass SubagentProgressTracker {\n private lastActivityEmit = 0;\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 /**\n * Record what a node is doing, rate-limited.\n *\n * Status changes are rare and each one matters, so `update` emits every\n * time. Activity is the opposite — it can change several times a second\n * while text streams — and every emission redraws the whole response, on a\n * path that is deliberately not batched. Left unbounded this would spend the\n * platform's edit budget on a character counter.\n */\n activity(id: string, activity: string): void {\n const previous = this.metrics.get(id) ?? {};\n this.metrics.set(id, { ...previous, activity });\n const now = Date.now();\n if (now - this.lastActivityEmit < ACTIVITY_EMIT_INTERVAL_MS) return;\n this.lastActivityEmit = now;\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 const item = items[index];\n if (item === undefined) continue;\n await worker(item, 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 recordSubagentOutcome({\n itemId: item.id,\n mode: plan.mode,\n status: \"skipped\",\n profile: item.task.profile,\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 try {\n result = await runSubagent(planRequest(item, shared, outcomes, signal), {\n onActivity: (activity: string) => progress.activity(item.id, activity),\n });\n } catch (error) {\n reportSubagentLaunchError(error, {\n itemId: item.id,\n mode: plan.mode,\n profile: item.task.profile,\n });\n throw error;\n }\n outcomes.set(item.id, { id: item.id, ...result });\n recordSubagentOutcome({\n itemId: item.id,\n mode: plan.mode,\n status: result.status,\n profile: item.task.profile,\n error: result.error,\n turns: result.turns,\n toolCalls: result.toolCalls,\n tokens: result.tokens,\n costUsd: result.costUsd,\n durationMs: result.durationMs,\n cleanupPending: result.cleanupPending,\n });\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 single = ordered[0];\n if (single === undefined) {\n throw new Error(\"Subagent plan produced no outcome\");\n }\n const { id: _id, ...result } = single;\n return {\n content: [{ type: \"text\", text: formatOutcome(result) }],\n details: result,\n };\n }\n }\n },\n };\n}\n\n// Subagent progress protocol: the tool owns construction, transport validation,\n// settlement and its canonical response-source dashboard. Presenters consume it.\n\n/** Longest label the dashboard renders; longer ones are clamped, never rejected. */\nexport const MAX_SUBAGENT_LABEL_CHARS = 100;\nconst MAX_PROFILE_CHARS = 64;\nconst MAX_REASON_CHARS = 240;\nconst MAX_ACTIVITY_CHARS = 80;\n\nconst SUBAGENT_STATUS_MARKER = {\n pending: \"○\",\n running: \"●\",\n completed: \"✓\",\n failed: \"✗\",\n cancelled: \"■\",\n timeout: \"◷\",\n budget_exceeded: \"!\",\n invalid_output: \"✗\",\n skipped: \"⊘\",\n} satisfies Record<SubagentProgressStatus, string>;\n\nconst SUBAGENT_STATUS_LABEL = {\n pending: \"Waiting\",\n running: \"Running\",\n completed: \"Completed\",\n failed: \"Failed\",\n cancelled: \"Cancelled\",\n timeout: \"Timed out\",\n budget_exceeded: \"Budget exceeded\",\n invalid_output: \"Invalid output\",\n skipped: \"Skipped\",\n} satisfies Record<SubagentProgressStatus, string>;\n\n/**\n * Derived from the marker table, which `satisfies` keeps exhaustive: a new\n * terminal status is a compile error there, and this runtime set follows —\n * the validator can never silently drop a status the tables know about.\n */\nconst VALID_STATUSES: ReadonlySet<string> = new Set(Object.keys(SUBAGENT_STATUS_MARKER));\n\n/** Clamp a label to the display bound, ending a truncation visibly with `…`. */\nfunction clampSubagentLabel(label: string): string {\n if (label.length <= MAX_SUBAGENT_LABEL_CHARS) return label;\n return `${label.slice(0, MAX_SUBAGENT_LABEL_CHARS - 1)}…`;\n}\n\n/** The display bounds, applied once at construction and again on parse. */\nexport function boundSubagentProgressNode(node: SubagentProgressNode): SubagentProgressNode {\n return {\n ...node,\n label: clampSubagentLabel(node.label),\n ...(node.profile !== undefined ? { profile: node.profile.slice(0, MAX_PROFILE_CHARS) } : {}),\n ...(node.activity !== undefined\n ? { activity: node.activity.slice(0, MAX_ACTIVITY_CHARS) }\n : {}),\n ...(node.reason !== undefined ? { reason: node.reason.slice(0, MAX_REASON_CHARS) } : {}),\n };\n}\n\nfunction parseNode(value: unknown): SubagentProgressNode | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const item = value as Record<keyof SubagentProgressNode, unknown>;\n if (\n typeof item.id !== \"string\" ||\n typeof item.label !== \"string\" ||\n typeof item.status !== \"string\" ||\n !VALID_STATUSES.has(item.status)\n ) {\n return undefined;\n }\n return boundSubagentProgressNode({\n id: item.id,\n label: item.label,\n status: item.status as SubagentProgressStatus,\n ...(typeof item.profile === \"string\" ? { profile: item.profile } : {}),\n ...(typeof item.turns === \"number\" ? { turns: item.turns } : {}),\n ...(typeof item.toolCalls === \"number\" ? { toolCalls: item.toolCalls } : {}),\n ...(item.toolCallCounts && typeof item.toolCallCounts === \"object\"\n ? {\n toolCallCounts: Object.fromEntries(\n Object.entries(item.toolCallCounts).filter(\n (entry): entry is [string, number] => typeof entry[1] === \"number\",\n ),\n ),\n }\n : {}),\n ...(typeof item.tokens === \"number\" ? { tokens: item.tokens } : {}),\n ...(typeof item.costUsd === \"number\" ? { costUsd: item.costUsd } : {}),\n ...(typeof item.durationMs === \"number\" ? { durationMs: item.durationMs } : {}),\n ...(typeof item.activity === \"string\" ? { activity: item.activity } : {}),\n ...(typeof item.reason === \"string\" ? { reason: item.reason } : {}),\n ...(item.cleanupPending === true ? { cleanupPending: true } : {}),\n });\n}\n\n/**\n * Parse a snapshot back off the untyped transport. All-or-nothing: one\n * malformed node means the payload is not ours (any tool can put anything in\n * `details`), so the whole candidate is rejected rather than partially shown.\n */\nexport function parseSubagentProgressSnapshot(\n value: unknown,\n): SubagentProgressSnapshot | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const candidate = value as { mode?: unknown; nodes?: unknown };\n if (\n (candidate.mode !== \"single\" && candidate.mode !== \"parallel\" && candidate.mode !== \"dag\") ||\n !Array.isArray(candidate.nodes)\n ) {\n return undefined;\n }\n const nodes: SubagentProgressNode[] = [];\n for (const node of candidate.nodes) {\n const parsed = parseNode(node);\n if (!parsed) return undefined;\n nodes.push(parsed);\n }\n return { mode: candidate.mode, nodes };\n}\n\n/**\n * Project a live snapshot to its end-of-tool state: nodes still pending or\n * running settle to the tool call's outcome. Metrics spread through\n * unchanged — an unsettled node never reported any.\n */\nexport function settleSubagentProgress(\n snapshot: SubagentProgressSnapshot,\n isError: boolean,\n): SubagentProgressSnapshot {\n return {\n ...snapshot,\n nodes: snapshot.nodes.map((node) =>\n node.status !== \"running\" && node.status !== \"pending\"\n ? node\n : { ...node, status: isError ? \"failed\" : \"completed\" },\n ),\n };\n}\n\n/**\n * Fold concurrent or successive subagent fan-outs into the single snapshot the\n * dashboard renders. A run can call the subagent tool more than once; picking\n * one snapshot would drop the others' cost and status, and alternating between\n * them makes the live view flicker. Node ids are namespaced by source because\n * each fan-out numbers its own nodes from zero.\n */\nexport function mergeSubagentProgress(\n snapshots: readonly SubagentProgressSnapshot[],\n): SubagentProgressSnapshot | undefined {\n if (snapshots.length === 0) return undefined;\n if (snapshots.length === 1) return snapshots[0];\n const nodes = snapshots.flatMap((snapshot, index) =>\n snapshot.nodes.map((node) => ({ ...node, id: `${index}:${node.id}` })),\n );\n const mode = snapshots.some((snapshot) => snapshot.mode === \"dag\")\n ? \"dag\"\n : nodes.length > 1\n ? \"parallel\"\n : \"single\";\n return { mode, nodes };\n}\n\n// ---------------------------------------------------------------------------\n// Dashboard text\n// ---------------------------------------------------------------------------\n\nfunction settledCount(snapshot: SubagentProgressSnapshot): number {\n return snapshot.nodes.filter((node) => node.status !== \"pending\" && node.status !== \"running\")\n .length;\n}\n\nfunction modeLabel(snapshot: SubagentProgressSnapshot): string {\n if (snapshot.mode === \"dag\") return \"DAG\";\n if (snapshot.mode === \"parallel\") return \"Parallel\";\n return \"Run\";\n}\n\nfunction escapeMarkdown(text: string): string {\n return text.replace(/([\\\\`*_{}[\\]()<>#+\\-.!|~])/g, \"\\\\$1\");\n}\n\nfunction compactNumber(value: number): string {\n return new Intl.NumberFormat(\"en\", { notation: \"compact\", maximumFractionDigits: 1 }).format(\n value,\n );\n}\n\nfunction summaryText(snapshot: SubagentProgressSnapshot): string {\n const totals = snapshot.nodes.reduce(\n (sum, node) => ({\n turns: sum.turns + (node.turns ?? 0),\n toolCalls: sum.toolCalls + (node.toolCalls ?? 0),\n tokens: sum.tokens + (node.tokens ?? 0),\n costUsd: sum.costUsd + (node.costUsd ?? 0),\n }),\n { turns: 0, toolCalls: 0, tokens: 0, costUsd: 0 },\n );\n return [\n totals.turns > 0 ? `${totals.turns} LLM turns` : undefined,\n totals.toolCalls > 0 ? `${totals.toolCalls} tool calls` : undefined,\n totals.tokens > 0 ? `${compactNumber(totals.tokens)} tokens` : undefined,\n totals.costUsd > 0 ? `$${totals.costUsd.toFixed(4)}` : undefined,\n ]\n .filter(Boolean)\n .join(\" · \");\n}\n\n/** The dashboard's one-line summary header, unformatted. */\nfunction dashboardHeader(snapshot: SubagentProgressSnapshot): string {\n const base = `Subagents · ${settledCount(snapshot)}/${snapshot.nodes.length} · ${modeLabel(snapshot)}`;\n const summary = summaryText(snapshot);\n return summary ? `${base} · ${summary}` : base;\n}\n\nfunction countLabel(count: number, singular: string): string {\n return `${count} ${singular}${count === 1 ? \"\" : \"s\"}`;\n}\n\nfunction detailText(node: SubagentProgressNode): string {\n const toolBreakdown = node.toolCallCounts\n ? Object.entries(node.toolCallCounts)\n .map(([name, count]) => `${name} ×${count}`)\n .join(\" · \")\n : undefined;\n const metrics = [\n node.turns !== undefined ? countLabel(node.turns, \"LLM turn\") : undefined,\n node.toolCalls !== undefined ? countLabel(node.toolCalls, \"tool call\") : undefined,\n toolBreakdown,\n node.tokens !== undefined ? `${compactNumber(node.tokens)} tokens` : undefined,\n node.costUsd !== undefined ? `$${node.costUsd.toFixed(4)}` : undefined,\n node.durationMs !== undefined ? `${(node.durationMs / 1000).toFixed(1)}s` : undefined,\n ].filter(Boolean);\n const reason = node.cleanupPending ? \"Cleanup pending; usage is provisional\" : node.reason;\n // Activity is shown only while running, and that is exactly when there is\n // nothing else: a node reports its metrics on the way out, so without this\n // the whole of a long step reads \"Running · profile\" and never changes.\n const activity = node.status === \"running\" ? node.activity : undefined;\n // Profile leads the line: when a node reports no tool calls, the profile is\n // what says whether that was the plan or a bad pick.\n return [SUBAGENT_STATUS_LABEL[node.status], node.profile, activity, ...metrics, reason]\n .filter(Boolean)\n .join(\" · \");\n}\n\n/** The dashboard as response source Markdown; adapters own any conversion. */\nexport function renderSubagentDashboard(snapshot: SubagentProgressSnapshot): string {\n const header = `**${dashboardHeader(snapshot)}**`;\n const rows = snapshot.nodes.flatMap((node) => [\n `${SUBAGENT_STATUS_MARKER[node.status]} ${escapeMarkdown(node.label)}`,\n `└ ${detailText(node)}`,\n ]);\n return [header, ...rows].join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/harness/tools/subagent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAA6B,MAAM,mBAAmB,CAAC;AAUpE,OAAO,EAAE,qBAAqB,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAEhG,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,E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,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,uBAAuB,CAAC,QAAkC;IACxE,MAAM,MAAM,GAAG,KAAK,eAAe,CAAC,QAAQ,CAAC,IAAI,CAAC;IAClD,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC5C,GAAG,sBAAsB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;QACtE,KAAK,UAAU,CAAC,IAAI,CAAC,EAAE;KACxB,CAAC,CAAC;IACH,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACtC,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 \"../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 {\n SubagentProgressNode,\n SubagentProgressSnapshot,\n SubagentProgressStatus,\n} from \"../../types.js\";\nimport { recordSubagentOutcome, reportSubagentLaunchError } from \"../../observability/index.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. The model may request a larger token allowance,\n * but cannot accidentally shrink the profile's turn, cost, or duration limits.\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 maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),\n },\n {\n description: \"Optionally requests a larger token allowance than the profile default.\",\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\">;\n/**\n * `hooks` carries host-side callbacks rather than widening the request: the\n * request is the public shape the model asks for, and a\n * progress sink belongs to whoever is displaying the run.\n */\ntype RunSubagent = <TOutputSchema extends TSchema | undefined = undefined>(\n request: SubagentRunRequest<TOutputSchema>,\n hooks?: { onActivity?: (activity: string) => void },\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\n/** Shortest gap between activity-driven redraws of the dashboard. */\nconst ACTIVITY_EMIT_INTERVAL_MS = 2000;\n\nclass SubagentProgressTracker {\n private lastActivityEmit = 0;\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 /**\n * Record what a node is doing, rate-limited.\n *\n * Status changes are rare and each one matters, so `update` emits every\n * time. Activity is the opposite — it can change several times a second\n * while text streams — and every emission redraws the whole response, on a\n * path that is deliberately not batched. Left unbounded this would spend the\n * platform's edit budget on a character counter.\n */\n activity(id: string, activity: string): void {\n const previous = this.metrics.get(id) ?? {};\n this.metrics.set(id, { ...previous, activity });\n const now = Date.now();\n if (now - this.lastActivityEmit < ACTIVITY_EMIT_INTERVAL_MS) return;\n this.lastActivityEmit = now;\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 const item = items[index];\n if (item === undefined) continue;\n await worker(item, 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 recordSubagentOutcome({\n itemId: item.id,\n mode: plan.mode,\n status: \"skipped\",\n profile: item.task.profile,\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 try {\n result = await runSubagent(planRequest(item, shared, outcomes, signal), {\n onActivity: (activity: string) => progress.activity(item.id, activity),\n });\n } catch (error) {\n reportSubagentLaunchError(error, {\n itemId: item.id,\n mode: plan.mode,\n profile: item.task.profile,\n });\n throw error;\n }\n outcomes.set(item.id, { id: item.id, ...result });\n recordSubagentOutcome({\n itemId: item.id,\n mode: plan.mode,\n status: result.status,\n profile: item.task.profile,\n error: result.error,\n turns: result.turns,\n toolCalls: result.toolCalls,\n tokens: result.tokens,\n costUsd: result.costUsd,\n durationMs: result.durationMs,\n cleanupPending: result.cleanupPending,\n });\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 single = ordered[0];\n if (single === undefined) {\n throw new Error(\"Subagent plan produced no outcome\");\n }\n const { id: _id, ...result } = single;\n return {\n content: [{ type: \"text\", text: formatOutcome(result) }],\n details: result,\n };\n }\n }\n },\n };\n}\n\n// Subagent progress protocol: the tool owns construction, transport validation,\n// settlement and its canonical response-source dashboard. Presenters consume it.\n\n/** Longest label the dashboard renders; longer ones are clamped, never rejected. */\nexport const MAX_SUBAGENT_LABEL_CHARS = 100;\nconst MAX_PROFILE_CHARS = 64;\nconst MAX_REASON_CHARS = 240;\nconst MAX_ACTIVITY_CHARS = 80;\n\nconst SUBAGENT_STATUS_MARKER = {\n pending: \"○\",\n running: \"●\",\n completed: \"✓\",\n failed: \"✗\",\n cancelled: \"■\",\n timeout: \"◷\",\n budget_exceeded: \"!\",\n invalid_output: \"✗\",\n skipped: \"⊘\",\n} satisfies Record<SubagentProgressStatus, string>;\n\nconst SUBAGENT_STATUS_LABEL = {\n pending: \"Waiting\",\n running: \"Running\",\n completed: \"Completed\",\n failed: \"Failed\",\n cancelled: \"Cancelled\",\n timeout: \"Timed out\",\n budget_exceeded: \"Budget exceeded\",\n invalid_output: \"Invalid output\",\n skipped: \"Skipped\",\n} satisfies Record<SubagentProgressStatus, string>;\n\n/**\n * Derived from the marker table, which `satisfies` keeps exhaustive: a new\n * terminal status is a compile error there, and this runtime set follows —\n * the validator can never silently drop a status the tables know about.\n */\nconst VALID_STATUSES: ReadonlySet<string> = new Set(Object.keys(SUBAGENT_STATUS_MARKER));\n\n/** Clamp a label to the display bound, ending a truncation visibly with `…`. */\nfunction clampSubagentLabel(label: string): string {\n if (label.length <= MAX_SUBAGENT_LABEL_CHARS) return label;\n return `${label.slice(0, MAX_SUBAGENT_LABEL_CHARS - 1)}…`;\n}\n\n/** The display bounds, applied once at construction and again on parse. */\nexport function boundSubagentProgressNode(node: SubagentProgressNode): SubagentProgressNode {\n return {\n ...node,\n label: clampSubagentLabel(node.label),\n ...(node.profile !== undefined ? { profile: node.profile.slice(0, MAX_PROFILE_CHARS) } : {}),\n ...(node.activity !== undefined\n ? { activity: node.activity.slice(0, MAX_ACTIVITY_CHARS) }\n : {}),\n ...(node.reason !== undefined ? { reason: node.reason.slice(0, MAX_REASON_CHARS) } : {}),\n };\n}\n\nfunction parseNode(value: unknown): SubagentProgressNode | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const item = value as Record<keyof SubagentProgressNode, unknown>;\n if (\n typeof item.id !== \"string\" ||\n typeof item.label !== \"string\" ||\n typeof item.status !== \"string\" ||\n !VALID_STATUSES.has(item.status)\n ) {\n return undefined;\n }\n return boundSubagentProgressNode({\n id: item.id,\n label: item.label,\n status: item.status as SubagentProgressStatus,\n ...(typeof item.profile === \"string\" ? { profile: item.profile } : {}),\n ...(typeof item.turns === \"number\" ? { turns: item.turns } : {}),\n ...(typeof item.toolCalls === \"number\" ? { toolCalls: item.toolCalls } : {}),\n ...(item.toolCallCounts && typeof item.toolCallCounts === \"object\"\n ? {\n toolCallCounts: Object.fromEntries(\n Object.entries(item.toolCallCounts).filter(\n (entry): entry is [string, number] => typeof entry[1] === \"number\",\n ),\n ),\n }\n : {}),\n ...(typeof item.tokens === \"number\" ? { tokens: item.tokens } : {}),\n ...(typeof item.costUsd === \"number\" ? { costUsd: item.costUsd } : {}),\n ...(typeof item.durationMs === \"number\" ? { durationMs: item.durationMs } : {}),\n ...(typeof item.activity === \"string\" ? { activity: item.activity } : {}),\n ...(typeof item.reason === \"string\" ? { reason: item.reason } : {}),\n ...(item.cleanupPending === true ? { cleanupPending: true } : {}),\n });\n}\n\n/**\n * Parse a snapshot back off the untyped transport. All-or-nothing: one\n * malformed node means the payload is not ours (any tool can put anything in\n * `details`), so the whole candidate is rejected rather than partially shown.\n */\nexport function parseSubagentProgressSnapshot(\n value: unknown,\n): SubagentProgressSnapshot | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const candidate = value as { mode?: unknown; nodes?: unknown };\n if (\n (candidate.mode !== \"single\" && candidate.mode !== \"parallel\" && candidate.mode !== \"dag\") ||\n !Array.isArray(candidate.nodes)\n ) {\n return undefined;\n }\n const nodes: SubagentProgressNode[] = [];\n for (const node of candidate.nodes) {\n const parsed = parseNode(node);\n if (!parsed) return undefined;\n nodes.push(parsed);\n }\n return { mode: candidate.mode, nodes };\n}\n\n/**\n * Project a live snapshot to its end-of-tool state: nodes still pending or\n * running settle to the tool call's outcome. Metrics spread through\n * unchanged — an unsettled node never reported any.\n */\nexport function settleSubagentProgress(\n snapshot: SubagentProgressSnapshot,\n isError: boolean,\n): SubagentProgressSnapshot {\n return {\n ...snapshot,\n nodes: snapshot.nodes.map((node) =>\n node.status !== \"running\" && node.status !== \"pending\"\n ? node\n : { ...node, status: isError ? \"failed\" : \"completed\" },\n ),\n };\n}\n\n/**\n * Fold concurrent or successive subagent fan-outs into the single snapshot the\n * dashboard renders. A run can call the subagent tool more than once; picking\n * one snapshot would drop the others' cost and status, and alternating between\n * them makes the live view flicker. Node ids are namespaced by source because\n * each fan-out numbers its own nodes from zero.\n */\nexport function mergeSubagentProgress(\n snapshots: readonly SubagentProgressSnapshot[],\n): SubagentProgressSnapshot | undefined {\n if (snapshots.length === 0) return undefined;\n if (snapshots.length === 1) return snapshots[0];\n const nodes = snapshots.flatMap((snapshot, index) =>\n snapshot.nodes.map((node) => ({ ...node, id: `${index}:${node.id}` })),\n );\n const mode = snapshots.some((snapshot) => snapshot.mode === \"dag\")\n ? \"dag\"\n : nodes.length > 1\n ? \"parallel\"\n : \"single\";\n return { mode, nodes };\n}\n\n// ---------------------------------------------------------------------------\n// Dashboard text\n// ---------------------------------------------------------------------------\n\nfunction settledCount(snapshot: SubagentProgressSnapshot): number {\n return snapshot.nodes.filter((node) => node.status !== \"pending\" && node.status !== \"running\")\n .length;\n}\n\nfunction modeLabel(snapshot: SubagentProgressSnapshot): string {\n if (snapshot.mode === \"dag\") return \"DAG\";\n if (snapshot.mode === \"parallel\") return \"Parallel\";\n return \"Run\";\n}\n\nfunction escapeMarkdown(text: string): string {\n return text.replace(/([\\\\`*_{}[\\]()<>#+\\-.!|~])/g, \"\\\\$1\");\n}\n\nfunction compactNumber(value: number): string {\n return new Intl.NumberFormat(\"en\", { notation: \"compact\", maximumFractionDigits: 1 }).format(\n value,\n );\n}\n\nfunction summaryText(snapshot: SubagentProgressSnapshot): string {\n const totals = snapshot.nodes.reduce(\n (sum, node) => ({\n turns: sum.turns + (node.turns ?? 0),\n toolCalls: sum.toolCalls + (node.toolCalls ?? 0),\n tokens: sum.tokens + (node.tokens ?? 0),\n costUsd: sum.costUsd + (node.costUsd ?? 0),\n }),\n { turns: 0, toolCalls: 0, tokens: 0, costUsd: 0 },\n );\n return [\n totals.turns > 0 ? `${totals.turns} LLM turns` : undefined,\n totals.toolCalls > 0 ? `${totals.toolCalls} tool calls` : undefined,\n totals.tokens > 0 ? `${compactNumber(totals.tokens)} tokens` : undefined,\n totals.costUsd > 0 ? `$${totals.costUsd.toFixed(4)}` : undefined,\n ]\n .filter(Boolean)\n .join(\" · \");\n}\n\n/** The dashboard's one-line summary header, unformatted. */\nfunction dashboardHeader(snapshot: SubagentProgressSnapshot): string {\n const base = `Subagents · ${settledCount(snapshot)}/${snapshot.nodes.length} · ${modeLabel(snapshot)}`;\n const summary = summaryText(snapshot);\n return summary ? `${base} · ${summary}` : base;\n}\n\nfunction countLabel(count: number, singular: string): string {\n return `${count} ${singular}${count === 1 ? \"\" : \"s\"}`;\n}\n\nfunction detailText(node: SubagentProgressNode): string {\n const toolBreakdown = node.toolCallCounts\n ? Object.entries(node.toolCallCounts)\n .map(([name, count]) => `${name} ×${count}`)\n .join(\" · \")\n : undefined;\n const metrics = [\n node.turns !== undefined ? countLabel(node.turns, \"LLM turn\") : undefined,\n node.toolCalls !== undefined ? countLabel(node.toolCalls, \"tool call\") : undefined,\n toolBreakdown,\n node.tokens !== undefined ? `${compactNumber(node.tokens)} tokens` : undefined,\n node.costUsd !== undefined ? `$${node.costUsd.toFixed(4)}` : undefined,\n node.durationMs !== undefined ? `${(node.durationMs / 1000).toFixed(1)}s` : undefined,\n ].filter(Boolean);\n const reason = node.cleanupPending ? \"Cleanup pending; usage is provisional\" : node.reason;\n // Activity is shown only while running, and that is exactly when there is\n // nothing else: a node reports its metrics on the way out, so without this\n // the whole of a long step reads \"Running · profile\" and never changes.\n const activity = node.status === \"running\" ? node.activity : undefined;\n // Profile leads the line: when a node reports no tool calls, the profile is\n // what says whether that was the plan or a bad pick.\n return [SUBAGENT_STATUS_LABEL[node.status], node.profile, activity, ...metrics, reason]\n .filter(Boolean)\n .join(\" · \");\n}\n\n/** The dashboard as response source Markdown; adapters own any conversion. */\nexport function renderSubagentDashboard(snapshot: SubagentProgressSnapshot): string {\n const header = `**${dashboardHeader(snapshot)}**`;\n const rows = snapshot.nodes.flatMap((node) => [\n `${SUBAGENT_STATUS_MARKER[node.status]} ${escapeMarkdown(node.label)}`,\n `└ ${detailText(node)}`,\n ]);\n return [header, ...rows].join(\"\\n\");\n}\n"]}
|
package/dist/log.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAGA,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,UAAU,E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AW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI,CAElF;AAED,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAOnF"}
|
package/dist/log.js
CHANGED
|
@@ -142,7 +142,10 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
|
142
142
|
lines.push(`Cost: ` + costParts.join(" + ") + ` = *\$${usage.cost.total.toFixed(4)}*`);
|
|
143
143
|
const summary = lines.join("\n");
|
|
144
144
|
console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💰 Usage`));
|
|
145
|
-
|
|
145
|
+
// Show cache hits alongside fresh input; otherwise a warm-cache turn reads
|
|
146
|
+
// as if the system prompt had not been sent at all.
|
|
147
|
+
const cached = usage.cacheRead > 0 ? ` (+${usage.cacheRead.toLocaleString()} cached)` : "";
|
|
148
|
+
console.log(chalk.dim(` in ${usage.input.toLocaleString()}${cached} → out ${usage.output.toLocaleString()} = $${usage.cost.total.toFixed(4)}`));
|
|
146
149
|
return summary;
|
|
147
150
|
}
|
|
148
151
|
// Startup (no context needed)
|
package/dist/log.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAKtD,SAAS,SAAS;IAChB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACnD,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACrD,MAAM,EAAE,GAA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iB,CAAC,CAAC;IAChE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AACrC,CAAC;AAED,WAAW;AACX,MAAM,UAAU,gBAAgB,CAAC,YAAoB;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,yBAAyB,YAAY,cAAc,CAAC,CAAC,CAAC;AAC7F,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,WAAmB,EAAE,YAAoB;IAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,gBAAgB,WAAW,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC;AACjG,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,aAAqB,EAAE,UAAkB;IAC3E,MAAM,QAAQ,GAAG,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,IAAI,CACR,GAAG,SAAS,EAAE,gCAAgC,aAAa,gBAAgB,QAAQ,GAAG,CACvF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import chalk from \"chalk\";\nimport { formatToolArgs } from \"./adapters/shared.js\";\n\nexport type { LogContext } from \"./types.js\";\nimport type { LogContext } from \"./types.js\";\n\nfunction timestamp(): string {\n const now = new Date();\n const hh = String(now.getHours()).padStart(2, \"0\");\n const mm = String(now.getMinutes()).padStart(2, \"0\");\n const ss = String(now.getSeconds()).padStart(2, \"0\");\n return `[${hh}:${mm}:${ss}]`;\n}\n\nfunction formatContext(ctx: LogContext): string {\n const session = ctx.sessionId ? `:${ctx.sessionId}` : \"\";\n if (ctx.conversationId.startsWith(\"D\")) {\n return `[DM:${ctx.userName || ctx.conversationId}${session}]`;\n }\n const conversation = ctx.conversationName || ctx.conversationId;\n const user = ctx.userName || \"unknown\";\n return `[${conversation.startsWith(\"#\") ? conversation : `#${conversation}`}:${user}${session}]`;\n}\n\n// Keep stdout/stderr lines manageable when echoing tool/agent output. Long bodies\n// flow through Sentry and session storage; the console stream just needs a preview.\nconst LOG_PREVIEW_MAX = 1000;\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen)}\\n(truncated at ${maxLen} chars)`;\n}\n\n// User messages\nexport function logUserMessage(ctx: LogContext, text: string): void {\n console.log(chalk.green(`${timestamp()} ${formatContext(ctx)} ${text}`));\n}\n\n// Tool execution\nexport function logToolStart(\n ctx: LogContext,\n toolName: string,\n label: string,\n args: Record<string, unknown>,\n): void {\n const formattedArgs = formatToolArgs(args);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));\n if (formattedArgs) {\n // Indent the args\n const indented = formattedArgs\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolSuccess(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n result: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));\n\n const truncated = truncate(result, LOG_PREVIEW_MAX);\n if (truncated) {\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolError(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n error: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));\n\n const truncated = truncate(error, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// Agent run\nexport function logAgentRunStart(\n ctx: LogContext,\n provider: string,\n model: string,\n modelName?: string,\n): void {\n const displayName = modelName && modelName !== model ? ` (${modelName})` : \"\";\n console.log(\n chalk.blue(\n `${timestamp()} ${formatContext(ctx)} ▶ Agent run: ${provider}/${model}${displayName}`,\n ),\n );\n}\n\n// Response streaming\nexport function logResponseStart(ctx: LogContext): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} → Streaming response...`));\n}\n\nexport function logThinking(ctx: LogContext, thinking: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💭 Thinking`));\n const truncated = truncate(thinking, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nexport function logResponse(ctx: LogContext, text: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💬 Response`));\n const truncated = truncate(text, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// System\nexport function logInfo(message: string): void {\n console.log(chalk.blue(`${timestamp()} [system] ${message}`));\n}\n\nexport function logWarning(message: string, details?: string): void {\n console.log(chalk.yellow(`${timestamp()} [system] ⚠ ${message}`));\n if (details) {\n const indented = details\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logAgentError(ctx: LogContext | \"system\", error: string): void {\n const context = ctx === \"system\" ? \"[system]\" : formatContext(ctx);\n console.log(chalk.yellow(`${timestamp()} ${context} ✗ Agent error`));\n const indented = error\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nfunction formatTokenCount(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n return `${(count / 1000000).toFixed(1)}M`;\n}\n\n// Usage summary\nexport function logUsageSummary(\n ctx: LogContext,\n usage: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n },\n contextTokens?: number,\n contextWindow?: number,\n): string {\n const lines: string[] = [];\n lines.push(\"_Usage Summary_\");\n const cacheHitBase = usage.input + usage.cacheRead + usage.cacheWrite;\n const cacheHitPct =\n cacheHitBase > 0 ? ((usage.cacheRead / cacheHitBase) * 100).toFixed(1) : \"0.0\";\n lines.push(\n `Input: ${usage.input.toLocaleString()} tokens · ${usage.cacheRead.toLocaleString()} cached · CH ${cacheHitPct}%`,\n );\n lines.push(`Output: ${usage.output.toLocaleString()} tokens`);\n if (contextTokens && contextWindow) {\n const contextPercent = ((contextTokens / contextWindow) * 100).toFixed(1);\n lines.push(\n `Context: ${formatTokenCount(contextTokens)} / ${formatTokenCount(contextWindow)} (${contextPercent}%)`,\n );\n }\n const costParts: string[] = [\n `\\$${usage.cost.input.toFixed(4)} in`,\n `\\$${usage.cost.cacheRead.toFixed(4)} cache`,\n `\\$${usage.cost.output.toFixed(4)} out`,\n ];\n lines.push(`Cost: ` + costParts.join(\" + \") + ` = *\\$${usage.cost.total.toFixed(4)}*`);\n\n const summary = lines.join(\"\\n\");\n\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💰 Usage`));\n console.log(\n chalk.dim(\n ` in ${usage.input.toLocaleString()} → out ${usage.output.toLocaleString()} = $${usage.cost.total.toFixed(4)}`,\n ),\n );\n\n return summary;\n}\n\n// Startup (no context needed)\nexport function logStartup(workingDir: string, sandbox: string): void {\n console.log(\"Starting mikan...\");\n console.log(` Working directory: ${workingDir}`);\n console.log(` Sandbox: ${sandbox}`);\n}\n\nexport function logConnected(platform: string): void {\n console.log(`⚡️ Mikan connected to ${platform} and listening!`);\n console.log(\"\");\n}\n\nexport function logDisconnected(): void {\n console.log(\"Mikan disconnected.\");\n}\n\n// Backfill\nexport function logBackfillStart(channelCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] Backfilling ${channelCount} channels...`));\n}\n\nexport function logBackfillChannel(channelName: string, messageCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] #${channelName}: ${messageCount} messages`));\n}\n\nexport function logBackfillComplete(totalMessages: number, durationMs: number): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(\n chalk.blue(\n `${timestamp()} [system] Backfill complete: ${totalMessages} messages in ${duration}s`,\n ),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAKtD,SAAS,SAAS;IAChB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACnD,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACrD,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACrD,OAAO,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC;AAC/B,CAAC;AAED,SAAS,aAAa,CAAC,GAAe;IACpC,MAAM,OAAO,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACzD,IAAI,GAAG,CAAC,cAAc,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACvC,OAAO,OAAO,GAAG,CAAC,QA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C,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,yBAAyB,YAAY,cAAc,CAAC,CAAC,CAAC;AAC7F,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,WAAmB,EAAE,YAAoB;IAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,SAAS,EAAE,gBAAgB,WAAW,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC;AACjG,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,aAAqB,EAAE,UAAkB;IAC3E,MAAM,QAAQ,GAAG,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAChD,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,IAAI,CACR,GAAG,SAAS,EAAE,gCAAgC,aAAa,gBAAgB,QAAQ,GAAG,CACvF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import chalk from \"chalk\";\nimport { formatToolArgs } from \"./adapters/shared.js\";\n\nexport type { LogContext } from \"./types.js\";\nimport type { LogContext } from \"./types.js\";\n\nfunction timestamp(): string {\n const now = new Date();\n const hh = String(now.getHours()).padStart(2, \"0\");\n const mm = String(now.getMinutes()).padStart(2, \"0\");\n const ss = String(now.getSeconds()).padStart(2, \"0\");\n return `[${hh}:${mm}:${ss}]`;\n}\n\nfunction formatContext(ctx: LogContext): string {\n const session = ctx.sessionId ? `:${ctx.sessionId}` : \"\";\n if (ctx.conversationId.startsWith(\"D\")) {\n return `[DM:${ctx.userName || ctx.conversationId}${session}]`;\n }\n const conversation = ctx.conversationName || ctx.conversationId;\n const user = ctx.userName || \"unknown\";\n return `[${conversation.startsWith(\"#\") ? conversation : `#${conversation}`}:${user}${session}]`;\n}\n\n// Keep stdout/stderr lines manageable when echoing tool/agent output. Long bodies\n// flow through Sentry and session storage; the console stream just needs a preview.\nconst LOG_PREVIEW_MAX = 1000;\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen)}\\n(truncated at ${maxLen} chars)`;\n}\n\n// User messages\nexport function logUserMessage(ctx: LogContext, text: string): void {\n console.log(chalk.green(`${timestamp()} ${formatContext(ctx)} ${text}`));\n}\n\n// Tool execution\nexport function logToolStart(\n ctx: LogContext,\n toolName: string,\n label: string,\n args: Record<string, unknown>,\n): void {\n const formattedArgs = formatToolArgs(args);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));\n if (formattedArgs) {\n // Indent the args\n const indented = formattedArgs\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolSuccess(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n result: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));\n\n const truncated = truncate(result, LOG_PREVIEW_MAX);\n if (truncated) {\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logToolError(\n ctx: LogContext,\n toolName: string,\n durationMs: number,\n error: string,\n): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));\n\n const truncated = truncate(error, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// Agent run\nexport function logAgentRunStart(\n ctx: LogContext,\n provider: string,\n model: string,\n modelName?: string,\n): void {\n const displayName = modelName && modelName !== model ? ` (${modelName})` : \"\";\n console.log(\n chalk.blue(\n `${timestamp()} ${formatContext(ctx)} ▶ Agent run: ${provider}/${model}${displayName}`,\n ),\n );\n}\n\n// Response streaming\nexport function logResponseStart(ctx: LogContext): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} → Streaming response...`));\n}\n\nexport function logThinking(ctx: LogContext, thinking: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💭 Thinking`));\n const truncated = truncate(thinking, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nexport function logResponse(ctx: LogContext, text: string): void {\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💬 Response`));\n const truncated = truncate(text, LOG_PREVIEW_MAX);\n const indented = truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\n// System\nexport function logInfo(message: string): void {\n console.log(chalk.blue(`${timestamp()} [system] ${message}`));\n}\n\nexport function logWarning(message: string, details?: string): void {\n console.log(chalk.yellow(`${timestamp()} [system] ⚠ ${message}`));\n if (details) {\n const indented = details\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n }\n}\n\nexport function logAgentError(ctx: LogContext | \"system\", error: string): void {\n const context = ctx === \"system\" ? \"[system]\" : formatContext(ctx);\n console.log(chalk.yellow(`${timestamp()} ${context} ✗ Agent error`));\n const indented = error\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\");\n console.log(chalk.dim(indented));\n}\n\nfunction formatTokenCount(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n return `${(count / 1000000).toFixed(1)}M`;\n}\n\n// Usage summary\nexport function logUsageSummary(\n ctx: LogContext,\n usage: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n },\n contextTokens?: number,\n contextWindow?: number,\n): string {\n const lines: string[] = [];\n lines.push(\"_Usage Summary_\");\n const cacheHitBase = usage.input + usage.cacheRead + usage.cacheWrite;\n const cacheHitPct =\n cacheHitBase > 0 ? ((usage.cacheRead / cacheHitBase) * 100).toFixed(1) : \"0.0\";\n lines.push(\n `Input: ${usage.input.toLocaleString()} tokens · ${usage.cacheRead.toLocaleString()} cached · CH ${cacheHitPct}%`,\n );\n lines.push(`Output: ${usage.output.toLocaleString()} tokens`);\n if (contextTokens && contextWindow) {\n const contextPercent = ((contextTokens / contextWindow) * 100).toFixed(1);\n lines.push(\n `Context: ${formatTokenCount(contextTokens)} / ${formatTokenCount(contextWindow)} (${contextPercent}%)`,\n );\n }\n const costParts: string[] = [\n `\\$${usage.cost.input.toFixed(4)} in`,\n `\\$${usage.cost.cacheRead.toFixed(4)} cache`,\n `\\$${usage.cost.output.toFixed(4)} out`,\n ];\n lines.push(`Cost: ` + costParts.join(\" + \") + ` = *\\$${usage.cost.total.toFixed(4)}*`);\n\n const summary = lines.join(\"\\n\");\n\n console.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💰 Usage`));\n // Show cache hits alongside fresh input; otherwise a warm-cache turn reads\n // as if the system prompt had not been sent at all.\n const cached = usage.cacheRead > 0 ? ` (+${usage.cacheRead.toLocaleString()} cached)` : \"\";\n console.log(\n chalk.dim(\n ` in ${usage.input.toLocaleString()}${cached} → out ${usage.output.toLocaleString()} = $${usage.cost.total.toFixed(4)}`,\n ),\n );\n\n return summary;\n}\n\n// Startup (no context needed)\nexport function logStartup(workingDir: string, sandbox: string): void {\n console.log(\"Starting mikan...\");\n console.log(` Working directory: ${workingDir}`);\n console.log(` Sandbox: ${sandbox}`);\n}\n\nexport function logConnected(platform: string): void {\n console.log(`⚡️ Mikan connected to ${platform} and listening!`);\n console.log(\"\");\n}\n\nexport function logDisconnected(): void {\n console.log(\"Mikan disconnected.\");\n}\n\n// Backfill\nexport function logBackfillStart(channelCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] Backfilling ${channelCount} channels...`));\n}\n\nexport function logBackfillChannel(channelName: string, messageCount: number): void {\n console.log(chalk.blue(`${timestamp()} [system] #${channelName}: ${messageCount} messages`));\n}\n\nexport function logBackfillComplete(totalMessages: number, durationMs: number): void {\n const duration = (durationMs / 1000).toFixed(1);\n console.log(\n chalk.blue(\n `${timestamp()} [system] Backfill complete: ${totalMessages} messages in ${duration}s`,\n ),\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provisioner.d.ts","sourceRoot":"","sources":["../../src/sandbox/provisioner.ts"],"names":[],"mappings":"AAoCA,YAAY,EACV,uBAAuB,EACvB,cAAc,EACd,6BAA6B,EAC7B,gBAAgB,EAChB,cAAc,EACd,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACV,uBAAuB,EAEvB,6BAA6B,EAC7B,gBAAgB,EAChB,cAAc,EACd,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAcrB,qBAAa,sBAAsB;IAqB/B,OAAO,CAAC,QAAQ,CAAC,KAAK;IApBxB,OAAO,CAAC,KAAK,CAAqC;IAClD,OAAO,CAAC,QAAQ,CAAsC;IACtD,wEAAwE;IACxE,OAAO,CAAC,cAAc,CAAC,CAA0B;IACjD,OAAO,CAAC,gBAAgB,CAAoC;IAC5D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAwB;IAC7D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAyB;IACjE,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAoB;IAC9D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAA2B;IAC5E,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAA2B;IAC5E,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,oBAAoB,CAAmB;IAC/D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,uBAAuB,CAAyB;IAExE,OAAO,CAAC,QAAQ,CAAC,MA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