ceulen 0.5.1 → 0.8.0
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 +365 -12
- package/README.md +87 -91
- package/extensions/lib/advisor-marker.ts +33 -0
- package/extensions/lib/panel.ts +25 -2
- package/extensions/lib/rate.ts +24 -0
- package/extensions/lib/registry.test.ts +67 -0
- package/extensions/lib/registry.ts +104 -8
- package/extensions/lib/tools.ts +47 -0
- package/extensions/lib/usage-store.ts +33 -0
- package/extensions/modules/advisor/commands/advisor.ts +244 -0
- package/extensions/modules/advisor/configPanel.ts +194 -0
- package/extensions/modules/advisor/index.ts +235 -0
- package/extensions/modules/advisor/lib/config.ts +248 -0
- package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
- package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
- package/extensions/modules/advisor/lib/model-picker.ts +47 -0
- package/extensions/modules/advisor/lib/watcher.ts +288 -0
- package/extensions/modules/advisor/test/compliance.test.ts +125 -0
- package/extensions/modules/advisor/test/config.test.ts +202 -0
- package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
- package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
- package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
- package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
- package/extensions/modules/advisor/test/module.test.ts +649 -0
- package/extensions/modules/advisor/test/watcher.test.ts +478 -0
- package/extensions/modules/classifier/configPanel.ts +104 -0
- package/extensions/modules/classifier/index.ts +297 -0
- package/extensions/modules/classifier/lib/settings.ts +95 -0
- package/extensions/modules/classifier/test/classifier.test.ts +475 -0
- package/extensions/modules/composer/index.ts +152 -3
- package/extensions/modules/composer/lib/footer.ts +119 -0
- package/extensions/modules/composer/lib/shapes.ts +265 -26
- package/extensions/modules/composer/test/editor.test.ts +1 -1
- package/extensions/modules/composer/test/footer.test.ts +96 -0
- package/extensions/modules/composer/test/module.test.ts +113 -11
- package/extensions/modules/composer/test/screen.test.ts +29 -1
- package/extensions/modules/composer/test/shapes.test.ts +224 -8
- package/extensions/modules/config/defaultTools.ts +96 -0
- package/extensions/modules/config/index.ts +147 -7
- package/extensions/modules/config/piSettings.ts +254 -69
- package/extensions/modules/config/test/defaultTools.test.ts +122 -0
- package/extensions/modules/config/test/menu.test.ts +64 -0
- package/extensions/modules/config/test/panel.test.ts +38 -23
- package/extensions/modules/config/test/piSettings.test.ts +130 -3
- package/extensions/modules/config/test/renderTools.test.ts +71 -0
- package/extensions/modules/config/test/tools.test.ts +146 -0
- package/extensions/modules/fff/index.ts +2094 -0
- package/extensions/modules/fff/lib/query.ts +129 -0
- package/extensions/modules/fff/test/index.test.ts +607 -0
- package/extensions/modules/fff/test/query.test.ts +71 -0
- package/extensions/modules/munin/configPanel.ts +108 -0
- package/extensions/modules/munin/index.ts +641 -0
- package/extensions/modules/munin/lib/helpers.ts +471 -0
- package/extensions/modules/munin/lib/retry.ts +20 -0
- package/extensions/modules/munin/lib/sdk.ts +218 -0
- package/extensions/modules/munin/test/config.test.ts +168 -0
- package/extensions/modules/munin/test/configPanel.test.ts +186 -0
- package/extensions/modules/munin/test/extension.test.ts +224 -0
- package/extensions/modules/munin/test/helpers.test.ts +523 -0
- package/extensions/modules/munin/test/retry.test.ts +145 -0
- package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
- package/extensions/modules/plan/configPanel.ts +152 -0
- package/extensions/modules/plan/index.ts +917 -0
- package/extensions/modules/plan/lib/plan-tools.ts +72 -0
- package/extensions/modules/plan/lib/prompt.ts +65 -0
- package/extensions/modules/plan/lib/settings.ts +166 -0
- package/extensions/modules/plan/lib/shell-gate.ts +200 -0
- package/extensions/modules/plan/test/configPanel.test.ts +96 -0
- package/extensions/modules/plan/test/harness.ts +133 -0
- package/extensions/modules/plan/test/module.test.ts +305 -0
- package/extensions/modules/plan/test/settings.test.ts +114 -0
- package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
- package/extensions/modules/ponytail/index.ts +23 -73
- package/extensions/modules/ponytail/lib/config.ts +1 -6
- package/extensions/modules/ponytail/test/extension.test.ts +1 -85
- package/extensions/modules/repair/configPanel.ts +96 -0
- package/extensions/modules/repair/index.ts +414 -0
- package/extensions/modules/repair/lib/auto-bg.ts +333 -0
- package/extensions/modules/repair/lib/edit-repair.ts +155 -0
- package/extensions/modules/repair/lib/editor.ts +251 -0
- package/extensions/modules/repair/lib/guards.ts +34 -0
- package/extensions/modules/repair/lib/input-repair.ts +324 -0
- package/extensions/modules/repair/lib/patch.ts +481 -0
- package/extensions/modules/repair/lib/settings.ts +114 -0
- package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
- package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
- package/extensions/modules/repair/test/editor.test.ts +141 -0
- package/extensions/modules/repair/test/guards.test.ts +64 -0
- package/extensions/modules/repair/test/input-repair.test.ts +231 -0
- package/extensions/modules/repair/test/patch.test.ts +563 -0
- package/extensions/modules/repair/test/settings.test.ts +167 -0
- package/extensions/modules/repair/test/wrapper.test.ts +210 -0
- package/extensions/modules/router/commands/commands.ts +4 -0
- package/extensions/modules/router/configPanel.ts +24 -10
- package/extensions/modules/router/lib/client.ts +63 -0
- package/extensions/modules/router/lib/provider.ts +34 -13
- package/extensions/modules/router/lib/systemone.ts +152 -0
- package/extensions/modules/router/test/unit.test.ts +260 -0
- package/extensions/modules/rtk/findFallback.js +68 -0
- package/extensions/modules/rtk/index.ts +248 -0
- package/extensions/modules/rtk/safe-rewrite.js +74 -0
- package/extensions/modules/rtk/test/findFallback.test.js +66 -0
- package/extensions/modules/rtk/test/index.test.js +131 -0
- package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
- package/extensions/modules/rtk/version-gate.js +34 -0
- package/extensions/modules/rules/index.ts +120 -0
- package/extensions/modules/rules/lib/rules.ts +348 -0
- package/extensions/modules/rules/test/lib.test.ts +263 -0
- package/extensions/modules/rules/test/module.test.ts +222 -0
- package/extensions/modules/serena/index.ts +629 -0
- package/extensions/modules/serena/lib/detect.ts +73 -0
- package/extensions/modules/serena/lib/env.ts +76 -0
- package/extensions/modules/serena/lib/guidance.ts +26 -0
- package/extensions/modules/serena/lib/normalize.ts +27 -0
- package/extensions/modules/serena/lib/symbol-key.ts +20 -0
- package/extensions/modules/serena/lib/truncate.ts +20 -0
- package/extensions/modules/serena/test/env.test.ts +122 -0
- package/extensions/modules/serena/test/index.test.ts +347 -0
- package/extensions/modules/serena/test/worker.test.ts +562 -0
- package/extensions/modules/serena/worker.ts +858 -0
- package/extensions/modules/steering/configPanel.ts +122 -0
- package/extensions/modules/steering/index.ts +616 -0
- package/extensions/modules/steering/lib/anchor.ts +175 -0
- package/extensions/modules/steering/lib/errors.ts +253 -0
- package/extensions/modules/steering/lib/family.ts +33 -0
- package/extensions/modules/steering/lib/guidance.ts +172 -0
- package/extensions/modules/steering/lib/history.ts +170 -0
- package/extensions/modules/steering/lib/settings.ts +127 -0
- package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
- package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
- package/extensions/modules/steering/test/anchor.test.ts +160 -0
- package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
- package/extensions/modules/steering/test/errors.test.ts +309 -0
- package/extensions/modules/steering/test/family.test.ts +43 -0
- package/extensions/modules/steering/test/guidance.test.ts +357 -0
- package/extensions/modules/steering/test/harness.ts +93 -0
- package/extensions/modules/steering/test/history.test.ts +118 -0
- package/extensions/modules/steering/test/settings.test.ts +182 -0
- package/extensions/modules/steering/test/status.test.ts +71 -0
- package/extensions/modules/steering/test/toolCall.test.ts +99 -0
- package/extensions/modules/subagent/agents/planner.md +14 -0
- package/extensions/modules/subagent/agents/reviewer.md +42 -0
- package/extensions/modules/subagent/agents/scout.md +47 -0
- package/extensions/modules/subagent/agents/tester.md +12 -0
- package/extensions/modules/subagent/agents/worker.md +18 -0
- package/extensions/modules/subagent/configPanel.ts +219 -0
- package/extensions/modules/subagent/index.ts +2464 -0
- package/extensions/modules/subagent/lib/agents.ts +408 -0
- package/extensions/modules/subagent/lib/background.ts +383 -0
- package/extensions/modules/subagent/lib/herdr.ts +1019 -0
- package/extensions/modules/subagent/lib/history.ts +126 -0
- package/extensions/modules/subagent/lib/model.ts +156 -0
- package/extensions/modules/subagent/lib/render.ts +335 -0
- package/extensions/modules/subagent/lib/result.ts +110 -0
- package/extensions/modules/subagent/lib/roles.ts +296 -0
- package/extensions/modules/subagent/lib/routing.ts +228 -0
- package/extensions/modules/subagent/lib/runner.ts +559 -0
- package/extensions/modules/subagent/lib/schema.ts +21 -0
- package/extensions/modules/subagent/lib/security.ts +763 -0
- package/extensions/modules/subagent/lib/settings.ts +159 -0
- package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
- package/extensions/modules/subagent/lib/threads.ts +135 -0
- package/extensions/modules/subagent/lib/types.ts +18 -0
- package/extensions/modules/subagent/lib/widget.ts +475 -0
- package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
- package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
- package/extensions/modules/subagent/test/routing.test.ts +524 -0
- package/extensions/modules/subagent/test/widget.test.ts +208 -0
- package/extensions/modules/todo/index.ts +478 -0
- package/extensions/modules/todo/test/todo.test.ts +252 -0
- package/extensions/modules/usage/index.ts +70 -16
- package/extensions/modules/usage/test/genrate.test.ts +70 -0
- package/extensions/modules/usage/test/parsers.test.ts +13 -0
- package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
- package/extensions/modules/ux/UPSTREAM +24 -0
- package/extensions/modules/ux/index.ts +393 -0
- package/extensions/modules/ux/lib/audit.ts +562 -0
- package/extensions/modules/ux/lib/config.ts +136 -0
- package/extensions/modules/ux/lib/instructions.ts +77 -0
- package/extensions/modules/ux/test/audit.test.ts +756 -0
- package/extensions/modules/ux/test/extension.test.ts +394 -0
- package/extensions/modules/ux/test/instructions.test.ts +19 -0
- package/extensions/modules/web/configPanel.ts +218 -0
- package/extensions/modules/web/index.ts +978 -0
- package/extensions/modules/web/lib/agy.ts +209 -0
- package/extensions/modules/web/lib/brave.ts +42 -0
- package/extensions/modules/web/lib/cdp.ts +686 -0
- package/extensions/modules/web/lib/chatapi.ts +101 -0
- package/extensions/modules/web/lib/chatgpt.ts +796 -0
- package/extensions/modules/web/lib/chrome.ts +328 -0
- package/extensions/modules/web/lib/config.ts +136 -0
- package/extensions/modules/web/lib/content.ts +99 -0
- package/extensions/modules/web/lib/crawl4ai.ts +172 -0
- package/extensions/modules/web/lib/extract.ts +235 -0
- package/extensions/modules/web/lib/firecrawl.ts +56 -0
- package/extensions/modules/web/lib/format.ts +197 -0
- package/extensions/modules/web/lib/gemini-auth.ts +286 -0
- package/extensions/modules/web/lib/gemini-dr.ts +338 -0
- package/extensions/modules/web/lib/gemini.ts +551 -0
- package/extensions/modules/web/lib/imageapi.ts +559 -0
- package/extensions/modules/web/lib/retry.ts +71 -0
- package/extensions/modules/web/lib/search.ts +237 -0
- package/extensions/modules/web/lib/searxng.ts +69 -0
- package/extensions/modules/web/lib/settings.ts +157 -0
- package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
- package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
- package/extensions/modules/web/test/agy.test.ts +383 -0
- package/extensions/modules/web/test/cdp.test.ts +717 -0
- package/extensions/modules/web/test/chat.test.ts +171 -0
- package/extensions/modules/web/test/chatgpt.test.ts +633 -0
- package/extensions/modules/web/test/chrome.test.ts +282 -0
- package/extensions/modules/web/test/config.test.ts +218 -0
- package/extensions/modules/web/test/configPanel.test.ts +198 -0
- package/extensions/modules/web/test/crawl.test.ts +134 -0
- package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
- package/extensions/modules/web/test/extension.test.ts +118 -0
- package/extensions/modules/web/test/extract.test.ts +436 -0
- package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
- package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
- package/extensions/modules/web/test/fixtures/interaction.html +31 -0
- package/extensions/modules/web/test/format.test.ts +230 -0
- package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
- package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
- package/extensions/modules/web/test/gemini.test.ts +472 -0
- package/extensions/modules/web/test/hook.test.ts +101 -0
- package/extensions/modules/web/test/image.test.ts +1089 -0
- package/extensions/modules/web/test/retry.test.ts +119 -0
- package/extensions/modules/web/test/screenshot.test.ts +109 -0
- package/extensions/modules/web/test/search.test.ts +210 -0
- package/extensions/modules/web/test/settings.test.ts +165 -0
- package/extensions/modules/web/test/skill.test.ts +72 -0
- package/extensions/modules/web/types.d.ts +3 -0
- package/extensions/modules/web/vendor/package.json +1 -0
- package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
- package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
- package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
- package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
- package/extensions/modules/web/vendor/readability/index.js +9 -0
- package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
- package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
- package/extensions/modules/zai/configPanel.ts +154 -0
- package/extensions/modules/zai/index.ts +186 -0
- package/extensions/modules/zai/lib/anthropic.ts +159 -0
- package/extensions/modules/zai/lib/settings.ts +198 -0
- package/extensions/modules/zai/lib/signing.ts +721 -0
- package/extensions/modules/zai/lib/throttle.ts +198 -0
- package/extensions/modules/zai/test/anthropic.test.ts +132 -0
- package/extensions/modules/zai/test/configPanel.test.ts +230 -0
- package/extensions/modules/zai/test/extension.test.ts +249 -0
- package/extensions/modules/zai/test/settings.test.ts +183 -0
- package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
- package/extensions/modules/zai/test/signing.test.ts +364 -0
- package/extensions/modules/zai/test/throttle.test.ts +329 -0
- package/package.json +19 -4
- package/scripts/validate-themes.mjs +75 -0
- package/skills/munin/SKILL.md +117 -0
- package/skills/ux-capture/SKILL.md +202 -0
- package/skills/ux-design/SKILL.md +279 -0
- package/skills/ux-presets/SKILL.md +484 -0
- package/skills/ux-routing/SKILL.md +46 -0
- package/skills/web/SKILL.md +153 -0
- package/themes/alabaster.json +93 -0
- package/themes/amethyst.json +96 -0
- package/themes/anthracite.json +93 -0
- package/themes/basalt.json +91 -0
- package/themes/birch.json +95 -0
- package/themes/catppuccin-mocha.json +91 -0
- package/themes/dark-abyss.json +91 -0
- package/themes/dark-arctic.json +104 -0
- package/themes/dark-aurora.json +95 -0
- package/themes/dark-catppuccin.json +107 -0
- package/themes/dark-cavern.json +91 -0
- package/themes/dark-celestial.json +106 -0
- package/themes/dark-copper.json +95 -0
- package/themes/dark-cosmos.json +90 -0
- package/themes/dark-cyberpunk.json +102 -0
- package/themes/dark-dracula.json +98 -0
- package/themes/dark-eclipse.json +91 -0
- package/themes/dark-ember.json +95 -0
- package/themes/dark-equinox.json +90 -0
- package/themes/dark-forest.json +96 -0
- package/themes/dark-github.json +105 -0
- package/themes/dark-gruvbox.json +112 -0
- package/themes/dark-lavender.json +95 -0
- package/themes/dark-lunar.json +89 -0
- package/themes/dark-midnight.json +95 -0
- package/themes/dark-monochrome.json +94 -0
- package/themes/dark-monokai.json +98 -0
- package/themes/dark-nebula.json +90 -0
- package/themes/dark-neon-noir.json +100 -0
- package/themes/dark-nord.json +98 -0
- package/themes/dark-ocean.json +101 -0
- package/themes/dark-one.json +100 -0
- package/themes/dark-poimandres.json +115 -0
- package/themes/dark-rainforest.json +91 -0
- package/themes/dark-reef.json +91 -0
- package/themes/dark-retro.json +92 -0
- package/themes/dark-rose-pine.json +96 -0
- package/themes/dark-sakura.json +95 -0
- package/themes/dark-slate.json +95 -0
- package/themes/dark-solarized.json +97 -0
- package/themes/dark-solstice.json +90 -0
- package/themes/dark-starfall.json +91 -0
- package/themes/dark-sunset.json +99 -0
- package/themes/dark-swamp.json +90 -0
- package/themes/dark-synthwave.json +103 -0
- package/themes/dark-taiga.json +91 -0
- package/themes/dark-terminal.json +95 -0
- package/themes/dark-tokyo-night.json +101 -0
- package/themes/dark-tundra.json +91 -0
- package/themes/dark-twilight.json +91 -0
- package/themes/dark-volcanic.json +91 -0
- package/themes/dark.json +80 -0
- package/themes/graphite.json +92 -0
- package/themes/light-arctic.json +107 -0
- package/themes/light-aurora-day.json +91 -0
- package/themes/light-canyon.json +91 -0
- package/themes/light-catppuccin.json +106 -0
- package/themes/light-cirrus.json +90 -0
- package/themes/light-coral.json +95 -0
- package/themes/light-cyberpunk.json +96 -0
- package/themes/light-dawn.json +90 -0
- package/themes/light-dunes.json +91 -0
- package/themes/light-eucalyptus.json +95 -0
- package/themes/light-forest.json +100 -0
- package/themes/light-frost.json +95 -0
- package/themes/light-github.json +115 -0
- package/themes/light-glacier.json +91 -0
- package/themes/light-gruvbox.json +108 -0
- package/themes/light-haze.json +90 -0
- package/themes/light-honeycomb.json +95 -0
- package/themes/light-lagoon.json +91 -0
- package/themes/light-lavender.json +95 -0
- package/themes/light-meadow.json +91 -0
- package/themes/light-mint.json +95 -0
- package/themes/light-monochrome.json +101 -0
- package/themes/light-ocean.json +99 -0
- package/themes/light-one.json +99 -0
- package/themes/light-opal.json +91 -0
- package/themes/light-orchard.json +91 -0
- package/themes/light-paper.json +95 -0
- package/themes/light-poimandres.json +115 -0
- package/themes/light-prism.json +90 -0
- package/themes/light-retro.json +98 -0
- package/themes/light-sand.json +95 -0
- package/themes/light-savanna.json +91 -0
- package/themes/light-solarized.json +102 -0
- package/themes/light-soleil.json +90 -0
- package/themes/light-sunset.json +99 -0
- package/themes/light-synthwave.json +98 -0
- package/themes/light-tokyo-night.json +111 -0
- package/themes/light-wetland.json +91 -0
- package/themes/light-zenith.json +89 -0
- package/themes/light.json +80 -0
- package/themes/limestone.json +94 -0
- package/themes/mahogany.json +97 -0
- package/themes/marble.json +93 -0
- package/themes/mirage.json +79 -0
- package/themes/obsidian.json +91 -0
- package/themes/onyx.json +91 -0
- package/themes/pearl.json +93 -0
- package/themes/porcelain.json +91 -0
- package/themes/quartz.json +96 -0
- package/themes/sandstone.json +95 -0
- package/themes/titanium.json +90 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
// ponytail: vendored from @bacnh85/pi-subagent 0.23.2 (extensions/runner.ts).
|
|
2
|
+
// ceulen delta: hardTimeoutMs <= 0 arms NO hard timer — the cap is opt-in
|
|
3
|
+
// (subagent.hardTimeoutMins, 0=off); the idle timer is the hang detector.
|
|
4
|
+
/**
|
|
5
|
+
* SDK-based sub-agent runner for pi-subagent.
|
|
6
|
+
*
|
|
7
|
+
* Creates an in-process AgentSession via the pi SDK instead of spawning a
|
|
8
|
+
* separate `pi` process. This eliminates cold-start overhead and allows
|
|
9
|
+
* fine-grained control over token budget:
|
|
10
|
+
*
|
|
11
|
+
* - Only the agent's system prompt is used (no pi defaults).
|
|
12
|
+
* - No AGENTS.md, no extensions, no skills, no prompt templates loaded.
|
|
13
|
+
* - Thinking disabled, compaction disabled, one transient retry.
|
|
14
|
+
* - In-memory session (no disk I/O).
|
|
15
|
+
* - Shared auth/model infrastructure (no re-connection).
|
|
16
|
+
*
|
|
17
|
+
* Estimated token savings vs process-spawn: ~4-11K tokens per invocation.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { Message, Model } from "./types.ts";
|
|
21
|
+
import type { AgentMessage } from "./types.ts";
|
|
22
|
+
import * as fs from "node:fs/promises";
|
|
23
|
+
import * as os from "node:os";
|
|
24
|
+
import * as path from "node:path";
|
|
25
|
+
import {
|
|
26
|
+
createAgentSession,
|
|
27
|
+
createExtensionRuntime,
|
|
28
|
+
DefaultResourceLoader,
|
|
29
|
+
getAgentDir,
|
|
30
|
+
type ResourceLoader,
|
|
31
|
+
SessionManager,
|
|
32
|
+
SettingsManager,
|
|
33
|
+
} from "@earendil-works/pi-coding-agent";
|
|
34
|
+
import {
|
|
35
|
+
classifyStopReason,
|
|
36
|
+
createCombinedAbortSignal,
|
|
37
|
+
type SubagentStatus,
|
|
38
|
+
DEFAULT_TIMEOUT_MS,
|
|
39
|
+
HARD_TIMEOUT_MS,
|
|
40
|
+
truncateParallelOutput,
|
|
41
|
+
} from "./security.ts";
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// Types
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
export interface UsageStats {
|
|
48
|
+
input: number;
|
|
49
|
+
output: number;
|
|
50
|
+
cacheRead: number;
|
|
51
|
+
cacheWrite: number;
|
|
52
|
+
cost: number;
|
|
53
|
+
contextTokens: number;
|
|
54
|
+
turns: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Re-export from security.ts — single source of truth for both timeouts. */
|
|
58
|
+
export const DEFAULT_INACTIVITY_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
|
|
59
|
+
export { HARD_TIMEOUT_MS };
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
// Extension resource loader
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Build a FRESH lean DefaultResourceLoader for this child — no skills, prompt
|
|
68
|
+
* templates, context files (AGENTS.md), or themes. Extensions are loaded per
|
|
69
|
+
* child so their factories run against a runtime that THIS child's session will
|
|
70
|
+
* bind.
|
|
71
|
+
*
|
|
72
|
+
* Do NOT cache/share this loader. Extensions capture the ExtensionAPI (`pi`)
|
|
73
|
+
* at factory load time, and its actions delegate to the runtime passed to the
|
|
74
|
+
* factory (see createExtensionAPI: pi.getAllTools() → runtime.getAllTools()).
|
|
75
|
+
* If extensions were loaded once against a shared/cached runtime, that runtime
|
|
76
|
+
* is never the one any single child binds: a session binds the runtime its own
|
|
77
|
+
* getExtensions() returned (AgentSession constructor), while the factory-captured
|
|
78
|
+
* pi still points at the shared runtime. A child then hits the runtime's throwing
|
|
79
|
+
* "Extension runtime not initialized" stubs on the first provider request
|
|
80
|
+
* (pi-model-tools' before_provider_request calls pi.getAllTools()), or stale-ctx
|
|
81
|
+
* errors when the shared runtime is invalidated by the first child's dispose.
|
|
82
|
+
* A per-child loader keeps every captured `pi` pointing at a runtime this child
|
|
83
|
+
* both binds and owns.
|
|
84
|
+
*
|
|
85
|
+
* Project-extension trust is resolved from the parent (`projectTrusted`) so a
|
|
86
|
+
* child never prompts for trust (it has no UI). reload() per child re-reads
|
|
87
|
+
* extension files + re-runs factories; acceptable for short-lived children.
|
|
88
|
+
*/
|
|
89
|
+
async function getExtensionLoader(cwd: string, projectTrusted: boolean): Promise<ResourceLoader> {
|
|
90
|
+
const loader = new DefaultResourceLoader({
|
|
91
|
+
cwd,
|
|
92
|
+
agentDir: getAgentDir(),
|
|
93
|
+
noSkills: true,
|
|
94
|
+
noPromptTemplates: true,
|
|
95
|
+
noContextFiles: true,
|
|
96
|
+
noThemes: true,
|
|
97
|
+
});
|
|
98
|
+
await loader.reload({ resolveProjectTrust: async () => projectTrusted });
|
|
99
|
+
// Log (don't throw on) extension load errors — a misbehaving extension must
|
|
100
|
+
// not crash the child; the agent simply won't have that tool.
|
|
101
|
+
const loadErrors = loader.getExtensions().errors;
|
|
102
|
+
if (loadErrors.length > 0) {
|
|
103
|
+
process.stderr.write(
|
|
104
|
+
`[pi-subagent] extension load warnings in child loader: ${loadErrors.map((e) => `${e.path}: ${e.error}`).join("; ")}\n`,
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return loader;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface SubAgentProgress {
|
|
111
|
+
label: string;
|
|
112
|
+
at: number;
|
|
113
|
+
elapsedMs: number;
|
|
114
|
+
inactivityDeadline: number;
|
|
115
|
+
hardDeadline: number;
|
|
116
|
+
result: SubAgentResult;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface SubAgentResult {
|
|
120
|
+
agent: string;
|
|
121
|
+
task: string;
|
|
122
|
+
exitCode: number;
|
|
123
|
+
messages: Message[];
|
|
124
|
+
stderr: string;
|
|
125
|
+
usage: UsageStats;
|
|
126
|
+
model?: string;
|
|
127
|
+
/** Thinking level the child actually ran with (after routing/pins). */
|
|
128
|
+
thinking?: string;
|
|
129
|
+
/** Steered advisor revisions folded into this result (herdr runner waited
|
|
130
|
+
* for the child's own advisor before collecting — see lib/herdr.ts). */
|
|
131
|
+
advisorRounds?: number;
|
|
132
|
+
stopReason?: string;
|
|
133
|
+
errorMessage?: string;
|
|
134
|
+
/** Unified diff of changes made in an isolated worktree (sandbox: "worktree"). */
|
|
135
|
+
patch?: string;
|
|
136
|
+
/** Set when merge:"3way" was requested: outcome of applying the patch to the parent checkout. */
|
|
137
|
+
mergeStatus?: "applied" | "conflict";
|
|
138
|
+
/** git apply error excerpt when mergeStatus === "conflict". */
|
|
139
|
+
mergeError?: string;
|
|
140
|
+
/** Canonical result status (added in 0.6.0). */
|
|
141
|
+
status?: SubagentStatus;
|
|
142
|
+
/** Wall-clock duration of the run, set by runSubAgent (Date.now() - startedAt). */
|
|
143
|
+
durationMs?: number;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// Public API
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
export function startHeartbeat(onHeartbeat: () => void, intervalMs = 30_000): () => void {
|
|
151
|
+
const timer = setInterval(onHeartbeat, intervalMs);
|
|
152
|
+
timer.unref?.();
|
|
153
|
+
return () => clearInterval(timer);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function runSubAgent(options: {
|
|
157
|
+
cwd: string;
|
|
158
|
+
systemPrompt: string;
|
|
159
|
+
task: string;
|
|
160
|
+
tools: string[];
|
|
161
|
+
model: Model;
|
|
162
|
+
/** "worktree" runs the child in an isolated git worktree; the resulting diff is returned as result.patch. */
|
|
163
|
+
sandbox?: "worktree";
|
|
164
|
+
/** With sandbox:"worktree", apply the captured diff to the parent checkout via `git apply --3way` after the run. */
|
|
165
|
+
merge?: "3way";
|
|
166
|
+
/** Pi 0.80.10's canonical credential/model runtime. */
|
|
167
|
+
modelRuntime?: unknown;
|
|
168
|
+
/** Legacy Pi SDK session options retained for 0.80.6 tests and hosts. */
|
|
169
|
+
authStorage?: unknown;
|
|
170
|
+
modelRegistry?: unknown;
|
|
171
|
+
signal?: AbortSignal;
|
|
172
|
+
agentName?: string;
|
|
173
|
+
thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
174
|
+
onMessage?: (partialResult: SubAgentResult) => void;
|
|
175
|
+
onProgress?: (progress: SubAgentProgress) => void;
|
|
176
|
+
timeoutMs?: number;
|
|
177
|
+
hardTimeoutMs?: number;
|
|
178
|
+
/** Exec used for the git worktree lifecycle (add/remove/diff). Defaults to a child_process spawn when unset. */
|
|
179
|
+
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>;
|
|
180
|
+
/**
|
|
181
|
+
* When true, build a DefaultResourceLoader so the child inherits the parent's
|
|
182
|
+
* extensions (and thus extension tools: web, serena, munin, …). When false or
|
|
183
|
+
* unset, the lean empty-loader stub is used (no extensions).
|
|
184
|
+
*/
|
|
185
|
+
loadExtensions?: boolean;
|
|
186
|
+
/**
|
|
187
|
+
* Whether the parent session trusts the project. Forwarded to the loader's
|
|
188
|
+
* resolveProjectTrust so children inherit the parent's trust decision and
|
|
189
|
+
* never prompt for project-extension trust (children have no UI). Defaults true.
|
|
190
|
+
*/
|
|
191
|
+
projectTrusted?: boolean;
|
|
192
|
+
}): Promise<SubAgentResult> {
|
|
193
|
+
const {
|
|
194
|
+
cwd, systemPrompt, task, tools, model, modelRuntime, authStorage, modelRegistry, signal,
|
|
195
|
+
agentName = "subagent", thinkingLevel = "off", onMessage, onProgress,
|
|
196
|
+
timeoutMs = DEFAULT_INACTIVITY_TIMEOUT_MS, hardTimeoutMs = HARD_TIMEOUT_MS,
|
|
197
|
+
loadExtensions = false, projectTrusted = true, sandbox, merge, exec,
|
|
198
|
+
} = options;
|
|
199
|
+
const result: SubAgentResult = {
|
|
200
|
+
agent: agentName, task, exitCode: 0, messages: [], stderr: "",
|
|
201
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
|
|
202
|
+
model: `${model.provider}/${model.id}`, status: undefined,
|
|
203
|
+
thinking: thinkingLevel,
|
|
204
|
+
};
|
|
205
|
+
const resourceLoader: ResourceLoader = loadExtensions
|
|
206
|
+
? await getExtensionLoader(cwd, projectTrusted)
|
|
207
|
+
: {
|
|
208
|
+
getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),
|
|
209
|
+
getSkills: () => ({ skills: [], diagnostics: [] }), getPrompts: () => ({ prompts: [], diagnostics: [] }),
|
|
210
|
+
getThemes: () => ({ themes: [], diagnostics: [] }), getAgentsFiles: () => ({ agentsFiles: [] }),
|
|
211
|
+
getSystemPrompt: () => systemPrompt, getSystemPromptSource: () => undefined,
|
|
212
|
+
getAppendSystemPrompt: () => [], getAppendSystemPromptSources: () => [],
|
|
213
|
+
extendResources: () => {}, reload: async () => {},
|
|
214
|
+
};
|
|
215
|
+
const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: true, maxRetries: 1 } });
|
|
216
|
+
const startedAt = Date.now();
|
|
217
|
+
let inactivityDeadline = startedAt + timeoutMs;
|
|
218
|
+
const hardDeadline = startedAt + hardTimeoutMs;
|
|
219
|
+
let timeoutKind: "idle" | "hard" | undefined;
|
|
220
|
+
const timeoutController = new AbortController();
|
|
221
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
222
|
+
let hardTimer: ReturnType<typeof setTimeout> | undefined;
|
|
223
|
+
let cleanupCombined: (() => void) | undefined;
|
|
224
|
+
const clearTimers = () => { if (idleTimer) clearTimeout(idleTimer); if (hardTimer) clearTimeout(hardTimer); };
|
|
225
|
+
const armIdle = () => {
|
|
226
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
227
|
+
inactivityDeadline = Date.now() + timeoutMs;
|
|
228
|
+
idleTimer = setTimeout(() => { timeoutKind = "idle"; timeoutController.abort(new Error(`Idle timeout after ${timeoutMs}ms`)); }, timeoutMs);
|
|
229
|
+
};
|
|
230
|
+
const snapshot = (label: string): SubAgentProgress => ({ label, at: Date.now(), elapsedMs: Date.now() - startedAt, inactivityDeadline, hardDeadline, result: { ...result, messages: [...result.messages] } });
|
|
231
|
+
try {
|
|
232
|
+
armIdle();
|
|
233
|
+
// ceulen: hardTimeoutMs <= 0 (subagent.hardTimeoutMins: 0, the default) arms
|
|
234
|
+
// NO hard timer — a child producing events is never hard-killed. The idle
|
|
235
|
+
// timer above is the hang detector.
|
|
236
|
+
if (hardTimeoutMs > 0) {
|
|
237
|
+
hardTimer = setTimeout(() => { timeoutKind = "hard"; timeoutController.abort(new Error(`Hard timeout after ${hardTimeoutMs}ms`)); }, hardTimeoutMs);
|
|
238
|
+
}
|
|
239
|
+
const { signal: combinedSignal, cleanup } = createCombinedAbortSignal([signal, timeoutController.signal]);
|
|
240
|
+
cleanupCombined = cleanup;
|
|
241
|
+
if (combinedSignal.aborted) {
|
|
242
|
+
result.exitCode = 1;
|
|
243
|
+
const timedOut = timeoutController.signal.aborted && !signal?.aborted;
|
|
244
|
+
result.stopReason = timedOut ? "timeout" : "aborted";
|
|
245
|
+
result.errorMessage = timedOut ? `${timeoutKind === "idle" ? "Idle" : "Hard"} timeout after ${timeoutKind === "idle" ? timeoutMs : hardTimeoutMs}ms` : "Sub-agent aborted before start";
|
|
246
|
+
result.status = classifyStopReason(result.stopReason, !timedOut, timedOut);
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Isolated git worktree: the child edits a sibling checkout; the resulting
|
|
251
|
+
// diff is returned as result.patch and the worktree is removed on exit.
|
|
252
|
+
// ponytail: falls back to the in-process cwd when git is unavailable — the
|
|
253
|
+
// worktree is an isolation optimization, not a hard requirement.
|
|
254
|
+
let worktreeDir: string | undefined;
|
|
255
|
+
let worktreeRepoRoot: string | undefined;
|
|
256
|
+
let childCwd = cwd;
|
|
257
|
+
if (sandbox === "worktree") {
|
|
258
|
+
const wt = await createWorktree(cwd, exec);
|
|
259
|
+
if (wt.ok) {
|
|
260
|
+
worktreeDir = wt.path;
|
|
261
|
+
worktreeRepoRoot = wt.repoRoot;
|
|
262
|
+
childCwd = wt.path!;
|
|
263
|
+
} else if (wt.error) {
|
|
264
|
+
result.stderr = `Worktree unavailable (${wt.error}); running in workspace.`;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
let session: Awaited<ReturnType<typeof createAgentSession>>["session"];
|
|
269
|
+
try {
|
|
270
|
+
const created = await createAgentSession({
|
|
271
|
+
cwd: childCwd, model, thinkingLevel, resourceLoader, tools, sessionManager: SessionManager.inMemory(childCwd), settingsManager,
|
|
272
|
+
...(modelRuntime ? { modelRuntime } : {}),
|
|
273
|
+
// Pi 0.80.10 owns credentials in ModelRuntime; older SDKs still accept these.
|
|
274
|
+
...(authStorage ? { authStorage, modelRegistry } : {}),
|
|
275
|
+
} as any);
|
|
276
|
+
session = created.session;
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (worktreeDir) await removeWorktree(cwd, worktreeDir, exec);
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
let unsubscribe: (() => void) | undefined;
|
|
282
|
+
let removeAbort: (() => void) | undefined;
|
|
283
|
+
try {
|
|
284
|
+
const eventDone = new Promise<void>((resolve, reject) => {
|
|
285
|
+
let done = false;
|
|
286
|
+
const finish = (fn: () => void) => { if (!done) { done = true; unsubscribe?.(); fn(); } };
|
|
287
|
+
unsubscribe = session.subscribe((event) => {
|
|
288
|
+
try {
|
|
289
|
+
// Any SDK session event — including message_update streaming
|
|
290
|
+
// deltas (thinking_delta/text_delta) — is real child activity
|
|
291
|
+
// and resets the idle timer. Only a stream with NO events at all
|
|
292
|
+
// for timeoutMs indicates a hung child.
|
|
293
|
+
armIdle(); onProgress?.(snapshot(event.type));
|
|
294
|
+
if (event.type === "message_end") {
|
|
295
|
+
const msg = event.message as AgentMessage;
|
|
296
|
+
if (msg.role === "assistant") {
|
|
297
|
+
result.usage.turns++;
|
|
298
|
+
if (msg.usage) { result.usage.input += msg.usage.input || 0; result.usage.output += msg.usage.output || 0; result.usage.cacheRead += msg.usage.cacheRead || 0; result.usage.cacheWrite += msg.usage.cacheWrite || 0; result.usage.cost += msg.usage.cost?.total || 0; result.usage.contextTokens = msg.usage.totalTokens || 0; }
|
|
299
|
+
if (!result.model && msg.model) result.model = `${msg.provider || "?"}/${msg.model}`;
|
|
300
|
+
if (msg.stopReason) result.stopReason = msg.stopReason;
|
|
301
|
+
result.errorMessage = msg.errorMessage;
|
|
302
|
+
}
|
|
303
|
+
result.messages.push(msg as unknown as Message);
|
|
304
|
+
onMessage?.({ ...result, messages: [...result.messages] });
|
|
305
|
+
} else if (event.type === "agent_end" && !event.willRetry) {
|
|
306
|
+
if (!result.messages.length && event.messages) result.messages = event.messages as unknown as Message[];
|
|
307
|
+
finish(resolve);
|
|
308
|
+
}
|
|
309
|
+
} catch (error) { finish(() => reject(error)); }
|
|
310
|
+
});
|
|
311
|
+
const abort = () => finish(resolve);
|
|
312
|
+
combinedSignal.addEventListener("abort", abort, { once: true });
|
|
313
|
+
removeAbort = () => combinedSignal.removeEventListener("abort", abort);
|
|
314
|
+
});
|
|
315
|
+
const abortSession = () => session.abort();
|
|
316
|
+
combinedSignal.addEventListener("abort", abortSession, { once: true });
|
|
317
|
+
const removeSessionAbort = () => combinedSignal.removeEventListener("abort", abortSession);
|
|
318
|
+
await Promise.race([session.prompt(task), eventDone]);
|
|
319
|
+
removeSessionAbort();
|
|
320
|
+
const timedOut = timeoutController.signal.aborted && !signal?.aborted;
|
|
321
|
+
if (timedOut) { result.stopReason = "timeout"; result.errorMessage = `${timeoutKind === "idle" ? "Idle" : "Hard"} timeout after ${timeoutKind === "idle" ? timeoutMs : hardTimeoutMs}ms`; }
|
|
322
|
+
else if (combinedSignal.aborted) { result.stopReason = "aborted"; result.errorMessage ||= "Sub-agent aborted"; }
|
|
323
|
+
result.status = classifyStopReason(result.stopReason, result.stopReason === "aborted", result.stopReason === "timeout");
|
|
324
|
+
result.exitCode = result.status === "success" || result.status === "partial" ? 0 : 1;
|
|
325
|
+
if (worktreeDir) {
|
|
326
|
+
// Capture the child's changes as a unified diff before tearing down.
|
|
327
|
+
const diff = await captureWorktreeDiff(cwd, worktreeDir, exec);
|
|
328
|
+
if (diff.ok) {
|
|
329
|
+
result.patch = diff.diff;
|
|
330
|
+
// Opt-in 3-way merge: apply while the worktree still exists — the
|
|
331
|
+
// blobs `git add -A` staged live in the shared object DB and
|
|
332
|
+
// `git apply --3way` needs them. Applies are serialized (see
|
|
333
|
+
// applyWorktreePatch3way) so parallel siblings cannot race. Only
|
|
334
|
+
// successfully completed children auto-merge: a timed-out or
|
|
335
|
+
// aborted child's half-finished edits must not land on the parent
|
|
336
|
+
// checkout — their patch is still delivered for manual review.
|
|
337
|
+
if (merge === "3way" && result.status === "success" && worktreeRepoRoot && diff.diff && diff.diff !== "(no changes)") {
|
|
338
|
+
const applied = await applyWorktreePatch3way(worktreeRepoRoot, diff.diff, exec);
|
|
339
|
+
if (applied.ok) {
|
|
340
|
+
result.mergeStatus = "applied";
|
|
341
|
+
} else {
|
|
342
|
+
result.mergeStatus = "conflict";
|
|
343
|
+
result.mergeError = applied.stderr.slice(0, 1000);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
else if (diff.error) result.stderr = result.stderr ? `${result.stderr}; diff unavailable (${diff.error})` : `Diff unavailable (${diff.error})`;
|
|
348
|
+
}
|
|
349
|
+
return result;
|
|
350
|
+
} finally {
|
|
351
|
+
unsubscribe?.(); removeAbort?.();
|
|
352
|
+
try { session.dispose(); } catch { /* best effort */ }
|
|
353
|
+
if (worktreeDir) await removeWorktree(cwd, worktreeDir, exec);
|
|
354
|
+
}
|
|
355
|
+
} catch (error) {
|
|
356
|
+
result.exitCode = 1;
|
|
357
|
+
result.errorMessage = error instanceof Error ? error.message : String(error);
|
|
358
|
+
result.stopReason ||= "error";
|
|
359
|
+
result.status = classifyStopReason(result.stopReason, false, false);
|
|
360
|
+
return result;
|
|
361
|
+
} finally {
|
|
362
|
+
clearTimers(); cleanupCombined?.();
|
|
363
|
+
result.durationMs = Date.now() - startedAt;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ---------------------------------------------------------------------------
|
|
368
|
+
// Helpers
|
|
369
|
+
// ---------------------------------------------------------------------------
|
|
370
|
+
|
|
371
|
+
/** Minimal exec fallback (child_process spawn) used when no exec is injected. */
|
|
372
|
+
export async function defaultExec(
|
|
373
|
+
command: string,
|
|
374
|
+
args: string[],
|
|
375
|
+
options?: { cwd?: string; timeout?: number },
|
|
376
|
+
): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
377
|
+
const { spawn } = await import("node:child_process");
|
|
378
|
+
return new Promise((resolve) => {
|
|
379
|
+
const child = spawn(command, args, { cwd: options?.cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
380
|
+
// Decode each chunk as a complete UTF-8 stream (Buffer.toString per chunk
|
|
381
|
+
// would corrupt multi-byte sequences straddling chunk boundaries).
|
|
382
|
+
child.stdout.setEncoding("utf8");
|
|
383
|
+
child.stderr.setEncoding("utf8");
|
|
384
|
+
let stdout = ""; let stderr = "";
|
|
385
|
+
const timer = options?.timeout ? setTimeout(() => child.kill("SIGKILL"), options.timeout) : undefined;
|
|
386
|
+
child.stdout.on("data", (d) => { stdout += d; });
|
|
387
|
+
child.stderr.on("data", (d) => { stderr += d; });
|
|
388
|
+
child.on("error", (err) => { if (timer) clearTimeout(timer); resolve({ code: 1, stdout, stderr: String(err.message ?? err) }); });
|
|
389
|
+
child.on("close", (code) => { if (timer) clearTimeout(timer); resolve({ code: code ?? 1, stdout, stderr }); });
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function runGit(
|
|
394
|
+
cwd: string,
|
|
395
|
+
args: string[],
|
|
396
|
+
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
|
|
397
|
+
): Promise<{ ok: boolean; stdout: string; stderr: string }> {
|
|
398
|
+
const run = exec ?? defaultExec;
|
|
399
|
+
const res = await run("git", args, { cwd, timeout: 30_000 });
|
|
400
|
+
return { ok: res.code === 0, stdout: res.stdout, stderr: res.stderr };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Create a detached git worktree at .pi-worktrees/<rand> under the repo root. */
|
|
404
|
+
export async function createWorktree(
|
|
405
|
+
cwd: string,
|
|
406
|
+
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
|
|
407
|
+
): Promise<{ ok: boolean; path?: string; repoRoot?: string; error?: string }> {
|
|
408
|
+
try {
|
|
409
|
+
const root = await runGit(cwd, ["rev-parse", "--show-toplevel"], exec);
|
|
410
|
+
if (!root.ok) return { ok: false, error: root.stderr.trim() || "not a git repo" };
|
|
411
|
+
const repoRoot = root.stdout.trim();
|
|
412
|
+
if (!repoRoot) return { ok: false, error: "empty git root" };
|
|
413
|
+
const id = `pi-subagent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
414
|
+
const wtPath = path.join(repoRoot, ".pi-worktrees", id);
|
|
415
|
+
const add = await runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec);
|
|
416
|
+
if (!add.ok) return { ok: false, error: add.stderr.trim() || "git worktree add failed" };
|
|
417
|
+
return { ok: true, path: wtPath, repoRoot };
|
|
418
|
+
} catch (error) {
|
|
419
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Unified diff of ALL changes in the worktree vs HEAD (tracked edits, staged
|
|
424
|
+
* changes, AND new untracked files). Stages first so untracked files are
|
|
425
|
+
* captured — the worktree is removed right after, so mutating its index is
|
|
426
|
+
* safe. A single `diff --cached HEAD` avoids duplicate hunks from combining
|
|
427
|
+
* `diff HEAD` + `diff --cached`. */
|
|
428
|
+
export async function captureWorktreeDiff(
|
|
429
|
+
repoRoot: string,
|
|
430
|
+
worktreeDir: string,
|
|
431
|
+
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
|
|
432
|
+
): Promise<{ ok: boolean; diff?: string; error?: string }> {
|
|
433
|
+
const add = await runGit(worktreeDir, ["add", "-A"], exec);
|
|
434
|
+
if (!add.ok) return { ok: false, error: add.stderr.trim() || "git add -A failed" };
|
|
435
|
+
const diff = await runGit(worktreeDir, ["diff", "--cached", "HEAD"], exec);
|
|
436
|
+
if (!diff.ok) return { ok: false, error: diff.stderr.trim() || "git diff --cached HEAD failed" };
|
|
437
|
+
const text = diff.stdout.trim();
|
|
438
|
+
return { ok: true, diff: text || "(no changes)" };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Remove a worktree and its metadata, best-effort. */
|
|
442
|
+
export async function removeWorktree(
|
|
443
|
+
repoRoot: string,
|
|
444
|
+
worktreeDir: string,
|
|
445
|
+
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
|
|
446
|
+
): Promise<void> {
|
|
447
|
+
try {
|
|
448
|
+
await runGit(repoRoot, ["worktree", "remove", "--force", worktreeDir], exec);
|
|
449
|
+
} catch { /* best effort */ }
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Serialized `git apply` on the parent checkout: parallel siblings finishing
|
|
453
|
+
* at the same time must not race the merge (OMP's withRepoLock equivalent). */
|
|
454
|
+
let applyChain: Promise<unknown> = Promise.resolve();
|
|
455
|
+
|
|
456
|
+
/** Apply a unified diff to the repo root via `git apply --3way`. Never throws;
|
|
457
|
+
* ok:false means conflict/failure — the caller reports it and still delivers
|
|
458
|
+
* the patch text for manual merging. */
|
|
459
|
+
export async function applyWorktreePatch3way(
|
|
460
|
+
repoRoot: string,
|
|
461
|
+
diff: string,
|
|
462
|
+
exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
|
|
463
|
+
): Promise<{ ok: boolean; stderr: string }> {
|
|
464
|
+
const run = applyChain.then(async (): Promise<{ ok: boolean; stderr: string }> => {
|
|
465
|
+
const tmp = path.join(os.tmpdir(), `pi-subagent-apply-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}.patch`);
|
|
466
|
+
try {
|
|
467
|
+
// git apply interprets paths relative to cwd — write the diff to a file
|
|
468
|
+
// and apply at the repo root. captureWorktreeDiff trims trailing
|
|
469
|
+
// whitespace; git rejects a patch whose last line has no newline, so
|
|
470
|
+
// restore it (CRLF-aware: trimming "...\r\n" must not downgrade the
|
|
471
|
+
// final line ending to LF).
|
|
472
|
+
const patchText = diff.endsWith("\n") ? diff : `${diff}${diff.includes("\r\n") ? "\r\n" : "\n"}`;
|
|
473
|
+
await fs.writeFile(tmp, patchText, "utf8");
|
|
474
|
+
const res = await runGit(repoRoot, ["apply", "--3way", tmp], exec);
|
|
475
|
+
return { ok: res.ok, stderr: (res.stderr || res.stdout).trim() };
|
|
476
|
+
} catch (error) {
|
|
477
|
+
return { ok: false, stderr: error instanceof Error ? error.message : String(error) };
|
|
478
|
+
} finally {
|
|
479
|
+
await fs.rm(tmp, { force: true }).catch(() => { /* best effort */ });
|
|
480
|
+
}
|
|
481
|
+
});
|
|
482
|
+
applyChain = run.then(() => undefined, () => undefined);
|
|
483
|
+
return run;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Model-facing patch block for a worktree result; "" when there is no patch.
|
|
487
|
+
* Applied merges omit the diff (the parent checkout already has it);
|
|
488
|
+
* conflicts include it plus the git apply error. */
|
|
489
|
+
export function formatPatchBlock(result: SubAgentResult): string {
|
|
490
|
+
if (!result.patch || result.patch === "(no changes)") return "";
|
|
491
|
+
const lines = result.patch.split("\n").length;
|
|
492
|
+
if (result.mergeStatus === "applied") {
|
|
493
|
+
return `🌿 worktree patch (${lines} diff lines) — already applied to the parent checkout via 3-way merge.`;
|
|
494
|
+
}
|
|
495
|
+
const head = result.mergeStatus === "conflict"
|
|
496
|
+
? `🌿 worktree patch (${lines} diff lines) — 3-way merge CONFLICTED; resolve the markers in the files, or merge manually:`
|
|
497
|
+
: `🌿 worktree patch (${lines} diff lines) — merge explicitly via apply_patch or \`git apply\` (or pass merge:"3way" next time):`;
|
|
498
|
+
const err = result.mergeError ? `\n\ngit apply: ${result.mergeError}` : "";
|
|
499
|
+
return `${head}${err}\n\n${truncateParallelOutput(result.patch)}`;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
export function getFinalOutput(messages: Message[]): string {
|
|
504
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
505
|
+
const msg = messages[i];
|
|
506
|
+
if (msg.role !== "assistant") continue;
|
|
507
|
+
const texts: string[] = [];
|
|
508
|
+
for (const part of msg.content) {
|
|
509
|
+
if (part.type === "text" && part.text.trim()) texts.push(part.text);
|
|
510
|
+
}
|
|
511
|
+
if (texts.length === 0) continue;
|
|
512
|
+
// Join with a newline so interleaved text segments (text around toolCall
|
|
513
|
+
// parts in one message) stay separated instead of gluing "…done.Next step…".
|
|
514
|
+
return texts.join("\n");
|
|
515
|
+
}
|
|
516
|
+
return "";
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export function isFailedResult(result: SubAgentResult): boolean {
|
|
520
|
+
// Use canonical status if available.
|
|
521
|
+
if (result.status) {
|
|
522
|
+
return result.status === "error" || result.status === "aborted" || result.status === "timeout";
|
|
523
|
+
}
|
|
524
|
+
// Fall back to legacy heuristics.
|
|
525
|
+
return (
|
|
526
|
+
result.exitCode !== 0 ||
|
|
527
|
+
result.stopReason === "error" ||
|
|
528
|
+
result.stopReason === "aborted" ||
|
|
529
|
+
result.stopReason === "timeout"
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export function getResultOutput(result: SubAgentResult): string {
|
|
534
|
+
if (isFailedResult(result)) {
|
|
535
|
+
return result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
|
|
536
|
+
}
|
|
537
|
+
return getFinalOutput(result.messages) || "(no output)";
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Concurrency-limited map. Runs up to `concurrency` async operations at a time. */
|
|
541
|
+
export async function mapWithConcurrencyLimit<TIn, TOut>(
|
|
542
|
+
items: TIn[],
|
|
543
|
+
concurrency: number,
|
|
544
|
+
fn: (item: TIn, index: number) => Promise<TOut>,
|
|
545
|
+
): Promise<TOut[]> {
|
|
546
|
+
if (items.length === 0) return [];
|
|
547
|
+
const limit = Math.max(1, Math.min(concurrency, items.length));
|
|
548
|
+
const results: TOut[] = new Array(items.length);
|
|
549
|
+
let nextIndex = 0;
|
|
550
|
+
const workers = new Array(limit).fill(null).map(async () => {
|
|
551
|
+
while (true) {
|
|
552
|
+
const current = nextIndex++;
|
|
553
|
+
if (current >= items.length) return;
|
|
554
|
+
results[current] = await fn(items[current], current);
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
await Promise.all(workers);
|
|
558
|
+
return results;
|
|
559
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// ponytail: inlined from @earendil-works/pi-ai utils/typebox-helpers (StringEnum)
|
|
2
|
+
// — the bundle never imports pi-ai at runtime (single-peer contract); this is
|
|
3
|
+
// the only runtime value index.ts took from it.
|
|
4
|
+
|
|
5
|
+
import { type TUnsafe, Type } from "typebox";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Creates a string enum schema compatible with Google's API and other providers
|
|
9
|
+
* that don't support anyOf/const patterns.
|
|
10
|
+
*/
|
|
11
|
+
export function StringEnum<T extends readonly string[]>(values: T, options?: {
|
|
12
|
+
description?: string;
|
|
13
|
+
default?: T[number];
|
|
14
|
+
}): TUnsafe<T[number]> {
|
|
15
|
+
return Type.Unsafe<T[number]>({
|
|
16
|
+
type: "string",
|
|
17
|
+
enum: values as unknown as string[],
|
|
18
|
+
...(options?.description ? { description: options.description } : {}),
|
|
19
|
+
...(options?.default !== undefined ? { default: options.default } : {}),
|
|
20
|
+
});
|
|
21
|
+
}
|