pi-keeper 0.0.0-stage → 0.1.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +36 -0
  4. package/README.md +71 -2
  5. package/extensions/ask-heartbeat.ts +55 -0
  6. package/extensions/ask-mailbox.ts +497 -0
  7. package/extensions/ask-server.ts +452 -0
  8. package/extensions/attention.ts +24 -0
  9. package/extensions/cc-extensions-compat.ts +103 -0
  10. package/extensions/child-auto.ts +32 -0
  11. package/extensions/child-cwd.ts +76 -0
  12. package/extensions/child-default.ts +32 -0
  13. package/extensions/child-lane.ts +134 -0
  14. package/extensions/child-plan.ts +12 -0
  15. package/extensions/config.ts +347 -0
  16. package/extensions/dialog-lock.ts +70 -0
  17. package/extensions/dialog.ts +420 -0
  18. package/extensions/index.ts +3453 -0
  19. package/extensions/modes.ts +1330 -0
  20. package/extensions/options.ts +109 -0
  21. package/extensions/perf.ts +54 -0
  22. package/extensions/plan-approval.ts +345 -0
  23. package/extensions/preview.ts +232 -0
  24. package/extensions/project-rules.ts +565 -0
  25. package/extensions/prompt-blocks.ts +163 -0
  26. package/extensions/remote-relay.ts +163 -0
  27. package/extensions/rtk-rewrite.ts +60 -0
  28. package/extensions/rulebook.ts +302 -0
  29. package/extensions/rules-line.ts +71 -0
  30. package/extensions/rules-view.ts +168 -0
  31. package/extensions/rules.ts +412 -0
  32. package/extensions/secure-file.ts +157 -0
  33. package/extensions/session-grant-store.ts +139 -0
  34. package/extensions/session-grants.ts +154 -0
  35. package/extensions/settings-panel.ts +194 -0
  36. package/extensions/shell-highlight-bridge.ts +50 -0
  37. package/extensions/subagents-bridge.ts +129 -0
  38. package/extensions/telemetry.ts +213 -0
  39. package/extensions/thinking.ts +62 -0
  40. package/extensions/title.ts +80 -0
  41. package/extensions/ui-relay.ts +149 -0
  42. package/extensions/utils.ts +3981 -0
  43. package/package.json +64 -5
  44. package/prompts/auto-mode.md +16 -0
  45. package/prompts/child-auto.md +26 -0
  46. package/prompts/child-default.md +21 -0
  47. package/prompts/child-plan.md +16 -0
  48. package/prompts/contract.md +29 -0
  49. package/prompts/default-mode.md +8 -0
  50. package/prompts/plan-mode.md +45 -0
  51. package/prompts/rule-warning.md +8 -0
