auto-permission-system 3.9.0 → 3.12.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.
@@ -9,11 +9,12 @@ import { homedir } from "node:os";
9
9
  import { dirname } from "node:path";
10
10
  import { SandboxManager, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime";
11
11
  import { type BashOperations } from "@earendil-works/pi-coding-agent";
12
- import { askReadCandidates, extractBlockedPath, isBlockedAccessError, isSafeFolderGrant, isWriteBlockError, matchedAskCommands, matchesPolicyPattern, outsideProjectMode, outsideProjectReadCandidates, outsideProjectReadDenied, sandboxFilesystem } from "../core/index";
12
+ import { askReadCandidates, extractBlockedPath, extractLoopbackEndpoint, isBlockedAccessError, isLoopbackConnectionRefused, isSafeFolderGrant, isWriteBlockError, matchedAskCommands, matchesPolicyPattern, outsideProjectMode, outsideProjectReadCandidates, outsideProjectReadDenied, sandboxFilesystem } from "../core/index";
13
13
  import { audit } from "../shared/audit";
14
14
  import { canonicalize } from "../shared/canonicalize";
15
15
  import { askMain, askMainWithRemember, askRememberFile, MainChoice, type AskCtx } from "../ui/ask-flow";
16
16
  import { loadConfig, projectTrusted } from "./config";
17
+ import { injectBridgesIntoBwrap, startHostPortBridges, type HostPortBridge } from "./host-bridge";
17
18
 
18
19
  /** First whitespace-separated token of a bash command — used to name the binary in prompt titles. */
19
20
  function firstWord(command: string): string {
@@ -40,7 +41,7 @@ function linkRow(absPath: string, spelled: string | undefined): string[] {
40
41
  const auditL1 = (entry: Record<string, unknown>) => audit({ layer: 1, tool: "bash", ...entry });
41
42
 
42
43
  /**
43
- * In-memory filesystem grants from "Yes, for this session" (ADR-010, ADR-012).
44
+ * In-memory filesystem grants from "Yes, for this conversation" (ADR-010, ADR-012).
44
45
  * A read grant is the absolute path; a write grant is the parent directory (a
45
46
  * whole path would not let a new file be created — ADR-021), falling back to the
46
47
  * exact path when the parent is an unsafe folder to grant (root, home, …).
@@ -48,7 +49,7 @@ const auditL1 = (entry: Record<string, unknown>) => audit({ layer: 1, tool: "bas
48
49
  */
49
50
  const sessionReadGrants: string[] = [];
50
51
  const sessionWriteGrants: string[] = [];
51
- /** askRead (.env) session grants, kept apart so they never leak into allowRead (ADR-019). */
52
+ /** askRead (.env) conversation grants, kept apart so they never leak into allowRead (ADR-019). */
52
53
  const sessionAskReadGrants: string[] = [];
53
54
 
54
55
  export function clearFilesystemSessionGrants(): void {
@@ -76,11 +77,15 @@ async function preflightSensitiveCommands(
76
77
  const matched = matchedAskCommands(command, ask, cwd, homedir());
77
78
  if (!matched.length) return undefined;
78
79
  const ui = opts.ctx as AskCtx;
79
- const body = [
80
+ const bodyLines: string[] = [
80
81
  `Command ${matched.join(", ")}`,
81
82
  `Risk environment variables often hold API keys and tokens`,
82
83
  `Note can only be allowed one run at a time`,
83
- ].join("\n");
84
+ ];
85
+ if (command.includes("\n")) {
86
+ bodyLines.push(`\nScript:\n${command}`);
87
+ }
88
+ const body = bodyLines.join("\n");
84
89
  const choice = await askMain(ui, `Let ${matched[0]} print your environment variables?`, body, { once: true, remember: false, icon: "cred" });
85
90
  const subject = matched.join(", ");
86
91
  if (choice === "once") {
@@ -158,7 +163,7 @@ async function preflightOutsideReads(
158
163
  if (choice === MainChoice.Session) {
159
164
  sessionReadGrants.push(absPath);
160
165
  auditL1({ subject: absPath, decision: "session", scope: "session", reason: "outside-project-read", note: "preflight", cwd });
161
- opts.ctx.ui?.notify?.(`pi-sandbox: allowed read of ${absPath} for this session (not saved)`, "info");
166
+ opts.ctx.ui?.notify?.(`pi-sandbox: allowed read of ${absPath} for this conversation (not saved)`, "info");
162
167
  continue;
163
168
  }
164
169
  if (choice !== MainChoice.Remember || !grant) {
@@ -215,7 +220,26 @@ export function createSandboxedBashOps(opts?: SandboxedBashOpts): BashOperations
215
220
  const grantedWriteFolders = new Set<string>();
216
221
  const grantedWriteFiles = new Set<string>();
217
222
  const attempt = async (writeOnce: string[]): Promise<{ exitCode: number | null }> => {
218
- const wrappedCommand = await SandboxManager.wrapWithSandbox(command, undefined, buildCustom(writeOnce));
223
+ const cfg = loadConfig(cwd);
224
+ const allowLocalhost = cfg.allowLocalhost ?? cfg.network?.allowLocalhost ?? true;
225
+ let bridges: HostPortBridge[] = [];
226
+ if (!allowLocalhost && process.platform === "linux") {
227
+ const hostPorts = cfg.bridgeHostPorts ?? [3274];
228
+ bridges = await startHostPortBridges(hostPorts);
229
+ }
230
+ const rawWrapped = await SandboxManager.wrapWithSandbox(command, undefined, buildCustom(writeOnce));
231
+ let wrappedCommand = rawWrapped;
232
+ if (process.platform === "linux") {
233
+ if (allowLocalhost) {
234
+ wrappedCommand = wrappedCommand.replace(" --unshare-net ", " ");
235
+ } else if (bridges.length > 0) {
236
+ wrappedCommand = injectBridgesIntoBwrap(wrappedCommand, bridges);
237
+ }
238
+ }
239
+
240
+ const cleanupBridges = () => {
241
+ bridges.forEach((b) => b.close());
242
+ };
219
243
 
220
244
  return new Promise((resolve, reject) => {
221
245
  const child = spawn("bash", ["-c", wrappedCommand], {
@@ -251,11 +275,13 @@ export function createSandboxedBashOps(opts?: SandboxedBashOpts): BashOperations
251
275
 
252
276
  child.on("error", (err) => {
253
277
  if (timeoutHandle) clearTimeout(timeoutHandle);
278
+ cleanupBridges();
254
279
  SandboxManager.cleanupAfterCommand();
255
280
  reject(err);
256
281
  });
257
282
 
258
283
  const onAbort = () => {
284
+ cleanupBridges();
259
285
  if (child.pid) {
260
286
  try {
261
287
  process.kill(-child.pid, "SIGKILL");
@@ -270,6 +296,7 @@ export function createSandboxedBashOps(opts?: SandboxedBashOpts): BashOperations
270
296
  child.on("close", async (code) => {
271
297
  if (timeoutHandle) clearTimeout(timeoutHandle);
272
298
  signal?.removeEventListener("abort", onAbort);
299
+ cleanupBridges();
273
300
 
274
301
  SandboxManager.cleanupAfterCommand();
275
302
 
@@ -326,6 +353,50 @@ export function createSandboxedBashOps(opts?: SandboxedBashOpts): BashOperations
326
353
  ` or write inside the project directory (${cwd}).\n`;
327
354
  }
328
355
  blockedHint += ` Policy: ~/.pi/agent/extensions/sandbox.json (+ <cwd>/.pi/sandbox.json overrides).\n`;
356
+ } else if (code !== 0 && isLoopbackConnectionRefused(outputTail)) {
357
+ const endpointInfo = extractLoopbackEndpoint(outputTail, command);
358
+ const endpointStr = endpointInfo?.port ? `${endpointInfo.host}:${endpointInfo.port}` : (endpointInfo?.host ?? "127.0.0.1");
359
+ const serviceName = endpointInfo?.service;
360
+
361
+ auditL1({
362
+ subject: endpointStr,
363
+ decision: "loopback-refused",
364
+ reason: "Linux sandbox network namespace (--unshare-net) isolates host loopback",
365
+ cwd: opts?.ctx?.cwd,
366
+ note: serviceName ? `service:${serviceName}` : undefined,
367
+ });
368
+
369
+ const notifyMsg = serviceName === "Diffusion Studio"
370
+ ? "pi-sandbox: Diffusion Studio is running on host port 3274, but sandboxed bash cannot reach host localhost. Connect it via MCP in ~/.pi/agent/mcp.json."
371
+ : `pi-sandbox: connection to host ${endpointStr} refused. Sandboxed bash cannot reach host localhost.`;
372
+ opts?.ctx?.ui?.notify?.(notifyMsg, "warning");
373
+
374
+ blockedHint = `\n💡 pi-sandbox: localhost / loopback connection refused.\n` +
375
+ ` Target: ${endpointStr}${serviceName ? ` (${serviceName})` : ""}\n` +
376
+ ` Why: The Linux sandbox runs inside an isolated network namespace (--unshare-net).\n` +
377
+ ` Services running on your HOST's 127.0.0.1/localhost are isolated and cannot\n` +
378
+ ` be reached directly from sandboxed bash commands.\n`;
379
+
380
+ if (serviceName === "Diffusion Studio" || /dapi|diffusion|3274/i.test(command)) {
381
+ blockedHint +=
382
+ ` Resolution for Diffusion Studio:\n` +
383
+ ` • Diffusion Studio exposes an MCP server on http://127.0.0.1:3274/mcp\n` +
384
+ ` • Add it to ~/.pi/agent/mcp.json so Pi connects directly on the host:\n` +
385
+ ` {\n` +
386
+ ` "mcpServers": {\n` +
387
+ ` "diffusion-studio": { "url": "http://127.0.0.1:3274/mcp" }\n` +
388
+ ` }\n` +
389
+ ` }\n` +
390
+ ` • Once added, restart or reload Pi: the agent gets native MCP tools\n` +
391
+ ` (context, check, capture, probe) with Layer 2 security, no bash needed.\n` +
392
+ ` • Or run pi with --yolo for one-off host access.\n`;
393
+ } else {
394
+ blockedHint +=
395
+ ` Resolution:\n` +
396
+ ` • If this is an MCP service, configure it in ~/.pi/agent/mcp.json.\n` +
397
+ ` • Pi runs on the host and can communicate with local MCP servers directly.\n` +
398
+ ` • Or run pi with --yolo if this task requires interacting with host network services.\n`;
399
+ }
329
400
  }
330
401
  /**
331
402
  * Emit the block explanation only when the command is not re-run with a
@@ -366,8 +437,8 @@ export function createSandboxedBashOps(opts?: SandboxedBashOpts): BashOperations
366
437
  if (choice === MainChoice.Once) readOnce.push(absPath);
367
438
  else sessionReadGrants.push(absPath);
368
439
  auditL1({ subject: absPath, decision: choice, scope: choice === MainChoice.Once ? "invocation" : "session", cwd: opts.ctx.cwd, note: "outside-project-read" });
369
- opts.ctx.ui?.notify?.(`pi-sandbox: allowed read of ${absPath} ${choice === MainChoice.Once ? "once" : "for this session"} — re-running the command`, "warning");
370
- onData(Buffer.from(`\n✅ pi-sandbox: read of ${absPath} allowed ${choice === MainChoice.Once ? "once" : "for this session"}. Command output with the new permission follows.\n`));
440
+ opts.ctx.ui?.notify?.(`pi-sandbox: allowed read of ${absPath} ${choice === MainChoice.Once ? "once" : "for this conversation"} — re-running the command`, "warning");
441
+ onData(Buffer.from(`\n✅ pi-sandbox: read of ${absPath} allowed ${choice === MainChoice.Once ? "once" : "for this conversation"}. Command output with the new permission follows.\n`));
371
442
  resolve(attempt([]));
372
443
  return;
373
444
  }
@@ -441,8 +512,8 @@ export function createSandboxedBashOps(opts?: SandboxedBashOpts): BashOperations
441
512
  sessionWriteGrants.push(value);
442
513
  (value === parentDir ? grantedWriteFolders : grantedWriteFiles).add(value);
443
514
  auditL1({ subject: value, granularity: value === parentDir ? "folder" : "file", original: absPath, decision: "session", scope: "session", cwd: opts.ctx.cwd, note: "write-session" });
444
- opts.ctx.ui?.notify?.(`pi-sandbox: allowed ${value} for this session (not saved) — re-running the command`, "info");
445
- onData(Buffer.from(`\n✅ pi-sandbox: write to ${value} allowed for this session. Command output with the new permission follows.\n`));
515
+ opts.ctx.ui?.notify?.(`pi-sandbox: allowed ${value} for this conversation (not saved) — re-running the command`, "info");
516
+ onData(Buffer.from(`\n✅ pi-sandbox: write to ${value} allowed for this conversation. Command output with the new permission follows.\n`));
446
517
  resolve(attempt([]));
447
518
  return;
448
519
  }
@@ -22,10 +22,18 @@ export interface SandboxFilesystem extends NonNullable<SandboxRuntimeConfig["fil
22
22
  outsideProject?: { read?: ReadPosture; allowRead?: string[] };
23
23
  }
24
24
 
25
- export interface SandboxConfig extends Omit<SandboxRuntimeConfig, "filesystem"> {
25
+ export interface SandboxNetwork extends Partial<NonNullable<SandboxRuntimeConfig["network"]>> {
26
+ /** Whether to allow localhost / loopback on all ports (default: true). Set false to strictly isolate network. */
27
+ allowLocalhost?: boolean;
28
+ /** Host TCP ports to bridge into the Linux sandbox namespace when allowLocalhost is false. */
29
+ bridgeHostPorts?: number[];
30
+ }
31
+
32
+ export interface SandboxConfig extends Omit<SandboxRuntimeConfig, "filesystem" | "network"> {
26
33
  enabled?: boolean;
27
34
  /** `default` = rules only; `advanced-secure` adds secret/credential detection (ADR-018). */
28
35
  mode?: PermissionMode;
36
+ network?: SandboxNetwork;
29
37
  filesystem?: SandboxFilesystem;
30
38
  /**
31
39
  * Additive project-local overrides written by the ask-tier prompts (Layer 1
@@ -40,6 +48,14 @@ export interface SandboxConfig extends Omit<SandboxRuntimeConfig, "filesystem">
40
48
  };
41
49
  /** Commands/paths that can print secrets (env, proc environ) and must ask first. */
42
50
  commands?: { ask?: string[] };
51
+ /** Allow all Unix domain sockets on Linux (disables seccomp socket blocking). */
52
+ allowAllUnixSockets?: boolean;
53
+ /** Allow local port binding. */
54
+ allowLocalBinding?: boolean;
55
+ /** Whether to allow localhost / loopback on all ports (default: true). Set false to strictly isolate network. */
56
+ allowLocalhost?: boolean;
57
+ /** Host TCP ports to bridge into the Linux sandbox namespace when allowLocalhost is false. */
58
+ bridgeHostPorts?: number[];
43
59
  }
44
60
 
45
61
  const BUILTIN_CONFIG: SandboxConfig = {
@@ -48,6 +64,7 @@ const BUILTIN_CONFIG: SandboxConfig = {
48
64
  network: {
49
65
  allowedDomains: [...BUILTIN_NETWORK_ALLOWED],
50
66
  deniedDomains: [],
67
+ allowLocalhost: true,
51
68
  },
52
69
  filesystem: {
53
70
  denyRead: [...DEFAULT_DENY_READ],
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Host loopback port bridge for Linux sandbox.
3
+ *
4
+ * Bubblewrap on Linux isolates the network namespace via `--unshare-net`.
5
+ * In that isolated namespace, loopback `127.0.0.1` is disconnected from the host,
6
+ * preventing tools (like Diffusion Studio CLI `dapi` or local dev servers) from
7
+ * reaching services running on the host's localhost (e.g. port 3274).
8
+ *
9
+ * This module creates a lightweight Unix domain socket bridge on the host
10
+ * (using Node's built-in `node:net`), bind-mounts the socket into bwrap,
11
+ * and starts a `socat` listener inside the container forwarding container
12
+ * `127.0.0.1:${port}` to the host service.
13
+ */
14
+
15
+ import { randomBytes } from "node:crypto";
16
+ import { existsSync, unlinkSync } from "node:fs";
17
+ import net from "node:net";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+
21
+ export interface HostPortBridge {
22
+ port: number;
23
+ sockPath: string;
24
+ close: () => void;
25
+ }
26
+
27
+ /**
28
+ * Start a Unix domain socket bridge on the host forwarding to host 127.0.0.1:port.
29
+ */
30
+ export async function startHostPortBridge(port: number): Promise<HostPortBridge> {
31
+ const id = randomBytes(6).toString("hex");
32
+ const sockPath = join(tmpdir(), `pi-host-bridge-${port}-${id}.sock`);
33
+
34
+ const server = net.createServer((client) => {
35
+ const target = net.connect(port, "127.0.0.1");
36
+ client.pipe(target).pipe(client);
37
+ client.on("error", () => target.destroy());
38
+ target.on("error", () => client.destroy());
39
+ });
40
+
41
+ await new Promise<void>((resolve, reject) => {
42
+ server.listen(sockPath, () => resolve());
43
+ server.on("error", reject);
44
+ });
45
+
46
+ return {
47
+ port,
48
+ sockPath,
49
+ close: () => {
50
+ try {
51
+ server.close();
52
+ } catch (err) {
53
+ void err;
54
+ }
55
+ try {
56
+ if (existsSync(sockPath)) unlinkSync(sockPath);
57
+ } catch (err) {
58
+ void err;
59
+ }
60
+ },
61
+ };
62
+ }
63
+
64
+ /**
65
+ * Start bridges for multiple ports concurrently.
66
+ */
67
+ export async function startHostPortBridges(ports: number[]): Promise<HostPortBridge[]> {
68
+ if (process.platform !== "linux" || !ports.length) return [];
69
+ return Promise.all(ports.map((p) => startHostPortBridge(p)));
70
+ }
71
+
72
+ /**
73
+ * Inject the bridges into the bwrap command invocation on Linux.
74
+ */
75
+ export function injectBridgesIntoBwrap(wrappedCommand: string, bridges: HostPortBridge[]): string {
76
+ if (process.platform !== "linux" || !bridges.length) return wrappedCommand;
77
+
78
+ const dashIndex = wrappedCommand.indexOf(" -- ");
79
+ if (dashIndex === -1) return wrappedCommand;
80
+
81
+ // 1. Add --bind for each socket before " -- "
82
+ const binds = bridges.map((b) => `--bind ${b.sockPath} ${b.sockPath}`).join(" ");
83
+ const bwrapPart = `${wrappedCommand.slice(0, dashIndex)} ${binds}`;
84
+ let shellPart = wrappedCommand.slice(dashIndex + 4);
85
+
86
+ // 2. Start socat listeners inside the container
87
+ const socatStarters = bridges
88
+ .map((b) => `socat TCP-LISTEN:${b.port},fork,reuseaddr UNIX-CONNECT:${b.sockPath} >/dev/null 2>&1 &\n_pi_bridge_pids="$_pi_bridge_pids $!"`)
89
+ .join("\n");
90
+
91
+ if (shellPart.includes("socat TCP-LISTEN:3128")) {
92
+ shellPart = shellPart.replace("socat TCP-LISTEN:3128", `${socatStarters}\nsocat TCP-LISTEN:3128`);
93
+ // Include our bridge pids in the script EXIT trap cleanup
94
+ shellPart = shellPart.replace("kill %1 %2 2>/dev/null;", "kill %1 %2 $_pi_bridge_pids 2>/dev/null;");
95
+ return `${bwrapPart} -- ${shellPart}`;
96
+ }
97
+
98
+ return wrappedCommand;
99
+ }
@@ -36,11 +36,13 @@ const SUPPRESSED_PROJECT_FILES = new Set([
36
36
  */
37
37
  export function suppressGhostDotfiles(): void {
38
38
  try {
39
+ /* SAFETY: DANGEROUS_FILES is an array of strings in sandbox-runtime. */
39
40
  const files = DANGEROUS_FILES as unknown as string[];
40
41
  const filteredFiles = files.filter((f) => !SUPPRESSED_PROJECT_FILES.has(f));
41
42
  files.length = 0;
42
43
  files.push(...filteredFiles);
43
44
 
45
+ /* SAFETY: DANGEROUS_DIRECTORIES is an array of strings in sandbox-runtime. */
44
46
  const dirs = DANGEROUS_DIRECTORIES as unknown as string[];
45
47
  const filteredDirs = dirs.filter((d) => d === ".git");
46
48
  dirs.length = 0;
@@ -64,8 +66,17 @@ type Layer1FilesystemKind = typeof OverrideKind.AllowWrite | typeof OverrideKind
64
66
  * filesystem.outsideProject.read gates reads.
65
67
  */
66
68
  function runtimeConfig(cwd: string, config: SandboxConfig): SandboxRuntimeConfig {
69
+ const allowLocalhost = config.allowLocalhost ?? config.network?.allowLocalhost ?? true;
70
+ const network = config.network
71
+ ? {
72
+ ...config.network,
73
+ allowAllUnixSockets: config.allowAllUnixSockets ?? config.network.allowAllUnixSockets,
74
+ allowLocalBinding: config.allowLocalBinding ?? config.network.allowLocalBinding ?? allowLocalhost,
75
+ }
76
+ : undefined;
77
+
67
78
  return {
68
- network: config.network,
79
+ network: network as NonNullable<SandboxRuntimeConfig["network"]>,
69
80
  filesystem: config.filesystem
70
81
  ? sandboxFilesystem(config.filesystem, { cwd, home: homedir() })
71
82
  : { denyRead: [], allowRead: [], allowWrite: [], denyWrite: [], disabled: true },
@@ -87,7 +98,8 @@ export async function initSandbox(cwd: string, config: SandboxConfig, deps?: Net
87
98
  export async function resetSandbox(): Promise<void> {
88
99
  try {
89
100
  await SandboxManager.reset();
90
- } catch {
101
+ } catch (err) {
102
+ void err;
91
103
  }
92
104
  }
93
105
 
@@ -4,7 +4,7 @@
4
4
  * Uses the same two-screen ask-tier as Layer 2 (once / session / remember
5
5
  * project|global) and the same grant semantics:
6
6
  *
7
- * - session grants: in memory only, cleared at `session_start`, never saved;
7
+ * - conversation grants: in memory only, cleared at `session_start`, never saved;
8
8
  * - "once" grants: one bash command's connections to that host (the proxy
9
9
  * calls back per request, so a redirect or a parallel connection must not
10
10
  * re-prompt), scoped by `beginNetworkCommand`/`endNetworkCommand`;
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * Headless (`hasUI === false`) denies, like every other gate.
16
16
  *
17
- * Session grants use the parent-domain wildcard when useful (covers all sibling
17
+ * Conversation grants use the parent-domain wildcard when useful (covers all sibling
18
18
  * subdomains). Screen 2 hides the "in this project" rows in untrusted
19
19
  * projects so the user can't quietly trust a widening file.
20
20
  */
@@ -22,7 +22,7 @@
22
22
  import { domainMatches, GrantScope, OverrideKind } from "../core/index";
23
23
  import { askMainWithRemember, askRememberHost, ASK_TIMEOUT_MS, MainChoice, parentDomainWildcard, type AskCtx, type HostGrant } from "../ui/ask-flow";
24
24
 
25
- /** In-memory session grants ("Yes, for this session"). Cleared at session_start. */
25
+ /** In-memory conversation grants ("Yes, for this conversation"). Cleared at session_start. */
26
26
  const sessionGrants: string[] = [];
27
27
  /** Hosts allowed for the current bash command ("Yes, just this once" covers its connections). */
28
28
  let commandGrants: Set<string> | null = null;
@@ -87,7 +87,7 @@ function firstWord(command: string | undefined): string | null {
87
87
 
88
88
  /**
89
89
  * Screen 1 (once / session / remember) plus, for remember, screen 2 (scope and
90
- * pattern). A session grant uses the parent-domain wildcard when the host has
90
+ * pattern). A conversation grant uses the parent-domain wildcard when the host has
91
91
  * a useful parent, so any sibling subdomain is covered for the rest of the
92
92
  * session; apex hosts (2 parts) fall back to the exact host because
93
93
  * `*.example.com` would not match `example.com`.
@@ -124,7 +124,7 @@ async function decide(deps: NetworkAskDeps, host: string, port: number | undefin
124
124
  bodyParts.join("\n"),
125
125
  {
126
126
  session: true,
127
- sessionLabel: "Yes, all in group for this session",
127
+ sessionLabel: "Yes, all in group for this conversation",
128
128
  allowFirst: true,
129
129
  icon: "net",
130
130
  timeoutMs: ASK_TIMEOUT_MS,
@@ -161,7 +161,7 @@ async function decide(deps: NetworkAskDeps, host: string, port: number | undefin
161
161
  if (mainChoice === MainChoice.Session) {
162
162
  sessionGrants.push(wildcard);
163
163
  deps.audit({ ...base, decision: "session", grant: wildcard, requested: host });
164
- ctx.ui.notify?.(`pi-sandbox: allowed for this session (not saved) → ${wildcard}`, "info");
164
+ ctx.ui.notify?.(`pi-sandbox: allowed for this conversation (not saved) → ${wildcard}`, "info");
165
165
  return true;
166
166
  }
167
167
 
@@ -5,15 +5,10 @@ import { scanToolOutput } from "../detect/index";
5
5
  export interface Exposure {
6
6
  /** Finding types, e.g. ["SECRET_ASSIGNMENT"]. Empty means clean. */
7
7
  types: string[];
8
- /** One block: `subject` then `lineNo: text` per detected line (max 8). */
8
+ /** One block: `Tool` header then `Finding <lineNo>: <line>` per detected line. */
9
9
  hits: string[];
10
10
  }
11
11
 
12
- const MAX_LINES = 8;
13
- const MAX_LINE_CHARS = 200;
14
-
15
- const clip = (s: string) => (s.length > MAX_LINE_CHARS ? `${s.slice(0, MAX_LINE_CHARS)}…` : s);
16
-
17
12
  export function collectExposure(content: ReadonlyArray<{ type: string; text?: string }>, subject: string): Exposure {
18
13
  const types = new Set<string>();
19
14
  const lines: string[] = [];
@@ -29,14 +24,9 @@ export function collectExposure(content: ReadonlyArray<{ type: string; text?: st
29
24
  if (after[i] !== before[i] && before[i].trim()) matchedIndices.push(i);
30
25
  }
31
26
  if (matchedIndices.length === 0) continue;
32
- const shown = matchedIndices.slice(0, MAX_LINES);
33
- const firstIdx = shown[0];
34
- const lastIdx = shown[shown.length - 1];
35
- const moreMatched = matchedIndices.length > MAX_LINES;
36
- const moreBelow = lastIdx < before.length - 1;
37
- if (firstIdx > 0) lines.push(" \u2026");
38
- for (const idx of shown) lines.push(`${idx + 1}: ${clip(before[idx].trim())}`);
39
- if (moreMatched || moreBelow) lines.push(" \u2026");
27
+ lines.push(`Tool ${subject}`);
28
+ // One `Finding` row per detected line, showing the complete line (no clipping).
29
+ for (const idx of matchedIndices) lines.push(`Finding ${idx + 1}: ${before[idx].trim()}`);
40
30
  }
41
- return { types: [...types], hits: lines.length ? [`From ${subject}\n${lines.join("\n")}`] : [] };
31
+ return { types: [...types], hits: lines.length ? [lines.join("\n")] : [] };
42
32
  }
@@ -1,11 +1,11 @@
1
1
  /**
2
- * In-memory session grants for the Advanced Secure output gate (ADR-018).
2
+ * In-memory conversation grants for the Advanced Secure output gate (ADR-018).
3
3
  *
4
4
  * When a CLI like `composio` returns output that matches a secret pattern
5
5
  * (JWT, OAuth refresh token, etc.), the user can pick "Yes, all <program>
6
- * output for this session" instead of approving every block. The program id
6
+ * output for this conversation" instead of approving every block. The program id
7
7
  * is added here, and the output gate short-circuits for the rest of the
8
- * session — same shape as path/host session grants, but for tool output.
8
+ * conversation — same shape as path/host conversation grants, but for tool output.
9
9
  *
10
10
  * Cleared at session_start (ADR-010), never written to disk. The credential
11
11
  * tier (denyRead / askRead) still wins on the file side; this only loosens
@@ -19,12 +19,12 @@ export function clearProgramOutputSessionGrants(): void {
19
19
  programOutputSessionGrants.clear();
20
20
  }
21
21
 
22
- /** Add a program to the session grant list. Idempotent. */
22
+ /** Add a program to the conversation grant list. Idempotent. */
23
23
  export function grantProgramOutputSession(programId: string): void {
24
24
  programOutputSessionGrants.add(programId.toLowerCase());
25
25
  }
26
26
 
27
- /** True when the program is already granted for the rest of the session. */
27
+ /** True when the program is already granted for the rest of the conversation. */
28
28
  export function isProgramOutputGranted(programId: string | undefined): boolean {
29
29
  if (!programId) return false;
30
30
  return programOutputSessionGrants.has(programId.toLowerCase());
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Program-id detection for the Advanced Secure output gate.
3
3
  *
4
- * Used to label the "This output may contain a secret" prompt with the binary
4
+ * Used to label the Advanced Secure output prompt with the binary
5
5
  * that produced it (`composio`, `aws`, `gcloud`, …) and to key the per-program
6
- * session grant (`isProgramOutputGranted`). Pure functions, no pi / fs / audit.
6
+ * conversation grant (`isProgramOutputGranted`). Pure functions, no pi / fs / audit.
7
7
  */
8
8
 
9
9
  /** Strip env assignments (`FOO=bar`), common wrappers (sudo, nice, command, …), and the
@@ -27,7 +27,7 @@ export function bashBinary(command: string | undefined): string | undefined {
27
27
 
28
28
  /** The program id for a tool call. Bash binaries only — MCP and other tools return
29
29
  * `undefined` so the Advanced Secure output gate doesn't offer them a per-program
30
- * session grant (MCP tools handle their own secrets and don't share the
30
+ * conversation grant (MCP tools handle their own secrets and don't share the
31
31
  * composio-style "same binary, same surface" pattern). */
32
32
  export function programIdForToolCall(toolName: string | undefined, input: unknown): string | undefined {
33
33
  if (!toolName) return undefined;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Layer 2 ask-tier prompts, session grants, and persisted "always" overrides
2
+ * Layer 2 ask-tier prompts, conversation grants, and persisted "always" overrides
3
3
  * (ADR-009, ADR-010). Owns the interactive UI calls; policy decisions come from
4
4
  * matching.ts.
5
5
  */
@@ -32,7 +32,7 @@ export function persistOverride(scope: GrantScope, cwd: string, kind: OverrideKi
32
32
  }
33
33
 
34
34
  /**
35
- * Grants from "yes — for this session" (ADR-010). In memory only, cleared on
35
+ * Grants from "yes — for this conversation" (ADR-010). In memory only, cleared on
36
36
  * session_start, never written to sandbox.json, never consulted for the
37
37
  * absolute-deny tier.
38
38
  */
@@ -67,7 +67,7 @@ export type UICtx = {
67
67
  };
68
68
 
69
69
  /**
70
- * Ask the user, then apply the answer: session grants stay in memory, "always"
70
+ * Ask the user, then apply the answer: conversation grants stay in memory, "always"
71
71
  * grants are persisted and announced to the other layer via `onPersist`.
72
72
  * Headless asks deny. A `null` return means the call may proceed.
73
73
  */
@@ -102,7 +102,7 @@ export async function askOrBlock(
102
102
  const value = ask.overrideKind === OverrideKind.AllowDomains || isSafeFolderGrant(parent, homedir()) ? parent : ask.overrideValue;
103
103
  sessionGrants.push({ kind: ask.overrideKind, value });
104
104
  audit({ layer: 2, tool: ask.tool, subject: ask.subject, reason: ask.reason, decision, grant: value, cwd: ctx.cwd });
105
- ctx.ui.notify(`security-guard: allowed for this session (not saved) → ${value}`, "info");
105
+ ctx.ui.notify(`security-guard: allowed for this conversation (not saved) → ${value}`, "info");
106
106
  return null;
107
107
  }
108
108
  if (decision === Decision.AlwaysCwd || decision === Decision.AlwaysGlobal || decision === Decision.AlwaysCwdFolder || decision === Decision.AlwaysGlobalFolder) {
@@ -3,7 +3,7 @@
3
3
  * it only calls the caller's `ctx.ui.select`, so the contract tests can script it.
4
4
  *
5
5
  * Every prompt is a question. Answers are uniformly `No` / `Yes, just this once` /
6
- * `Yes, for this session` / `Yes, always…` so row 2 is always "once". Screen 2
6
+ * `Yes, for this conversation` / `Yes, always…` so row 2 is always "once". Screen 2
7
7
  * collapses to "All in folder · in this project" / "Only <name> · in this project" /
8
8
  * "All in folder · in all projects" / "Only <name> · in all projects" — folder /
9
9
  * wildcard is preselected (the wider grant is the right answer almost every time).
@@ -214,7 +214,17 @@ async function askWithSelect(
214
214
  timeoutMs: number,
215
215
  footer: string | null,
216
216
  ): Promise<{ picked: string | undefined; expired: boolean }> {
217
- const selectTitle = footer ? `${title}\n\n${footer}` : title;
217
+ // Guard against terminal overflow in non-custom/RPC mode for long scripts
218
+ let boundedTitle = title;
219
+ const lines = title.split("\n");
220
+ const MAX_FALLBACK_LINES = 16;
221
+ if (lines.length > MAX_FALLBACK_LINES) {
222
+ const header = lines[0];
223
+ const preview = lines.slice(1, MAX_FALLBACK_LINES).join("\n");
224
+ boundedTitle = `${header}\n${preview}\n\n[... ${lines.length - MAX_FALLBACK_LINES} more lines truncated]`;
225
+ }
226
+
227
+ const selectTitle = footer ? `${boundedTitle}\n\n${footer}` : boundedTitle;
218
228
  if (timeoutMs === 0) {
219
229
  const picked = await ctx.ui.select(selectTitle, options);
220
230
  return { picked, expired: false };
@@ -294,10 +304,10 @@ function withIcon(icon: string | undefined, header: string): string {
294
304
  export type MainOpts = {
295
305
  /** Offer `Yes, just this once` (default on). */
296
306
  once?: boolean;
297
- /** Offer `Yes, for this session` (opt-in). */
307
+ /** Offer `Yes, for this conversation` (opt-in). */
298
308
  session?: boolean;
299
- /** Override the session label so the caller can name what the session grant covers
300
- * (`Yes, for this session` for files, `Yes, all in group for this session` for networks). */
309
+ /** Override the session label so the caller can name what the conversation grant covers
310
+ * (`Yes, for this conversation` for files, `Yes, all in group for this conversation` for networks). */
301
311
  sessionLabel?: string;
302
312
  /** Offer `Yes, always…` (default on). */
303
313
  remember?: boolean;
@@ -322,7 +332,7 @@ export type MainOpts = {
322
332
  * highlighted.
323
333
  */
324
334
  export async function askMain(ctx: AskCtx, header: string, body: string, opts: MainOpts = {}): Promise<MainChoice> {
325
- const sessionLabel = opts.sessionLabel ?? "Yes, for this session";
335
+ const sessionLabel = opts.sessionLabel ?? "Yes, for this conversation";
326
336
  const choices: Array<{ label: string; value: MainChoice }> = [];
327
337
  choices.push({ label: "No", value: MainChoice.Block });
328
338
  if (opts.once !== false) choices.push({ label: "Yes, just this once", value: MainChoice.Once });
@@ -444,19 +454,21 @@ export type ExposureChoice = (typeof ExposureChoice)[keyof typeof ExposureChoice
444
454
 
445
455
  /** Advanced Secure output gate (ADR-018): show where it was found and ask before the output reaches the model.
446
456
  * When `programId` is set, an extra option lets the user grant the rest of the
447
- * session for that program — same pattern as path/host session grants, but for
457
+ * conversation for that program — same pattern as path/host conversation grants, but for
448
458
  * tool output (display, not access). */
449
459
  export async function askExposure(ctx: AskCtx, hits: string[], programId?: string): Promise<ExposureChoice> {
450
460
  const choices: Array<{ label: string; value: ExposureChoice }> = [
451
461
  { label: "No, keep it hidden (recommended)", value: ExposureChoice.Block },
452
462
  { label: "Yes, show it this once", value: ExposureChoice.Allow },
453
463
  ];
454
- if (programId) choices.push({ label: `Yes, all ${programId} output for this session`, value: ExposureChoice.ProgramSession });
464
+ if (programId) choices.push({ label: `Yes, all ${programId} output for this conversation`, value: ExposureChoice.ProgramSession });
455
465
  const titleParts = [
456
- `${ICON.cred} This output may contain a secret \u2014 show it to the AI?`,
466
+ `${ICON.warn} Sensitive information detected`,
457
467
  "",
458
468
  hits.join("\n\n"),
459
469
  "",
470
+ "Question Should the AI be allowed to see it?",
471
+ "",
460
472
  "Note you'll be asked again each time a secret shows up",
461
473
  ];
462
474
  const { picked } = await askSelect(ctx, titleParts.join("\n"), choices.map((c) => c.label), undefined, { footer: "Default: No" });