ceulen 0.28.2 → 0.29.1
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 +57 -0
- package/extensions/lib/registry.ts +2 -2
- package/extensions/modules/a2a/index.ts +1 -1
- package/extensions/modules/repair/configPanel.ts +8 -1
- package/extensions/modules/repair/index.ts +29 -6
- package/extensions/modules/repair/lib/persistent-bash.ts +440 -0
- package/extensions/modules/repair/lib/settings.ts +5 -1
- package/extensions/modules/repair/test/persistent-bash.test.ts +402 -0
- package/extensions/modules/repair/test/settings.test.ts +6 -3
- package/extensions/modules/steering/configPanel.ts +0 -15
- package/extensions/modules/steering/index.ts +26 -201
- package/extensions/modules/steering/lib/settings.ts +6 -7
- package/extensions/modules/steering/test/harness.ts +3 -3
- package/extensions/modules/steering/test/settings.test.ts +14 -19
- package/extensions/modules/steering/test/status.test.ts +6 -9
- package/package.json +1 -1
- package/extensions/modules/steering/lib/anchor.ts +0 -189
- package/extensions/modules/steering/test/anchor-plan.test.ts +0 -74
- package/extensions/modules/steering/test/anchor-regressions.test.ts +0 -123
- package/extensions/modules/steering/test/anchor-wiring.test.ts +0 -82
- package/extensions/modules/steering/test/anchor.test.ts +0 -162
package/CHANGELOG.md
CHANGED
|
@@ -1,4 +1,61 @@
|
|
|
1
1
|
# Changelog
|
|
2
|
+
## 0.29.1 — 2026-11-22
|
|
3
|
+
|
|
4
|
+
- **npm provenance actually enabled.** `publish.yml` ran `npm publish --access
|
|
5
|
+
public` and nothing else; `id-token: write` permits provenance but does not
|
|
6
|
+
request it, so every release up to and including 0.29.0 shipped with **no
|
|
7
|
+
attestation** (`dist.attestations` absent, and
|
|
8
|
+
`registry.npmjs.org/-/npm/v1/attestations/ceulen@0.28.2` 404s). The flag is
|
|
9
|
+
now `--provenance` on the publish command, and AGENTS.md documents the check
|
|
10
|
+
so a workflow permissions block is never mistaken for evidence again.
|
|
11
|
+
- Nothing else changed: no module, setting, or tool behavior differs from
|
|
12
|
+
0.29.0.
|
|
13
|
+
|
|
14
|
+
## 0.29.0 — 2026-11-22
|
|
15
|
+
|
|
16
|
+
**The ds-anchor is gone; DeepSeek gets the composition DSH actually ships.**
|
|
17
|
+
|
|
18
|
+
- **`ds-anchor` DELETED** (steering). The first-request bootstrap — swap the
|
|
19
|
+
wire prompt to the DSH minimal persona and the tool list to
|
|
20
|
+
`bash`/`str_replace_editor` — was measured to make DeepSeek V4.1 Flash
|
|
21
|
+
*worse*: 3/5 on cold tool fixtures with it on versus 5/5 with it off and 5/5
|
|
22
|
+
with steering unloaded, because the pair-only request #1 hides `codemode` and
|
|
23
|
+
`tool_search` and explicit requests for them ended without any tool call
|
|
24
|
+
before promotion. DeepSeek Harness itself dropped that composition on
|
|
25
|
+
2026-09-03 ("one file-mutation interface = the shell"); its benchmark scores
|
|
26
|
+
belong to the persistent-shell whole-task composition, not a first-round
|
|
27
|
+
bootstrap. Removed with it: `steering.dsAnchor`, `steering.weNeed`, both
|
|
28
|
+
`/config` rows, the `/steering` anchor state and trace, and the anchor tests.
|
|
29
|
+
Existing settings files need no migration — the reader ignores unknown keys.
|
|
30
|
+
Everything else in steering (first-tool hints, selection guidance, strict
|
|
31
|
+
Serena, reasoning strip, error recovery, apply_patch preference) is unchanged.
|
|
32
|
+
- **`repair.persistentBash` (new, default off)** brings the DSH
|
|
33
|
+
`tool-bash-persistent` behavior: ONE long-lived `bash --noprofile --norc` per
|
|
34
|
+
session over pi's own `BashOperations` seam, so working directory, exported
|
|
35
|
+
variables, functions, and background jobs survive across bash calls. Framing
|
|
36
|
+
is DSH's single physical line — `command builtin eval $'…'; command builtin
|
|
37
|
+
printf '<marker>%s\n' "$?"` — so a syntactically incomplete command is a
|
|
38
|
+
syntax error instead of a swallowed completion marker. `command builtin` (not
|
|
39
|
+
bare, not `builtin` alone) is load-bearing: `printf()`, `eval()`, and even
|
|
40
|
+
`builtin()` are shadowable by a function the model defined in an earlier call,
|
|
41
|
+
and a suppressed marker makes a *successful* command hang until the timeout
|
|
42
|
+
(`builtin` is itself resolved by name; `command` is what escapes that).
|
|
43
|
+
Reset-never-repair: exit, timeout, abort, or shell death kills the process
|
|
44
|
+
group and the next call starts fresh.
|
|
45
|
+
- **A default per-command deadline (300 s)** applies when the caller supplies no
|
|
46
|
+
`timeout`. pi's bash timeout is optional, and without a floor one stuck command
|
|
47
|
+
would wedge the shell *and every queued call behind it* forever with no reset
|
|
48
|
+
to recover by. An explicit `timeout` still wins.
|
|
49
|
+
- **Plan mode always runs one-shot.** While plan mode is active the wrapper
|
|
50
|
+
delegates to pi's stateless local shell: the plan gate auto-allows reads by
|
|
51
|
+
command text, and a shell retaining a pre-plan `cd`, function, or alias could
|
|
52
|
+
change what that text actually does. The persistent shell is left untouched —
|
|
53
|
+
verified by process identity (same `$$` before and after, different per-call
|
|
54
|
+
`$$` inside) — its pre-plan state resumes on exit, and plan-mode mutations are
|
|
55
|
+
discarded. While `persistentBash` is on, `autoBg` is suspended: a
|
|
56
|
+
backgrounded queued exec would park later foreground calls behind the job, and
|
|
57
|
+
the shell's own `&` backgrounding is the taught model.
|
|
58
|
+
|
|
2
59
|
## 0.28.2 — 2026-11-20
|
|
3
60
|
|
|
4
61
|
- DeepSeek V4.1 Flash gets the same minimal-mode bootstrap as V4 Pro, including
|
|
@@ -221,9 +221,9 @@ export const MODULES: ModuleEntry[] = [
|
|
|
221
221
|
// notify: harmless desktop ping (bell fallback), herdr multi-pane ergonomics.
|
|
222
222
|
{ name: "notify", category: "Tools", describe: "Desktop notification tool: ping the user when long work settles or input is needed (osascript / notify-send / bell).", load: notifyModule, deferredTools: ["notify"] },
|
|
223
223
|
// Steering sees the prompt and tool loadout after the other composers run
|
|
224
|
-
// (including RTK)
|
|
224
|
+
// (including RTK), so it is the last system-prompt composer.
|
|
225
225
|
{ name: "rtk", category: "Shell", describe: "Route shell commands through RTK where RTK supports them; chains and unsupported commands pass through.", load: rtkModule, config: rtkConfig },
|
|
226
|
-
{ name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): tool guidance, reasoning strip, error recovery
|
|
226
|
+
{ name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): tool guidance, reasoning strip, error recovery.", load: steeringModule, config: steeringConfig },
|
|
227
227
|
// ── Shell ──────────────────────────────────────────────────────────────
|
|
228
228
|
// Permission after rtk: persistent allow/ask/deny gating. Inert until rules
|
|
229
229
|
// exist; defers to plan mode via the shared plan-bridge flag (order-free).
|
|
@@ -100,7 +100,7 @@ function makeSessionRunner(ctx: ExtensionContext, cfg?: A2AConfig): SessionRunne
|
|
|
100
100
|
});
|
|
101
101
|
// The loader must NOT receive the inMemory settingsManager: it would then
|
|
102
102
|
// resolve zero extension packages and the child session would run without
|
|
103
|
-
// any host extensions
|
|
103
|
+
// any host extensions.
|
|
104
104
|
// Letting DefaultResourceLoader fall back to SettingsManager.create(cwd,
|
|
105
105
|
// agentDir) loads the real on-disk settings/packages — the same path
|
|
106
106
|
// pi-subagent's runner uses.
|
|
@@ -71,13 +71,20 @@ export function buildRepairGroups(cfg: RepairSettings): PanelGroup[] {
|
|
|
71
71
|
defaultValue: DEFAULT_REPAIR_SETTINGS.autoBgSecs,
|
|
72
72
|
description: "Seconds a foreground bash call may run before it is auto-backgrounded.",
|
|
73
73
|
}),
|
|
74
|
+
row("repair.persistentBash", "Persistent bash shell", "toggle", cfg.persistentBash, (v) => {
|
|
75
|
+
cfg.persistentBash = v === true;
|
|
76
|
+
}, {
|
|
77
|
+
defaultValue: DEFAULT_REPAIR_SETTINGS.persistentBash,
|
|
78
|
+
description: "One bash per session: cwd, exported variables, functions, and background jobs survive across calls (DeepSeek Harness parity). Plan mode always runs one-shot.",
|
|
79
|
+
warning: "Binds at session start — applies to the next session. While on, auto-background bash is suspended: background long jobs inside the shell with '&'.",
|
|
80
|
+
}),
|
|
74
81
|
],
|
|
75
82
|
},
|
|
76
83
|
];
|
|
77
84
|
}
|
|
78
85
|
|
|
79
86
|
const OWNED_PREFIX = "repair.";
|
|
80
|
-
const BOOL_KEYS = ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg"] as const;
|
|
87
|
+
const BOOL_KEYS = ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash"] as const;
|
|
81
88
|
|
|
82
89
|
/** repair's ModuleConfig for the central /config panel. The factory receives
|
|
83
90
|
* the module's guarded pi but needs nothing from it — settings live in the
|
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
} from "@earendil-works/pi-coding-agent";
|
|
43
43
|
import { Type } from "typebox";
|
|
44
44
|
import { abortAllBgJobs, bashAutoBgClause, setBgDeliveryEnabled, wrapWithAutoBg } from "./lib/auto-bg.js";
|
|
45
|
+
import { killPersistentShells, persistentBashClause, wrapWithPersistentShell } from "./lib/persistent-bash.js";
|
|
45
46
|
import {
|
|
46
47
|
computeRetryEdit,
|
|
47
48
|
isEditMismatchError,
|
|
@@ -658,6 +659,9 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
658
659
|
// byte-stable per session (never per-turn guidance).
|
|
659
660
|
const autoBgOn = settings.autoBg;
|
|
660
661
|
const autoBgSecs = settings.autoBgSecs;
|
|
662
|
+
// Same bind-at-load contract: the persistent-bash description half sits in
|
|
663
|
+
// the cache-safe request head.
|
|
664
|
+
const persistentBashOn = settings.persistentBash;
|
|
661
665
|
|
|
662
666
|
const repairCounts = new Map<string, number>();
|
|
663
667
|
// Per-file edit-mismatch counters — escalate to apply_patch after repeated
|
|
@@ -679,11 +683,17 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
679
683
|
find: createFindToolDefinition,
|
|
680
684
|
ls: createLsToolDefinition,
|
|
681
685
|
bash: (cwd: string) => {
|
|
682
|
-
const
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
686
|
+
const local = createLocalBashOperations();
|
|
687
|
+
// ponytail: persistent wins over autoBg when both are on — auto-backgrounding
|
|
688
|
+
// a QUEUED persistent exec would park later foreground calls behind a long
|
|
689
|
+
// job, while the shell's own `&` backgrounding covers the same need (and the
|
|
690
|
+
// description teaches it). /repair status discloses the suspension.
|
|
691
|
+
const operations = persistentBashOn
|
|
692
|
+
? wrapWithPersistentShell(local)
|
|
693
|
+
: autoBgOn ? wrapWithAutoBg(local, { pi, thresholdSecs: autoBgSecs }) : undefined;
|
|
694
|
+
const def = createBashToolDefinition(cwd, operations ? { operations } : undefined);
|
|
695
|
+
const clause = persistentBashOn ? persistentBashClause() : bashAutoBgClause(autoBgOn, autoBgSecs);
|
|
696
|
+
return { ...def, description: `${def.description}\n\n${clause}` };
|
|
687
697
|
},
|
|
688
698
|
};
|
|
689
699
|
for (const factory of Object.values(toolFactories)) {
|
|
@@ -796,6 +806,18 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
796
806
|
abortAllBgJobs(true);
|
|
797
807
|
});
|
|
798
808
|
}
|
|
809
|
+
if (persistentBashOn) {
|
|
810
|
+
// Keyed kill: a child session's shell dies with the child while the HOST's
|
|
811
|
+
// shell (a different PI_SESSION_ID) is untouched — the scoping is inherent,
|
|
812
|
+
// so no isChildSession gate is needed here.
|
|
813
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
814
|
+
try {
|
|
815
|
+
killPersistentShells(ctx?.sessionManager?.getSessionId?.());
|
|
816
|
+
} catch {
|
|
817
|
+
/* a dying session must not throw */
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
}
|
|
799
821
|
|
|
800
822
|
// ── tool_call: destructive-bash + read-on-guessed-path guards (ALL models).
|
|
801
823
|
// Upstream gated these on a detected family; repair is the model-agnostic
|
|
@@ -847,7 +869,7 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
847
869
|
|
|
848
870
|
// ── /repair (bare = status) ──
|
|
849
871
|
pi.registerCommand("repair", {
|
|
850
|
-
description: "Show tool-hardening status: repair counts, guards, bash auto-background.",
|
|
872
|
+
description: "Show tool-hardening status: repair counts, guards, bash auto-background, persistent shell.",
|
|
851
873
|
handler: async (_args, ctx) => {
|
|
852
874
|
const live = readRepairSettings(ctx?.cwd);
|
|
853
875
|
const total = [...repairCounts.values()].reduce((a, b) => a + b, 0);
|
|
@@ -860,6 +882,7 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
860
882
|
` Tool-call guards: ${live.guards ? "on" : "off"}`,
|
|
861
883
|
` Auto-generated write guard: ${live.autoGenGuard ? "on" : "off"}`,
|
|
862
884
|
` Auto-background bash: ${live.autoBg ? `on @${live.autoBgSecs}s` : "off"}${live.autoBg !== autoBgOn || live.autoBgSecs !== autoBgSecs ? ` (bound at load: ${autoBgOn ? `on @${autoBgSecs}s` : "off"} — next session applies)` : ""}`,
|
|
885
|
+
` Persistent bash: ${live.persistentBash ? "on" : "off"}${live.persistentBash !== persistentBashOn ? ` (bound at load: ${persistentBashOn ? "on" : "off"} — next session applies)` : ""}${persistentBashOn && (live.autoBg || autoBgOn) ? " · auto-background suspended while persistent is on" : ""}`,
|
|
863
886
|
"",
|
|
864
887
|
`**Repairs this session:** ${total} total`,
|
|
865
888
|
];
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
// persistent-bash.ts — one long-lived bash per pi session, so cwd, exported
|
|
2
|
+
// variables, functions, and background jobs survive across bash tool calls.
|
|
3
|
+
//
|
|
4
|
+
// Ported in behavior from DeepSeek Harness `@deepseek-ai/dsh-tool-bash-persistent`
|
|
5
|
+
// (packages/shell/tool-bash-persistent, DSH 0.2.3-alpha.1) onto pi's public
|
|
6
|
+
// `BashOperations` seam. DELIBERATE DEVIATIONS from DSH, each load-bearing:
|
|
7
|
+
//
|
|
8
|
+
// 1. Transport is pipes on a non-interactive `bash --noprofile --norc`, not a
|
|
9
|
+
// PTY scrollback. No prompt detection, no `stty -echo`, no scrollback ring
|
|
10
|
+
// to page: stdout/stderr are read directly and the command's exit status
|
|
11
|
+
// arrives on a marker line. Same observable contract, far less machinery.
|
|
12
|
+
// 2. Each command is one physical line — `eval $'<ANSI-C-escaped body>'; printf
|
|
13
|
+
// '<marker>%s\n' "$?"` (DSH's wrapCommand, kept verbatim in spirit). The
|
|
14
|
+
// eval-$'…' wrap makes a syntactically incomplete command a bash SYNTAX
|
|
15
|
+
// ERROR (the status printf still runs) instead of swallowing the marker.
|
|
16
|
+
// 3. No `PI_SESSION_ID` in `options.env` (ctx-less execution) falls back to a
|
|
17
|
+
// shared `_default_` shell — a documented ceiling, not a crash.
|
|
18
|
+
// 4. No output clipping here: pi's bash tool already truncates to
|
|
19
|
+
// DEFAULT_MAX_LINES/DEFAULT_MAX_BYTES and spills the rest to a temp file.
|
|
20
|
+
// DSH clipped at 16000 chars because its own loop had no such stage.
|
|
21
|
+
//
|
|
22
|
+
// PLAN MODE delegates to the one-shot local operations (see exec below): the
|
|
23
|
+
// plan gate auto-allows reads by COMMAND TEXT, and a shell retaining a cwd,
|
|
24
|
+
// function, or alias exported before plan mode could change what that text
|
|
25
|
+
// actually does. Plan-mode mutations are therefore discarded (one-shot), while
|
|
26
|
+
// the persistent shell keeps its pre-plan state and resumes when plan mode ends.
|
|
27
|
+
//
|
|
28
|
+
// Reset, never repair (DSH's rule): `exit`, a timeout, an abort, a spawn
|
|
29
|
+
// failure, or EOF-before-marker kills the process GROUP (spawned detached, so
|
|
30
|
+
// children die too) and forgets the shell; the next call respawns fresh.
|
|
31
|
+
|
|
32
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
33
|
+
import { randomBytes } from "node:crypto";
|
|
34
|
+
import type { BashOperations } from "@earendil-works/pi-coding-agent";
|
|
35
|
+
import { isPlanActive } from "../../../lib/plan-bridge.ts";
|
|
36
|
+
|
|
37
|
+
/** Marker prefix; the per-command nonce follows it (one token). */
|
|
38
|
+
const MARKER_PREFIX = "__CEULEN_PS_";
|
|
39
|
+
/** Key used when the caller supplied no PI_SESSION_ID (documented ceiling). */
|
|
40
|
+
const DEFAULT_KEY = "_default_";
|
|
41
|
+
/** Synthetic note appended when the shell died under a running command. */
|
|
42
|
+
const EXITED_NOTE = "\n[persistent shell exited — the next bash call starts a fresh shell in the session directory]\n";
|
|
43
|
+
/** Cap on retained between-command output (background-job noise guard). */
|
|
44
|
+
const PENDING_MAX_CHARS = 256 * 1024;
|
|
45
|
+
/**
|
|
46
|
+
* Default per-command deadline when the caller supplies none (seconds).
|
|
47
|
+
*
|
|
48
|
+
* pi's bash `timeout` is OPTIONAL — undefined means the one-shot path has no
|
|
49
|
+
* timer at all. For a persistent shell that is not survivable: a command that
|
|
50
|
+
* never settles (a shadowed framing primitive, a foreground child reading
|
|
51
|
+
* stdin, a runaway job) blocks the shell AND every queued call behind it
|
|
52
|
+
* forever, with no reset to recover by. DSH's own tool-bash-persistent defaults
|
|
53
|
+
* `timeoutMs` to 300 000 for exactly this reason. This is a FLOOR, not an
|
|
54
|
+
* override: an explicit `timeout` always wins, and the timeout RESETS the shell
|
|
55
|
+
* (reset-never-repair), which is what turns the `command`-shadow ceiling into a
|
|
56
|
+
* bounded, self-healing failure instead of a wedged session.
|
|
57
|
+
*/
|
|
58
|
+
export const DEFAULT_COMMAND_TIMEOUT_SECS = 300;
|
|
59
|
+
|
|
60
|
+
/** The command currently owning this shell's stream, if any. */
|
|
61
|
+
interface ActiveCommand {
|
|
62
|
+
marker: string;
|
|
63
|
+
onData: (data: Buffer) => void;
|
|
64
|
+
settle: (code: number) => void;
|
|
65
|
+
/** Text held back until a newline proves it is not the marker. */
|
|
66
|
+
carry: string;
|
|
67
|
+
settled: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface PersistentShell {
|
|
71
|
+
child: ChildProcess;
|
|
72
|
+
/** Output observed BETWEEN commands (background jobs). Prepended to the next
|
|
73
|
+
* command's stream so nothing is lost across calls (DSH parity). */
|
|
74
|
+
pending: string;
|
|
75
|
+
active: ActiveCommand | undefined;
|
|
76
|
+
alive: boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Per-shell bookkeeping keyed by pi session id. */
|
|
80
|
+
const shells = new Map<string, PersistentShell>();
|
|
81
|
+
/**
|
|
82
|
+
* Serialization queues keyed by SESSION, not by shell object. A shell can be
|
|
83
|
+
* reset (timeout/abort/exit) while calls are still queued behind it; keying the
|
|
84
|
+
* queue on the shell would make those queued calls run against the dead child
|
|
85
|
+
* ("persistent shell is not running") instead of respawning. Keeping the queue
|
|
86
|
+
* on the key lets every dequeued call re-resolve the CURRENT shell.
|
|
87
|
+
*/
|
|
88
|
+
const queues = new Map<string, Promise<unknown>>();
|
|
89
|
+
|
|
90
|
+
/** Test seam: a fixed marker source (marker-collision coverage). */
|
|
91
|
+
export interface PersistentBashDeps {
|
|
92
|
+
/** Returns the command's end marker (must start with `__CEULEN_PS_`). */
|
|
93
|
+
newMarker?: () => string;
|
|
94
|
+
/** Overrides DEFAULT_COMMAND_TIMEOUT_SECS (tests only — a lower floor keeps
|
|
95
|
+
* the never-settles coverage fast). */
|
|
96
|
+
defaultTimeoutSecs?: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function defaultMarker(): string {
|
|
100
|
+
return `${MARKER_PREFIX}${randomBytes(8).toString("hex")}__`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Escape a command for bash's `$'…'` ANSI-C quoting (DSH quoteForBash). */
|
|
104
|
+
export function quoteForEval(command: string): string {
|
|
105
|
+
let out = "";
|
|
106
|
+
for (const ch of command) {
|
|
107
|
+
if (ch === "\\") out += "\\\\";
|
|
108
|
+
else if (ch === "'") out += "\\'";
|
|
109
|
+
else if (ch === "\n") out += "\\n";
|
|
110
|
+
else if (ch === "\r") out += "\\r";
|
|
111
|
+
else if (ch === "\t") out += "\\t";
|
|
112
|
+
else {
|
|
113
|
+
const code = ch.codePointAt(0)!;
|
|
114
|
+
if (code > 0 && code < 0x20) out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
115
|
+
else out += ch;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return `$'${out}'`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The one physical line sent to the shell (DSH wrapCommand).
|
|
123
|
+
*
|
|
124
|
+
* Every framing step is reached through `command builtin`, so each step
|
|
125
|
+
* bypasses function AND alias lookup. The shell is persistent by design, so a
|
|
126
|
+
* function the model defined in an earlier call is still live when the framing
|
|
127
|
+
* runs. Probed shadowings, in escalating order of reach:
|
|
128
|
+
*
|
|
129
|
+
* `printf() { :; }` — suppressed the marker bare → a SUCCESSFUL command hung
|
|
130
|
+
* until the timeout (the first reported defect);
|
|
131
|
+
* `eval() { … }` — captured the body dispatch the same way;
|
|
132
|
+
* `builtin() { :; }` — ALSO suppressed it through `builtin printf`, because
|
|
133
|
+
* `builtin` is itself resolved by NAME. `command` fixes
|
|
134
|
+
* this one: with only `builtin` shadowed and `command`
|
|
135
|
+
* intact the marker PRINTS.
|
|
136
|
+
* `command() { :; }` — THE REMAINING CEILING, and it needs no help from
|
|
137
|
+
* `builtin`: `command` is resolved first and is itself
|
|
138
|
+
* shadowable, so this alone SKIPS THE BODY and suppresses
|
|
139
|
+
* the marker. Escaping it would need an absolute external
|
|
140
|
+
* path (`/usr/bin/printf`), which is not portable to
|
|
141
|
+
* every platform pi runs on — accepting a
|
|
142
|
+
* deliberate-self-harm timeout beats framing that cannot
|
|
143
|
+
* start on a box without that binary.
|
|
144
|
+
*
|
|
145
|
+
* The ceiling is self-limiting rather than silent: the offending call times out
|
|
146
|
+
* (pi's "Command timed out after N seconds"), the timeout RESETS the shell
|
|
147
|
+
* (reset-never-repair), and the next call therefore runs on a fresh shell with
|
|
148
|
+
* the shadowing function gone — verified, including `type command` reporting
|
|
149
|
+
* the builtin again. The model wrote the shadowing function, so this is
|
|
150
|
+
* self-inflicted; the reset makes it self-healing.
|
|
151
|
+
*
|
|
152
|
+
* ponytail: body evaluation keeps `command builtin eval` for symmetry, but a
|
|
153
|
+
* redirected command name INSIDE the body is the model's own doing, not framing.
|
|
154
|
+
*/
|
|
155
|
+
export function wrapCommand(command: string, marker: string): string {
|
|
156
|
+
return `command builtin eval ${quoteForEval(command)}; command builtin printf '${marker}%s\\n' "$?"\n`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Kill a process GROUP (spawned detached). Safe on an already-dead pid. */
|
|
160
|
+
function killGroup(child: ChildProcess): void {
|
|
161
|
+
const pid = child.pid;
|
|
162
|
+
if (pid === undefined) return;
|
|
163
|
+
try {
|
|
164
|
+
process.kill(-pid, "SIGKILL");
|
|
165
|
+
} catch {
|
|
166
|
+
try {
|
|
167
|
+
child.kill("SIGKILL");
|
|
168
|
+
} catch {
|
|
169
|
+
/* already gone */
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Forget (and kill) one shell, or all of them. */
|
|
175
|
+
export function killPersistentShells(sessionId?: string): void {
|
|
176
|
+
const keys = sessionId === undefined ? [...new Set([...shells.keys(), ...queues.keys()])] : [sessionId];
|
|
177
|
+
for (const key of keys) {
|
|
178
|
+
// Drop the serialization chain too: a session that is killed must not
|
|
179
|
+
// inherit a queue whose head can never settle.
|
|
180
|
+
queues.delete(key);
|
|
181
|
+
const shell = shells.get(key);
|
|
182
|
+
if (!shell) continue;
|
|
183
|
+
shells.delete(key);
|
|
184
|
+
shell.alive = false;
|
|
185
|
+
killGroup(shell.child);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Route one chunk of shell output. While a command owns the stream it is
|
|
191
|
+
* forwarded with the trailing partial line held back (a marker split across
|
|
192
|
+
* chunks must never be read as output); between commands everything lands in
|
|
193
|
+
* `pending` for the next command to replay.
|
|
194
|
+
*/
|
|
195
|
+
function feed(shell: PersistentShell, chunk: string): void {
|
|
196
|
+
const active = shell.active;
|
|
197
|
+
if (!active || active.settled) {
|
|
198
|
+
shell.pending = (shell.pending + chunk).slice(-PENDING_MAX_CHARS);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
active.carry += chunk;
|
|
202
|
+
const nl = active.carry.lastIndexOf("\n");
|
|
203
|
+
if (nl < 0) return;
|
|
204
|
+
const complete = active.carry.slice(0, nl + 1);
|
|
205
|
+
active.carry = active.carry.slice(nl + 1);
|
|
206
|
+
|
|
207
|
+
// LAST occurrence, not first: an earlier line carrying the marker token is
|
|
208
|
+
// command OUTPUT, and settling on it would strand the rest of the output in
|
|
209
|
+
// the next call's stream.
|
|
210
|
+
// ponytail: the nonce is generated per command, AFTER the command text exists,
|
|
211
|
+
// so a model cannot echo a marker it has never seen. A same-chunk echo is
|
|
212
|
+
// handled by lastIndexOf; a CROSS-chunk echo would need a settle timer (DSH
|
|
213
|
+
// polls its scrollback for exactly this reason). Accepted ceiling — a pipe
|
|
214
|
+
// stream has no "nothing new for N ms" notion without one.
|
|
215
|
+
const idx = complete.lastIndexOf(active.marker);
|
|
216
|
+
if (idx < 0) {
|
|
217
|
+
active.onData(Buffer.from(complete, "utf8"));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
// Marker line: text before it is real output, the rest of that line is the
|
|
221
|
+
// exit status, and anything still buffered belongs to a later call.
|
|
222
|
+
const before = complete.slice(0, idx);
|
|
223
|
+
if (before.length > 0) active.onData(Buffer.from(before, "utf8"));
|
|
224
|
+
const afterMarker = complete.slice(idx + active.marker.length);
|
|
225
|
+
const statusEnd = afterMarker.indexOf("\n");
|
|
226
|
+
const status = afterMarker.slice(0, statusEnd);
|
|
227
|
+
shell.pending = (afterMarker.slice(statusEnd + 1) + active.carry).slice(-PENDING_MAX_CHARS);
|
|
228
|
+
active.carry = "";
|
|
229
|
+
active.settle(Number.parseInt(status, 10));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function spawnShell(cwd: string, env: Record<string, string> | undefined): PersistentShell {
|
|
233
|
+
const child = spawn("bash", ["--noprofile", "--norc"], {
|
|
234
|
+
cwd,
|
|
235
|
+
env: { ...(env ?? (process.env as unknown as Record<string, string>)) },
|
|
236
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
237
|
+
detached: process.platform !== "win32",
|
|
238
|
+
windowsHide: true,
|
|
239
|
+
});
|
|
240
|
+
const shell: PersistentShell = { child, pending: "", active: undefined, alive: true };
|
|
241
|
+
// ONE permanent pair of listeners per shell: output arriving between commands
|
|
242
|
+
// is retained instead of dropped, and a command never attaches/detaches its
|
|
243
|
+
// own listeners (which would race a chunk landing mid-attach).
|
|
244
|
+
child.stdout?.setEncoding("utf8");
|
|
245
|
+
child.stderr?.setEncoding("utf8");
|
|
246
|
+
child.stdout?.on("data", (chunk: string) => feed(shell, chunk));
|
|
247
|
+
child.stderr?.on("data", (chunk: string) => feed(shell, chunk));
|
|
248
|
+
child.on("error", () => {
|
|
249
|
+
shell.alive = false;
|
|
250
|
+
});
|
|
251
|
+
child.on("exit", () => {
|
|
252
|
+
shell.alive = false;
|
|
253
|
+
const active = shell.active;
|
|
254
|
+
if (!active || active.settled) return;
|
|
255
|
+
// The shell died under the command (exit, crash, or signal): report its
|
|
256
|
+
// real status and tell the model the next call starts fresh.
|
|
257
|
+
if (active.carry.length > 0) active.onData(Buffer.from(active.carry, "utf8"));
|
|
258
|
+
active.carry = "";
|
|
259
|
+
active.onData(Buffer.from(EXITED_NOTE, "utf8"));
|
|
260
|
+
active.settle(shell.child.exitCode ?? 1);
|
|
261
|
+
});
|
|
262
|
+
// A dying shell's pipes must never crash the host (EPIPE on write).
|
|
263
|
+
child.stdin?.on("error", () => {});
|
|
264
|
+
child.stdout?.on("error", () => {});
|
|
265
|
+
child.stderr?.on("error", () => {});
|
|
266
|
+
return shell;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Resolve the shell for a key, spawning lazily and evicting dead ones. */
|
|
270
|
+
function shellFor(key: string, cwd: string, env: Record<string, string> | undefined): PersistentShell {
|
|
271
|
+
const existing = shells.get(key);
|
|
272
|
+
if (existing && existing.alive) return existing;
|
|
273
|
+
if (existing) shells.delete(key);
|
|
274
|
+
const shell = spawnShell(cwd, env);
|
|
275
|
+
shells.set(key, shell);
|
|
276
|
+
return shell;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Reset (kill + forget) a shell — the "never repair" half. */
|
|
280
|
+
function resetShell(key: string, shell: PersistentShell): void {
|
|
281
|
+
shells.delete(key);
|
|
282
|
+
shell.alive = false;
|
|
283
|
+
killGroup(shell.child);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Run ONE command on an existing shell, resolving with its exit code and
|
|
287
|
+
* feeding output to `onData`. Rejects on timeout/abort after resetting it. */
|
|
288
|
+
function runOnShell(
|
|
289
|
+
shell: PersistentShell,
|
|
290
|
+
key: string,
|
|
291
|
+
command: string,
|
|
292
|
+
options: { onData: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
293
|
+
marker: string,
|
|
294
|
+
): Promise<{ exitCode: number | null }> {
|
|
295
|
+
return new Promise<{ exitCode: number | null }>((resolve, reject) => {
|
|
296
|
+
if (!shell.alive || shell.child.stdin === null) {
|
|
297
|
+
shells.delete(key);
|
|
298
|
+
reject(new Error("persistent shell is not running"));
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
// Background-job output observed after the previous marker belongs to this
|
|
302
|
+
// command's stream (DSH parity: nothing is lost between calls).
|
|
303
|
+
if (shell.pending.length > 0) {
|
|
304
|
+
options.onData(Buffer.from(shell.pending, "utf8"));
|
|
305
|
+
shell.pending = "";
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
let timer: NodeJS.Timeout | undefined;
|
|
309
|
+
const active: ActiveCommand = {
|
|
310
|
+
marker,
|
|
311
|
+
onData: options.onData,
|
|
312
|
+
carry: "",
|
|
313
|
+
settled: false,
|
|
314
|
+
settle: (code: number) => {
|
|
315
|
+
if (active.settled) return;
|
|
316
|
+
active.settled = true;
|
|
317
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
318
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
319
|
+
if (shell.active === active) shell.active = undefined;
|
|
320
|
+
if (!shell.alive) shells.delete(key);
|
|
321
|
+
resolve({ exitCode: Number.isFinite(code) ? code : 1 });
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
function onAbort(): void {
|
|
325
|
+
if (active.settled) return;
|
|
326
|
+
active.settled = true;
|
|
327
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
328
|
+
shell.active = undefined;
|
|
329
|
+
resetShell(key, shell);
|
|
330
|
+
reject(new Error("aborted"));
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
shell.active = active;
|
|
334
|
+
// `wrapWithPersistentShell` guarantees a positive timeout here: an explicit
|
|
335
|
+
// caller timeout wins, otherwise the default FLOOR applies so a
|
|
336
|
+
// never-settling command can never wedge the shell (and every queued call
|
|
337
|
+
// behind it) forever. See DEFAULT_COMMAND_TIMEOUT_SECS.
|
|
338
|
+
const timeoutSecs = options.timeout !== undefined && options.timeout > 0
|
|
339
|
+
? options.timeout
|
|
340
|
+
: DEFAULT_COMMAND_TIMEOUT_SECS;
|
|
341
|
+
timer = setTimeout(() => {
|
|
342
|
+
if (active.settled) return;
|
|
343
|
+
active.settled = true;
|
|
344
|
+
shell.active = undefined;
|
|
345
|
+
resetShell(key, shell);
|
|
346
|
+
// pi's bash tool parses this exact prefix into its timeout message.
|
|
347
|
+
reject(new Error(`timeout:${timeoutSecs}`));
|
|
348
|
+
}, timeoutSecs * 1000);
|
|
349
|
+
if (options.signal) {
|
|
350
|
+
if (options.signal.aborted) {
|
|
351
|
+
onAbort();
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
try {
|
|
358
|
+
shell.child.stdin!.write(wrapCommand(command, marker));
|
|
359
|
+
} catch {
|
|
360
|
+
active.settled = true;
|
|
361
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
362
|
+
shell.active = undefined;
|
|
363
|
+
resetShell(key, shell);
|
|
364
|
+
reject(new Error("persistent shell rejected input"));
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Wrap one-shot local bash operations with a per-session persistent shell.
|
|
371
|
+
* `local` remains the spawn/fallback path AND the plan-mode one-shot path, so
|
|
372
|
+
* a box without bash behaves exactly like the unwrapped tool.
|
|
373
|
+
*/
|
|
374
|
+
export function wrapWithPersistentShell(local: BashOperations, deps: PersistentBashDeps = {}): BashOperations {
|
|
375
|
+
const newMarker = deps.newMarker ?? defaultMarker;
|
|
376
|
+
const defaultTimeoutSecs = deps.defaultTimeoutSecs ?? DEFAULT_COMMAND_TIMEOUT_SECS;
|
|
377
|
+
return {
|
|
378
|
+
exec: (command, cwd, options) => {
|
|
379
|
+
// Plan mode: one-shot, stateless. The plan gate auto-allows reads by
|
|
380
|
+
// COMMAND TEXT; retained cwd/functions/aliases from before plan mode
|
|
381
|
+
// could change what that text does, so nothing retained may be in play
|
|
382
|
+
// while it gates. The persistent shell is left untouched (its pre-plan
|
|
383
|
+
// state resumes on exit) and plan-mode mutations are discarded.
|
|
384
|
+
if (isPlanActive()) return local.exec(command, cwd, options);
|
|
385
|
+
|
|
386
|
+
const env = options.env as Record<string, string> | undefined;
|
|
387
|
+
const key = env?.PI_SESSION_ID ?? DEFAULT_KEY;
|
|
388
|
+
const marker = newMarker();
|
|
389
|
+
const timeout = options.timeout ?? defaultTimeoutSecs;
|
|
390
|
+
|
|
391
|
+
// Serialize per SESSION: parallel bash calls (a codemode batch) must never
|
|
392
|
+
// interleave their streams on one shell. The shell is re-resolved INSIDE
|
|
393
|
+
// the queue slot, so a call queued behind a reset (timeout/abort/exit)
|
|
394
|
+
// respawns instead of running against the dead child. `catch` so a prior
|
|
395
|
+
// failure never poisons the queue for the next command.
|
|
396
|
+
const run = (queues.get(key) ?? Promise.resolve())
|
|
397
|
+
.catch(() => undefined)
|
|
398
|
+
.then(() => runOnShell(shellFor(key, cwd, env), key, command, { ...options, timeout }, marker));
|
|
399
|
+
queues.set(key, run.then(
|
|
400
|
+
() => undefined,
|
|
401
|
+
() => undefined,
|
|
402
|
+
));
|
|
403
|
+
return run;
|
|
404
|
+
},
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* The bash-description addendum. Binds at module load so it stays byte-stable
|
|
410
|
+
* in the cache-safe request head (the repair autoBg precedent). Teaches DSH's
|
|
411
|
+
* backgrounding model — `&` inside the shell — and the reset contract.
|
|
412
|
+
*/
|
|
413
|
+
export function persistentBashClause(): string {
|
|
414
|
+
return [
|
|
415
|
+
"Commands run in ONE persistent bash session: the working directory, exported variables, functions, and",
|
|
416
|
+
"background jobs persist across calls. Run long-lived commands in the background (e.g. 'sleep 10 &' or start",
|
|
417
|
+
"a server with '&') and read their output on a later call. 'exit', a timeout, or an abort resets the shell —",
|
|
418
|
+
"the next call starts fresh in the session's working directory. In plan mode each call runs as a one-shot shell.",
|
|
419
|
+
].join(" ");
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** Test seam: install the process-exit sweeper once per process. */
|
|
423
|
+
export function installPersistentExitSweepForTests(): void {
|
|
424
|
+
installExitSweep();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function installExitSweep(): void {
|
|
428
|
+
// Key the once-guard on a globalThis slot: a module-level flag RESETS on
|
|
429
|
+
// /reload and would stack duplicate exit listeners on the shared process
|
|
430
|
+
// (the autoBg/theme-slot pattern).
|
|
431
|
+
const armed = Symbol.for("ceulen.repair.psExitSweep.armed");
|
|
432
|
+
const host = globalThis as unknown as Record<symbol, boolean>;
|
|
433
|
+
if (host[armed]) return;
|
|
434
|
+
host[armed] = true;
|
|
435
|
+
const sweep = () => killPersistentShells();
|
|
436
|
+
process.once("exit", sweep);
|
|
437
|
+
process.once("SIGTERM", sweep);
|
|
438
|
+
process.once("SIGINT", sweep);
|
|
439
|
+
}
|
|
440
|
+
installExitSweep();
|
|
@@ -31,6 +31,9 @@ export interface RepairSettings {
|
|
|
31
31
|
autoBg: boolean;
|
|
32
32
|
/** Foreground threshold (seconds) before auto-backgrounding. */
|
|
33
33
|
autoBgSecs: number;
|
|
34
|
+
/** One persistent bash shell per session (cwd/env/jobs survive across calls).
|
|
35
|
+
* Binds at load — the shell description sits in the cache-safe request head. */
|
|
36
|
+
persistentBash: boolean;
|
|
34
37
|
}
|
|
35
38
|
|
|
36
39
|
export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
|
|
@@ -40,6 +43,7 @@ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
|
|
|
40
43
|
autoGenGuard: true,
|
|
41
44
|
autoBg: false,
|
|
42
45
|
autoBgSecs: 120,
|
|
46
|
+
persistentBash: false,
|
|
43
47
|
};
|
|
44
48
|
|
|
45
49
|
function agentDir(): string {
|
|
@@ -63,7 +67,7 @@ function section(json: Record<string, unknown> | null, key: string): Record<stri
|
|
|
63
67
|
/** Merge one settings layer's `repair` keys over out (field-wise override). */
|
|
64
68
|
function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
|
|
65
69
|
const s = section(json, "repair");
|
|
66
|
-
for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg"] as const) {
|
|
70
|
+
for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg", "persistentBash"] as const) {
|
|
67
71
|
if (typeof s[key] === "boolean") out[key] = s[key];
|
|
68
72
|
}
|
|
69
73
|
if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {
|