pi-keeper 0.1.0 → 0.1.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.
@@ -8,6 +8,7 @@
8
8
  * rule matches, the mode's fallback applies.
9
9
  */
10
10
 
11
+ import { isAbsolute, join } from "node:path";
11
12
  import {
12
13
  bashWritesInsideArtifactDirs,
13
14
  isCoveredByPrefixes,
@@ -172,16 +173,16 @@ function matches(matcher: Matcher, call: ToolCall, ctx: EvalContext): boolean {
172
173
  switch (matcher) {
173
174
  // Read-only analysis is bash syntax: powershell never matches it (fail closed)
174
175
  case "readOnlyBash":
175
- return call.toolName === "bash" && isReadOnlyCommand(commandOf(call.input), ctx.cwd, ctx.scratchDir, ctx.fetchHosts);
176
+ return call.toolName === "bash" && isReadOnlyCommand(commandOf(call.input), ctx.cwd, ctx.scratchDir, ctx.fetchHosts, ctx.gitRepos);
176
177
  // Not read-only and not covered by "Yes, and always allow" prefixes. Excluding
177
178
  // remembered commands here keeps a rememberedBash allow from being
178
179
  // outranked by this ask (strictest wins).
179
180
  case "unapprovedBash": {
180
181
  const command = commandOf(call.input);
181
- return call.toolName === "bash" && !isReadOnlyCommand(command, ctx.cwd, ctx.scratchDir, ctx.fetchHosts) && !isCoveredByPrefixes(command, ctx.remembered, ctx.cwd, ctx.rememberedExact ?? [], ctx.scratchDir, ctx.fetchHosts);
182
+ return call.toolName === "bash" && !isReadOnlyCommand(command, ctx.cwd, ctx.scratchDir, ctx.fetchHosts, ctx.gitRepos) && !isCoveredByPrefixes(command, ctx.remembered, ctx.cwd, ctx.rememberedExact ?? [], ctx.scratchDir, ctx.fetchHosts, ctx.gitRepos);
182
183
  }
183
184
  case "rememberedBash":
184
- return call.toolName === "bash" && isCoveredByPrefixes(commandOf(call.input), ctx.remembered, ctx.cwd, ctx.rememberedExact ?? [], ctx.scratchDir, ctx.fetchHosts);
185
+ return call.toolName === "bash" && isCoveredByPrefixes(commandOf(call.input), ctx.remembered, ctx.cwd, ctx.rememberedExact ?? [], ctx.scratchDir, ctx.fetchHosts, ctx.gitRepos);
185
186
  // The whole command, character for character, was approved for the session (default mode only lists this matcher)
186
187
  case "rememberedVerbatim":
187
188
  return call.toolName === "bash" && ctx.rememberedVerbatim?.includes(verbatimKey(commandOf(call.input))) === true;
@@ -193,7 +194,7 @@ function matches(matcher: Matcher, call: ToolCall, ctx: EvalContext): boolean {
193
194
  const prefixes = [...(allow?.prefixes ?? []), ...(grants?.prefixes ?? [])];
194
195
  const exact = [...(allow?.exact ?? []), ...(grants?.exact ?? [])];
195
196
  if (call.toolName !== "bash" || (prefixes.length === 0 && exact.length === 0)) return false;
196
- return isCoveredByPrefixes(commandOf(call.input), [...ctx.remembered, ...prefixes], ctx.cwd, [...(ctx.rememberedExact ?? []), ...exact], ctx.scratchDir, ctx.fetchHosts);
197
+ return isCoveredByPrefixes(commandOf(call.input), [...ctx.remembered, ...prefixes], ctx.cwd, [...(ctx.rememberedExact ?? []), ...exact], ctx.scratchDir, ctx.fetchHosts, ctx.gitRepos);
197
198
  }
198
199
  // A tool that declares itself read-only and not destructive (MCP hints), or that the user listed in pi-keeper.json
199
200
  case "readOnlyTool": {
@@ -314,10 +315,11 @@ export function evaluate(mode: ModeRules, globalRules: readonly Rule[], call: To
314
315
  }
315
316
 
316
317
  /**
317
- * The calls a `subagent_launch` call will make on this machine after its child
318
- * stops: one `bash` call per entry of `commands` (the child's `gate` and
319
- * `acceptance.verify` commands), and one `write` call for `output` (the file the
320
- * child's result is written to). Empty for every other tool.
318
+ * The calls a `subagent_launch` call, a single-child `subagent` call, or a
319
+ * `schedule.create` call (its gate and output, when given) will make
320
+ * on this machine after its child stops: one `bash` call per entry of `commands`
321
+ * (the child's `gate` and `acceptance.verify` commands), and one `write` call for
322
+ * `output` (the file the child's result is written to). Empty for every other tool.
321
323
  *
322
324
  * The gate judges each with the mode's own rules, so pi-keeper's bash and write
323
325
  * rules cover what the parent runs on the child's behalf. A command runs in the
@@ -325,6 +327,7 @@ export function evaluate(mode: ModeRules, globalRules: readonly Rule[], call: To
325
327
  * working directory, which is the child's unless the call says otherwise.
326
328
  */
327
329
  export function launchNestedCalls(call: ToolCall): ToolCall[] {
330
+ if (call.toolName === "subagent") return singleLaunchNested(call);
328
331
  if (call.toolName !== SUBAGENT_LAUNCH_TOOL) return [];
329
332
  const input = call.input as { commands?: unknown; output?: unknown } | undefined;
330
333
  const nested: ToolCall[] = [];
@@ -350,28 +353,192 @@ export function launchNestedCalls(call: ToolCall): ToolCall[] {
350
353
  * - a `commands`, `cwd`, `env` or `output` value of a shape this check cannot
351
354
  * read: unreadable is never "nothing to check".
352
355
  *
353
- * Empty for every tool but `subagent_launch`.
356
+ * A single-child `subagent` call carries the same things in its `gate`,
357
+ * `acceptance` and `output` fields (singleLaunch reads them), so it gets the same
358
+ * lines. Empty for every other tool.
354
359
  */
355
360
  export function launchNestedHazards(call: ToolCall, ctx: PathContext): string[] {
361
+ if (call.toolName === "subagent") return singleLaunchHazards(call, ctx);
356
362
  if (call.toolName !== SUBAGENT_LAUNCH_TOOL) return [];
357
363
  const input = call.input as { commands?: unknown; output?: unknown } | undefined;
358
364
  const hazards: string[] = [];
359
365
  const commands = input?.commands;
360
366
  if (commands !== undefined && !Array.isArray(commands)) hazards.push("commands: a list this check cannot read");
361
- for (const entry of Array.isArray(commands) ? commands : []) {
362
- const item = entry as { command?: unknown; cwd?: unknown; env?: unknown } | null | undefined;
363
- if (typeof item !== "object" || item === null || typeof item.command !== "string") {
364
- hazards.push("bash: a command this check cannot read");
365
- continue;
367
+ for (const entry of Array.isArray(commands) ? commands : []) hazards.push(...commandHazards(entry, ctx));
368
+ if (input?.output !== undefined && typeof input.output !== "string") hazards.push("write: an output path this check cannot read");
369
+ return hazards;
370
+ }
371
+
372
+ /** The hazard lines of one `{command, cwd?, env?}` entry of a launch (`commands`, `acceptance.verify`, or a gate). */
373
+ function commandHazards(entry: unknown, ctx: PathContext): string[] {
374
+ const item = entry as { command?: unknown; cwd?: unknown; env?: unknown } | null | undefined;
375
+ if (typeof item !== "object" || item === null || typeof item.command !== "string") return ["bash: a command this check cannot read"];
376
+ const hazards: string[] = [];
377
+ const shown = item.command.length > 120 ? `${item.command.slice(0, 120)}…` : item.command;
378
+ const names = typeof item.env === "object" && item.env !== null && !Array.isArray(item.env) ? Object.keys(item.env) : item.env === undefined ? [] : ["?"];
379
+ if (names.length > 0) hazards.push(`bash: ${shown} (sets ${names.slice(0, 3).join(", ")}${names.length > 3 ? ", …" : ""} in its environment)`);
380
+ if (item.cwd !== undefined && (typeof item.cwd !== "string" || isOutsideCwd(item.cwd, ctx))) {
381
+ hazards.push(`bash: ${shown} (runs in ${typeof item.cwd === "string" ? item.cwd : "a directory this check cannot read"}, outside this project)`);
382
+ }
383
+ return hazards;
384
+ }
385
+
386
+ /** A field as pi-subagents reads it: the string "null" is dropped (flattenSubagentToolOptions). */
387
+ function given(value: unknown): boolean {
388
+ return value !== undefined && value !== "null";
389
+ }
390
+
391
+ /** What a single-child launch makes the host run and write, and what this check cannot read. */
392
+ interface SingleLaunch {
393
+ /** `{command, cwd?, env?}` entries (gate, acceptance.verify), not yet checked for shape. */
394
+ commands: unknown[];
395
+ /** Paths of nested `write` calls (the child's `output`). */
396
+ writes: string[];
397
+ /** Lines for values this check cannot read. */
398
+ hazards: string[];
399
+ }
400
+
401
+ /** Fields that make a `subagent` call a workflow or multi-child launch: judged per child as `subagent_launch`, not here. */
402
+ const MULTI_CHILD_FIELDS = ["workflow", "workflowScript", "script", "tasks", "chain", "parallel"];
403
+
404
+ /**
405
+ * A single-child `subagent` launch (`agent` as a string, no workflow, script or
406
+ * multi-child field, no management `action`), read from the top level and from
407
+ * `options` (both may be set). Undefined for any other call.
408
+ */
409
+ function singleLaunch(call: ToolCall): SingleLaunch | undefined {
410
+ if (call.toolName !== "subagent") return undefined;
411
+ const { top, options } = subagentFields(call.input);
412
+ if (given(top.action) || !given(top.agent) || typeof top.agent !== "string") return undefined;
413
+ for (const source of [top, options]) {
414
+ for (const key of MULTI_CHILD_FIELDS) {
415
+ if (given(source[key]) && !(key === "workflow" && source[key] === "false")) return undefined;
366
416
  }
367
- const shown = item.command.length > 120 ? `${item.command.slice(0, 120)}…` : item.command;
368
- const names = typeof item.env === "object" && item.env !== null && !Array.isArray(item.env) ? Object.keys(item.env) : item.env === undefined ? [] : ["?"];
369
- if (names.length > 0) hazards.push(`bash: ${shown} (sets ${names.slice(0, 3).join(", ")}${names.length > 3 ? ", …" : ""} in its environment)`);
370
- if (item.cwd !== undefined && (typeof item.cwd !== "string" || isOutsideCwd(item.cwd, ctx))) {
371
- hazards.push(`bash: ${shown} (runs in ${typeof item.cwd === "string" ? item.cwd : "a directory this check cannot read"}, outside this project)`);
417
+ }
418
+ return readLaunch(top, options);
419
+ }
420
+
421
+ /** The top level and `options` of a `subagent` call; a value that is not a plain object is read as empty (pi-subagents refuses that call). */
422
+ function subagentFields(input: unknown): { top: Record<string, unknown>; options: Record<string, unknown> } {
423
+ const top = (typeof input === "object" && input !== null ? input : {}) as Record<string, unknown>;
424
+ const options = (typeof top.options === "object" && top.options !== null && !Array.isArray(top.options) ? top.options : {}) as Record<string, unknown>;
425
+ return { top, options };
426
+ }
427
+
428
+ /** The action that stores a workflow script to run later, with no tool call behind its children. */
429
+ const SCHEDULE_ACTION = "schedule.create";
430
+
431
+ /**
432
+ * A `schedule.create` call: its gate, acceptance and output fields are judged as a
433
+ * single launch. The workflow it stores runs later with no tool call behind it
434
+ * (approveWorkflowChildLaunch returns without judging), and its children launch
435
+ * from the script, which this check cannot read: so the creation itself asks.
436
+ */
437
+ function scheduleLaunch(call: ToolCall): SingleLaunch | undefined {
438
+ if (call.toolName !== "subagent") return undefined;
439
+ const { top, options } = subagentFields(call.input);
440
+ if (!given(top.action) || typeof top.action !== "string" || top.action.trim() !== SCHEDULE_ACTION) return undefined;
441
+ const launch = readLaunch(top, options);
442
+ if (given(top.options) && (typeof top.options !== "object" || top.options === null || Array.isArray(top.options))) {
443
+ launch.hazards.push("schedule: launch parameters this check cannot read");
444
+ }
445
+ if ([top, options].some((source) => ["workflow", "workflowScript", "script"].some((key) => given(source[key]) && source[key] !== "false"))) {
446
+ launch.hazards.push("schedule: a workflow script that runs later, with no tool call behind its children, so their gates are not judged");
447
+ }
448
+ return launch;
449
+ }
450
+
451
+ /** The launch a `subagent` call makes after its child stops, or a schedule it stores. */
452
+ function launchOf(call: ToolCall): SingleLaunch | undefined {
453
+ return singleLaunch(call) ?? scheduleLaunch(call);
454
+ }
455
+
456
+ /** Judge the gate, acceptance and output fields, from the top level and from `options` (both may be set). */
457
+ function readLaunch(top: Record<string, unknown>, options: Record<string, unknown>): SingleLaunch {
458
+ const sources = [top, options];
459
+ const cwd = given(top.cwd) ? top.cwd : undefined;
460
+ const artifactsOff = sources.some((source) => source.artifacts === false || source.artifacts === "false");
461
+ const launch: SingleLaunch = { commands: [], writes: [], hazards: [] };
462
+ for (const source of sources) {
463
+ launch.commands.push(...gateEntries(source.gate, cwd, launch.hazards));
464
+ launch.commands.push(...acceptanceEntries(source.acceptance, cwd, launch.hazards));
465
+ const output = singleOutput(source.output, cwd, artifactsOff);
466
+ if (output.write !== undefined) launch.writes.push(output.write);
467
+ if (output.hazard !== undefined) launch.hazards.push(output.hazard);
468
+ }
469
+ return launch;
470
+ }
471
+
472
+ /** The entry a gate runs as: a string, or an object with a string `command`; it runs in the call's cwd. */
473
+ function gateEntries(gate: unknown, cwd: unknown, hazards: string[]): unknown[] {
474
+ if (!given(gate)) return [];
475
+ if (typeof gate === "string") return [{ command: gate, cwd }];
476
+ if (typeof gate === "object" && gate !== null && typeof (gate as { command?: unknown }).command === "string") return [{ cwd, ...gate }];
477
+ hazards.push("gate: a value this check cannot read");
478
+ return [];
479
+ }
480
+
481
+ /** The `verify` entries of an acceptance object or JSON string; a policy name carries none. */
482
+ function acceptanceEntries(acceptance: unknown, cwd: unknown, hazards: string[]): unknown[] {
483
+ if (!given(acceptance) || typeof acceptance === "boolean") return [];
484
+ let spec: unknown = acceptance;
485
+ if (typeof acceptance === "string") {
486
+ if (acceptance.trim().startsWith("[")) {
487
+ hazards.push("acceptance: a value this check cannot read");
488
+ return [];
489
+ }
490
+ if (!acceptance.trim().startsWith("{")) return [];
491
+ try {
492
+ spec = JSON.parse(acceptance);
493
+ } catch {
494
+ hazards.push("acceptance: JSON this check cannot read");
495
+ return [];
372
496
  }
373
497
  }
374
- if (input?.output !== undefined && typeof input.output !== "string") hazards.push("write: an output path this check cannot read");
498
+ if (typeof spec !== "object" || spec === null || Array.isArray(spec)) {
499
+ hazards.push("acceptance: a value this check cannot read");
500
+ return [];
501
+ }
502
+ const verify = (spec as { verify?: unknown }).verify;
503
+ if (verify === undefined) return [];
504
+ if (!Array.isArray(verify)) {
505
+ hazards.push("acceptance: a verify list this check cannot read");
506
+ return [];
507
+ }
508
+ return verify.map((entry) => (typeof entry === "object" && entry !== null && !Array.isArray(entry) ? { cwd, ...entry } : entry));
509
+ }
510
+
511
+ /**
512
+ * What a launch's `output` makes the host write: an absolute path, or (with
513
+ * `artifacts: false`) a relative path under the call's cwd. A relative path
514
+ * otherwise lands in the run's artifacts directory, unless it climbs out of it.
515
+ */
516
+ function singleOutput(output: unknown, cwd: unknown, artifactsOff: boolean): { write?: string; hazard?: string } {
517
+ if (output === undefined || typeof output === "boolean" || output === "true" || output === "false" || output === "null" || output === "") return {};
518
+ if (typeof output !== "string") return { hazard: "write: an output path this check cannot read" };
519
+ if (isAbsolute(output)) return { write: output };
520
+ if (artifactsOff) return { write: join(typeof cwd === "string" ? cwd : ".", output) };
521
+ if (output.split(/[\\/]/).includes("..")) return { hazard: `write: output path ${output} leaves the run's directory` };
522
+ return {};
523
+ }
524
+
525
+ function singleLaunchNested(call: ToolCall): ToolCall[] {
526
+ const launch = launchOf(call);
527
+ if (launch === undefined) return [];
528
+ const nested: ToolCall[] = [];
529
+ for (const entry of launch.commands) {
530
+ const command = (entry as { command?: unknown } | null)?.command;
531
+ if (typeof command === "string" && command.trim() !== "") nested.push({ toolName: "bash", input: { command } });
532
+ }
533
+ for (const path of launch.writes) nested.push({ toolName: "write", input: { path } });
534
+ return nested;
535
+ }
536
+
537
+ function singleLaunchHazards(call: ToolCall, ctx: PathContext): string[] {
538
+ const launch = launchOf(call);
539
+ if (launch === undefined) return [];
540
+ const hazards = [...launch.hazards];
541
+ for (const entry of launch.commands) hazards.push(...commandHazards(entry, ctx));
375
542
  return hazards;
376
543
  }
377
544
 
@@ -395,14 +562,14 @@ const MAX_EXPLAINED_PATTERNS = 40;
395
562
  * sources' patterns that still covers it (earlier sources are kept over later
396
563
  * ones). Empty when the command is not covered (e.g. it is read-only).
397
564
  */
398
- export function coveringPatterns(command: string, sources: readonly PatternSource[], cwd: string, scratch?: string, fetchHosts?: readonly string[]): Array<{ label: string; tokens: readonly string[]; exact: boolean }> {
565
+ export function coveringPatterns(command: string, sources: readonly PatternSource[], cwd: string, scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): Array<{ label: string; tokens: readonly string[]; exact: boolean }> {
399
566
  let items = sources.flatMap((s) => [
400
567
  ...s.prefixes.map((tokens) => ({ label: s.label, tokens, exact: false })),
401
568
  ...s.exact.map((tokens) => ({ label: s.label, tokens, exact: true })),
402
569
  ]);
403
570
  if (items.length === 0 || items.length > MAX_EXPLAINED_PATTERNS) return [];
404
571
  const covers = (set: typeof items): boolean =>
405
- set.length === 0 ? isReadOnlyCommand(command, cwd, scratch, fetchHosts) : isCoveredByPrefixes(command, set.filter((i) => !i.exact).map((i) => i.tokens), cwd, set.filter((i) => i.exact).map((i) => i.tokens), scratch, fetchHosts);
572
+ set.length === 0 ? isReadOnlyCommand(command, cwd, scratch, fetchHosts, gitRepos) : isCoveredByPrefixes(command, set.filter((i) => !i.exact).map((i) => i.tokens), cwd, set.filter((i) => i.exact).map((i) => i.tokens), scratch, fetchHosts, gitRepos);
406
573
  if (!covers(items)) return [];
407
574
  for (let k = items.length - 1; k >= 0; k--) {
408
575
  const without = items.filter((_, j) => j !== k);
@@ -27,6 +27,7 @@ export interface SessionGrantsSnapshot {
27
27
  readonly outsideReadsAllowed: boolean;
28
28
  readonly outsideReadDirs: readonly string[];
29
29
  readonly fetchHosts: readonly string[];
30
+ readonly gitRepos: readonly string[];
30
31
  }
31
32
 
32
33
  export class SessionGrants {
@@ -36,6 +37,7 @@ export class SessionGrants {
36
37
  #outsideReadsAllowed = false;
37
38
  readonly #outsideReadDirs: string[] = [];
38
39
  readonly #fetchHosts: string[] = [];
40
+ readonly #gitRepos: string[] = [];
39
41
 
40
42
  /** Command prefixes approved for the session. */
41
43
  get prefixes(): readonly (readonly string[])[] {
@@ -67,6 +69,11 @@ export class SessionGrants {
67
69
  return this.#fetchHosts;
68
70
  }
69
71
 
72
+ /** "Yes, and allow git in <repo>/ this session": realpaths of granted git repository roots. */
73
+ get gitRepos(): readonly string[] {
74
+ return this.#gitRepos;
75
+ }
76
+
70
77
  /** Empty everything in place (the arrays keep their identity, so a live reader sees the reset). */
71
78
  reset(): void {
72
79
  this.#prefixes.length = 0;
@@ -75,6 +82,7 @@ export class SessionGrants {
75
82
  this.#outsideReadsAllowed = false;
76
83
  this.#outsideReadDirs.length = 0;
77
84
  this.#fetchHosts.length = 0;
85
+ this.#gitRepos.length = 0;
78
86
  }
79
87
 
80
88
  /** A deep copy, frozen: mutating it can't reach the live state. */
@@ -87,6 +95,7 @@ export class SessionGrants {
87
95
  outsideReadsAllowed: this.#outsideReadsAllowed,
88
96
  outsideReadDirs: Object.freeze([...this.#outsideReadDirs]),
89
97
  fetchHosts: Object.freeze([...this.#fetchHosts]),
98
+ gitRepos: Object.freeze([...this.#gitRepos]),
90
99
  });
91
100
  }
92
101
 
@@ -136,4 +145,13 @@ export class SessionGrants {
136
145
  const at = this.#fetchHosts.indexOf(host);
137
146
  if (at !== -1) this.#fetchHosts.splice(at, 1);
138
147
  }
148
+
149
+ addGitRepo(realpath: string): void {
150
+ if (!this.#gitRepos.includes(realpath)) this.#gitRepos.push(realpath);
151
+ }
152
+
153
+ removeGitRepo(realpath: string): void {
154
+ const at = this.#gitRepos.indexOf(realpath);
155
+ if (at !== -1) this.#gitRepos.splice(at, 1);
156
+ }
139
157
  }
@@ -36,7 +36,10 @@ const VERSION = 1;
36
36
  /** A snapshot larger than this is not a snapshot we wrote. */
37
37
  const MAX_BYTES = 256 * 1024;
38
38
 
39
- interface Snapshot extends UiRelaySessionRules {
39
+ /** The session-scope rules a child reads (the relay's, which carry the optional gitRepos). */
40
+ export type SessionGitRules = UiRelaySessionRules;
41
+
42
+ interface Snapshot extends SessionGitRules {
40
43
  version: number;
41
44
  sessionId: string;
42
45
  /** The parent pi process; a snapshot whose process is gone is stale. */
@@ -52,7 +55,7 @@ export function grantsFile(agentDir: string, sessionId: string): string {
52
55
  }
53
56
 
54
57
  /** Parent: write (or replace) this session's snapshot. Atomic, 0600. */
55
- export function publishGrants(agentDir: string, sessionId: string, rules: UiRelaySessionRules): void {
58
+ export function publishGrants(agentDir: string, sessionId: string, rules: SessionGitRules): void {
56
59
  try {
57
60
  mkdirSync(grantsDir(agentDir), { recursive: true, mode: 0o700 });
58
61
  const file = grantsFile(agentDir, sessionId);
@@ -66,6 +69,7 @@ export function publishGrants(agentDir: string, sessionId: string, rules: UiRela
66
69
  outsideReads: rules.outsideReads,
67
70
  outsideReadDirs: rules.outsideReadDirs ?? [],
68
71
  fetchHosts: rules.fetchHosts ?? [],
72
+ gitRepos: rules.gitRepos ?? [],
69
73
  ...(rules.cwd !== undefined ? { cwd: rules.cwd } : {}),
70
74
  ...(rules.thinking !== undefined ? { thinking: rules.thinking } : {}),
71
75
  };
@@ -116,6 +120,7 @@ function parse(file: string): Snapshot | undefined {
116
120
  if (typeof value.edits !== "boolean" || typeof value.outsideReads !== "boolean") return undefined;
117
121
  if (!strings(value.outsideReadDirs)) return undefined;
118
122
  if (value.fetchHosts !== undefined && !strings(value.fetchHosts)) return undefined;
123
+ if (value.gitRepos !== undefined && !strings(value.gitRepos)) return undefined;
119
124
  if (value.cwd !== undefined && (typeof value.cwd !== "string" || !value.cwd.startsWith("/"))) return undefined;
120
125
  if (value.thinking !== undefined && typeof value.thinking !== "string") return undefined;
121
126
  return value as Snapshot;
@@ -128,7 +133,7 @@ function parse(file: string): Snapshot | undefined {
128
133
  * Child: the parent session's grants, or undefined (no parent session in the
129
134
  * env, no file, a foreign or malformed file, or a parent process that is gone).
130
135
  */
131
- export function readParentGrants(agentDir: string, env: NodeJS.ProcessEnv = process.env): UiRelaySessionRules | undefined {
136
+ export function readParentGrants(agentDir: string, env: NodeJS.ProcessEnv = process.env): SessionGitRules | undefined {
132
137
  const sessionId = env[PARENT_SESSION_ENV];
133
138
  if (typeof sessionId !== "string" || sessionId === "") return undefined;
134
139
  const snapshot = parse(grantsFile(agentDir, sessionId));
@@ -140,6 +145,7 @@ export function readParentGrants(agentDir: string, env: NodeJS.ProcessEnv = proc
140
145
  outsideReads: snapshot.outsideReads,
141
146
  outsideReadDirs: snapshot.outsideReadDirs,
142
147
  fetchHosts: snapshot.fetchHosts ?? [],
148
+ gitRepos: snapshot.gitRepos ?? [],
143
149
  ...(snapshot.cwd !== undefined ? { cwd: snapshot.cwd } : {}),
144
150
  ...(snapshot.thinking !== undefined ? { thinking: snapshot.thinking } : {}),
145
151
  };
@@ -17,7 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
20
- import { Input, Key, matchesKey, SettingsList, truncateToWidth, type Component, type SettingItem, type SettingsListTheme } from "@earendil-works/pi-tui";
20
+ import { getKeybindings, Input, Key, matchesKey, SettingsList, truncateToWidth, type Component, type SettingItem, type SettingsListTheme } from "@earendil-works/pi-tui";
21
21
 
22
22
  export interface PanelItem {
23
23
  readonly id: string;
@@ -31,10 +31,19 @@ export interface PanelItem {
31
31
  readonly placeholder?: string;
32
32
  }
33
33
 
34
+ /** A heading and its rows, inside one section. */
35
+ export interface PanelGroup {
36
+ readonly label: string;
37
+ readonly items: readonly PanelItem[];
38
+ }
39
+
34
40
  export interface PanelSection {
35
41
  readonly id: string;
36
42
  readonly label: string;
43
+ /** Every row of the section, in order. */
37
44
  readonly items: readonly PanelItem[];
45
+ /** When set, the rows are shown under these headings (a blank line between groups; an empty label has no heading). */
46
+ readonly groups?: readonly PanelGroup[];
38
47
  }
39
48
 
40
49
  /** What to show in the footer after a change. */
@@ -55,6 +64,11 @@ const HINTS = " Enter/Space change · Tab/Shift+Tab sections · Esc close";
55
64
  /** Rows kept on screen; longer sections scroll (SettingsList shows "n/total"). */
56
65
  const MAX_VISIBLE_ROWS = 10;
57
66
 
67
+ /** Heading and spacer rows are list items with these ids; the panel's cursor never rests on them. */
68
+ const HEADING_PREFIX = "__heading:";
69
+ const SPACER_PREFIX = "__spacer:";
70
+ const isDecoration = (id: string): boolean => id.startsWith(HEADING_PREFIX) || id.startsWith(SPACER_PREFIX);
71
+
58
72
  function panelTheme(theme: Theme): SettingsListTheme {
59
73
  return {
60
74
  label: (text, selected) => (selected ? theme.bold(theme.fg("text", text)) : theme.fg("text", text)),
@@ -125,25 +139,40 @@ export async function settingsPanel(
125
139
  finish();
126
140
  };
127
141
 
128
- const itemsOf = (section: PanelSection): SettingItem[] =>
129
- section.items.map((item) => ({
130
- id: item.id,
131
- label: item.label,
132
- ...(item.description === undefined ? {} : { description: item.description }),
133
- currentValue: options.currentValue(item.id),
134
- ...(item.values === undefined
135
- ? {
136
- submenu: (current: string, done: (value?: string) => void) => {
137
- inSubmenu = true;
138
- return textRow(theme, item.placeholder ?? "new value", (value) => {
139
- inSubmenu = false;
140
- done(value);
141
- tui.requestRender();
142
- });
143
- },
144
- }
145
- : { values: [...item.values] }),
146
- }));
142
+ const rowOf = (item: PanelItem): SettingItem => ({
143
+ id: item.id,
144
+ label: item.label,
145
+ ...(item.description === undefined ? {} : { description: item.description }),
146
+ currentValue: options.currentValue(item.id),
147
+ ...(item.values === undefined
148
+ ? {
149
+ submenu: (current: string, done: (value?: string) => void) => {
150
+ inSubmenu = true;
151
+ return textRow(theme, item.placeholder ?? "new value", (value) => {
152
+ inSubmenu = false;
153
+ done(value);
154
+ tui.requestRender();
155
+ });
156
+ },
157
+ }
158
+ : { values: [...item.values] }),
159
+ });
160
+
161
+ /**
162
+ * The list's items: the rows, and for a grouped section a heading before each
163
+ * group and a blank row between groups. Headings and blanks have no values and
164
+ * no submenu, so Enter does nothing on them; the cursor skips them anyway.
165
+ */
166
+ const itemsOf = (section: PanelSection): SettingItem[] => {
167
+ if (section.groups === undefined) return section.items.map(rowOf);
168
+ const out: SettingItem[] = [];
169
+ for (const [index, group] of section.groups.entries()) {
170
+ if (index > 0) out.push({ id: `${SPACER_PREFIX}${index}`, label: "", currentValue: "" });
171
+ if (group.label !== "") out.push({ id: `${HEADING_PREFIX}${index}`, label: theme.bold(theme.fg("dim", group.label)), currentValue: "" });
172
+ out.push(...group.items.map(rowOf));
173
+ }
174
+ return out;
175
+ };
147
176
 
148
177
  const onChange = (id: string, value: string): void => {
149
178
  notice = options.apply(id, value);
@@ -154,11 +183,36 @@ export async function settingsPanel(
154
183
  tui.requestRender();
155
184
  };
156
185
 
186
+ const listItems = shown.map(itemsOf);
157
187
  const lists = shown.map(
158
- (section) =>
159
- new SettingsList(itemsOf(section), Math.min(MAX_VISIBLE_ROWS, Math.max(section.items.length, 1)), panelTheme(theme), onChange, close, { enableSearch: false }),
188
+ (section, index) =>
189
+ // a grouped section shows every row, headings included: it never scrolls
190
+ new SettingsList(listItems[index] ?? [], section.groups === undefined ? Math.min(MAX_VISIBLE_ROWS, Math.max(section.items.length, 1)) : Math.max(1, listItems[index]?.length ?? 1), panelTheme(theme), onChange, close, { enableSearch: false }),
160
191
  );
161
192
 
193
+ // A grouped section's cursor is the panel's, so it can step over headings and blanks.
194
+ const selectable = listItems.map((items) => items.filter((item) => !isDecoration(item.id)).map((item) => item.id));
195
+ const cursor = shown.map((section, index) => (section.groups === undefined ? undefined : selectable[index]?.[0]));
196
+ for (const [index, id] of cursor.entries()) if (id !== undefined) lists[index]?.selectItem(id);
197
+
198
+ /** Up/Down on a grouped section; true when the key was handled here (page keys are swallowed). */
199
+ const moveCursor = (data: string): boolean => {
200
+ const current = cursor[active];
201
+ if (current === undefined) return false;
202
+ const keys = getKeybindings();
203
+ const ids = selectable[active] ?? [];
204
+ const up = keys.matches(data, "tui.select.up");
205
+ const down = keys.matches(data, "tui.select.down");
206
+ if (!up && !down) return keys.matches(data, "tui.select.pageUp") || keys.matches(data, "tui.select.pageDown");
207
+ const at = ids.indexOf(current);
208
+ const next = ids[(at + (down ? 1 : -1) + ids.length) % ids.length];
209
+ if (next !== undefined) {
210
+ cursor[active] = next;
211
+ lists[active]?.selectItem(next);
212
+ }
213
+ return true;
214
+ };
215
+
162
216
  return {
163
217
  render(width: number): string[] {
164
218
  const w = Math.max(1, Math.floor(width));
@@ -186,6 +240,10 @@ export async function settingsPanel(
186
240
  tui.requestRender();
187
241
  return;
188
242
  }
243
+ if (!inSubmenu && moveCursor(data)) {
244
+ tui.requestRender();
245
+ return;
246
+ }
189
247
  lists[active]?.handleInput(data);
190
248
  tui.requestRender();
191
249
  },