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,333 @@
|
|
|
1
|
+
// ponytail: vendored from @bacnh85/pi-model-tools 0.9.5 — lib/bash-auto-bg.ts
|
|
2
|
+
// Local changes: (1) the PI_MODEL_TOOLS_BASH_AUTO_BG[_SECS] env readers are
|
|
3
|
+
// dropped — enable/threshold now come from the `repair` settings section
|
|
4
|
+
// (lib/settings.ts) and are bound once at module load; (2) the follow-up
|
|
5
|
+
// customType and the tmp log prefix take the ceulen- namespace
|
|
6
|
+
// (`ceulen-repair-bg`) per the bundle's customType convention.
|
|
7
|
+
/**
|
|
8
|
+
* bash-auto-bg.ts — auto-background long foreground bash commands.
|
|
9
|
+
*
|
|
10
|
+
* OMP 18.2.8 parity ("background job notifications … discourage unnecessary
|
|
11
|
+
* polling"): a foreground bash call still running at the threshold returns a
|
|
12
|
+
* receipt immediately; when the job settles, its output is delivered as a
|
|
13
|
+
* follow-up turn via pi.sendMessage({deliverAs: "followUp", triggerTurn: true})
|
|
14
|
+
* — the wake-up mechanism subagent already proved. The prompt-only half
|
|
15
|
+
* (anti-poll clause) lives in bashAutoBgClause(); both halves ship together so
|
|
16
|
+
* the description text and the mechanism can never drift apart.
|
|
17
|
+
*
|
|
18
|
+
* The caller-supplied `timeout` (seconds) is passed through untouched: the
|
|
19
|
+
* underlying local operations enforce it as a total-runtime kill, so a
|
|
20
|
+
* backgrounded job still dies at its deadline without a second timer here.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import type { BashOperations } from "@earendil-works/pi-coding-agent";
|
|
25
|
+
import { randomUUID } from "node:crypto";
|
|
26
|
+
import { open, rm, type FileHandle } from "node:fs/promises";
|
|
27
|
+
import { unlinkSync } from "node:fs";
|
|
28
|
+
import { tmpdir } from "node:os";
|
|
29
|
+
import { join } from "node:path";
|
|
30
|
+
|
|
31
|
+
/** Follow-up wake-up customType — `ceulen-` prefixed (bundle convention). */
|
|
32
|
+
const BG_CUSTOM_TYPE = "ceulen-repair-bg";
|
|
33
|
+
|
|
34
|
+
// ── Job registry ──
|
|
35
|
+
|
|
36
|
+
const MAX_CONCURRENT_BG = 4; // ponytail: hard cap, no queue — over cap stays foreground
|
|
37
|
+
const LOG_TAIL_BYTES = 2048;
|
|
38
|
+
const LOG_MAX_BYTES = 5 * 1024 * 1024; // on-disk cap; further chunks dropped (noted in the wake-up)
|
|
39
|
+
|
|
40
|
+
interface BgJob {
|
|
41
|
+
id: string;
|
|
42
|
+
command: string;
|
|
43
|
+
controller: AbortController;
|
|
44
|
+
logPath: string;
|
|
45
|
+
/** Output received after backgrounding, bounded to the last LOG_TAIL_BYTES. */
|
|
46
|
+
tail: string;
|
|
47
|
+
logBytes: number;
|
|
48
|
+
logTruncated: boolean;
|
|
49
|
+
/** Open log file handle — set asynchronously once open() resolves. */
|
|
50
|
+
logFile?: FileHandle;
|
|
51
|
+
/** Set by finishJob so a racing async open() knows to discard the fd. */
|
|
52
|
+
finished?: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const jobs = new Map<string, BgJob>();
|
|
56
|
+
let jobSeq = 0;
|
|
57
|
+
// Wake-up delivery gate: session_shutdown aborts jobs and suppresses delivery
|
|
58
|
+
// (a dying session must not fire triggerTurn follow-ups); the next
|
|
59
|
+
// session_start re-enables it. Tests use the default (enabled).
|
|
60
|
+
let deliveryEnabled = true;
|
|
61
|
+
|
|
62
|
+
/** Enable/disable follow-up wake-up delivery (session lifecycle wiring). */
|
|
63
|
+
export function setBgDeliveryEnabled(enabled: boolean): void {
|
|
64
|
+
deliveryEnabled = enabled;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Abort every live background job and clear the registry. Pass
|
|
69
|
+
* `suppressDelivery=true` from session_shutdown so the aborts do not fire
|
|
70
|
+
* wake-up turns into a session that is going away.
|
|
71
|
+
*/
|
|
72
|
+
export function abortAllBgJobs(suppressDelivery = false): void {
|
|
73
|
+
if (suppressDelivery) deliveryEnabled = false;
|
|
74
|
+
for (const job of jobs.values()) {
|
|
75
|
+
job.controller.abort();
|
|
76
|
+
// Graceful shutdown: remove the log synchronously — the aborted job's
|
|
77
|
+
// wake-up is suppressed, so nothing will ever read this file (async rm
|
|
78
|
+
// can lose the race against process exit).
|
|
79
|
+
if (!job.logTruncated) {
|
|
80
|
+
try { unlinkSync(job.logPath); } catch {}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
jobs.clear();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Number of currently live background jobs (status panel). */
|
|
87
|
+
export function bgJobCount(): number {
|
|
88
|
+
return jobs.size;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Log paths of currently live background jobs (status panel / tests). */
|
|
92
|
+
export function activeBgLogPaths(): string[] {
|
|
93
|
+
return [...jobs.values()].map((j) => j.logPath);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Process-death sweep: if pi dies while a job is live (SIGTERM, crash),
|
|
97
|
+
// finishJob never runs and the log file would leak. Sync unlink is the only
|
|
98
|
+
// thing allowed in an 'exit' handler. Hard SIGKILL remains uncleanable (tmp
|
|
99
|
+
// cleaners bound it).
|
|
100
|
+
let exitSweepInstalled = false;
|
|
101
|
+
function installExitSweep(): void {
|
|
102
|
+
if (exitSweepInstalled) return;
|
|
103
|
+
exitSweepInstalled = true;
|
|
104
|
+
const sweep = () => {
|
|
105
|
+
for (const j of jobs.values()) {
|
|
106
|
+
if (j.logTruncated) continue;
|
|
107
|
+
try { unlinkSync(j.logPath); } catch {}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
// Normal exit & fatal errors: 'exit' handlers run.
|
|
111
|
+
process.on("exit", sweep);
|
|
112
|
+
// SIGTERM/SIGINT: Node's default handler bypasses 'exit' handlers — sweep
|
|
113
|
+
// then re-raise. (SIGKILL is uncleanable by definition; tmp cleaners bound
|
|
114
|
+
// that residual.)
|
|
115
|
+
for (const sig of ["SIGTERM", "SIGINT"] as const) {
|
|
116
|
+
const own = () => {
|
|
117
|
+
sweep();
|
|
118
|
+
process.removeListener(sig, own);
|
|
119
|
+
process.kill(process.pid, sig); // re-raise: now falls through to the
|
|
120
|
+
// default/other handlers — external kill still terminates pi.
|
|
121
|
+
};
|
|
122
|
+
process.on(sig, own);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ── Description clause (the prompt-only half) ──
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Static bash-description clause. OFF = anti-poll guidance for unattended
|
|
130
|
+
* work; ON = OMP's "you will be woken — NEVER poll" contract. Byte-stable per
|
|
131
|
+
* session: the enabled flag + threshold are read once at registration, so this
|
|
132
|
+
* stays in the cache-safe request head (never per-turn guidance).
|
|
133
|
+
*/
|
|
134
|
+
export function bashAutoBgClause(enabled: boolean, thresholdSecs: number): string {
|
|
135
|
+
if (!enabled) {
|
|
136
|
+
return [
|
|
137
|
+
"Long-running commands: set `timeout` generously rather than polling. NEVER wait by looping",
|
|
138
|
+
"`sleep`/`ps`/`pgrep`/`top` — every poll costs a full model round. If a job must run unattended,",
|
|
139
|
+
"background it once (`nohup <cmd> > /tmp/log 2>&1 &`), do other work, and read the log once when you need the result.",
|
|
140
|
+
].join(" ");
|
|
141
|
+
}
|
|
142
|
+
return [
|
|
143
|
+
`Foreground calls longer than ~${thresholdSecs}s auto-background: you get a receipt immediately and the result`,
|
|
144
|
+
"is delivered as a follow-up message when the job finishes. NEVER poll a backgrounded job (`sleep`/`ps`/`pgrep`/`top`) —",
|
|
145
|
+
"do other work or end your reply and you will be woken with its output.",
|
|
146
|
+
"`timeout`, if set, still applies as a total-runtime kill (measured from command start, not from backgrounding).",
|
|
147
|
+
].join(" ");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ── Operations wrapper (the mechanism half) ──
|
|
151
|
+
|
|
152
|
+
export interface AutoBgDeps {
|
|
153
|
+
pi: ExtensionAPI;
|
|
154
|
+
/** Foreground threshold in seconds. */
|
|
155
|
+
thresholdSecs: number;
|
|
156
|
+
maxConcurrent?: number;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Wrap BashOperations: commands still running at the threshold are detached —
|
|
161
|
+
* the pending exec resolves as a receipt (exit 0 + the receipt text riding the
|
|
162
|
+
* output stream, so the built-in formats it like normal output), the real exec
|
|
163
|
+
* keeps running, and its outcome is delivered as a follow-up turn on
|
|
164
|
+
* settlement. Fast commands pass through untouched.
|
|
165
|
+
*/
|
|
166
|
+
export function wrapWithAutoBg(local: BashOperations, deps: AutoBgDeps): BashOperations {
|
|
167
|
+
const maxConcurrent = deps.maxConcurrent ?? MAX_CONCURRENT_BG;
|
|
168
|
+
installExitSweep();
|
|
169
|
+
return {
|
|
170
|
+
exec: (command, cwd, options) =>
|
|
171
|
+
new Promise((resolveBg, rejectBg) => {
|
|
172
|
+
const controller = new AbortController();
|
|
173
|
+
const onToolAbort = () => controller.abort();
|
|
174
|
+
// Forward the tool signal ONLY during the foreground wait. Once the job
|
|
175
|
+
// is backgrounded the listener is removed — turn end / abort after that
|
|
176
|
+
// must NOT kill the detached job (it's nohup-like).
|
|
177
|
+
options.signal?.addEventListener("abort", onToolAbort, { once: true });
|
|
178
|
+
|
|
179
|
+
let settled = false;
|
|
180
|
+
let backgrounded = false;
|
|
181
|
+
let job: BgJob | undefined;
|
|
182
|
+
let thresholdTimer: NodeJS.Timeout | undefined;
|
|
183
|
+
|
|
184
|
+
const forwardedOnData = options.onData;
|
|
185
|
+
// Output ALWAYS streams through to the tool consumer (live view +
|
|
186
|
+
// tool-result text). After backgrounding it additionally feeds the
|
|
187
|
+
// job's bounded tail + on-disk log; before it, it accumulates in
|
|
188
|
+
// `preBg` so a backgrounded job's wake-up includes output the model
|
|
189
|
+
// already saw. The receipt itself must NOT enter the tail/log — it is
|
|
190
|
+
// forwarded after backgrounding via forward(), which skips the tee.
|
|
191
|
+
let preBg = "";
|
|
192
|
+
const teeOnData = (data: Buffer) => {
|
|
193
|
+
forwardedOnData?.(data);
|
|
194
|
+
const text = data.toString("utf8");
|
|
195
|
+
if (!backgrounded) {
|
|
196
|
+
preBg = (preBg + text).slice(-LOG_TAIL_BYTES);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (!job) return;
|
|
200
|
+
job.tail = (job.tail + text).slice(-LOG_TAIL_BYTES);
|
|
201
|
+
if (job.logBytes >= LOG_MAX_BYTES) {
|
|
202
|
+
job.logTruncated = true;
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
job.logBytes += data.length;
|
|
206
|
+
// Chunks racing the async open() are dropped from the file (counted
|
|
207
|
+
// anyway — the cap is approximate); the 2KB tail always has them.
|
|
208
|
+
void job.logFile?.write(data).catch(() => {});
|
|
209
|
+
};
|
|
210
|
+
// Tool-result stream passthrough (never teed into the job).
|
|
211
|
+
const forward = (data: Buffer) => forwardedOnData?.(data);
|
|
212
|
+
|
|
213
|
+
// Clears foreground wiring only; the registry entry is removed by the
|
|
214
|
+
// completion handlers (a backgrounded job must outlive the settle).
|
|
215
|
+
const cleanup = () => {
|
|
216
|
+
options.signal?.removeEventListener("abort", onToolAbort);
|
|
217
|
+
if (thresholdTimer) clearTimeout(thresholdTimer);
|
|
218
|
+
};
|
|
219
|
+
const settle = (finish: () => void) => {
|
|
220
|
+
if (settled) return;
|
|
221
|
+
settled = true;
|
|
222
|
+
cleanup();
|
|
223
|
+
finish();
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
const execPromise = local.exec(command, cwd, { ...options, onData: teeOnData, signal: controller.signal });
|
|
227
|
+
void execPromise.then(
|
|
228
|
+
(result) => {
|
|
229
|
+
if (!backgrounded) return settle(() => resolveBg(result));
|
|
230
|
+
const exitNote = result.exitCode === null ? "terminated without an exit code" : `exit ${result.exitCode}`;
|
|
231
|
+
finishJob(deps.pi, job, [
|
|
232
|
+
`Background job ${job?.id} finished (${exitNote}).`,
|
|
233
|
+
`Command: ${command}`,
|
|
234
|
+
job?.tail ? `Output (tail):\n${job.tail}` : "(no output)",
|
|
235
|
+
]);
|
|
236
|
+
},
|
|
237
|
+
(err: unknown) => {
|
|
238
|
+
if (!backgrounded) return settle(() => rejectBg(err));
|
|
239
|
+
const raw = err instanceof Error ? err.message : String(err);
|
|
240
|
+
const reason = raw.startsWith("timeout:") ? `timed out after ${raw.split(":")[1]} seconds (deadline reached)` : raw;
|
|
241
|
+
finishJob(deps.pi, job, [
|
|
242
|
+
`Background job ${job?.id} failed: ${reason}.`,
|
|
243
|
+
`Command: ${command}`,
|
|
244
|
+
job?.tail ? `Output before failure (tail):\n${job.tail}` : "",
|
|
245
|
+
]);
|
|
246
|
+
},
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
thresholdTimer = setTimeout(() => {
|
|
250
|
+
if (settled || backgrounded) return;
|
|
251
|
+
if (jobs.size >= maxConcurrent) return; // ponytail: no queue — stays foreground
|
|
252
|
+
backgrounded = true;
|
|
253
|
+
const id = `bg-${++jobSeq}`;
|
|
254
|
+
// Random component: the sequential id is predictable, the log path
|
|
255
|
+
// must not be (pre-planted symlink/file attack on shared tmp).
|
|
256
|
+
const logPath = join(tmpdir(), `ceulen-repair-bg-${randomUUID()}.log`);
|
|
257
|
+
// Seed tail/log with the foreground-phase output the model already
|
|
258
|
+
// saw, so the wake-up is self-contained.
|
|
259
|
+
const seed = preBg;
|
|
260
|
+
job = { id, command, controller, logPath, tail: seed, logBytes: Buffer.byteLength(seed), logTruncated: false };
|
|
261
|
+
const j = job;
|
|
262
|
+
jobs.set(id, j);
|
|
263
|
+
// O_CREAT|O_EXCL mode 0600: never follows a pre-planted symlink, never
|
|
264
|
+
// opens an existing file, owner-only perms. Best-effort — on failure
|
|
265
|
+
// (tmp unwritable) the tail still feeds the wake-up.
|
|
266
|
+
void open(logPath, "wx", 0o600)
|
|
267
|
+
.then((fh) => {
|
|
268
|
+
if (j.finished) {
|
|
269
|
+
// Job completed before the open resolved — close immediately
|
|
270
|
+
// and remove (finishJob's rm raced this async open).
|
|
271
|
+
void fh.close().then(() => rm(logPath, { force: true })).catch(() => {});
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
j.logFile = fh;
|
|
275
|
+
if (seed) void fh.write(seed).catch(() => {});
|
|
276
|
+
})
|
|
277
|
+
.catch(() => {});
|
|
278
|
+
// Receipt rides the output stream — the built-in formats it into the
|
|
279
|
+
// tool result exactly like command output. Direct forward (bypasses
|
|
280
|
+
// the tee) so it never pollutes the wake-up tail/log. No log path in
|
|
281
|
+
// the receipt: the log is deleted at completion unless truncated
|
|
282
|
+
// (the wake-up then carries the tail, or the kept path).
|
|
283
|
+
forward(
|
|
284
|
+
Buffer.from(
|
|
285
|
+
`\n[ceulen-repair] Backgrounded as job ${id} (still running). The result arrives as a follow-up message — NEVER poll (sleep/ps/pgrep/top); do other work or end your reply and you will be woken with its output.\n`,
|
|
286
|
+
),
|
|
287
|
+
);
|
|
288
|
+
settle(() => resolveBg({ exitCode: 0 }));
|
|
289
|
+
}, deps.thresholdSecs * 1000);
|
|
290
|
+
}),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Settle a backgrounded job: unregister, close the log fd, deliver the
|
|
296
|
+
* wake-up (gated by deliveryEnabled) with a truncation note when the on-disk
|
|
297
|
+
* log hit its cap.
|
|
298
|
+
*/
|
|
299
|
+
function finishJob(pi: ExtensionAPI, job: BgJob | undefined, lines: string[]): void {
|
|
300
|
+
if (!job) return;
|
|
301
|
+
jobs.delete(job.id);
|
|
302
|
+
job.finished = true;
|
|
303
|
+
const fh = job.logFile;
|
|
304
|
+
if (fh) {
|
|
305
|
+
void fh.close().catch(() => {});
|
|
306
|
+
}
|
|
307
|
+
if (job.logTruncated) {
|
|
308
|
+
// Truncated: the log is the only place the full output lives — keep it
|
|
309
|
+
// and advertise the path.
|
|
310
|
+
// ponytail: rare ≥5MB-output jobs leak a ≤5MB file to tmp; OS tmp
|
|
311
|
+
// cleaners bound the rest. A sweep can come later if it ever matters.
|
|
312
|
+
lines.push(`Full log (kept, truncated at ${Math.floor(LOG_MAX_BYTES / 1024)}KB): ${job.logPath}`);
|
|
313
|
+
} else {
|
|
314
|
+
// The 2KB tail above carries everything worth keeping — remove the file
|
|
315
|
+
// so backgrounded jobs don't leak sensitive output into tmp forever.
|
|
316
|
+
// The open() race is handled job.finished-side (see the open handler).
|
|
317
|
+
void rm(job.logPath, { force: true }).catch(() => {});
|
|
318
|
+
}
|
|
319
|
+
deliver(pi, lines.filter(Boolean).join("\n"));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Fire-and-forget follow-up delivery (never rejects into the exec path). */
|
|
323
|
+
function deliver(pi: ExtensionAPI, text: string): void {
|
|
324
|
+
if (!deliveryEnabled) return;
|
|
325
|
+
try {
|
|
326
|
+
pi.sendMessage(
|
|
327
|
+
{ customType: BG_CUSTOM_TYPE, content: text, display: true },
|
|
328
|
+
{ deliverAs: "followUp", triggerTurn: true },
|
|
329
|
+
);
|
|
330
|
+
} catch {
|
|
331
|
+
// Best-effort; the job's log survives on disk either way.
|
|
332
|
+
}
|
|
333
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// ponytail: vendored from @bacnh85/pi-model-tools 0.9.5 — lib/edit-repair.ts
|
|
2
|
+
// Local change: none (byte-faithful port).
|
|
3
|
+
/**
|
|
4
|
+
* edit-repair.ts — helpers that harden the built-in `edit` tool against the
|
|
5
|
+
* two documented failure modes for weaker models:
|
|
6
|
+
*
|
|
7
|
+
* 1. read-tool contamination: `read` appends truncation/continuation notices
|
|
8
|
+
* to file content; models copy them into oldText, where they don't exist
|
|
9
|
+
* in the file → every match (exact and fuzzy) fails.
|
|
10
|
+
* 2. leading-whitespace drift: pi's matcher normalizes trailing whitespace
|
|
11
|
+
* only; Codex's seek_sequence also tolerates leading-ws differences.
|
|
12
|
+
*
|
|
13
|
+
* Pure + testable. The wiring (prepareArguments/execute) lives in index.ts.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** Strip a UTF-8 BOM if present. */
|
|
17
|
+
export function stripBom(content: string): string {
|
|
18
|
+
return content.startsWith("\uFEFF") ? content.slice(1) : content;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Normalize CRLF/CR to LF. */
|
|
22
|
+
export function normalizeToLF(text: string): string {
|
|
23
|
+
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The exact read-tool notice shapes that contaminate oldText (see
|
|
27
|
+
// pi-coding-agent dist/core/tools/read.js). Contamination is APPENDED by the
|
|
28
|
+
// read tool after the last shown line, so the model's copy carries it as a
|
|
29
|
+
// suffix — strip only a notice anchored at the END of oldText. A mid-text
|
|
30
|
+
// occurrence is real file content (e.g. repos documenting these very strings)
|
|
31
|
+
// and must survive verbatim matching; the trim-tolerant retry path covers the
|
|
32
|
+
// rare mid-copy page-boundary case.
|
|
33
|
+
const TRAILING_READ_NOTICE = /(?:\n{1,2}(?:\[Showing lines \d+-\d+ of \d+(?: \([^)]+\))?\.\s*Use offset=\d+ to continue\.\]|\[\d+ more lines in file\.\s*Use offset=\d+ to continue\.\])|\n\[Line \d+ is [^,]+, exceeds [^\]]+ limit\.[^\]]*\])\s*$/;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Strip read-tool contamination notices from an oldText string.
|
|
37
|
+
* Returns the cleaned text and whether anything changed.
|
|
38
|
+
* Safe: these notice shapes never legitimately appear inside matched source.
|
|
39
|
+
*/
|
|
40
|
+
export function stripReadContamination(text: string): { text: string; changed: boolean } {
|
|
41
|
+
const m = text.match(TRAILING_READ_NOTICE);
|
|
42
|
+
if (!m || m.index === undefined) return { text, changed: false };
|
|
43
|
+
return { text: text.slice(0, m.index), changed: true };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function splitLines(content: string): string[] {
|
|
47
|
+
return content.length === 0 ? [] : content.split("\n");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Count contiguous block matches of oldText in content, tolerating
|
|
52
|
+
* per-line leading+trailing whitespace differences (Codex seek_sequence pass 3).
|
|
53
|
+
* Returns the number of matches and the start line of the first match.
|
|
54
|
+
*/
|
|
55
|
+
export function findTrimMatch(content: string, oldText: string): { count: number; firstIndex: number } {
|
|
56
|
+
const fileLines = splitLines(content).map((l) => l.trim());
|
|
57
|
+
const patternLines = splitLines(oldText).map((l) => l.trim());
|
|
58
|
+
// Drop a single trailing empty pattern line so a stray trailing newline in
|
|
59
|
+
// oldText doesn't break an otherwise-exact block match.
|
|
60
|
+
if (patternLines.length > 1 && patternLines[patternLines.length - 1] === "") patternLines.pop();
|
|
61
|
+
if (patternLines.length === 0 || patternLines.length > fileLines.length) return { count: 0, firstIndex: -1 };
|
|
62
|
+
|
|
63
|
+
let count = 0;
|
|
64
|
+
let firstIndex = -1;
|
|
65
|
+
for (let i = 0; i <= fileLines.length - patternLines.length; i++) {
|
|
66
|
+
let ok = true;
|
|
67
|
+
for (let j = 0; j < patternLines.length; j++) {
|
|
68
|
+
if (fileLines[i + j] !== patternLines[j]) { ok = false; break; }
|
|
69
|
+
}
|
|
70
|
+
if (ok) {
|
|
71
|
+
count++;
|
|
72
|
+
if (firstIndex === -1) firstIndex = i;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { count, firstIndex };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Extract the ACTUAL file bytes for a matched block (with real indentation),
|
|
80
|
+
* given the content and the 0-based start line + block length. Used to rebuild
|
|
81
|
+
* oldText from the file so the core matcher's exact pass succeeds.
|
|
82
|
+
*/
|
|
83
|
+
export function fileBytesForBlock(content: string, startLine: number, blockLen: number): string {
|
|
84
|
+
const lines = splitLines(content);
|
|
85
|
+
return lines.slice(startLine, startLine + blockLen).join("\n");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Compute a retry edit set after a trim-tolerant re-match. Returns the rebuilt
|
|
90
|
+
* edits (oldText taken from the file's real bytes so the core exact matcher
|
|
91
|
+
* succeeds) when there is exactly one trim match, otherwise null. Pure/testable
|
|
92
|
+
* — the orchestration (read file, catch throw, retry) lives in index.ts.
|
|
93
|
+
*
|
|
94
|
+
* IMPORTANT: blockLen drops a single trailing empty line to stay in sync with
|
|
95
|
+
* findTrimMatch, which pops one trailing empty pattern line before matching.
|
|
96
|
+
*/
|
|
97
|
+
export function computeRetryEdit(fileContent: string, edits: { oldText: string; newText: string }[], failIdx: number): { fixedEdits: { oldText: string; newText: string }[] } | null {
|
|
98
|
+
const idx = Math.min(failIdx, edits.length - 1);
|
|
99
|
+
const failing = edits[idx];
|
|
100
|
+
const oldText = typeof failing?.oldText === "string" ? failing.oldText : "";
|
|
101
|
+
if (!oldText) return null;
|
|
102
|
+
const decontaminated = stripReadContamination(oldText).text;
|
|
103
|
+
const { count, firstIndex } = findTrimMatch(fileContent, decontaminated);
|
|
104
|
+
if (count !== 1) return null;
|
|
105
|
+
const patternLines = decontaminated.split("\n");
|
|
106
|
+
if (patternLines.length > 1 && patternLines[patternLines.length - 1] === "") patternLines.pop();
|
|
107
|
+
const realOld = fileBytesForBlock(fileContent, firstIndex, patternLines.length);
|
|
108
|
+
const fixedEdits = edits.map((e, i) => i === idx ? { ...e, oldText: realOld } : e);
|
|
109
|
+
return { fixedEdits };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Return a numbered snippet of the file region most similar to oldText, to help
|
|
114
|
+
* the model self-correct on an unresolvable mismatch. Picks the window with the
|
|
115
|
+
* most overlapping (trimmed) lines.
|
|
116
|
+
*/
|
|
117
|
+
export function nearestBlock(content: string, oldText: string, ctx = 6): string {
|
|
118
|
+
const fileLines = splitLines(content);
|
|
119
|
+
const patternSet = new Set(splitLines(oldText).map((l) => l.trim()).filter((l) => l.length > 0));
|
|
120
|
+
if (patternSet.size === 0 || fileLines.length === 0) return "";
|
|
121
|
+
|
|
122
|
+
const window = Math.max(ctx, Math.min(40, fileLines.length));
|
|
123
|
+
let bestStart = 0;
|
|
124
|
+
let bestScore = -1;
|
|
125
|
+
for (let i = 0; i <= fileLines.length - window; i++) {
|
|
126
|
+
let score = 0;
|
|
127
|
+
for (let j = 0; j < window; j++) {
|
|
128
|
+
if (patternSet.has(fileLines[i + j].trim())) score++;
|
|
129
|
+
}
|
|
130
|
+
if (score > bestScore) { bestScore = score; bestStart = i; }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const width = String(fileLines.length).length;
|
|
134
|
+
const start = Math.max(0, bestStart - 1);
|
|
135
|
+
const end = Math.min(fileLines.length, bestStart + window + 1);
|
|
136
|
+
const shown = fileLines.slice(start, end).map((l, idx) => {
|
|
137
|
+
const num = String(start + idx + 1).padStart(width, " ");
|
|
138
|
+
return `${num} | ${l}`;
|
|
139
|
+
});
|
|
140
|
+
return `Nearest matching region (lines ${start + 1}-${end}):\n${shown.join("\n")}`;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Parse the failing edit index from an edit-tool error message.
|
|
145
|
+
* Returns the 0-based index, or 0 when it can't be determined (single-edit).
|
|
146
|
+
*/
|
|
147
|
+
export function parseFailedEditIndex(message: string): number {
|
|
148
|
+
const m = message.match(/edits\[(\d+)\]/i);
|
|
149
|
+
return m ? Number(m[1]) : 0;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** True if an error message/result indicates an edit match failure. */
|
|
153
|
+
export function isEditMismatchError(message: string): boolean {
|
|
154
|
+
return /could not find|oldtext must match exactly|found \d+ occurrences|text must be unique|provide more context to make it unique/i.test(message);
|
|
155
|
+
}
|