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,32 @@
1
+ /**
2
+ * Entry point pi-subagents loads in children of a parent in default or auto mode
3
+ * (registered by subagents-bridge.ts). Not listed in package.json: pi must
4
+ * not load it itself.
5
+ *
6
+ * A foreground child runs in the parent's process and finds its UI relay, so
7
+ * default mode works: its asks reach the parent's user. A background child
8
+ * (`async: true`) is a separate process with no relay; with background asks
9
+ * on (the default) its asks reach the parent's user through the mailbox, so
10
+ * it stays in default mode too. Without a way to ask, its asks would be
11
+ * denied; the `/keeper` setting `background-auto-fallback` then runs such a
12
+ * relay-less child in auto mode instead: edits and commands inside the project
13
+ * run unasked, while dangerous commands, secrets and protected paths still ask
14
+ * (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 childDefault(pi: ExtensionAPI): void {
26
+ let childMode: "default" | "auto" = "default";
27
+ if (findUiRelay() === undefined) {
28
+ const config = loadConfig(getAgentDir());
29
+ childMode = relaylessChildMode("default", { backgroundAsks: canAskParent(config, getAgentDir()), backgroundAutoFallback: config.backgroundAutoFallback });
30
+ }
31
+ keeperExtension(pi, { childMode });
32
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The lane line: a short, concrete statement of what THIS subagent child can
3
+ * and cannot do, appended to the child prompt (index.ts, before_agent_start).
4
+ *
5
+ * The split, locked by tests/unit/child-prompts.test.ts and
6
+ * tests/integration/child-lanes.test.ts:
7
+ * - the child prompt (prompts/child-<mode>.md) holds only what is true in
8
+ * every lane of its mode: what runs freely and which actions are gated;
9
+ * - this line holds everything that depends on the relay or the tools: what
10
+ * happens to a gated action (asked through the parent's user, by relay or
11
+ * by the parent's mailbox for a background child, or denied),
12
+ * the retry guidance, and the mutation tools the child actually has.
13
+ * The deny messages (ask() without a relay, denyReason for a child) reuse the
14
+ * same lane names and phrases, so a denial reads like the lane line made
15
+ * specific to one call, and the model stops after one attempt instead of
16
+ * probing edit -> bash -> write -> path variants.
17
+ *
18
+ * Free of pi types so it is testable (like config.ts).
19
+ */
20
+
21
+ import type { ChildMode } from "./modes.ts";
22
+
23
+ /** Tools that change things; the lane line names the ones the child has. */
24
+ const MUTATION_TOOLS = ["edit", "write", "bash", "powershell"] as const;
25
+
26
+ export interface LaneOptions {
27
+ /** The child's effective mode (already resolved: child-auto.ts / child-default.ts may have picked it). */
28
+ readonly mode: ChildMode;
29
+ /** Whether the child's asks can reach the parent's user through a UI relay (a foreground child). */
30
+ readonly relay: boolean;
31
+ /** Whether a relay-less (background) child files its asks in the parent's mailbox instead (ask-mailbox.ts). Default false. */
32
+ readonly parentAsks?: boolean;
33
+ /** The tools active in the child session (pi.getActiveTools()). */
34
+ readonly activeTools: readonly string[];
35
+ }
36
+
37
+ /** The mutation tools the child actually has, in a stable order. */
38
+ export function mutationToolsOf(activeTools: readonly string[]): string[] {
39
+ return MUTATION_TOOLS.filter((tool) => activeTools.includes(tool));
40
+ }
41
+
42
+ /** "edit, write and bash" / "edit and write" / "edit" — named tools for the deny sentences. */
43
+ function listNames(names: readonly string[]): string {
44
+ if (names.length <= 1) return names[0] ?? "";
45
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
46
+ }
47
+
48
+ /** The lane name, shared by the lane line and the deny messages. */
49
+ export function childLaneName(mode: ChildMode, relay: boolean, parentAsks = false): string {
50
+ if (mode === "plan") return "read-only plan child";
51
+ if (relay) return `${mode} child with a relay`;
52
+ return parentAsks ? `${mode} background child` : `${mode} child with no relay`;
53
+ }
54
+
55
+ /** How a denied action is escalated: report or contact_supervisor (never a retry, never a probe). */
56
+ const ESCALATION =
57
+ 'Put what you needed in your final report, or ask the parent with contact_supervisor (reason "need_decision") if it is available.';
58
+
59
+ /** "do not probe" — the sentence that stops edit -> bash -> write -> path probing after a denial. */
60
+ const NO_PROBE = "do not retry, and do not probe another tool or another path, the gate is the same for all of them";
61
+
62
+ /** What a relayed rejection means: the relay lanes' counterpart of NO_PROBE. */
63
+ const REJECTED = "The user may approve or decline each ask. If an ask is rejected, do not retry it or probe variants; if the rejection has a note, follow the note, otherwise continue without that call.";
64
+
65
+ /** The same for a background child: no note comes back, and an ask nobody answers in time is denied. */
66
+ const DECLINED = "The user may approve or decline each ask. If one is declined or goes unanswered, continue without that call: do not retry it or probe variants, and say in your report what you skipped.";
67
+
68
+ /**
69
+ * The lane line for a subagent child, or "" when the inputs say nothing
70
+ * (a mode with no tools that change anything still gets its read-only lane).
71
+ */
72
+ export function childLaneLine({ mode, relay, parentAsks = false, activeTools }: LaneOptions): string {
73
+ const relayed = relay || parentAsks;
74
+ const outcome = relay ? REJECTED : DECLINED;
75
+ const name = childLaneName(mode, relay, parentAsks);
76
+ const tools = mutationToolsOf(activeTools);
77
+ const writeTools = tools.filter((tool) => tool === "edit" || tool === "write");
78
+ const shellTools = tools.filter((tool) => tool === "bash" || tool === "powershell");
79
+ const shell = shellTools[0] ?? "commands";
80
+ const writesLine =
81
+ writeTools.length > 0
82
+ ? `File edits and writes (${listNames(writeTools)}) are denied everywhere except the scratch dir named below and your own report artifact.`
83
+ : "You have no file-writing tools.";
84
+
85
+ if (mode === "plan") {
86
+ const asks = relayed
87
+ ? `Non-read-only ${shell}, first reads outside the working directory and secrets ask, relayed to the parent's user, who is told to approve only what gathers context for the plan. ${outcome}`
88
+ : `Non-read-only ${shell}, first reads outside the working directory and secrets are denied too (no interactive user): ${NO_PROBE}. ${ESCALATION}`;
89
+ return `Your lane: ${name}. Reading, searching and read-only ${shell} run freely. ${writesLine} ${asks}`;
90
+ }
91
+
92
+ if (mode === "default") {
93
+ if (relayed) {
94
+ return `Your lane: ${name}. Mutations, secrets and first reads outside the working directory ask first: the permission dialog is relayed to the parent's user, exactly as if the parent had called the tool. ${outcome} What runs without asking: reading, searching, read-only ${shell}, project-allowed commands, session-remembered prefixes, the scratch dir named below and your own report artifact. Name files from the working directory instead of \`cd\`-ing into it; for a second tree ask once for its directory, and that answer covers every command in it.`;
95
+ }
96
+ const mutations =
97
+ writeTools.length > 0 && shellTools.length > 0
98
+ ? `Every mutation — ${writeTools.join(", ")} and non-read-only ${shell} — is denied, for every path: ${NO_PROBE}.`
99
+ : writeTools.length > 0 || shellTools.length > 0
100
+ ? `Every mutation (${writeTools.length > 0 ? listNames(writeTools) : `non-read-only ${shell}`}) is denied, for every path: ${NO_PROBE}.`
101
+ : "";
102
+ const opening = [`Your lane: ${name}.`, mutations].filter((part) => part !== "").join(" ");
103
+ const reads = mutations === ""
104
+ ? "First reads outside the working directory and secrets are denied: do not retry them."
105
+ : "First reads outside the working directory and secrets are denied too.";
106
+ return `${opening} ${reads} What still runs: reading, searching, read-only ${shell}, project-allowed commands, the scratch dir named below and your own report artifact. Stage deliverables in the scratch dir and list them in your report. ${ESCALATION}`;
107
+ }
108
+
109
+ // auto
110
+ const guarded = relayed
111
+ ? "Dangerous commands, secrets, protected paths (.git, .pi, shell rc files, tool configuration), writes and destructive commands outside the working directory, and first reads outside it still ask, relayed to the parent's user. " + outcome
112
+ : `Dangerous commands, secrets, protected paths (.git, .pi, shell rc files, tool configuration), writes and destructive commands outside the working directory, and first reads outside it are denied instead (fail-closed): do not retry, and do not probe variants, the gate is the same for all of them. ${ESCALATION}`;
113
+ return `Your lane: ${name}. Edits and commands inside the working directory run without asking — inside it, deleting and overwriting has no undo. ${guarded}`;
114
+ }
115
+
116
+ /**
117
+ * The one-sentence parent hint: what the children this session can launch
118
+ * can and cannot do, appended to the parent's mode prompt when the subagent
119
+ * tool is active. Kept to a single sentence per mode so it never bloats the
120
+ * prompt; the lane line carries the details inside each child.
121
+ */
122
+ export function parentLaneHint(mode: "plan" | "default" | "auto", backgroundAutoFallback: boolean, backgroundAsks = false): string {
123
+ // One sentence on purpose (a test pins the single period): what a child may do, then how to fan out.
124
+ const fanOut = 'for a scripted fan-out pass the source inline as `options: { script: "…" }` — a fenced ```js workflow block is dropped once the reply has already made a tool call';
125
+ if (mode === "plan") {
126
+ return `Subagents you launch stay read-only like you (scout = explorer, worker = implementer), whatever tools their agent lists; their findings come back in their reports, and ${fanOut}.`;
127
+ }
128
+ const background = backgroundAsks
129
+ ? "background (async) children ask the user through this session like foreground ones, so a gated call may wait for an answer"
130
+ : backgroundAutoFallback
131
+ ? "background (async) children run in the auto lane and can write inside this directory"
132
+ : "background (async) children have every mutation denied (no relay): they stage work in their scratch dir and report it, so copy it in yourself or launch them foreground";
133
+ return `Subagents you launch: scout = explorer, worker = implementer, reviewer = checker; each runs in its lane below whatever tools its agent lists, and ${background}; ${fanOut}.`;
134
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Entry point pi-subagents loads in children of a parent in plan mode
3
+ * (registered by subagents-bridge.ts). Not listed in package.json: pi must
4
+ * not load it itself.
5
+ */
6
+
7
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
+ import keeperExtension from "./index.ts";
9
+
10
+ export default function childPlan(pi: ExtensionAPI): void {
11
+ keeperExtension(pi, { childMode: "plan" });
12
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * User-level settings for pi-keeper, read from
3
+ * `<agent dir>/pi-keeper.json` (the same place pi-cc-extensions keeps
4
+ * its settings file):
5
+ *
6
+ * { "readOnlyTools": ["web_search", "fetch_content"],
7
+ * "subagentsFollowAuto": true }
8
+ *
9
+ * `readOnlyTools` names tools from other packages that only read: they run
10
+ * without a dialog in default mode and are allowed while planning. Global
11
+ * only, never read from the project: a cloned repository must not be able to
12
+ * grant itself tools. Names are exact (no wildcards). The shell and file
13
+ * writers, `exit_plan_mode`, and the two tools that front other tools (`mcp`
14
+ * runs any MCP sub-tool, `subagent` launches agents) can never be listed:
15
+ * they are rejected here with a warning, and rules.ts ignores them whatever
16
+ * this says.
17
+ *
18
+ * `subagentsFollowAuto` (default false) lets subagents of an auto-mode parent run in
19
+ * auto mode too, as long as their permission asks can reach the user; `/keeper`
20
+ * toggles it and saves it here.
21
+ * `projectExactCommands` (default false) adds "Yes, and always allow this exact
22
+ * command in this project" to the approval dialog for commands no prefix
23
+ * can cover, saved to the project's .pi/settings.local.json; `/keeper` toggles it and saves it here.
24
+ * `backgroundAutoFallback` (default false) lets children whose asks cannot reach a
25
+ * user (background asks off, or a parent without a UI, which writes no
26
+ * heartbeat so its children fall back at launch) run in auto mode
27
+ * instead of having every ask denied; `/keeper` toggles it and saves
28
+ * it here.
29
+ * `backgroundAsks` (default true) sends the permission asks of background
30
+ * subagents to this session's user instead of denying them; with it on, a
31
+ * background child follows its parent's mode (an auto parent with
32
+ * `subagentsFollowAuto` gives auto) and `backgroundAutoFallback` only matters when it is
33
+ * off. `backgroundAskTimeoutMs` (default 300000, 10 s to 30 min) is how long a
34
+ * background child waits for the answer before its ask is denied. The env var
35
+ * PI_KEEPER_BACKGROUND_ASKS=0 switches the feature off for a process.
36
+ * `modeInstructions` (default "message") says where the mode rules go: "message"
37
+ * appends them to the conversation when they change, which keeps the system
38
+ * prompt constant (a changed prompt flushes the prompt cache and, behind some
39
+ * gateways, fails every later request of a session with signed thinking);
40
+ * "prompt" is the old behaviour of appending them to the system prompt, for
41
+ * small local models that follow prompt rules better. Written by
42
+ * hand only — `/keeper` has no entry for it yet.
43
+ * `modeFlashSecs` (default 2; 0 turns it off, otherwise 0.1 to 10) is how long the
44
+ * mode (icon and badge, in the mode's color) shows above the prompt after a real
45
+ * switch; it adds no permanent row. Set by the `/keeper` panel (off, 1, 2, 3 or 5 s) or by hand.
46
+ * `backgroundAskPopup` (default "always") says when a permission ask from a
47
+ * background subagent opens its dialog in this session: "always" as soon as no
48
+ * other dialog is open, "idle" only when the session is idle and the editor is
49
+ * empty (otherwise a status badge and `/approvals`), "badge" only through
50
+ * `/approvals`. `/keeper` sets it, and `backgroundAskTimeoutMs`, and saves them here.
51
+ * `ccExtensionsPrompt` (default true) says whether the session-start dialog about
52
+ * pi-cc-extensions (see cc-extensions-compat.ts) may open. "Don't ask again" in that dialog
53
+ * sets it to false; it is not in `/keeper`.
54
+ * `commandColors` is how the permission dialog paints a long bash command, under its
55
+ * "full command" label: the theme slots "dim", "muted" or "text", or one of the two
56
+ * syntax values. Unset (the default) means "shell-highlight" when `pi-shell-highlight`
57
+ * is loaded and "dim" when it is not, resolved each time a dialog opens (see
58
+ * `effectiveCommandColors`). "builtin-syntax" is pi's own highlighter — strings,
59
+ * variables, keywords and comments in the theme's syntax colors, the same one the
60
+ * transcript uses for fenced code; it cannot color the name of an external command, and
61
+ * it paints a heredoc body as one string. "shell-highlight" asks `pi-shell-highlight`
62
+ * for a richer renderer (command names, and the inner language of a heredoc); set
63
+ * explicitly without that package it means "dim". A theme's `dim` is often
64
+ * only just readable on a dark background (obsidian-harbor's slate sits at 4.4:1), so a
65
+ * long command reads better as "muted" or as one of the syntax values. A diff preview
66
+ * keeps its added/removed colors. Set by the `/keeper` panel (section "Dialog")
67
+ * and by hand; read once at session start, and live again when the panel changes it.
68
+ * `subagentThinking` (default "follow") decides a child's thinking level.
69
+ * "role" keeps what the agent file (or a launch) asked for; "follow" runs the
70
+ * child at the higher of its own level and this session's current one, so a
71
+ * parent that goes to high lifts its children without touching a role file.
72
+ * `/keeper` sets it and saves it here.
73
+ * Free of pi types so it is testable.
74
+ */
75
+
76
+ import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
77
+ import { join } from "node:path";
78
+ import { isSubagentThinkingMode, type SubagentThinkingMode } from "./thinking.ts";
79
+
80
+ export const CONFIG_FILE = "pi-keeper.json";
81
+
82
+ /** Env kill switch for background asks: "0" in the environment of the parent or the child turns them off. */
83
+ export const BACKGROUND_ASKS_ENV = "PI_KEEPER_BACKGROUND_ASKS";
84
+
85
+ /** How long a background child waits for the parent's answer: default and bounds (ms). */
86
+ export const DEFAULT_BACKGROUND_ASK_TIMEOUT_MS = 300_000;
87
+ export const MIN_BACKGROUND_ASK_TIMEOUT_MS = 10_000;
88
+ export const MAX_BACKGROUND_ASK_TIMEOUT_MS = 30 * 60_000;
89
+
90
+ /** How long the mode line stays above the prompt after a switch: default and bounds (seconds); 0 turns it off. */
91
+ export const DEFAULT_MODE_FLASH_SECS = 2;
92
+ export const MIN_MODE_FLASH_SECS = 0.1;
93
+ export const MAX_MODE_FLASH_SECS = 10;
94
+
95
+ /**
96
+ * Read-only tools of the packages in use (web access, code overview, LSP, ast
97
+ * search, MCP resources) when the file doesn't say. `bg_wait` (pi-subagents)
98
+ * only waits for background runs the session launched; asking for it gated
99
+ * waiting on your own subagent. `todo` (rpiv-todo) only records the plan in the
100
+ * transcript: it changes no file and runs nothing, so it is allowed in every
101
+ * mode. The MCP resource tools are listed while `mcp` is not: `mcp` runs any
102
+ * MCP sub-tool, these three only read what a server already offers.
103
+ * `lsp_rename` is deliberately absent — it only previews a rename today, but
104
+ * the name promises a write, and this list fails closed on such names (a user
105
+ * can still add it by hand).
106
+ */
107
+ export const DEFAULT_READ_ONLY_TOOLS: readonly string[] = [
108
+ "web_search", "fetch_content", "get_search_content", "source_check", "code_overview",
109
+ "lsp_diagnostics", "lsp_hover", "lsp_definition", "lsp_references", "lsp_symbols", "lsp_code_actions", "lsp_completions",
110
+ "ast_search", "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource",
111
+ "bg_wait", "todo",
112
+ ];
113
+
114
+ /** When a background subagent's ask opens a dialog (see the header). */
115
+ export type BackgroundAskPopup = "idle" | "always" | "badge";
116
+
117
+ /** Theme slot for the full-command text in the permission dialog, or a syntax renderer (see the header). */
118
+ export type PreviewTextColor = "dim" | "muted" | "text" | "builtin-syntax" | "shell-highlight";
119
+
120
+ export const PREVIEW_TEXT_COLORS: readonly PreviewTextColor[] = ["dim", "muted", "text", "builtin-syntax", "shell-highlight"];
121
+
122
+ /** The plain theme slot the command is painted in when no highlighter is loaded. */
123
+ export const DEFAULT_PREVIEW_TEXT_COLOR: PreviewTextColor = "dim";
124
+
125
+ /**
126
+ * The color a command is painted with. An unset value (undefined) is "shell-highlight" when
127
+ * the highlighter is loaded, else "dim". An explicit "shell-highlight" without it is "dim";
128
+ * every other explicit value is kept.
129
+ */
130
+ export function effectiveCommandColors(configured: PreviewTextColor | undefined, highlighterAvailable: boolean): PreviewTextColor {
131
+ if (configured === undefined) return highlighterAvailable ? "shell-highlight" : DEFAULT_PREVIEW_TEXT_COLOR;
132
+ if (configured === "shell-highlight" && !highlighterAvailable) return DEFAULT_PREVIEW_TEXT_COLOR;
133
+ return configured;
134
+ }
135
+
136
+ export const POPUP_MODES: readonly string[] = ["idle", "always", "badge"];
137
+
138
+ export interface KeeperConfig {
139
+ readOnlyTools: ReadonlySet<string>;
140
+ /** Subagents of an auto-mode parent run in auto mode too, while their asks can reach the user (the `/keeper` setting). Default false. */
141
+ subagentsFollowAuto: boolean;
142
+ /** Exact-command dialogs offer a persistent project rule (the `/keeper` setting). Default false. */
143
+ projectExactCommands: boolean;
144
+ /** Relay-less (background) children run in auto mode instead of being denied (the `/keeper` setting). Default false. */
145
+ backgroundAutoFallback: boolean;
146
+ /** Command dialogs offer "always allow <prefix> in this project" (the `/keeper` setting). Default true. */
147
+ projectCommandApprovals: boolean;
148
+ /** The session-start dialog about pi-cc-extensions may open (set by its "Don't ask again"). Default true. */
149
+ ccExtensionsPrompt: boolean;
150
+ /** Where the mode rules go: a message in the conversation, or (old behaviour) the system prompt. */
151
+ modeInstructions: "message" | "prompt";
152
+ /** Seconds the mode line shows above the prompt after a switch; 0 = off (also hides the mode in the working row). Default 2. */
153
+ modeFlashSecs: number;
154
+ /** Outside-read dialogs offer "always allow reading from <dir>/ in this project" (the `/keeper` setting). Default false: read grants stay session-only. */
155
+ projectReadApprovals: boolean;
156
+ /** Background subagents' asks reach this session's user instead of being denied (the `/keeper` setting). Default true. */
157
+ backgroundAsks: boolean;
158
+ /** How long a background child waits for the answer, in ms (10 s to 30 min). Default 300000. */
159
+ backgroundAskTimeoutMs: number;
160
+ /** When a background subagent's ask opens its dialog here. Default "always". */
161
+ backgroundAskPopup: BackgroundAskPopup;
162
+ /** A child's thinking level: its own ("role") or the higher of its own and the parent's ("follow"). Default "follow". */
163
+ subagentThinking: SubagentThinkingMode;
164
+ /** Theme slot for the full-command text in the permission dialog, or a syntax renderer. Undefined when unset: see `effectiveCommandColors`. */
165
+ commandColors: PreviewTextColor | undefined;
166
+ /** One line per problem (unreadable file, wrong shape, rejected name); empty when the file is fine or absent. */
167
+ warnings: string[];
168
+ }
169
+
170
+ /** Tools a user cannot list: they write, or they front tools whose own behaviour the name hides. */
171
+ export const UNLISTABLE_TOOLS: ReadonlySet<string> = new Set(["bash", "powershell", "edit", "write", "exit_plan_mode", "mcp", "subagent", "subagent_launch"]);
172
+
173
+ /** Tool names are plain identifiers (letters, digits, `_`, `-`, `.`, `:`). */
174
+ const TOOL_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/;
175
+
176
+ /** Parse the file's text; defaults plus a warning on anything unusable. */
177
+ export function parseConfig(text: string): KeeperConfig {
178
+ const warnings: string[] = [];
179
+ let value: unknown;
180
+ try {
181
+ value = JSON.parse(text);
182
+ } catch (error) {
183
+ return fallback([`not valid JSON (${error instanceof Error ? error.message : String(error)}); using the defaults`]);
184
+ }
185
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
186
+ return fallback(["does not hold a JSON object; using the defaults"]);
187
+ }
188
+ const listed = (value as { readOnlyTools?: unknown }).readOnlyTools;
189
+ if (listed !== undefined && !Array.isArray(listed)) warnings.push("readOnlyTools must be a list of tool names; using the defaults");
190
+ const names = new Set<string>();
191
+ if (Array.isArray(listed)) {
192
+ for (const entry of listed) {
193
+ if (typeof entry === "string" && UNLISTABLE_TOOLS.has(entry)) warnings.push(`readOnlyTools: ignored "${entry}" (it can run or change things, so it can't be listed)`);
194
+ else if (typeof entry === "string" && TOOL_NAME.test(entry)) names.add(entry);
195
+ else warnings.push(`readOnlyTools: ignored ${JSON.stringify(entry)} (not a plain tool name)`);
196
+ }
197
+ }
198
+ let subagentsFollowAuto = false;
199
+ const rawAuto = (value as { subagentsFollowAuto?: unknown }).subagentsFollowAuto;
200
+ if (typeof rawAuto === "boolean") subagentsFollowAuto = rawAuto;
201
+ else if (rawAuto !== undefined) warnings.push("subagentsFollowAuto must be true or false; using false");
202
+ let projectExactCommands = false;
203
+ const rawExact = (value as { projectExactCommands?: unknown }).projectExactCommands;
204
+ if (typeof rawExact === "boolean") projectExactCommands = rawExact;
205
+ else if (rawExact !== undefined) warnings.push("projectExactCommands must be true or false; using false");
206
+ let backgroundAutoFallback = false;
207
+ const rawHeadless = (value as { backgroundAutoFallback?: unknown }).backgroundAutoFallback;
208
+ if (typeof rawHeadless === "boolean") backgroundAutoFallback = rawHeadless;
209
+ else if (rawHeadless !== undefined) warnings.push("backgroundAutoFallback must be true or false; using false");
210
+ const flag = (key: "projectCommandApprovals" | "projectReadApprovals" | "backgroundAsks" | "ccExtensionsPrompt", fallbackValue: boolean): boolean => {
211
+ const raw = (value as Record<string, unknown>)[key];
212
+ if (typeof raw === "boolean") return raw;
213
+ if (raw !== undefined) warnings.push(`${key} must be true or false; using ${fallbackValue}`);
214
+ return fallbackValue;
215
+ };
216
+ const projectCommandApprovals = flag("projectCommandApprovals", true);
217
+ const projectReadApprovals = flag("projectReadApprovals", false);
218
+ const ccExtensionsPrompt = flag("ccExtensionsPrompt", true);
219
+ let modeInstructions: "message" | "prompt" = "message";
220
+ const rawInstructions = (value as { modeInstructions?: unknown }).modeInstructions;
221
+ if (rawInstructions === "prompt") modeInstructions = "prompt";
222
+ else if (rawInstructions !== undefined && rawInstructions !== "message") warnings.push('modeInstructions must be "message" or "prompt"; using "message"');
223
+ let modeFlashSecs = DEFAULT_MODE_FLASH_SECS;
224
+ const rawFlash = (value as { modeFlashSecs?: unknown }).modeFlashSecs;
225
+ if (typeof rawFlash === "number" && Number.isFinite(rawFlash)) {
226
+ modeFlashSecs = rawFlash === 0 ? 0 : Math.min(MAX_MODE_FLASH_SECS, Math.max(MIN_MODE_FLASH_SECS, rawFlash));
227
+ if (modeFlashSecs !== rawFlash) warnings.push(`modeFlashSecs must be 0 (off) or between ${MIN_MODE_FLASH_SECS} and ${MAX_MODE_FLASH_SECS}; using ${modeFlashSecs}`);
228
+ } else if (rawFlash !== undefined) warnings.push(`modeFlashSecs must be a number of seconds; using ${DEFAULT_MODE_FLASH_SECS}`);
229
+ let backgroundAskPopup: BackgroundAskPopup = "always";
230
+ const rawPopup = (value as { backgroundAskPopup?: unknown }).backgroundAskPopup;
231
+ if (typeof rawPopup === "string" && POPUP_MODES.includes(rawPopup)) backgroundAskPopup = rawPopup as BackgroundAskPopup;
232
+ else if (rawPopup !== undefined) warnings.push('backgroundAskPopup must be "idle", "always" or "badge"; using "always"');
233
+ const backgroundAsks = flag("backgroundAsks", true);
234
+ let subagentThinking: SubagentThinkingMode = "follow";
235
+ const rawThinking = (value as { subagentThinking?: unknown }).subagentThinking;
236
+ if (isSubagentThinkingMode(rawThinking)) subagentThinking = rawThinking;
237
+ else if (rawThinking !== undefined) warnings.push('subagentThinking must be "follow" or "role"; using "follow"');
238
+ let commandColors: PreviewTextColor | undefined;
239
+ const rawPreviewColor = (value as { commandColors?: unknown }).commandColors;
240
+ if (typeof rawPreviewColor === "string" && (PREVIEW_TEXT_COLORS as readonly string[]).includes(rawPreviewColor)) commandColors = rawPreviewColor as PreviewTextColor;
241
+ else if (rawPreviewColor !== undefined) warnings.push(`commandColors must be "dim", "muted", "text", "builtin-syntax" or "shell-highlight"; using the default`);
242
+ let backgroundAskTimeoutMs = DEFAULT_BACKGROUND_ASK_TIMEOUT_MS;
243
+ const rawTimeout = (value as { backgroundAskTimeoutMs?: unknown }).backgroundAskTimeoutMs;
244
+ if (typeof rawTimeout === "number" && Number.isFinite(rawTimeout)) {
245
+ backgroundAskTimeoutMs = Math.min(MAX_BACKGROUND_ASK_TIMEOUT_MS, Math.max(MIN_BACKGROUND_ASK_TIMEOUT_MS, Math.round(rawTimeout)));
246
+ if (backgroundAskTimeoutMs !== rawTimeout) warnings.push(`backgroundAskTimeoutMs must be between ${MIN_BACKGROUND_ASK_TIMEOUT_MS} and ${MAX_BACKGROUND_ASK_TIMEOUT_MS}; using ${backgroundAskTimeoutMs}`);
247
+ } else if (rawTimeout !== undefined) warnings.push(`backgroundAskTimeoutMs must be a number of milliseconds; using ${DEFAULT_BACKGROUND_ASK_TIMEOUT_MS}`);
248
+ // readOnlyTools absent or unusable: the defaults; a valid list (empty included) replaces them
249
+ return { readOnlyTools: Array.isArray(listed) ? names : new Set(DEFAULT_READ_ONLY_TOOLS), subagentsFollowAuto, projectExactCommands, backgroundAutoFallback, projectCommandApprovals, projectReadApprovals, ccExtensionsPrompt, modeInstructions, modeFlashSecs, backgroundAsks, backgroundAskTimeoutMs, backgroundAskPopup, subagentThinking, commandColors, warnings };
250
+ }
251
+
252
+ function fallback(warnings: string[]): KeeperConfig {
253
+ return { readOnlyTools: new Set(DEFAULT_READ_ONLY_TOOLS), subagentsFollowAuto: false, projectExactCommands: false, backgroundAutoFallback: false, projectCommandApprovals: true, projectReadApprovals: false, ccExtensionsPrompt: true, modeInstructions: "message", modeFlashSecs: DEFAULT_MODE_FLASH_SECS, backgroundAsks: true, backgroundAskTimeoutMs: DEFAULT_BACKGROUND_ASK_TIMEOUT_MS, backgroundAskPopup: "always",subagentThinking: "follow", commandColors: undefined, warnings };
254
+ }
255
+
256
+ /** Background asks are on in this process: the setting, and the env kill switch not set to "0". */
257
+ export function backgroundAsksEnabled(config: Pick<KeeperConfig, "backgroundAsks">, env: NodeJS.ProcessEnv = process.env): boolean {
258
+ return config.backgroundAsks && env[BACKGROUND_ASKS_ENV] !== "0";
259
+ }
260
+
261
+ /** The config in `agentDir`: defaults when the file is absent, defaults plus warnings when it is unusable. Never throws. */
262
+ export function loadConfig(agentDir: string): KeeperConfig {
263
+ let text: string;
264
+ try {
265
+ text = readFileSync(join(agentDir, CONFIG_FILE), "utf8");
266
+ } catch (error) {
267
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return fallback([]);
268
+ return fallback([`could not read ${CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}; using the defaults`]);
269
+ }
270
+ return parseConfig(text);
271
+ }
272
+
273
+ /**
274
+ * Persist settings to `<agent dir>/pi-keeper.json`, merging into what is
275
+ * there: keys this package doesn't know are kept as they are. Atomic (a
276
+ * temp file in the same directory, then rename), so a crash mid-write leaves
277
+ * the old file. Returns a warning instead of throwing on any problem.
278
+ */
279
+ export function saveConfig(agentDir: string, update: { subagentsFollowAuto?: boolean; projectExactCommands?: boolean; backgroundAutoFallback?: boolean; backgroundAsks?: boolean; projectCommandApprovals?: boolean; projectReadApprovals?: boolean; ccExtensionsPrompt?: boolean; backgroundAskPopup?: BackgroundAskPopup; backgroundAskTimeoutMs?: number; subagentThinking?: SubagentThinkingMode; commandColors?: PreviewTextColor; modeFlashSecs?: number }): string | undefined {
280
+ const file = join(agentDir, CONFIG_FILE);
281
+ let value: Record<string, unknown>;
282
+ try {
283
+ const text = readFileSync(file, "utf8");
284
+ let parsed: unknown;
285
+ try {
286
+ parsed = JSON.parse(text);
287
+ } catch {
288
+ // refuse rather than overwrite: the user's settings are kept until the file is fixed
289
+ return `${CONFIG_FILE} is not valid JSON, so nothing was saved; fix or remove the file and try again`;
290
+ }
291
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
292
+ return `${CONFIG_FILE} is not a JSON object, so nothing was saved; fix or remove the file and try again`;
293
+ }
294
+ value = { ...(parsed as Record<string, unknown>) };
295
+ } catch (error) {
296
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
297
+ return `could not read ${CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`;
298
+ }
299
+ // first save: nothing to merge into
300
+ value = {};
301
+ }
302
+ if (update.subagentsFollowAuto !== undefined) value.subagentsFollowAuto = update.subagentsFollowAuto;
303
+ if (update.projectExactCommands !== undefined) value.projectExactCommands = update.projectExactCommands;
304
+ if (update.backgroundAutoFallback !== undefined) value.backgroundAutoFallback = update.backgroundAutoFallback;
305
+ if (update.backgroundAsks !== undefined) value.backgroundAsks = update.backgroundAsks;
306
+ if (update.projectCommandApprovals !== undefined) value.projectCommandApprovals = update.projectCommandApprovals;
307
+ if (update.projectReadApprovals !== undefined) value.projectReadApprovals = update.projectReadApprovals;
308
+ if (update.ccExtensionsPrompt !== undefined) value.ccExtensionsPrompt = update.ccExtensionsPrompt;
309
+ if (update.backgroundAskPopup !== undefined) value.backgroundAskPopup = update.backgroundAskPopup;
310
+ if (update.backgroundAskTimeoutMs !== undefined) value.backgroundAskTimeoutMs = update.backgroundAskTimeoutMs;
311
+ if (update.subagentThinking !== undefined) value.subagentThinking = update.subagentThinking;
312
+ if (update.commandColors !== undefined) value.commandColors = update.commandColors;
313
+ if (update.modeFlashSecs !== undefined) value.modeFlashSecs = update.modeFlashSecs;
314
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}`;
315
+ try {
316
+ writeFileSync(temp, `${JSON.stringify(value, null, "\t")}\n`);
317
+ renameSync(temp, file);
318
+ return undefined;
319
+ } catch (error) {
320
+ try {
321
+ unlinkSync(temp);
322
+ } catch {
323
+ // nothing to clean up
324
+ }
325
+ return `could not write ${CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`;
326
+ }
327
+ }
328
+
329
+ /**
330
+ * A duration as typed in `/keeper`: minutes and/or seconds, each with
331
+ * its unit and in that order (`90s`, `5m`, `2m30s`). A bare number is
332
+ * refused (is `5` seconds or minutes?). Milliseconds, or undefined when the
333
+ * text does not follow that form. Range is the caller's business.
334
+ */
335
+ export function parseDuration(text: string): number | undefined {
336
+ const match = /^(?:(\d{1,6})m)?(?:(\d{1,6})s)?$/i.exec(text.trim());
337
+ if (match === null || (match[1] === undefined && match[2] === undefined)) return undefined;
338
+ return (Number(match[1] ?? 0) * 60 + Number(match[2] ?? 0)) * 1000;
339
+ }
340
+
341
+ /** A duration for display: `90 s`, `5 min`, `2 min 30 s` (whole seconds). */
342
+ export function formatDuration(ms: number): string {
343
+ const total = Math.round(ms / 1000);
344
+ const minutes = Math.floor(total / 60);
345
+ const seconds = total % 60;
346
+ return [minutes > 0 ? `${minutes} min` : "", seconds > 0 || minutes === 0 ? `${seconds} s` : ""].filter((part) => part !== "").join(" ");
347
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * One dialog at a time. pi shows an extension dialog (select, input, custom,
3
+ * editor) in a single editor slot and does not queue them: a second dialog
4
+ * replaces the first, whose promise is never settled. Every place that opens
5
+ * one for the user takes this lock first.
6
+ *
7
+ * A bare FIFO mutex, no policy: waiters run in the order they asked, a
8
+ * rejection of one does not hold up the next, and a waiter whose signal
9
+ * aborts before its turn gives up without ever opening a dialog.
10
+ *
11
+ * The lock is module-level, so there is one per extension instance. That is
12
+ * the parent's: a subagent child has its own instance (and so its own,
13
+ * unused lock) but opens no dialog itself; its asks arrive through the UI
14
+ * relay (ui-relay.ts) and open in the parent, under the parent's lock, the
15
+ * same one the parent's own asks take.
16
+ *
17
+ * Not reentrant: code running inside the lock must not take it again (it
18
+ * would wait for itself). The dialogs here never nest; a follow-up dialog
19
+ * (the "different command pattern" input after its select) opens after the
20
+ * first one has closed, and takes the lock on its own.
21
+ *
22
+ * Free of pi types so it is testable (like session-grant-store.ts).
23
+ */
24
+
25
+ /** Settles when the last waiter in line has finished; never rejects. */
26
+ let tail: Promise<void> = Promise.resolve();
27
+ /** Waiters in line or running; 0 = free, so fn can start in the same tick. */
28
+ let queued = 0;
29
+
30
+ /** Runs fn once every earlier waiter has finished; undefined without running it when `signal` aborts first. */
31
+ export function withDialogLock<T>(fn: () => Promise<T>): Promise<T>;
32
+ export function withDialogLock<T>(fn: () => Promise<T>, signal: AbortSignal | undefined): Promise<T | undefined>;
33
+ export function withDialogLock<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T | undefined> {
34
+ if (signal?.aborted) return Promise.resolve(undefined);
35
+ const previous = tail;
36
+ const free = queued === 0;
37
+ queued++;
38
+ let release!: () => void;
39
+ tail = new Promise<void>((resolve) => {
40
+ release = resolve;
41
+ });
42
+ return (async () => {
43
+ let onAbort: (() => void) | undefined;
44
+ try {
45
+ if (!free) {
46
+ const turn = await Promise.race([
47
+ previous.then(() => true),
48
+ new Promise<false>((resolve) => {
49
+ onAbort = () => resolve(false);
50
+ signal?.addEventListener("abort", onAbort, { once: true });
51
+ }),
52
+ ]);
53
+ if (!turn || signal?.aborted) return undefined;
54
+ }
55
+ return await fn();
56
+ } finally {
57
+ if (onAbort !== undefined) signal?.removeEventListener("abort", onAbort);
58
+ // an aborted waiter still passes the turn on only once the one ahead is done
59
+ void previous.then(() => {
60
+ queued--;
61
+ release();
62
+ });
63
+ }
64
+ })();
65
+ }
66
+
67
+ /** True while a dialog is open or waiting for the slot. */
68
+ export function isDialogLocked(): boolean {
69
+ return queued > 0;
70
+ }