@@ -0,0 +1,452 @@
1
+ /**
2
+ * The parent side of the ask mailbox (ask-mailbox.ts): answers the permission
3
+ * asks of background subagents. The child asks, the parent decides: a request
4
+ * is untrusted (the child's model may be prompt-injected), so nothing in it is
5
+ * believed beyond the tool call and its working directory. The server only
6
+ * moves requests and replies and decides WHEN a dialog opens; what a call is
7
+ * judged as, and the dialog itself, come from the caller (`judge`, `ask`,
8
+ * index.ts), which uses the same rules, grants and dialog code as the
9
+ * session's own calls.
10
+ *
11
+ * Each poll (about every 500 ms): claim new requests, honour cancels, drop
12
+ * requests whose child is gone, expire old ones, sweep leftovers. Every
13
+ * queued request is judged again on each pass, so a grant given for one
14
+ * request settles an identical one without a second dialog. `allow` and
15
+ * `deny` are answered at once; only `ask` opens a dialog, one at a time,
16
+ * and only when no other dialog is open (dialog-lock.ts) and the popup
17
+ * policy says so:
18
+ *
19
+ * idle the session is idle and the editor empty, else a badge and /approvals
20
+ * always as soon as no other dialog is open
21
+ * badge only through /approvals
22
+ *
23
+ * Without a UI an ask is denied (reason `no-ui`), like a headless session's
24
+ * own asks. When the session ends every pending request is denied with
25
+ * `parent-session-ended` and its dialog is aborted, so no child waits for a
26
+ * parent that is gone.
27
+ *
28
+ * Free of pi types so it is testable (like ask-mailbox.ts).
29
+ */
30
+
31
+ import { HEARTBEAT_EVERY_MS, removeHeartbeat, writeHeartbeat } from "./ask-heartbeat.ts";
32
+ import { countWork } from "./perf.ts";
33
+ import { cleanup, ensureAskDir, pendingIds, readCancels, sweep, takeRequests, writeReply, type AskRequest, type ChildMode, type MailboxOptions, type ReplyDecision, type ReplyReason, type Taken } from "./ask-mailbox.ts";
34
+ import type { BackgroundAskPopup } from "./config.ts";
35
+ import type { ModeName } from "./modes.ts";
36
+ import { isPidAlive } from "./secure-file.ts";
37
+ import { childModeFor, relaylessChildMode } from "./subagents-bridge.ts";
38
+
39
+ /** Poll interval. */
40
+ export const POLL_MS = 500;
41
+ /** A request the user has not answered by then is denied (reason `timeout`). */
42
+ export const ASK_TTL_MS = 15 * 60_000;
43
+
44
+ /** The parent's per-request TTL: the child's own wait plus a minute, never below ASK_TTL_MS, so the parent never times out before the child. */
45
+ export function askTtlMs(childTimeoutMs: number): number {
46
+ return Math.max(ASK_TTL_MS, childTimeoutMs + 60_000);
47
+ }
48
+ /** Extra time the mailbox keeps a timed-out request, so its child can still read the reply. */
49
+ const SWEEP_GRACE_MS = 60_000;
50
+ /** Requests held at once; more are denied unseen (a flood is a bug or an attack, not a user). */
51
+ export const MAX_QUEUE = 100;
52
+
53
+ /**
54
+ * The mode a background child runs in, as this parent assigns it: the mode
55
+ * its registered entry file gives (subagents-bridge.ts), and for a child with
56
+ * no UI relay what child-default.ts / child-auto.ts pick (relaylessChildMode):
57
+ * with background asks on the registered mode itself (an auto parent with
58
+ * `subagentsFollowAuto` gives auto), else default, or auto with `background-auto-fallback`.
59
+ * Plan stays plan. `backgroundAsks` is the effective flag (the setting and
60
+ * the env kill switch).
61
+ */
62
+ export function backgroundChildMode(mode: ModeName, settings: { subagentsFollowAuto: boolean; backgroundAutoFallback: boolean; backgroundAsks: boolean }): ChildMode {
63
+ const registered = childModeFor(mode, settings.subagentsFollowAuto);
64
+ if (registered === "plan") return "plan";
65
+ return relaylessChildMode(registered, settings);
66
+ }
67
+
68
+ const STRICTNESS: Record<ChildMode, number> = { auto: 0, default: 1, plan: 2 };
69
+
70
+ /**
71
+ * The stricter of two modes (plan > default > auto). The parent judges a
72
+ * request in the stricter of its own clamp and the mode the child says it
73
+ * runs in: a child that fell back to default (e.g. it saw no fresh heartbeat
74
+ * at load) is never judged as auto, and one that claims more than the clamp
75
+ * allows is still clamped.
76
+ */
77
+ export function stricterMode(a: ChildMode, b: ChildMode): ChildMode {
78
+ return STRICTNESS[a] >= STRICTNESS[b] ? a : b;
79
+ }
80
+
81
+ /** The status line for `count` asks waiting in the queue. */
82
+ export function badgeText(count: number): string {
83
+ return `${count} background approval${count === 1 ? "" : "s"} waiting · /approvals`;
84
+ }
85
+
86
+ export interface PopupState {
87
+ policy: BackgroundAskPopup;
88
+ /** `/approvals` was run: open everything that waits. */
89
+ forced: boolean;
90
+ /** A run just ended: the session counts as idle. */
91
+ assumeIdle: boolean;
92
+ idle: boolean;
93
+ editorEmpty: boolean;
94
+ }
95
+
96
+ /** Whether the next dialog may open now (the caller also checks that no other dialog is open). */
97
+ export function mayPopUp(state: PopupState): boolean {
98
+ if (state.forced) return true;
99
+ if (state.policy === "always") return true;
100
+ if (state.policy === "badge") return false;
101
+ return (state.idle || state.assumeIdle) && state.editorEmpty;
102
+ }
103
+
104
+ /** How the parent judged a request. */
105
+ export interface Verdict {
106
+ action: "allow" | "deny" | "ask";
107
+ /** The mode the call was judged in: the parent's own choice. */
108
+ mode: ChildMode;
109
+ /** The mode the request claimed, when it differs from `mode` (the claim is ignored, only noted). */
110
+ claimed?: string;
111
+ /** The rule that decided, for telemetry; null for a mode's fallback. */
112
+ matcher: string | null;
113
+ }
114
+
115
+ type EventKind = "auto-allow" | "auto-deny" | "no-ui" | "cancelled" | "timeout" | "parent-gone" | "dropped" | "clamped";
116
+
117
+ /** What happened to a request without a dialog of its own (a dialog's answer is logged where it is shown). */
118
+ export interface ServerEvent {
119
+ kind: EventKind;
120
+ request: AskRequest;
121
+ verdict?: Verdict;
122
+ /** Parent-side ms since the request was claimed. */
123
+ waitMs: number;
124
+ }
125
+
126
+ export interface AskServerOptions {
127
+ /** The mailbox directory (askDirFor). */
128
+ dir: string;
129
+ /** Judge a request with the parent's own engine. Never trust the request beyond its call and cwd. */
130
+ judge(request: AskRequest): Verdict;
131
+ /** Show the dialog for a request judged `ask`; resolves "allow" or "deny". Aborting `signal` closes it. `receivedAt` is when the server claimed the request. */
132
+ ask(request: AskRequest, signal: AbortSignal, receivedAt: number): Promise<"allow" | "deny">;
133
+ hasUI(): boolean;
134
+ isIdle(): boolean;
135
+ editorEmpty(): boolean;
136
+ /** Another dialog is open or waiting for the slot (isDialogLocked). */
137
+ dialogBusy(): boolean;
138
+ popup(): BackgroundAskPopup;
139
+ /** Ring the terminal before a dialog opens. */
140
+ attention(): void;
141
+ /** Show (count > 0) or clear (0) the waiting badge. */
142
+ badge(count: number): void;
143
+ onEvent(event: ServerEvent): void;
144
+ /** A mailbox problem worth telling the user about (reported once per distinct text). */
145
+ warn?(message: string): void;
146
+ /** Test seams. */
147
+ setTimer?(tick: () => void, ms: number): { stop(): void };
148
+ now?(): number;
149
+ alive?(pid: number): boolean;
150
+ /** Per-request TTL; a function is read at every poll, so a setting change applies to pending requests too. */
151
+ ttlMs?: number | (() => number);
152
+ /** The pid the heartbeat names (default: this process). */
153
+ pid?: number;
154
+ }
155
+
156
+ export interface AskServer {
157
+ /** One poll; the timer calls this. */
158
+ tick(): void;
159
+ /** A run ended: look at the queue now instead of at the next poll. */
160
+ runEnded(): void;
161
+ /** `/approvals`: open what waits, whatever the popup policy says. Returns how many were waiting. */
162
+ openNow(): number;
163
+ /** Requests held (queued or on screen). */
164
+ pending(): number;
165
+ /** The session is ending: deny everything pending, close its dialogs, stop polling. */
166
+ stop(): void;
167
+ }
168
+
169
+ type Why = "cancel" | "timeout" | "dropped" | "ended";
170
+
171
+ interface Entry {
172
+ request: AskRequest;
173
+ receivedAt: number;
174
+ /** Set once something other than the user's answer ended it. */
175
+ why?: Why;
176
+ controller?: AbortController;
177
+ clampNoted?: boolean;
178
+ }
179
+
180
+ const defaultTimer = (tick: () => void, ms: number): { stop(): void } => {
181
+ const timer = setInterval(tick, ms);
182
+ timer.unref(); // polling must never keep the process alive
183
+ return { stop: () => clearInterval(timer) };
184
+ };
185
+
186
+ export function startAskServer(options: AskServerOptions): AskServer {
187
+ const { dir } = options;
188
+ const now = options.now ?? Date.now;
189
+ const alive = options.alive ?? isPidAlive;
190
+ const ttlSetting = options.ttlMs ?? ASK_TTL_MS;
191
+ let sweepTtl = 0;
192
+ const currentTtl = (): number => (typeof ttlSetting === "function" ? ttlSetting() : ttlSetting);
193
+ const taken: Taken = new Map();
194
+ const queue: Entry[] = [];
195
+ let open: Entry | undefined;
196
+ let forced = false;
197
+ let assumeIdle = false;
198
+ let stopped = false;
199
+ let shownBadge = 0;
200
+ const warned = new Set<string>();
201
+ let lastBeat = Number.NEGATIVE_INFINITY;
202
+
203
+ /** Keep the "listening" note fresh (throttled); a mailbox that cannot be written just leaves it stale. */
204
+ function beat(at: number): void {
205
+ if (at - lastBeat < HEARTBEAT_EVERY_MS) return;
206
+ lastBeat = at;
207
+ try {
208
+ writeHeartbeat(dir, options.pid ?? process.pid, at);
209
+ } catch {
210
+ // children then see a stale note and deny at once
211
+ }
212
+ }
213
+
214
+ function reply(entry: Entry, decision: ReplyDecision, reason?: ReplyReason): void {
215
+ try {
216
+ writeReply(dir, taken, entry.request.id, { decision, ...(reason !== undefined ? { reason } : {}) });
217
+ } catch {
218
+ // the child is gone or the mailbox unusable: its own timeout covers it
219
+ }
220
+ }
221
+
222
+ function emit(kind: EventKind, entry: Entry, verdict?: Verdict): void {
223
+ try {
224
+ options.onEvent({ kind, request: entry.request, ...(verdict !== undefined ? { verdict } : {}), waitMs: Math.max(0, now() - entry.receivedAt) });
225
+ } catch {
226
+ // telemetry must not break the mailbox
227
+ }
228
+ }
229
+
230
+ function forget(entry: Entry): void {
231
+ const at = queue.indexOf(entry);
232
+ if (at >= 0) queue.splice(at, 1);
233
+ if (open === entry) open = undefined;
234
+ }
235
+
236
+ /** Answer an entry that ended for a reason other than the user's answer. "ended" was answered by stop(). */
237
+ function settle(entry: Entry, why: Why): void {
238
+ if (why === "cancel") {
239
+ reply(entry, "cancelled");
240
+ emit("cancelled", entry);
241
+ } else if (why === "timeout") {
242
+ reply(entry, "deny", "timeout");
243
+ emit("timeout", entry);
244
+ } else if (why === "dropped") {
245
+ // nobody is left to read a reply
246
+ cleanup(dir, entry.request.id);
247
+ taken.delete(entry.request.id);
248
+ emit("dropped", entry);
249
+ }
250
+ }
251
+
252
+ /** End an entry that is not (or not only) the user's to answer. */
253
+ function end(entry: Entry, why: Why): void {
254
+ if (entry.why !== undefined) return;
255
+ entry.why = why;
256
+ if (open === entry) {
257
+ // its dialog closes; finish() settles it when the dialog returns
258
+ entry.controller?.abort();
259
+ return;
260
+ }
261
+ forget(entry);
262
+ settle(entry, why);
263
+ }
264
+
265
+ function enqueue(request: AskRequest): void {
266
+ const entry: Entry = { request, receivedAt: now() };
267
+ if (queue.length >= MAX_QUEUE) {
268
+ reply(entry, "deny", "rules");
269
+ emit("auto-deny", entry);
270
+ return;
271
+ }
272
+ queue.push(entry);
273
+ }
274
+
275
+ function judged(entry: Entry): Verdict {
276
+ let verdict: Verdict;
277
+ try {
278
+ verdict = options.judge(entry.request);
279
+ } catch {
280
+ verdict = { action: "deny", mode: "default", matcher: null }; // fail closed
281
+ }
282
+ if (verdict.claimed !== undefined && entry.clampNoted !== true) {
283
+ entry.clampNoted = true;
284
+ emit("clamped", entry, verdict);
285
+ }
286
+ return verdict;
287
+ }
288
+
289
+ function finish(entry: Entry, decision: "allow" | "deny"): void {
290
+ forget(entry);
291
+ if (entry.why !== undefined) settle(entry, entry.why);
292
+ else if (decision === "allow") reply(entry, "allow"); // the dialog logged the user's answer itself
293
+ else reply(entry, "deny", "user");
294
+ pump();
295
+ }
296
+
297
+ function openDialog(entry: Entry): void {
298
+ open = entry;
299
+ entry.controller = new AbortController();
300
+ options.attention();
301
+ let shown: Promise<"allow" | "deny">;
302
+ try {
303
+ shown = options.ask(entry.request, entry.controller.signal, entry.receivedAt);
304
+ } catch (error) {
305
+ shown = Promise.reject(error);
306
+ }
307
+ shown.then(
308
+ (decision) => finish(entry, decision),
309
+ () => finish(entry, "deny"), // a dialog that failed is no approval
310
+ );
311
+ }
312
+
313
+ /** Answer what the rules settle, then open the next dialog if the policy allows. Never throws. */
314
+ function pump(): void {
315
+ try {
316
+ settleAndOpen();
317
+ } catch {
318
+ // e.g. a stale context: the next poll tries again
319
+ }
320
+ }
321
+
322
+ function settleAndOpen(): void {
323
+ if (stopped) return;
324
+ const ui = options.hasUI();
325
+ for (const entry of [...queue]) {
326
+ if (entry === open) continue;
327
+ const verdict = judged(entry);
328
+ if (verdict.action === "allow") {
329
+ forget(entry);
330
+ reply(entry, "allow");
331
+ emit("auto-allow", entry, verdict);
332
+ } else if (verdict.action === "deny") {
333
+ forget(entry);
334
+ reply(entry, "deny", "rules");
335
+ emit("auto-deny", entry, verdict);
336
+ } else if (!ui) {
337
+ forget(entry);
338
+ reply(entry, "deny", "no-ui");
339
+ emit("no-ui", entry, verdict);
340
+ }
341
+ }
342
+ if (open === undefined && queue.length > 0 && !options.dialogBusy()) {
343
+ if (mayPopUp({ policy: options.popup(), forced, assumeIdle, idle: options.isIdle(), editorEmpty: options.editorEmpty() })) {
344
+ assumeIdle = false;
345
+ openDialog(queue[0]);
346
+ }
347
+ }
348
+ assumeIdle = false;
349
+ if (queue.length === 0) forced = false;
350
+ const waiting = queue.length - (open === undefined ? 0 : 1);
351
+ if (waiting !== shownBadge) {
352
+ shownBadge = waiting;
353
+ try {
354
+ options.badge(waiting);
355
+ } catch {
356
+ // a status line that cannot be set is not worth failing over
357
+ }
358
+ }
359
+ }
360
+
361
+ function tick(): void {
362
+ if (stopped) return;
363
+ countWork("askTick");
364
+ try {
365
+ const at = now();
366
+ const ttl = currentTtl();
367
+ sweepTtl = Math.max(sweepTtl, ttl); // never shrinks: a lowered setting must not sweep away a timeout reply the child has yet to read
368
+ beat(at);
369
+ // One check of the mailbox per pass: the three reads below would each re-walk the same
370
+ // directory chain. A refusal here is left to them, so their warnings stay what they were.
371
+ let mailbox: MailboxOptions = {};
372
+ try {
373
+ ensureAskDir(dir);
374
+ mailbox = { dirReady: true };
375
+ } catch {
376
+ // unusable: takeRequests reports it
377
+ }
378
+ const { requests, warnings } = takeRequests(dir, taken, at, mailbox);
379
+ for (const request of requests) enqueue(request);
380
+ for (const warning of warnings) {
381
+ if (warned.has(warning)) continue;
382
+ warned.add(warning);
383
+ options.warn?.(warning);
384
+ }
385
+ for (const id of readCancels(dir, mailbox)) {
386
+ const entry = queue.find((e) => e.request.id === id);
387
+ if (entry !== undefined) end(entry, "cancel");
388
+ }
389
+ for (const entry of [...queue]) {
390
+ if (entry.why !== undefined) continue;
391
+ if (!alive(entry.request.childPid)) end(entry, "dropped");
392
+ else if (at - entry.receivedAt >= ttl) end(entry, "timeout");
393
+ }
394
+ for (const id of sweep(dir, taken, at, sweepTtl + SWEEP_GRACE_MS, alive, mailbox)) {
395
+ const entry = queue.find((e) => e.request.id === id);
396
+ if (entry !== undefined) end(entry, "dropped");
397
+ }
398
+ pump();
399
+ } catch {
400
+ // one bad poll must not stop the next
401
+ }
402
+ }
403
+
404
+ const timer = (options.setTimer ?? defaultTimer)(tick, POLL_MS);
405
+ beat(now());
406
+
407
+ return {
408
+ tick,
409
+ runEnded() {
410
+ assumeIdle = true;
411
+ pump();
412
+ },
413
+ openNow() {
414
+ const waiting = queue.length;
415
+ if (waiting === 0) return 0;
416
+ forced = true;
417
+ pump();
418
+ return waiting;
419
+ },
420
+ pending: () => queue.length,
421
+ stop() {
422
+ if (stopped) return;
423
+ // one last look, so a request that just arrived is denied too and not left waiting
424
+ try {
425
+ for (const request of takeRequests(dir, taken, now()).requests) enqueue(request);
426
+ } catch {
427
+ // whatever was claimed is denied below
428
+ }
429
+ stopped = true;
430
+ timer.stop();
431
+ removeHeartbeat(dir);
432
+ const held = new Set(pendingIds(taken));
433
+ for (const entry of [...queue]) {
434
+ if (!held.has(entry.request.id)) continue;
435
+ entry.why = "ended";
436
+ reply(entry, "deny", "parent-session-ended");
437
+ emit("parent-gone", entry);
438
+ }
439
+ for (const entry of queue) entry.controller?.abort();
440
+ queue.length = 0;
441
+ open = undefined;
442
+ if (shownBadge !== 0) {
443
+ shownBadge = 0;
444
+ try {
445
+ options.badge(0);
446
+ } catch {
447
+ // the session is going away
448
+ }
449
+ }
450
+ },
451
+ };
452
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Terminal attention for dialogs: a BEL plus a desktop notification escape,
3
+ * so a backgrounded terminal tab gets noticed. The text is always a fixed
4
+ * label: command text and paths never leave the TUI.
5
+ */
6
+
7
+ /** Env var; `0` turns the notification off. */
8
+ export const BELL_ENV = "PI_KEEPER_BELL";
9
+
10
+ export type AttentionLabel = "pi: permission needed" | "pi: plan ready for approval" | "pi: rules need review";
11
+
12
+ /**
13
+ * The bytes to write, or "" when disabled. Kitty gets OSC 99, other
14
+ * terminals OSC 777 (Ghostty, iTerm2, WezTerm, rxvt-unicode), as in pi's
15
+ * notify.ts example; terminals that know neither ignore the sequence.
16
+ */
17
+ export function attentionSequence(label: AttentionLabel, env: NodeJS.ProcessEnv = process.env): string {
18
+ if (env[BELL_ENV] === "0") return "";
19
+ const notify =
20
+ env.KITTY_WINDOW_ID !== undefined && env.KITTY_WINDOW_ID !== ""
21
+ ? `\x1b]99;i=1:d=0;pi\x1b\\\x1b]99;i=1:p=body;${label}\x1b\\`
22
+ : `\x1b]777;notify;pi;${label}\x07`;
23
+ return `\x07${notify}`;
24
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Compatibility with pi-cc-extensions (an optional community package). It restyles
3
+ * every tool row and, while a tool runs, shows only "↳ Pending…", which hides
4
+ * pi-keeper's exit_plan_mode plan above the approval selector. The fix is to list
5
+ * "exit_plan_mode" in `excludeRenderers` of `<agent dir>/pi-cc-extensions.json`,
6
+ * keeping every other setting. At session start index.ts offers that edit in a dialog
7
+ * when the status is needs-fix, and scripts/exclude_exit_plan_mode.py does the same from a shell.
8
+ *
9
+ * Detection: pi reports the registered slash commands (pi.getCommands()), and
10
+ * pi-cc-extensions registers `/ccstyle`; the caller passes that as `loaded`. Without
11
+ * it, the package counts as present when `<agent dir>/settings.json` lists it or
12
+ * its settings file exists.
13
+ *
14
+ * Free of pi types so it is testable (like config.ts).
15
+ */
16
+
17
+ import { chmodSync, existsSync, readFileSync, statSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { writeFileAtomic } from "./secure-file.ts";
20
+
21
+ export const CC_SETTINGS_FILE = "pi-cc-extensions.json";
22
+ const CC_PACKAGE = "pi-cc-extensions";
23
+ /** The tool whose renderer pi-cc-extensions must leave alone. */
24
+ const PLAN_TOOL = "exit_plan_mode";
25
+
26
+ /**
27
+ * absent: not in use here. ok: the plan approval is shown. needs-fix: pi-cc-extensions is in
28
+ * use and hides the plan. unreadable: its settings file is there but cannot be used.
29
+ */
30
+ export type CcExtensionsStatus = "absent" | "ok" | "needs-fix" | "unreadable";
31
+
32
+ /** `<agent dir>/pi-cc-extensions.json`. */
33
+ export function ccSettingsPath(agentDir: string): string {
34
+ return join(agentDir, CC_SETTINGS_FILE);
35
+ }
36
+
37
+ /** True when `<agent dir>/settings.json` lists pi-cc-extensions as a package (a string or an object with `source`). */
38
+ function listedInSettings(agentDir: string): boolean {
39
+ try {
40
+ const parsed = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8")) as { packages?: unknown };
41
+ if (!Array.isArray(parsed.packages)) return false;
42
+ return parsed.packages.some((entry) => {
43
+ const source = typeof entry === "string" ? entry : (entry as { source?: unknown } | null)?.source;
44
+ return typeof source === "string" && source.includes(CC_PACKAGE);
45
+ });
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+
51
+ /** The status of pi-cc-extensions for this agent dir. `loaded`: pi reports its `/ccstyle` command. Never throws. */
52
+ export function ccExtensionsStatus(agentDir: string, loaded = false): CcExtensionsStatus {
53
+ const path = ccSettingsPath(agentDir);
54
+ const present = existsSync(path);
55
+ if (!loaded && !present && !listedInSettings(agentDir)) return "absent";
56
+ let value: unknown;
57
+ try {
58
+ value = JSON.parse(readFileSync(path, "utf8"));
59
+ } catch (error) {
60
+ // no file yet: the defaults, which hide the plan
61
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "needs-fix";
62
+ return "unreadable";
63
+ }
64
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return "unreadable";
65
+ const excluded = (value as { excludeRenderers?: unknown }).excludeRenderers;
66
+ if (excluded === undefined) return "needs-fix";
67
+ if (!Array.isArray(excluded)) return "unreadable";
68
+ return excluded.includes(PLAN_TOOL) ? "ok" : "needs-fix";
69
+ }
70
+
71
+ /**
72
+ * Add exit_plan_mode to `excludeRenderers` in the settings file (created when absent), keeping
73
+ * every other key. Idempotent. Returns the error text, or undefined when the file is now right.
74
+ * An unreadable file is refused and left as it is.
75
+ */
76
+ export function excludeExitPlanMode(agentDir: string): string | undefined {
77
+ const path = ccSettingsPath(agentDir);
78
+ let settings: Record<string, unknown> = {};
79
+ try {
80
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
81
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return `${path} does not hold a JSON object; fix it by hand`;
82
+ settings = parsed as Record<string, unknown>;
83
+ } catch (error) {
84
+ const code = (error as NodeJS.ErrnoException).code;
85
+ if (code !== "ENOENT") {
86
+ const reason = error instanceof SyntaxError ? "not valid JSON" : error instanceof Error ? error.message : String(error);
87
+ return `Could not read ${path}: ${reason}`;
88
+ }
89
+ }
90
+ const excluded: unknown = settings.excludeRenderers ?? [];
91
+ if (!Array.isArray(excluded)) return `excludeRenderers in ${path} is not a list; fix it by hand`;
92
+ if (excluded.includes(PLAN_TOOL)) return undefined;
93
+ settings.excludeRenderers = [...excluded, PLAN_TOOL];
94
+ try {
95
+ // another package's file: keep its permissions (writeFileAtomic creates files 0600)
96
+ const mode = existsSync(path) ? statSync(path).mode & 0o777 : undefined;
97
+ writeFileAtomic(path, `${JSON.stringify(settings, null, 2)}\n`);
98
+ if (mode !== undefined) chmodSync(path, mode);
99
+ } catch (error) {
100
+ return `Could not write ${path}: ${error instanceof Error ? error.message : String(error)}`;
101
+ }
102
+ return undefined;
103
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Entry point pi-subagents loads in children of a parent in auto mode with the
3
+ * `/keeper` setting enabled (registered by subagents-bridge.ts). Not
4
+ * listed in package.json: pi must not load it itself.
5
+ *
6
+ * Auto where the child's asks can reach the parent's user: a foreground child
7
+ * runs in the parent's process and finds its UI relay; a background child
8
+ * (async: true) is a separate process with no relay, but with background asks
9
+ * on (the default) it files its asks in the parent's mailbox, so it runs auto
10
+ * too. Without a way to ask, a relay-less child falls back to default mode,
11
+ * exactly as before background asks existed, unless the `/keeper`
12
+ * setting `background-auto-fallback` opts it into auto: edits and commands inside the
13
+ * project run unasked, while dangerous commands, secrets and protected paths
14
+ * still ask (and are denied, fail-closed). The choice is relaylessChildMode.
15
+ */
16
+
17
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
19
+ import keeperExtension from "./index.ts";
20
+ import { loadConfig } from "./config.ts";
21
+ import { canAskParent } from "./remote-relay.ts";
22
+ import { relaylessChildMode } from "./subagents-bridge.ts";
23
+ import { findUiRelay } from "./ui-relay.ts";
24
+
25
+ export default function childAuto(pi: ExtensionAPI): void {
26
+ let childMode: "default" | "auto" = "auto";
27
+ if (findUiRelay() === undefined) {
28
+ const config = loadConfig(getAgentDir());
29
+ childMode = relaylessChildMode("auto", { backgroundAsks: canAskParent(config, getAgentDir()), backgroundAutoFallback: config.backgroundAutoFallback });
30
+ }
31
+ keeperExtension(pi, { childMode });
32
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Where a subagent child may work. Every "inside the working directory" rule
3
+ * trusts the session cwd, and a child's cwd is whatever the parent model put
4
+ * in the subagent call: `cwd: "/"` made the whole disk "inside" (seen in a
5
+ * real run). A child therefore checks its cwd against its parent's project
6
+ * (shared through the UI relay or the background grant snapshot) and refuses
7
+ * a root no session should have. A child whose cwd fails is locked down
8
+ * (index.ts): every call is denied except contact_supervisor and its report.
9
+ *
10
+ * Accepted:
11
+ * - inside the parent's cwd, or inside the parent's project root (the nearest
12
+ * ancestor with .git: a parent started in a subdirectory may launch at the
13
+ * repository root);
14
+ * - a linked git worktree of the parent's repository (pi-subagents'
15
+ * `worktree: true` runs live beside the checkout, in
16
+ * `<repo parent>/worktrees/<project>/pi-worktree-*`): its `.git` file
17
+ * points into `<parent root>/.git/worktrees/`.
18
+ * Refused even without parent information: "/", the home directory and its
19
+ * ancestors.
20
+ *
21
+ * Free of pi types so it is testable (like config.ts).
22
+ */
23
+
24
+ import { readFileSync, realpathSync, statSync } from "node:fs";
25
+ import { homedir } from "node:os";
26
+ import { join, resolve, sep } from "node:path";
27
+ import { findProjectRoot } from "./project-rules.ts";
28
+
29
+ function real(path: string): string {
30
+ try {
31
+ return realpathSync(path);
32
+ } catch {
33
+ return resolve(path);
34
+ }
35
+ }
36
+
37
+ function inside(path: string, dir: string): boolean {
38
+ return path === dir || path.startsWith(dir.endsWith(sep) ? dir : `${dir}${sep}`);
39
+ }
40
+
41
+ /** The repository a linked worktree belongs to: `<main>/.git/worktrees/<name>` from its `.git` file, else undefined. */
42
+ function worktreeGitDir(dir: string): string | undefined {
43
+ const root = findProjectRoot(dir);
44
+ const marker = join(root, ".git");
45
+ try {
46
+ if (!statSync(marker).isFile()) return undefined;
47
+ const m = /^gitdir:\s*(.+)\s*$/m.exec(readFileSync(marker, "utf8"));
48
+ return m === null ? undefined : real(resolve(root, m[1].trim()));
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Why a child may not work in `childCwd`, or undefined when it may.
56
+ * `parentCwd` is undefined when the parent is unknown: then only the
57
+ * root/home check applies, unless `parentExpected` (the env names a parent
58
+ * session and the child runs in auto), where the cwd cannot be checked and
59
+ * the child fails closed.
60
+ */
61
+ export function childCwdProblem(childCwd: string, parentCwd: string | undefined, home: string = homedir(), parentExpected = false): string | undefined {
62
+ const cwd = real(childCwd);
63
+ const realHome = real(home);
64
+ if (cwd === sep || cwd === realHome || inside(realHome, cwd)) {
65
+ return `your working directory ${cwd} is / or the home directory (or above it), which would put every file "inside" it`;
66
+ }
67
+ if (parentCwd === undefined) {
68
+ return parentExpected ? `your working directory ${cwd} cannot be checked because the parent session's grants could not be read` : undefined;
69
+ }
70
+ const parent = real(parentCwd);
71
+ const parentRoot = real(findProjectRoot(parent));
72
+ if (inside(cwd, parent) || inside(cwd, parentRoot)) return undefined;
73
+ const gitDir = worktreeGitDir(cwd);
74
+ if (gitDir !== undefined && inside(gitDir, join(parentRoot, ".git", "worktrees"))) return undefined;
75
+ return `your working directory ${cwd} is outside the parent session's project (${parentRoot})`;
76
+ }