Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(hooks): structured hook-reply answers for plans and questions
review7a7e0d280b22
diff --git a/CLAUDE.md b/CLAUDE.mdindex f5caf83ef..995b1d164 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2176,6 +2176,24 @@ terminal opens keep their existing identity policy; Server Edition still requirefor every control verb. Legacy mobile/SSH callers must present this instance’s node token forcommand-bearing opens; this does not add a human-confirm dialog or change mobile transport APIs.+- **Hook-reply answers: plans and questions** (`core/agents/permission-decision.ts`, full write-up in+ **`docs/hook-reply-approvals.md`**) — the managed hook holds a Claude `PermissionRequest` and polls an+ answer file. For `ExitPlanMode` / `AskUserQuestion` (`requiresUserInteraction`) Claude **DROPS a bare+ allow**, so the answer must carry `updatedInput`: plan = `{}` (+ optional session `setMode+ acceptEdits|default`, never `auto`), question = the request's own `questions` + `answers`. Rules a+ refactor must not undo: (1) **only core builds decision JSON**, from the pending request file on the+ agent's host (never renderer-echoed questions), validating every field; (2) the script prints only the+ fixed words' decisions or a file that passes the strict prefix/size/one-line bound+ (`isBoundedAnswerContent` is the TS twin — both writers refuse anything the script would ignore);+ (3) answer content never rides an argv (the answered POST carries the decoded verb; SSH writes go on+ stdin); (4) a plain `allow` maps to `updatedInput:{}` for a plan and is swallowed (hook keeps+ holding) for a question — core refuses to write it and the header hides ✓ Approve for that ticket;+ (5) these two tools hold 540 s (`PERM_WAIT_SECS_INTERACTIVE`) under the 600 s default command-hook+ timeout our installers never override — except a subagent's request, whose dialog awaits the hook.+ An old script on an SSH host ignores JSON answers (prints nothing → TUI answers). The renderer gets+ `held: {pendingId, toolName}` on the event/store (kept while blocked OR waiting), separate from the+ approve/deny `pendingId` the mirror strips from a question. Desktop local + SSH, Server Edition local;+ relay unchanged; phone keeps `allow`/`deny` (its plan approve now works via the script mapping).- **Per-node hook identity** (`src/core/agents/node-auth-*.ts`, `node-token-*.ts`,`node-identity-policy.ts` — full write-up in **`docs/node-identity.md`**) — the shared bearer proves"a session on this machine", never *which* session, so every node also gets a capability deriveddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 25da39d88..c054b5b35 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -141,6 +141,14 @@ lane unaffected.from a background header: only the active SSH project is git-routable. SSH headers observeSource refreshes instead.+- **Hook decision JSON is built in core, never in the renderer or the script.** To answer a held+ Claude permission request with more than `allow`/`deny` (a plan's follow-on mode, a question's+ answers), send a `PermissionAnswer` through `answerPermission`; `core/agents/permission-decision.ts`+ validates it against the pending request file on the agent's host and writes the JSON. The managed+ hook prints a JSON answer only after a strict prefix/size/one-line check, so a new decision shape+ must pass `isBoundedAnswerContent` or it is silently ignored. Answer content never goes on an argv.+ See `docs/hook-reply-approvals.md`.+- **Never call the user's machine a Mac in user-visible copy.** Use `thisMachine()` /`thisMachineCap()` / `machineNoun()` from `src/renderer/lib/machineName.ts` — "this Mac" onmacOS, "this PC" on Windows, "this computer" elsewhere and in any Server Edition browser tabdiff --git a/docs/hook-reply-approvals.md b/docs/hook-reply-approvals.mdindex 11edfedcd..2f553d035 100644--- a/docs/hook-reply-approvals.md+++ b/docs/hook-reply-approvals.md@@ -9,9 +9,13 @@ host over SSH** (no route to the desktop's loopback server), so the reply channe## Why replace send-keysThe phone's quick-approve today types `1`/Escape into tmux. It depends on the permission-prompt being on screen, focused, and numbered the way we assume. Hook-reply is deterministic:-Claude Code applies the decision before ever painting the prompt; on timeout it falls through-to the normal interactive prompt (fail-open, bit-for-bit legacy).+prompt being on screen, focused, and numbered the way we assume. Hook-reply is deterministic.+On the main thread Claude Code runs the hook CONCURRENTLY with the painted dialog — whichever+answers first (the hook's decision or the user in the TUI) wins and the later one is ignored+(research: docs/superpowers/plans/2026-09-26-answer-paths-research.md §1; an earlier version of+this doc said the decision lands "before the prompt is painted", which is true only for a+subagent's request, whose dialog awaits the hook). On timeout the hook prints nothing and the+dialog simply stays (fail-open, bit-for-bit legacy).## Mechanism@@ -23,9 +27,10 @@ env:3. POST to the loopback hook server as today (fire-and-forget status flow — this is how themirror/inbox learns `pendingId`).4. Poll `~/.nodeterm/pending/<pendingId>.answer` every 0.5 s up to `NODETERM_PERM_WAIT_SECS`- (default injected: 45; hook must stay under Claude's own hook timeout).-5. Answer file appears: read it (`allow` | `deny`), `rm -f` both files, print the decision- JSON to stdout:+ (default injected: 45; hook must stay under Claude's own hook timeout) — or up to+ `PERM_WAIT_SECS_INTERACTIVE` (540) for `ExitPlanMode` / `AskUserQuestion`, see below.+5. Answer file appears: decode it (see "Plans and questions"), `rm -f` both files, print the+ decision JSON to stdout:`{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}`(deny adds a short `"message"`). Exit 0.6. Timeout: `rm -f` the request file, print **nothing**, exit 0 → Claude shows its normal@@ -59,9 +64,79 @@ boot and hourly (orphans from killed sessions). The phone/desktop never create afor pendingIds they didn't read from a live approval event, and re-check the event is stillunresolved before writing.-## Out of scope (v1)+## Plans and questions (structured answers, 2026-09)++`ExitPlanMode` and `AskUserQuestion` both set `requiresUserInteraction`, and for those two tools+Claude Code **drops a bare `{"behavior":"allow"}`** (`if(!I.updatedInput&&e.requiresUserInteraction?.())+return null` — research §2). So v1's Approve on a plan (header button, phone) was a silent no-op,+and a question could not be answered at all. A decision that carries `updatedInput` works:++- **Plan approve** = allow + `updatedInput:{}` — never the echoed `tool_input`, whose `plan` would+ read as "edited by user". No `updatedPermissions` = restore the mode that preceded plan mode (the+ tool's own `call()` restores it, including auto's dangerous-rule strip); accept-edits / ask-each-time+ add `[{"type":"setMode","mode":"acceptEdits"|"default","destination":"session"}]`. There is+ deliberately **no `setMode auto`** — that path skips the strip.+- **Plan revise** ("No, keep planning") = deny with the user's feedback as `message`, no `interrupt`.+- **Question** = allow + `updatedInput: {...tool_input, answers: {"<exact question>": "<label>"}}`;+ multi-select labels are joined with `", "`; an entry the answer marks as free text carries typed text.++**Who builds what.** The answer file may now hold, besides `allow`/`deny`, one line of decision JSON.+Core builds it (`core/agents/permission-decision.ts`, `buildPermissionDecision`) from a+`PermissionAnswer` (`shared/agents/permission-answer.ts`) and the **pending request file on the+agent's host** — the only source of truth for the tool and for `questions` (never renderer-echoed+data). Every field is validated: the tool must match, plan modes are a closed enum, a label must+exist in that question's options unless the entry is explicitly free text, several labels only on a+multiSelect question, sizes capped (text 8000 chars, the whole decision 64 KB). A structured answer+is refused when the request file is gone (the hold ended) — the call resolves `false`.++**What the script prints** (`managed-script.ts`, tested under a real `/bin/sh` in+`managed-script.answer.test.ts`): only (a) the fixed decisions for the words `allow`/`deny`, or (b)+the answer file VERBATIM when it starts with exactly+`{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":` + `"allow"`/`"deny"`,+ends with `}`, is at most 64 KB and has no control bytes (so it is one line). Anything else prints+nothing — exactly what every earlier build did with an unknown answer. The answered POST carries the+decoded VERB, never the file (a structured answer holds user text, and nothing from it may reach an+argv). Remote answers travel on the SSH command's stdin for the same reason.++**The plain words, per tool** (so the phone and the header button need no change):++| answer file | ExitPlanMode | AskUserQuestion | anything else |+|---|---|---|---|+| `allow` | allow + `updatedInput:{}` (restore mode) | consumed, **hook keeps holding** | bare allow (unchanged) |+| `deny` | fixed deny | fixed deny (declines the picker) | fixed deny |++A plain `allow` on a question is swallowed rather than printed because Claude would drop it anyway;+printing it would only end the hook, closing the chat-view answer path while changing nothing in+the TUI. Core also refuses to write it (`answerPermission` → `false`) so no surface flips the badge+for an answer that did nothing, and the header hides ✓ Approve for that ticket.++**Hold time.** For these two tools the hook holds `PERM_WAIT_SECS_INTERACTIVE` = 540 s instead of 45 s+— people read plans for minutes. Our installers write **no `timeout`** on the PermissionRequest entry,+so Claude's command-hook default of 600 s applies (pinned in `managed-script.answer.test.ts`), leaving a+60 s margin. Because the main-thread dialog is painted concurrently, a long hold blocks nothing. A+**subagent's** request keeps the short hold: its dialog awaits the hook, so 540 s there would hide the+prompt (detected by an `"agent_id":` key in the payload — a false positive only shortens the hold).+The tool name is read from the FIRST `"tool_name":` in the payload and trusted only when no+`"tool_input"` precedes it, so a nested key inside some tool's input can never make an ordinary tool+look like a plan (an empty/unsafe name degrades to today's default behavior).++**Old script on an SSH host.** The script on a host is rewritten only at connect. An old script reads a+JSON answer as neither `allow` nor `deny`, removes the files and prints nothing, so the TUI dialog still+answers — a safe degrade (verified by running the new sh tests against the previous script). Its plan+`allow` stays the old silent no-op until the project reconnects.++**Renderer.** A held request's `{pendingId, toolName}` rides the normalized event as `held` and the+agent-status store keeps it while the node is `blocked` or `waiting` — separate from `pendingId`, which+the mirror still strips from a question so approve/deny never lights on a picker. The phone mirror file+is unchanged (`held` is not persisted there).++**Surfaces.** Desktop: local + SSH (ControlMaster read + stdin write). Server Edition: local projects+(SSH projects remain unsupported there, as before). Relay: unchanged. Mobile: keeps writing+`allow`/`deny`; its plan approve now works through the script mapping once the host's script is current;+structured answers from the phone are an iOS follow-up.++## Out of scope-- Questions (AskUserQuestion) — a hook cannot inject an answer value; digits remain.- "Always allow" via hook `updatedPermissions`.- codex/gemini permission hooks (unverified decision contracts).- The desktop notch/HUD overlay (separate feature).diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 8aa145b72..2fddec6a7 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import fs from 'fs'import os from 'os'import path from 'path'-import type { NormalizedAgentEvent } from '@shared/agents/normalize'+import { normalizeClaude, type NormalizedAgentEvent } from '@shared/agents/normalize'import { syntheticAnsweredEvent } from './agents/pending-approvals'import {reduceEntry,@@ -1114,6 +1114,36 @@ describe('recordAgentEvent enrichment (returned broadcast event)', () => {expect(out.pendingId).toBeUndefined() // suppressed — approve/deny on a question is wrong UX})+ it('a held QUESTION keeps its `held` ticket for structured answers while pendingId stays stripped', () => {+ // Real sequence: the picker's PreToolUse, then its PermissionRequest held by the managed hook.+ const input = { questions: [{ question: 'Which theme?', options: [{ label: 'Dark' }, { label: 'Light' }] }] }+ const pre = { hook_event_name: 'PreToolUse', session_id: 's', tool_name: 'AskUserQuestion', tool_use_id: 't1', tool_input: input }+ recordRawToolEvent('e9', pre)+ const first = normalizeClaude({ nodeId: 'e9', agentId: 'claude', payload: pre })+ if (first) recordAgentEvent(first)+ const perm = normalizeClaude({+ nodeId: 'e9',+ agentId: 'claude',+ payload: { hook_event_name: 'PermissionRequest', session_id: 's', tool_name: 'AskUserQuestion', tool_input: input, nodeterm_pending_id: 'e9-1-1' }+ })!+ const out = recordAgentEvent(perm)+ expect(out.askKind).toBe('question')+ expect(out.pendingId).toBeUndefined() // no approve/deny on a picker — unchanged+ expect(out.held).toEqual({ pendingId: 'e9-1-1', toolName: 'AskUserQuestion' })+ })++ it('a held PLAN is an approval: keeps pendingId (header Approve works) and names ExitPlanMode', () => {+ const perm = normalizeClaude({+ nodeId: 'e10',+ agentId: 'claude',+ payload: { hook_event_name: 'PermissionRequest', session_id: 's', tool_name: 'ExitPlanMode', tool_input: { plan: 'p' }, nodeterm_pending_id: 'e10-1-1' }+ })!+ const out = recordAgentEvent(perm)+ expect(out.askKind).toBe('approval')+ expect(out.pendingId).toBe('e10-1-1')+ expect(out.held).toEqual({ pendingId: 'e10-1-1', toolName: 'ExitPlanMode' })+ })+it('a genuine approval keeps its pendingId and gains askKind:approval', () => {const out = recordAgentEvent(ev({ nodeId: 'e2', state: 'blocked', pendingId: 'e2-1-1' }))expect(out.state).toBe('blocked')diff --git a/src/core/agents/answer-permission-parity.test.ts b/src/core/agents/answer-permission-parity.test.tsnew file mode 100644index 000000000..1bd187af9--- /dev/null+++ b/src/core/agents/answer-permission-parity.test.ts@@ -0,0 +1,31 @@+// Both shells must answer a held permission request through the ONE core body+// (`answerHeldPermission`), passing the structured `answer` through. A handler that kept reading only+// `decision` would compile, pass every other test, and silently drop plan/question answers on that+// shell — the one-shell drift this repo has shipped before (see hook-verified-parity.test.ts).+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { describe, expect, it } from 'vitest'++const root = resolve(__dirname, '../../..')+const handler = (file: string): string => {+ const src = readFileSync(resolve(root, file), 'utf8')+ const at = src.indexOf('IPC.agentAnswerPermission')+ expect(at, `${file} registers the handler`).toBeGreaterThan(-1)+ return src.slice(at, at + 2500)+}++describe('answerPermission handler parity', () => {+ for (const file of ['src/main/index.ts', 'src/server/index.ts']) {+ it(`${file} routes through answerHeldPermission with the structured answer`, () => {+ const body = handler(file)+ expect(body).toContain('answerHeldPermission(')+ expect(body).toContain('answer: payload.answer')+ expect(body).toContain('decision: payload.decision')+ // The optimistic flip reports the verb core decided, not the renderer's legacy field.+ expect(body).toContain('syntheticAnsweredEvent(nodeId, pendingId, res.decision)')+ })+ }+ it('the desktop reads the held request over SSH for a remote node', () => {+ expect(handler('src/main/index.ts')).toContain('readPendingRequest(sshProjectId, pendingId)')+ })+})diff --git a/src/core/agents/hooks/managed-script.answer.test.ts b/src/core/agents/hooks/managed-script.answer.test.tsnew file mode 100644index 000000000..aa3205d17--- /dev/null+++ b/src/core/agents/hooks/managed-script.answer.test.ts@@ -0,0 +1,316 @@+// The managed hook's answer-file decoder, executed under a REAL /bin/sh (the discipline every+// generated shell in this repo is held to — canvas-control-shim.test.ts, remote-claude-usage.test.ts).+// A string assertion on the script proves nothing about what `case` or `${#x}` actually do in dash.+//+// Harness: a fake `curl` records every invocation (argv = what `ps` would show, stdin = the curl+// config), and a fake `sleep` — dash has no builtin sleep — counts the poll iterations and, on the+// Nth one, drops a scripted answer file next to the held request. That makes a 540 s hold testable+// in ~a second and every branch deterministic.+import { spawnSync } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, beforeEach, describe, expect, it } from 'vitest'+import { buildManagedScript } from './managed-script'+import {+ buildPermissionDecision,+ parsePendingRequest,+ PERMISSION_DECISION_MAX_BYTES,+ PERMISSION_DECISION_PREFIX,+ PERM_WAIT_SECS_INTERACTIVE,+ type PendingRequest+} from '../permission-decision'+import { mergeManagedHook } from './install-helper'+import { CLAUDE_HOOK_EVENTS } from '../../../shared/agents/hook-events'++const sh = spawnSync('sh', ['-c', 'exit 0'])+const shAvailable = sh.status === 0 && !sh.error && process.platform !== 'win32'++const ALLOW = `${PERMISSION_DECISION_PREFIX}"allow"}}}`+const ALLOW_PLAN = `${PERMISSION_DECISION_PREFIX}"allow","updatedInput":{}}}}`+const DENY = `${PERMISSION_DECISION_PREFIX}"deny","message":"Denied from nodeterm."}}}`++const QUESTIONS = [+ {+ question: 'Which surfaces should get it?',+ header: 'Surfaces',+ options: [{ label: 'Desktop', description: 'Electron' }, { label: 'Phone', description: 'iOS' }],+ multiSelect: true+ }+]++function envelope(toolName: string, toolInput: unknown, extra: Record<string, unknown> = {}): string {+ return JSON.stringify({+ session_id: 's-1',+ transcript_path: '/home/u/.claude/projects/x/s-1.jsonl',+ cwd: '/home/u/proj',+ permission_mode: 'plan',+ ...extra,+ hook_event_name: 'PermissionRequest',+ tool_name: toolName,+ tool_input: toolInput,+ permission_suggestions: []+ })+}++function built(payload: string, answer: Parameters<typeof buildPermissionDecision>[1]): string {+ const r = buildPermissionDecision(parsePendingRequest(payload) as PendingRequest, answer)+ if (!r.ok) throw new Error(r.reason)+ return r.content+}++interface Run {+ status: number | null+ stdout: string+ /** Poll iterations the hook waited through. */+ sleeps: number+ /** Every curl invocation: its argv and the config it read on stdin. */+ calls: { argv: string; cfg: string }[]+ pendingLeft: string[]+}++describe.skipIf(!shAvailable)('managed hook answer decoding, under /bin/sh', () => {+ const root = shAvailable ? mkdtempSync(join(tmpdir(), 'nt-hook-answer-')) : ''+ let n = 0+ afterAll(() => {+ if (root) rmSync(root, { recursive: true, force: true })+ })++ let dir = ''+ beforeEach(() => {+ fresh()+ })++ /**+ * Run claude's hook on `payload` with NODETERM_PERM_WAIT_SECS=1 (a 2-poll default hold).+ * `answers[k]` is written as the answer file on the k-th poll (1-based).+ */+ function run(payload: string, answers: Record<number, string> = {}): Run {+ const home = join(dir, 'home')+ const bin = join(dir, 'bin')+ const answersDir = join(dir, 'answers')+ const log = join(dir, 'curl.log')+ const count = join(dir, 'sleeps')+ mkdirSync(join(home, '.nodeterm'), { recursive: true })+ mkdirSync(bin, { recursive: true })+ mkdirSync(answersDir, { recursive: true })+ for (const [k, v] of Object.entries(answers)) writeFileSync(join(answersDir, k), v, 'utf8')+ const endpoint = join(home, '.nodeterm', 'hook-endpoint.env')+ writeFileSync(endpoint, 'NODETERM_HOOK_PORT=45999\nNODETERM_HOOK_TOKEN=tok\nNODETERM_HOOK_VERSION=2\n', 'utf8')+ writeFileSync(+ join(bin, 'curl'),+ [+ '#!/bin/sh',+ `printf 'ARGV %s\\n' "$*" >> ${JSON.stringify(log)}`,+ `sed 's/^/CFG /' >> ${JSON.stringify(log)}`,+ `printf 'END\\n' >> ${JSON.stringify(log)}`,+ "printf '200'",+ 'exit 0',+ ''+ ].join('\n'),+ { mode: 0o755 }+ )+ writeFileSync(+ join(bin, 'sleep'),+ [+ '#!/bin/sh',+ `c=$(cat ${JSON.stringify(count)} 2>/dev/null || echo 0)`,+ 'c=$((c + 1))',+ `echo "$c" > ${JSON.stringify(count)}`,+ `a=${JSON.stringify(answersDir)}/$c`,+ 'if [ -f "$a" ]; then',+ ' for p in "$HOME"/.nodeterm/pending/*.json; do',+ ' [ -f "$p" ] && cp "$a" "${p%.json}.answer"',+ ' done',+ 'fi',+ 'exit 0',+ ''+ ].join('\n'),+ { mode: 0o755 }+ )+ const script = join(dir, 'claude.sh')+ writeFileSync(script, buildManagedScript('claude'), { mode: 0o755 })+ const res = spawnSync('sh', [script], {+ encoding: 'utf8',+ input: payload,+ cwd: dir,+ env: {+ PATH: `${bin}:${process.env.PATH ?? ''}`,+ HOME: home,+ NODETERM_NODE_ID: 'node-1',+ NODETERM_HOOK_ENDPOINT: endpoint,+ NODETERM_PERM_WAIT_SECS: '1'+ }+ })+ // The "answered" POST is backgrounded; give it a moment to land before reading the log.+ const deadline = Date.now() + 3000+ const wantAnswered = res.stdout.trim().length > 0+ while (wantAnswered && Date.now() < deadline) {+ const txt = existsSync(log) ? readFileSync(log, 'utf8') : ''+ if ((txt.match(/^END$/gm) ?? []).length >= 2) break+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20)+ }+ const calls: { argv: string; cfg: string }[] = []+ if (existsSync(log)) {+ let argv = ''+ let cfg: string[] = []+ for (const line of readFileSync(log, 'utf8').split('\n')) {+ if (line.startsWith('ARGV ')) {+ argv = line.slice(5)+ cfg = []+ } else if (line.startsWith('CFG ')) cfg.push(line.slice(4))+ else if (line === 'END') calls.push({ argv, cfg: cfg.join('\n') })+ }+ }+ const pendingDir = join(home, '.nodeterm', 'pending')+ return {+ status: res.status,+ stdout: res.stdout,+ sleeps: existsSync(count) ? Number(readFileSync(count, 'utf8').trim()) : 0,+ calls,+ pendingLeft: existsSync(pendingDir)+ ? readdirSync(pendingDir).filter((f) => f.endsWith('.json') || f.endsWith('.answer'))+ : []+ }+ }++ /** Each run needs its own dir: the fake sleep's counter and the answer schedule live there. */+ function fresh(): void {+ dir = join(root, `case-${++n}`)+ mkdirSync(dir, { recursive: true })+ }++ const answeredVerbs = (r: Run): string[] =>+ r.calls.map((c) => /nodeterm_answered=(\S*)/.exec(c.argv)?.[1]).filter((v): v is string => v !== undefined)++ it('legacy allow / deny on an ordinary tool: byte-identical decisions', () => {+ const allow = run(envelope('Bash', { command: 'ls' }), { 1: 'allow' })+ expect(allow.stdout).toBe(`${ALLOW}\n`)+ expect(answeredVerbs(allow)).toEqual(['allow'])+ fresh()+ const deny = run(envelope('Bash', { command: 'ls' }), { 1: 'deny' })+ expect(deny.stdout).toBe(`${DENY}\n`)+ expect(answeredVerbs(deny)).toEqual(['deny'])+ })++ it('a plain allow on ExitPlanMode prints updatedInput:{} (Claude drops a bare allow there)', () => {+ const r = run(envelope('ExitPlanMode', { plan: '# Plan', planFilePath: '/p.md' }), { 1: 'allow' })+ expect(r.stdout).toBe(`${ALLOW_PLAN}\n`)+ expect(answeredVerbs(r)).toEqual(['allow'])+ expect(r.pendingLeft).toEqual([])+ })++ it('a plain deny on ExitPlanMode is still the fixed deny', () => {+ expect(run(envelope('ExitPlanMode', { plan: 'p' }), { 1: 'deny' }).stdout).toBe(`${DENY}\n`)+ })++ it('a plain allow on AskUserQuestion is consumed and the hook KEEPS HOLDING for a real answer', () => {+ const payload = envelope('AskUserQuestion', { questions: QUESTIONS })+ const answer = built(payload, { kind: 'question', answers: { 'Which surfaces should get it?': ['Desktop', 'Phone'] } })+ const r = run(payload, { 1: 'allow', 3: answer })+ expect(r.stdout).toBe(`${answer}\n`)+ expect(r.sleeps).toBe(3)+ // Exactly one answered POST (for the real answer), never one for the swallowed allow.+ expect(answeredVerbs(r)).toEqual(['allow'])+ })++ it('a core-built plan decision is printed verbatim and nothing from it reaches an argv', () => {+ const payload = envelope('ExitPlanMode', { plan: 'p' })+ const answer = built(payload, { kind: 'plan', mode: 'acceptEdits' })+ const r = run(payload, { 1: answer })+ expect(r.stdout).toBe(`${answer}\n`)+ expect(JSON.parse(r.stdout).hookSpecificOutput.decision.updatedPermissions).toEqual([+ { type: 'setMode', mode: 'acceptEdits', destination: 'session' }+ ])+ for (const c of r.calls) {+ expect(c.argv).not.toContain('hookSpecificOutput')+ expect(c.argv).not.toContain('setMode')+ }+ expect(answeredVerbs(r)).toEqual(['allow'])+ })++ it('hostile feedback text survives verbatim and executes nothing', () => {+ const payload = envelope('ExitPlanMode', { plan: 'p' })+ const hostile = `it's $(touch PWNED) \`touch PWNED2\` "q" \\ ; rm -rf ~ | x\ny`+ const answer = built(payload, { kind: 'plan-revise', message: hostile })+ const r = run(payload, { 1: answer })+ expect(r.stdout).toBe(`${answer}\n`)+ expect(JSON.parse(r.stdout).hookSpecificOutput.decision.message).toContain("$(touch PWNED)")+ expect(existsSync(join(dir, 'PWNED'))).toBe(false)+ expect(existsSync(join(dir, 'PWNED2'))).toBe(false)+ expect(answeredVerbs(r)).toEqual(['deny'])+ for (const c of r.calls) expect(c.argv).not.toContain('PWNED')+ })++ it('refuses anything that is not a bounded core decision: prints nothing, posts no answer', () => {+ const payload = envelope('Bash', { command: 'ls' })+ const hostile = [+ 'yes',+ 'allow deny',+ '{"hookSpecificOutput":{"hookEventName":"PreToolUse","decision":{"behavior":"allow"}}}',+ `${PERMISSION_DECISION_PREFIX}"ask"}}}`,+ `${ALLOW}\n{"hookSpecificOutput":{}}`,+ `${PERMISSION_DECISION_PREFIX}"allow","m":"\u001b]52;c;cHduZWQ=\u0007"}}}`,+ `${PERMISSION_DECISION_PREFIX}"allow"`,+ `${PERMISSION_DECISION_PREFIX}"allow","x":"${'a'.repeat(PERMISSION_DECISION_MAX_BYTES)}"}}}`+ ]+ for (const h of hostile) {+ fresh()+ const r = run(payload, { 1: h })+ expect(r.stdout, JSON.stringify(h.slice(0, 80))).toBe('')+ expect(answeredVerbs(r), JSON.stringify(h.slice(0, 80))).toEqual([])+ expect(r.status).toBe(0)+ }+ })++ it(`holds ExitPlanMode / AskUserQuestion for ${PERM_WAIT_SECS_INTERACTIVE}s, everything else for the armed default`, () => {+ const plan = run(envelope('ExitPlanMode', { plan: 'p' }))+ expect(plan.sleeps).toBe(PERM_WAIT_SECS_INTERACTIVE * 2)+ expect(plan.stdout).toBe('')+ expect(plan.pendingLeft).toEqual([]) // timeout still cleans up the request file+ fresh()+ expect(run(envelope('AskUserQuestion', { questions: QUESTIONS })).sleeps).toBe(PERM_WAIT_SECS_INTERACTIVE * 2)+ fresh()+ expect(run(envelope('Bash', { command: 'ls' })).sleeps).toBe(2)+ }, 60_000)++ it('a SUBAGENT\'s plan/question keeps the short hold (its dialog waits for the hook)', () => {+ const r = run(envelope('ExitPlanMode', { plan: 'p' }, { agent_id: 'a-1', agent_type: 'Plan' }))+ expect(r.sleeps).toBe(2)+ // …but its plain allow is still mapped, so an answer inside the window works.+ fresh()+ expect(run(envelope('ExitPlanMode', { plan: 'p' }, { agent_id: 'a-1' }), { 1: 'allow' }).stdout).toBe(`${ALLOW_PLAN}\n`)+ })++ it('a nested "tool_name" inside tool_input can never make an ordinary tool look like a plan', () => {+ // Reordered envelope: tool_input BEFORE tool_name, carrying a spoofed key. The script must not+ // trust the first match here — it would replace this MCP tool's input with {} on an allow.+ const spoof = JSON.stringify({+ session_id: 's',+ hook_event_name: 'PermissionRequest',+ tool_input: { tool_name: 'ExitPlanMode', q: 'x' },+ tool_name: 'mcp__srv__do'+ })+ const r = run(spoof, { 1: 'allow' })+ expect(r.stdout).toBe(`${ALLOW}\n`)+ fresh()+ expect(run(spoof).sleeps).toBe(2)+ // And a nested key AFTER the real one is simply never read.+ fresh()+ const after = envelope('mcp__srv__do', { nested: { tool_name: 'ExitPlanMode' } })+ expect(run(after, { 1: 'allow' }).stdout).toBe(`${ALLOW}\n`)+ })+})++describe('hold time vs Claude\'s command-hook timeout', () => {+ it('our installer writes NO timeout on the PermissionRequest entry, so Claude\'s 600 s default applies', () => {+ const merged = mergeManagedHook({}, "sh '/x/agent-hooks/claude.sh'", CLAUDE_HOOK_EVENTS)+ const entry = merged.hooks?.PermissionRequest?.[0]?.hooks?.[0] as Record<string, unknown>+ expect(entry).toBeDefined()+ expect(entry).not.toHaveProperty('timeout')+ })+ it('the interactive hold leaves at least a minute of margin under 600 s', () => {+ expect(PERM_WAIT_SECS_INTERACTIVE).toBeLessThanOrEqual(600 - 60)+ expect(PERM_WAIT_SECS_INTERACTIVE).toBeGreaterThan(45)+ })+})diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex 69565dbfb..1b0ff7490 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -96,8 +96,11 @@ describe('buildManagedScript', () => {it('fires a backgrounded "answered" POST in the wait branch after reading a valid answer', () => {// Guarded on a valid allow/deny answer, tagged nodeterm_answered on both transports, and// backgrounded (& + short --max-time) so the decision JSON is never delayed.- expect(s).toContain('if [ "$nt_decision" = "allow" ] || [ "$nt_decision" = "deny" ]; then')- const answered = s.match(/--data-urlencode "nodeterm_answered=\$\{nt_decision\}"/g) ?? []+ // The VERB decoded from the answer file (never the file itself: a structured answer carries+ // user text, which must not reach an argv) — see managed-script.answer.test.ts.+ expect(s).toContain('if [ "$nt_verb" = "allow" ] || [ "$nt_verb" = "deny" ]; then')+ expect(s).not.toContain('nodeterm_answered=${nt_decision}')+ const answered = s.match(/--data-urlencode "nodeterm_answered=\$\{nt_verb\}"/g) ?? []expect(answered.length).toBe(2)// Each backgrounded answered POST reads the payload from the temp file and self-deletes it// after curl returns (the file must never outlive its reader).@@ -119,7 +122,9 @@ describe('buildManagedScript', () => {})it('polls the answer file every 0.5s up to the armed seconds', () => {expect(s).toContain('nt_answer="$HOME/.nodeterm/pending/$nt_pending.answer"')- expect(s).toContain('nt_max=$((NODETERM_PERM_WAIT_SECS * 2))')+ // nt_wait = NODETERM_PERM_WAIT_SECS, or the long interactive hold for a plan / question.+ expect(s).toContain('nt_wait="$NODETERM_PERM_WAIT_SECS"')+ expect(s).toContain('nt_max=$((nt_wait * 2))')expect(s).toContain('sleep 0.5')})it('prints the exact allow / deny decision JSON', () => {@@ -143,14 +148,15 @@ describe('buildManagedScript', () => {it('the wait branch is ABSENT from a non-claude agent script, not merely env-inert', () => {for (const agent of ['codex', 'gemini', 'grok', 'copilot', 'opencode']) {const script = buildManagedScript(agent)- expect(script, `${agent} script arms the perm wait`).not.toContain('NODETERM_PERM_WAIT_SECS * 2')+ expect(script, `${agent} script arms the perm wait`).not.toContain('"$NODETERM_PERM_WAIT_SECS"')+ expect(script, `${agent} script holds`).not.toContain('nt_wait')expect(script, `${agent} script polls the answer file`).not.toContain('.answer')expect(script, `${agent} script can print a decision`).not.toContain('hookSpecificOutput')expect(script).toContain(`/hook/${agent}`)}// And claude keeps the whole branch.const claude = buildManagedScript('claude')- expect(claude).toContain('nt_max=$((NODETERM_PERM_WAIT_SECS * 2))')+ expect(claude).toContain('nt_max=$((nt_wait * 2))')expect(claude).toContain('"behavior":"deny"')})})diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex f7b2adc33..c37ef22fe 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -89,6 +89,12 @@ import { codexThreadIdentityRoot } from '../../codex-identity-proxy'import { HOOK_CURL_HEADERS_SH } from '../hook-curl-config-sh'import { NODE_TOKEN_READ_SH } from '../node-token-sh'import { HOOK_ENDPOINT_FALLBACK_SH } from '../hook-endpoint-failover-sh'+import {+ PERMISSION_DECISION_MAX_BYTES,+ PERMISSION_DECISION_PREFIX,+ PERM_WAIT_SECS_INTERACTIVE+} from '../permission-decision'+import { ASK_USER_QUESTION_TOOL, EXIT_PLAN_MODE_TOOL } from '../../../shared/agents/permission-answer'/*** Bumped by hand whenever this script's CONTRACT with the server changes. Not a git sha and not a@@ -117,6 +123,93 @@ export const MIN_TOKEN_AWARE_REVISION = 3* on purpose — rev 3 CAN read a token, which is the only question `MIN_TOKEN_AWARE_REVISION`* answers; calling it stale would tell a working session to reconnect for nothing. */+/**+ * Which tool the held PermissionRequest is about, and how long to hold it (claude only; spliced+ * into the arm branch). Structured answers are docs/hook-reply-approvals.md § "Plans and questions".+ *+ * `nt_tool` is read with parameter expansion (no subprocess, nothing on an argv) from the FIRST+ * `"tool_name":` in the payload. A JSON string cannot contain an unescaped `"tool_name":"` — its+ * quotes would be `\"` — so the only way to match an earlier one is a NESTED KEY inside an object+ * value, i.e. inside `tool_input`. Claude Code writes `tool_name` before `tool_input` (hook input+ * builder, research §1), so the first match is the top-level one; and if that order ever flips, the+ * `"tool_input"`-in-the-head check leaves `nt_tool` EMPTY rather than trusting a nested key. Empty is+ * the safe direction: the default hold and today's bare allow. The value is then held to a plain+ * identifier and only ever compared against two literals.+ *+ * `nt_wait`: ExitPlanMode / AskUserQuestion are read by a person for minutes, so they hold+ * PERM_WAIT_SECS_INTERACTIVE (< Claude's 600 s default command-hook timeout, which our installers+ * never override). EXCEPT for a subagent's request (payload names an `agent_id`): Claude awaits a+ * subagent's automated checks BEFORE painting its dialog (research §1), so a long hold there would+ * hide the prompt for minutes. A nested `"agent_id":` merely shortens the hold — the safe direction.+ */+const HELD_TOOL_SH: readonly string[] = [+ ' nt_tool=""',+ ' nt_head=${payload%%\'"tool_name":\'*}',+ ' if [ "$nt_head" != "$payload" ]; then',+ ' case "$nt_head" in',+ ' *\'"tool_input"\'*) ;;',+ ' *)',+ ' nt_rest=${payload#*\'"tool_name":\'}',+ ' nt_rest=${nt_rest# }',+ ' case "$nt_rest" in \'"\'*) nt_rest=${nt_rest#\'"\'}; nt_tool=${nt_rest%%\'"\'*} ;; esac',+ ' ;;',+ ' esac',+ ' fi',+ ' case "$nt_tool" in \'\'|*[!A-Za-z0-9_.:-]*) nt_tool="" ;; esac',+ ' nt_wait="$NODETERM_PERM_WAIT_SECS"',+ ' case "$nt_tool" in',+ ` ${EXIT_PLAN_MODE_TOOL}|${ASK_USER_QUESTION_TOOL})`,+ ' case "$payload" in',+ ' *\'"agent_id":\'*) ;;',+ ` *) nt_wait=${PERM_WAIT_SECS_INTERACTIVE} ;;`,+ ' esac',+ ' ;;',+ ' esac'+]++/**+ * Decode one answer file into `nt_verb` (allow | deny | hold | empty) and `nt_out` (the exact line+ * to print, or empty). The script prints ONLY:+ * - a fixed decision for the legacy words `allow` / `deny` (a plain `allow` on ExitPlanMode maps+ * to `updatedInput:{}` — Claude DROPS a bare allow on that tool, so the phone's and the header+ * button's Approve were silent no-ops; `{}` restores the pre-plan mode, like the dialog's own+ * default); or+ * - a JSON decision core built (core/agents/permission-decision.ts), printed verbatim only after+ * the same bound `isBoundedAnswerContent` applies: the exact prefix + a "allow"/"deny" behavior,+ * a closing brace, <= PERMISSION_DECISION_MAX_BYTES, no control bytes (so exactly one line).+ * A plain `allow` on AskUserQuestion is `hold`: Claude would drop it (a question needs answers),+ * so printing it would close the hook for nothing — the loop consumes the file and KEEPS HOLDING,+ * leaving the chat-view answer path open while the TUI dialog works as always. Anything else+ * (garbage, a hostile file, an over-long or multi-line JSON) prints nothing and falls through to+ * the TUI, exactly as every build before this one did for an unknown answer.+ *+ * An OLD script (an SSH host keeps the script it got at connect) reads a JSON answer as neither+ * `allow` nor `deny`, so it prints nothing and exits — the TUI still answers. Safe degrade.+ */+const ANSWER_DECODE_SH: readonly string[] = [+ ' nt_verb=""',+ ' nt_out=""',+ ' case "$nt_decision" in',+ ' allow)',+ ' case "$nt_tool" in',+ ` ${ASK_USER_QUESTION_TOOL}) nt_verb=hold ;;`,+ ` ${EXIT_PLAN_MODE_TOOL}) nt_verb=allow; nt_out='${PERMISSION_DECISION_PREFIX}"allow","updatedInput":{}}}}' ;;`,+ ` *) nt_verb=allow; nt_out='${PERMISSION_DECISION_PREFIX}"allow"}}}' ;;`,+ ' esac',+ ' ;;',+ ` deny) nt_verb=deny; nt_out='${PERMISSION_DECISION_PREFIX}"deny","message":"Denied from nodeterm."}}}' ;;`,+ ` '${PERMISSION_DECISION_PREFIX}"allow"'*) nt_verb=allow; nt_out="$nt_decision" ;;`,+ ` '${PERMISSION_DECISION_PREFIX}"deny"'*) nt_verb=deny; nt_out="$nt_decision" ;;`,+ ' esac',+ ' # Shape-check a core-built JSON answer before it can reach Claude\'s stdout.',+ ' if [ -n "$nt_out" ] && [ "$nt_out" = "$nt_decision" ]; then',+ ' case "$nt_out" in *\'}\') ;; *) nt_out="" ;; esac',+ ` if [ "\${#nt_out}" -gt ${PERMISSION_DECISION_MAX_BYTES} ]; then nt_out=""; fi`,+ " if [ -n \"$nt_out\" ] && [ \"$(printf '%s' \"$nt_out\" | tr -d '\\000-\\037')\" != \"$nt_out\" ]; then nt_out=\"\"; fi",+ ' [ -n "$nt_out" ] || nt_verb=""',+ ' fi'+]+function safeIdentityRoot(): string | null {try {return codexThreadIdentityRoot()@@ -260,6 +353,7 @@ export function buildManagedScript(' (umask 077; mkdir -p "$nt_dir") 2>/dev/null || :',' nt_pending_file="$nt_dir/$nt_pending.json"',' (umask 077; printf %s "$payload" > "$nt_pending_file") 2>/dev/null || :',+ ...HELD_TOOL_SH,' ;;',' esac','fi'@@ -367,56 +461,61 @@ export function buildManagedScript('# Hold the hook open for a phone/canvas answer file, polling every 0.5s up to the armed seconds.','if [ -n "$nt_pending" ]; then',' nt_answer="$HOME/.nodeterm/pending/$nt_pending.answer"',- ' nt_max=$((NODETERM_PERM_WAIT_SECS * 2))',+ ' nt_max=$((nt_wait * 2))',' nt_i=0',' while [ "$nt_i" -lt "$nt_max" ]; do',' if [ -f "$nt_answer" ]; then',' nt_decision=$(cat "$nt_answer" 2>/dev/null)',- ' rm -f "$nt_answer" "$nt_pending_file" 2>/dev/null || :',- ' # Fire-and-forget "answered" signal so the canvas/phone NEEDS YOU badge flips to working the',- ' # instant we read a valid answer, instead of sticking until the agent\'s next hook (which,',- ' # for a text-only reply, is not until the turn\'s Stop). Backgrounded (&) + short --max-time so',- ' # the decision JSON below is NEVER delayed. Same POST mechanism as above, tagged',- ' # nodeterm_answered=<decision>; only for a valid allow/deny (no POST on a bad/timed-out answer).',- ' # The payload temp file is still needed here (the foreground nt_send_request above read',- ' # it, and this backgrounded "answered" POST reads it again). Whichever backgrounded POST',- ' # is launched self-deletes it after curl returns; if none is (no transport, or a decision',- ' # that is neither allow nor deny), it is deleted inline just below.',- ' nt_payload_owned=0',- ' if [ "$nt_decision" = "allow" ] || [ "$nt_decision" = "deny" ]; then',- ' if [ -n "$NODETERM_HOOK_SOCK" ]; then',- ' { nt_hook_headers |',- ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,- ' --connect-timeout 0.5 --max-time 1 --config - \\',- ' -H "Content-Type: application/x-www-form-urlencoded" \\',- ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',- ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',- ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',- ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',- ' --data-urlencode "nodeterm_answered=${nt_decision}" \\',- ' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',- ' nt_payload_owned=1',- ' elif [ -n "$NODETERM_HOOK_PORT" ]; then',- ' { nt_hook_headers |',- ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,- ' --connect-timeout 0.5 --max-time 1 --config - \\',- ' -H "Content-Type: application/x-www-form-urlencoded" \\',- ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',- ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',- ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',- ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',- ' --data-urlencode "nodeterm_answered=${nt_decision}" \\',- ' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',- ' nt_payload_owned=1',+ ...ANSWER_DECODE_SH,+ ' if [ "$nt_verb" = hold ]; then',+ ' # A plain allow on a question: consume it and KEEP HOLDING (see ANSWER_DECODE_SH).',+ ' rm -f "$nt_answer" 2>/dev/null || :',+ ' else',+ ' rm -f "$nt_answer" "$nt_pending_file" 2>/dev/null || :',+ ' # Fire-and-forget "answered" signal so the canvas/phone NEEDS YOU badge flips to working the',+ ' # instant we read a valid answer, instead of sticking until the agent\'s next hook (which,',+ ' # for a text-only reply, is not until the turn\'s Stop). Backgrounded (&) + short --max-time so',+ ' # the decision JSON below is NEVER delayed. Same POST mechanism as above, tagged',+ ' # nodeterm_answered=<verb> — the VERB decoded above, never the answer file itself: a JSON',+ ' # answer carries the user\'s typed text, and nothing from that file may reach an argv.',+ ' # Only for a valid allow/deny (no POST on a bad/timed-out answer).',+ ' # The payload temp file is still needed here (the foreground nt_send_request above read',+ ' # it, and this backgrounded "answered" POST reads it again). Whichever backgrounded POST',+ ' # is launched self-deletes it after curl returns; if none is (no transport, or a decision',+ ' # that is neither allow nor deny), it is deleted inline just below.',+ ' nt_payload_owned=0',+ ' if [ "$nt_verb" = "allow" ] || [ "$nt_verb" = "deny" ]; then',+ ' if [ -n "$NODETERM_HOOK_SOCK" ]; then',+ ' { nt_hook_headers |',+ ` curl -sS -X POST --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/hook/${agentId}" \\`,+ ' --connect-timeout 0.5 --max-time 1 --config - \\',+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',+ ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',+ ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',+ ' --data-urlencode "nodeterm_answered=${nt_verb}" \\',+ ' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',+ ' nt_payload_owned=1',+ ' elif [ -n "$NODETERM_HOOK_PORT" ]; then',+ ' { nt_hook_headers |',+ ` curl -sS -X POST "http://127.0.0.1:\${NODETERM_HOOK_PORT}/hook/${agentId}" \\`,+ ' --connect-timeout 0.5 --max-time 1 --config - \\',+ ' -H "Content-Type: application/x-www-form-urlencoded" \\',+ ' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',+ ' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',+ ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',+ ' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',+ ' --data-urlencode "nodeterm_answered=${nt_verb}" \\',+ ' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',+ ' nt_payload_owned=1',+ ' fi',' fi',+ ' if [ "$nt_payload_owned" != 1 ]; then rm -f "$nt_payload_file" 2>/dev/null || :; fi',+ ' # printf is a shell builtin (dash, bash, busybox): the decision never becomes an argv.',+ ' if [ -n "$nt_out" ]; then printf \'%s\\n\' "$nt_out"; fi',+ ' exit 0',' fi',- ' if [ "$nt_payload_owned" != 1 ]; then rm -f "$nt_payload_file" 2>/dev/null || :; fi',- ' if [ "$nt_decision" = "allow" ]; then',- ' printf \'%s\\n\' \'{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}\'',- ' elif [ "$nt_decision" = "deny" ]; then',- ' printf \'%s\\n\' \'{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"Denied from nodeterm."}}}\'',- ' fi',- ' exit 0',' fi',' sleep 0.5 2>/dev/null || sleep 1',' nt_i=$((nt_i + 1))',diff --git a/src/core/agents/pending-approvals.test.ts b/src/core/agents/pending-approvals.test.tsindex c067f87af..b8dee6d29 100644--- a/src/core/agents/pending-approvals.test.ts+++ b/src/core/agents/pending-approvals.test.ts@@ -8,8 +8,11 @@ import {writePendingAnswerLocal,sweepPendingDir,syntheticAnsweredEvent,- PENDING_MAX_AGE_MS+ PENDING_MAX_AGE_MS,+ readPendingRequestLocal,+ localHeldPermissionIo} from './pending-approvals'+import { answerHeldPermission, PENDING_REQUEST_MAX_BYTES, PERMISSION_DECISION_PREFIX } from './permission-decision'let home: string@@ -60,9 +63,47 @@ describe('writePendingAnswerLocal', () => {expect(fs.existsSync(pendingDir(home))).toBe(false)})- it('refuses an out-of-contract decision', async () => {- // @ts-expect-error — exercising the runtime guard against a bad value+ it('refuses content the hook script would not print (the same bound)', async () => {expect(await writePendingAnswerLocal('n', 'always', home)).toBe(false)+ expect(await writePendingAnswerLocal('n', '{"hookSpecificOutput":{"hookEventName":"PreToolUse"}}', home)).toBe(false)+ expect(await writePendingAnswerLocal('n', `${PERMISSION_DECISION_PREFIX}"allow"}}}\nX`, home)).toBe(false)+ expect(fs.existsSync(path.join(pendingDir(home), 'n.answer'))).toBe(false)+ })++ it('writes a core-built JSON decision verbatim, 0600', async () => {+ const json = `${PERMISSION_DECISION_PREFIX}"allow","updatedInput":{}}}}`+ expect(await writePendingAnswerLocal('n', json, home)).toBe(true)+ const f = path.join(pendingDir(home), 'n.answer')+ expect(fs.readFileSync(f, 'utf8')).toBe(json)+ if (process.platform !== 'win32') expect(fs.statSync(f).mode & 0o777).toBe(0o600)+ })+})++describe('readPendingRequestLocal + localHeldPermissionIo', () => {+ it('reads the held request, and answers null once it is gone or for a bad id', async () => {+ fs.mkdirSync(pendingDir(home), { recursive: true })+ const req = JSON.stringify({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode', tool_input: { plan: 'p' } })+ fs.writeFileSync(path.join(pendingDir(home), 'n.json'), req)+ expect(await readPendingRequestLocal('n', home)).toBe(req)+ expect(await readPendingRequestLocal('gone', home)).toBeNull()+ expect(await readPendingRequestLocal('../n', home)).toBeNull()+ })+ it('refuses an over-long request file rather than reading it', async () => {+ fs.mkdirSync(pendingDir(home), { recursive: true })+ fs.writeFileSync(path.join(pendingDir(home), 'big.json'), 'x'.repeat(PENDING_REQUEST_MAX_BYTES + 1))+ expect(await readPendingRequestLocal('big', home)).toBeNull()+ })+ it('end to end: a plan answer is built from the file on disk and written beside it', async () => {+ fs.mkdirSync(pendingDir(home), { recursive: true })+ fs.writeFileSync(+ path.join(pendingDir(home), 'n.json'),+ JSON.stringify({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode', tool_input: { plan: 'p' } })+ )+ const res = await answerHeldPermission({ answer: { kind: 'plan', mode: 'restore' } }, localHeldPermissionIo('n', home))+ expect(res).toEqual({ ok: true, decision: 'allow' })+ expect(fs.readFileSync(path.join(pendingDir(home), 'n.answer'), 'utf8')).toBe(+ `${PERMISSION_DECISION_PREFIX}"allow","updatedInput":{}}}}`+ )})})diff --git a/src/core/agents/pending-approvals.ts b/src/core/agents/pending-approvals.tsindex 4997defe8..4da604a17 100644--- a/src/core/agents/pending-approvals.ts+++ b/src/core/agents/pending-approvals.ts@@ -13,6 +13,7 @@ import os from 'os'import path from 'path'import { writeFileAtomic } from '../fs-atomic'import { normalizeClaude, type NormalizedAgentEvent } from '../../shared/agents/normalize'+import { isBoundedAnswerContent, PENDING_REQUEST_MAX_BYTES, type HeldPermissionIo } from './permission-decision'/** pendingId shape the script generates (`<node>-<ms>-<pid>`) and the ONLY thing we interpolate* into a filename. Validated everywhere a pendingId becomes a path so a forged value can't@@ -34,30 +35,50 @@ export function pendingDir(homeDir: string = os.homedir()): string {}/**- * Write the one-line answer file for a held permission hook, atomically (tmp + rename, mode 0600).- * Resolves true on success, false on an invalid pendingId or any fs error (fail-open — the hook- * simply times out to the interactive prompt). The `decision` is written verbatim as the hook- * script compares it against the literals `allow` / `deny`.+ * Write the answer file for a held permission hook, atomically (tmp + rename, mode 0600).+ * Resolves true on success, false on an invalid pendingId, content the hook script would not+ * print (`isBoundedAnswerContent` — the legacy words, or a core-built JSON decision), or any fs+ * error (fail-open — the hook simply times out to the interactive prompt).*/export async function writePendingAnswerLocal(pendingId: string,- decision: 'allow' | 'deny',+ content: string,homeDir: string = os.homedir()): Promise<boolean> {if (!isValidPendingId(pendingId)) return false- if (decision !== 'allow' && decision !== 'deny') return false+ if (typeof content !== 'string' || !isBoundedAnswerContent(content)) return falseconst dir = pendingDir(homeDir)const file = path.join(dir, `${pendingId}.answer`)try {await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 })// writeFileAtomic: unique tmp + retrying rename (core/fs-atomic.ts); removes its temp on failure.- await writeFileAtomic(file, decision, { mode: 0o600 })+ await writeFileAtomic(file, content, { mode: 0o600 })return true} catch {return false}}+/**+ * Read the request file the held hook wrote (`<pendingId>.json` — the raw PermissionRequest+ * payload). This is the SOURCE OF TRUTH a structured answer is validated against. Null when the+ * file is missing (the hold ended: answered, timed out, or swept), over-long, or unreadable.+ */+export async function readPendingRequestLocal(+ pendingId: string,+ homeDir: string = os.homedir()+): Promise<string | null> {+ if (!isValidPendingId(pendingId)) return null+ const file = path.join(pendingDir(homeDir), `${pendingId}.json`)+ try {+ const st = await fs.promises.stat(file)+ if (!st.isFile() || st.size > PENDING_REQUEST_MAX_BYTES) return null+ return await fs.promises.readFile(file, 'utf8')+ } catch {+ return null+ }+}+/*** Build the synthetic "answered" agent event the managed hook's second POST would produce, so a* caller that just wrote the answer file (the desktop Approve/Deny handler) can OPTIMISTICALLY flip@@ -133,3 +154,11 @@ export function startPendingSweep(timer.unref?.()return { stop: () => clearInterval(timer) }}++/** The local-fs I/O pair for `answerHeldPermission` (the host the agent runs on IS this machine). */+export function localHeldPermissionIo(pendingId: string, homeDir: string = os.homedir()): HeldPermissionIo {+ return {+ readPending: () => readPendingRequestLocal(pendingId, homeDir),+ write: (content) => writePendingAnswerLocal(pendingId, content, homeDir)+ }+}diff --git a/src/core/agents/permission-decision.test.ts b/src/core/agents/permission-decision.test.tsnew file mode 100644index 000000000..ccfdc7ac8--- /dev/null+++ b/src/core/agents/permission-decision.test.ts@@ -0,0 +1,339 @@+import { describe, expect, it } from 'vitest'+import {+ answerHeldPermission,+ buildPermissionDecision,+ isBoundedAnswerContent,+ parsePermissionAnswer,+ parsePendingRequest,+ PERMISSION_DECISION_MAX_BYTES,+ PERMISSION_DECISION_PREFIX,+ type PendingRequest+} from './permission-decision'++// Real shapes. The PermissionRequest envelope is what Claude Code 2.1.283 builds (`FMe`, research+// §1: base fields + hook_event_name, tool_name, tool_input, permission_suggestions); the+// AskUserQuestion `questions` are copied from a real transcript's toolUseResult (v2.1.258), and the+// ExitPlanMode input carries the `plan` + `planFilePath` Claude injects.+const QUESTION_TEXT =+ "Canvas'a baktığında bir ipin sana öncelikle NEYİ söylemesini istiyorsun?"+const REAL_QUESTIONS = [+ {+ question: QUESTION_TEXT,+ header: 'İp anlamı',+ options: [+ { label: 'Sıra / bağımlılık (Recommended)', description: 'Kim kimden sonra çalışır (--after).' },+ { label: 'Kim kimi okuyabilir (context)', description: 'Bilgi akışı asıl şey.' },+ { label: 'Tek ip, tüm ilişkiler üstünde', description: 'Bir çift arasında her zaman tek çizgi.' },+ { label: 'Sadece kim kimi açtı (lineage)', description: 'Ağaç yapısı: açan → açılan.' }+ ],+ multiSelect: false+ },+ {+ question: 'Which surfaces should get it?',+ header: 'Surfaces',+ options: [+ { label: 'Desktop', description: 'Electron' },+ { label: 'Server Edition', description: 'Browser' },+ { label: 'Phone', description: 'iOS' }+ ],+ multiSelect: true+ }+]++function envelope(toolName: string, toolInput: unknown): string {+ return JSON.stringify({+ session_id: '006c9599-6961-4929-809d-546a518e1f61',+ transcript_path: '/root/.claude/projects/-root-nodeterm/006c9599.jsonl',+ cwd: '/root/nodeterm',+ permission_mode: 'plan',+ hook_event_name: 'PermissionRequest',+ tool_name: toolName,+ tool_input: toolInput,+ permission_suggestions: []+ })+}++const PLAN_REQ = parsePendingRequest(+ envelope('ExitPlanMode', {+ plan: '# Plan: MEMORY.md indeksini limitin altına indir\n\n## Bağlam\n…',+ planFilePath: '/root/.claude/plans/some-plan.md'+ })+) as PendingRequest+const QUESTION_REQ = parsePendingRequest(envelope('AskUserQuestion', { questions: REAL_QUESTIONS })) as PendingRequest+const BASH_REQ = parsePendingRequest(envelope('Bash', { command: 'rm -rf build', description: 'clean' })) as PendingRequest++function decisionOf(content: string): Record<string, unknown> {+ const parsed = JSON.parse(content) as { hookSpecificOutput: { hookEventName: string; decision: Record<string, unknown> } }+ expect(parsed.hookSpecificOutput.hookEventName).toBe('PermissionRequest')+ return parsed.hookSpecificOutput.decision+}++describe('parsePendingRequest', () => {+ it('reads tool_name + tool_input off the real envelope', () => {+ expect(PLAN_REQ.toolName).toBe('ExitPlanMode')+ expect(QUESTION_REQ.toolInput.questions).toEqual(REAL_QUESTIONS)+ })+ it('refuses anything that is not a PermissionRequest with an object tool_input', () => {+ expect(parsePendingRequest('not json')).toBeNull()+ expect(parsePendingRequest('')).toBeNull()+ expect(parsePendingRequest(JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: {} }))).toBeNull()+ expect(parsePendingRequest(JSON.stringify({ hook_event_name: 'PermissionRequest', tool_name: 'Bash' }))).toBeNull()+ expect(parsePendingRequest(JSON.stringify({ hook_event_name: 'PermissionRequest', tool_name: 'Bash', tool_input: [] }))).toBeNull()+ expect(parsePendingRequest(JSON.stringify({ hook_event_name: 'PermissionRequest', tool_name: 'a b', tool_input: {} }))).toBeNull()+ })+})++describe('parsePermissionAnswer (renderer input is untrusted)', () => {+ it('accepts the documented shapes', () => {+ expect(parsePermissionAnswer({ kind: 'allow' })).toEqual({ kind: 'allow' })+ expect(parsePermissionAnswer({ kind: 'plan', mode: 'acceptEdits' })).toEqual({ kind: 'plan', mode: 'acceptEdits' })+ expect(parsePermissionAnswer({ kind: 'plan-revise', message: 'x' })).toEqual({ kind: 'plan-revise', message: 'x' })+ expect(parsePermissionAnswer({ kind: 'question', answers: { a: 'b' } })).toEqual({ kind: 'question', answers: { a: 'b' } })+ })+ it('refuses unknown kinds, a plan mode outside the enum (auto included) and junk', () => {+ expect(parsePermissionAnswer({ kind: 'plan', mode: 'auto' })).toBeNull()+ expect(parsePermissionAnswer({ kind: 'plan', mode: 'bypassPermissions' })).toBeNull()+ expect(parsePermissionAnswer({ kind: 'constructor' })).toBeNull()+ expect(parsePermissionAnswer({ kind: 'plan-revise', message: 42 })).toBeNull()+ expect(parsePermissionAnswer({ kind: 'question', answers: 'x' })).toBeNull()+ expect(parsePermissionAnswer({ kind: 'question', answers: { a: 1 } })).toBeNull()+ expect(parsePermissionAnswer({ kind: 'question', answers: { a: 'b' }, freeText: 'a' })).toBeNull()+ expect(parsePermissionAnswer(null)).toBeNull()+ expect(parsePermissionAnswer('allow')).toBeNull()+ })+})++describe('buildPermissionDecision — legacy verbs', () => {+ it('keeps the one-word answer file for allow / deny on an ordinary permission', () => {+ expect(buildPermissionDecision(BASH_REQ, { kind: 'allow' })).toEqual({ ok: true, content: 'allow', decision: 'allow' })+ expect(buildPermissionDecision(BASH_REQ, { kind: 'deny' })).toEqual({ ok: true, content: 'deny', decision: 'deny' })+ })+ it('writes the word for a plan allow — the hook script maps it to updatedInput:{} (one mapping, also serving the phone)', () => {+ expect(buildPermissionDecision(PLAN_REQ, { kind: 'allow' })).toEqual({ ok: true, content: 'allow', decision: 'allow' })+ })+ it('REFUSES a plain allow on a question: Claude drops it, and the hook would keep holding anyway', () => {+ expect(buildPermissionDecision(QUESTION_REQ, { kind: 'allow' })).toMatchObject({ ok: false })+ })+ it('a deny on a question still works (declining the picker is a real answer)', () => {+ expect(buildPermissionDecision(QUESTION_REQ, { kind: 'deny' })).toEqual({ ok: true, content: 'deny', decision: 'deny' })+ })+ it('with no readable request the legacy verbs fail OPEN to today\'s behavior', () => {+ expect(buildPermissionDecision(null, { kind: 'allow' })).toEqual({ ok: true, content: 'allow', decision: 'allow' })+ expect(buildPermissionDecision(null, { kind: 'deny' })).toEqual({ ok: true, content: 'deny', decision: 'deny' })+ })+})++describe('buildPermissionDecision — plan', () => {+ it('restore = allow with updatedInput:{} and NO updatedPermissions (never the echoed plan)', () => {+ const r = buildPermissionDecision(PLAN_REQ, { kind: 'plan', mode: 'restore' })+ expect(r.ok).toBe(true)+ if (!r.ok) return+ expect(r.decision).toBe('allow')+ expect(r.content).toBe(+ '{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow","updatedInput":{}}}}'+ )+ // Echoing tool_input would carry `plan` and mark it "Approved Plan (edited by user)".+ expect(r.content).not.toContain('planFilePath')+ })+ it('acceptEdits / manual add a session setMode (manual = Claude\'s "default")', () => {+ const a = buildPermissionDecision(PLAN_REQ, { kind: 'plan', mode: 'acceptEdits' })+ const m = buildPermissionDecision(PLAN_REQ, { kind: 'plan', mode: 'manual' })+ if (!a.ok || !m.ok) throw new Error('expected ok')+ expect(decisionOf(a.content)).toEqual({+ behavior: 'allow',+ updatedInput: {},+ updatedPermissions: [{ type: 'setMode', mode: 'acceptEdits', destination: 'session' }]+ })+ expect(decisionOf(m.content)).toEqual({+ behavior: 'allow',+ updatedInput: {},+ updatedPermissions: [{ type: 'setMode', mode: 'default', destination: 'session' }]+ })+ })+ it('never emits setMode auto, whatever arrives', () => {+ const r = buildPermissionDecision(PLAN_REQ, { kind: 'plan', mode: 'auto' } as never)+ expect(r.ok).toBe(false)+ })+ it('plan-revise = deny with the feedback as message and no interrupt', () => {+ const r = buildPermissionDecision(PLAN_REQ, { kind: 'plan-revise', message: ' Split step 3 into two PRs.\n' })+ if (!r.ok) throw new Error(r.reason)+ expect(r.decision).toBe('deny')+ const d = decisionOf(r.content)+ expect(d.behavior).toBe('deny')+ expect(d.message).toBe('The user reviewed the plan and wants changes before you proceed: Split step 3 into two PRs.')+ expect(d).not.toHaveProperty('interrupt')+ })+ it('plan-revise refuses an empty or oversized message', () => {+ expect(buildPermissionDecision(PLAN_REQ, { kind: 'plan-revise', message: ' ' }).ok).toBe(false)+ expect(buildPermissionDecision(PLAN_REQ, { kind: 'plan-revise', message: 'x'.repeat(20_000) }).ok).toBe(false)+ })+ it('refuses a plan answer for any other held tool (tool name must match)', () => {+ expect(buildPermissionDecision(BASH_REQ, { kind: 'plan', mode: 'restore' }).ok).toBe(false)+ expect(buildPermissionDecision(QUESTION_REQ, { kind: 'plan-revise', message: 'x' }).ok).toBe(false)+ expect(buildPermissionDecision(null, { kind: 'plan', mode: 'restore' }).ok).toBe(false)+ })+})++describe('buildPermissionDecision — question', () => {+ it('echoes the PENDING request\'s questions verbatim and adds answers keyed by the exact question text', () => {+ const r = buildPermissionDecision(QUESTION_REQ, {+ kind: 'question',+ answers: { [QUESTION_TEXT]: 'Kim kimi okuyabilir (context)' }+ })+ if (!r.ok) throw new Error(r.reason)+ expect(r.decision).toBe('allow')+ const d = decisionOf(r.content)+ expect(d.behavior).toBe('allow')+ expect(d.updatedInput).toEqual({+ questions: REAL_QUESTIONS,+ answers: { [QUESTION_TEXT]: 'Kim kimi okuyabilir (context)' }+ })+ expect(r.content.startsWith(PERMISSION_DECISION_PREFIX)).toBe(true)+ })+ it('multiSelect: an array of labels is joined with ", " (the TUI\'s own transcript format)', () => {+ const r = buildPermissionDecision(QUESTION_REQ, {+ kind: 'question',+ answers: { 'Which surfaces should get it?': ['Desktop', 'Phone'] }+ })+ if (!r.ok) throw new Error(r.reason)+ expect((decisionOf(r.content).updatedInput as { answers: unknown }).answers).toEqual({+ 'Which surfaces should get it?': 'Desktop, Phone'+ })+ })+ it('free text is accepted ONLY for a key the answer marks explicitly as free text', () => {+ const typed = 'context bağlamak pazarlama değeri var kalabilir'+ expect(buildPermissionDecision(QUESTION_REQ, { kind: 'question', answers: { [QUESTION_TEXT]: typed } }).ok).toBe(false)+ const r = buildPermissionDecision(QUESTION_REQ, {+ kind: 'question',+ answers: { [QUESTION_TEXT]: typed },+ freeText: [QUESTION_TEXT]+ })+ if (!r.ok) throw new Error(r.reason)+ expect((decisionOf(r.content).updatedInput as { answers: Record<string, string> }).answers[QUESTION_TEXT]).toBe(typed)+ })+ it('refuses: unknown question, unknown label, array on a single-select, empty/duplicate/oversized picks', () => {+ const bad: Array<Record<string, string | string[]>> = [+ { 'Not a question we asked': 'Desktop' },+ { [QUESTION_TEXT]: 'Desktop' },+ { [QUESTION_TEXT]: ['Kim kimi okuyabilir (context)'] },+ { 'Which surfaces should get it?': [] },+ { 'Which surfaces should get it?': ['Desktop', 'Desktop'] },+ { 'Which surfaces should get it?': ['Desktop', 'Nope'] },+ {}+ ]+ for (const answers of bad) {+ expect(buildPermissionDecision(QUESTION_REQ, { kind: 'question', answers }).ok, JSON.stringify(answers)).toBe(false)+ }+ expect(+ buildPermissionDecision(QUESTION_REQ, {+ kind: 'question',+ answers: { [QUESTION_TEXT]: 'x'.repeat(20_000) },+ freeText: [QUESTION_TEXT]+ }).ok+ ).toBe(false)+ // A freeText entry must name a question it answers.+ expect(+ buildPermissionDecision(QUESTION_REQ, {+ kind: 'question',+ answers: { [QUESTION_TEXT]: 'Kim kimi okuyabilir (context)' },+ freeText: ['something else']+ }).ok+ ).toBe(false)+ })+ it('a question text of "__proto__" is an ordinary key, not a prototype write', () => {+ const req = parsePendingRequest(+ envelope('AskUserQuestion', { questions: [{ question: '__proto__', header: 'h', options: [{ label: 'a' }], multiSelect: false }] })+ ) as PendingRequest+ const answers = JSON.parse('{"__proto__":"a"}') as Record<string, string>+ const r = buildPermissionDecision(req, { kind: 'question', answers })+ if (!r.ok) throw new Error(r.reason)+ expect(r.content).toContain('"answers":{"__proto__":"a"}')+ })+ it('refuses a question answer for any other held tool, and when the questions are malformed', () => {+ expect(buildPermissionDecision(PLAN_REQ, { kind: 'question', answers: { q: 'a' } }).ok).toBe(false)+ const broken = parsePendingRequest(envelope('AskUserQuestion', { questions: 'nope' })) as PendingRequest+ expect(buildPermissionDecision(broken, { kind: 'question', answers: { q: 'a' } }).ok).toBe(false)+ })+ it('refuses a decision over the size cap the hook script also enforces', () => {+ const huge = parsePendingRequest(+ envelope('AskUserQuestion', {+ questions: [{ question: 'q', header: 'h', options: [{ label: 'a', description: 'd'.repeat(PERMISSION_DECISION_MAX_BYTES) }], multiSelect: false }]+ })+ ) as PendingRequest+ expect(buildPermissionDecision(huge, { kind: 'question', answers: { q: 'a' } })).toMatchObject({ ok: false })+ })+})++describe('isBoundedAnswerContent — the same bound the hook script applies', () => {+ it('accepts the verbs and core-built JSON only', () => {+ expect(isBoundedAnswerContent('allow')).toBe(true)+ expect(isBoundedAnswerContent('deny')).toBe(true)+ const r = buildPermissionDecision(PLAN_REQ, { kind: 'plan', mode: 'restore' })+ if (!r.ok) throw new Error(r.reason)+ expect(isBoundedAnswerContent(r.content)).toBe(true)+ })+ it('rejects other words, other hook events, raw newlines/control chars and oversize', () => {+ expect(isBoundedAnswerContent('yes')).toBe(false)+ expect(isBoundedAnswerContent('allow\n')).toBe(false)+ expect(isBoundedAnswerContent('{"hookSpecificOutput":{"hookEventName":"PreToolUse","decision":{"behavior":"allow"}}}')).toBe(false)+ expect(isBoundedAnswerContent(`${PERMISSION_DECISION_PREFIX}"allow"}}}\n{"x":1}`)).toBe(false)+ expect(isBoundedAnswerContent(`${PERMISSION_DECISION_PREFIX}"allow","m":"\u001b[2J"}}}`)).toBe(false)+ expect(isBoundedAnswerContent(`${PERMISSION_DECISION_PREFIX}"maybe"}}}`)).toBe(false)+ expect(isBoundedAnswerContent(`${PERMISSION_DECISION_PREFIX}"allow","x":"${'a'.repeat(PERMISSION_DECISION_MAX_BYTES)}"}}}`)).toBe(false)+ })+})++describe('answerHeldPermission — the one orchestration both shells call', () => {+ function io(pending: string | null) {+ const writes: string[] = []+ return {+ writes,+ readPending: async () => pending,+ write: async (content: string) => {+ writes.push(content)+ return true+ }+ }+ }+ it('legacy payload (decision only) keeps working', async () => {+ const x = io(envelope('Bash', { command: 'ls' }))+ expect(await answerHeldPermission({ decision: 'allow' }, x)).toEqual({ ok: true, decision: 'allow' })+ expect(x.writes).toEqual(['allow'])+ })+ it('a structured answer wins over decision and is built from the pending file', async () => {+ const x = io(envelope('ExitPlanMode', { plan: 'p' }))+ expect(await answerHeldPermission({ decision: 'deny', answer: { kind: 'plan', mode: 'manual' } }, x)).toEqual({+ ok: true,+ decision: 'allow'+ })+ expect(x.writes[0]).toContain('"mode":"default"')+ })+ it('a structured answer with no pending request (hold expired / already answered) writes NOTHING', async () => {+ const x = io(null)+ expect(await answerHeldPermission({ answer: { kind: 'plan', mode: 'restore' } }, x)).toEqual({ ok: false })+ expect(x.writes).toEqual([])+ })+ it('an invalid answer or missing decision writes nothing', async () => {+ const x = io(envelope('AskUserQuestion', { questions: REAL_QUESTIONS }))+ expect(await answerHeldPermission({ decision: 'allow' }, x)).toEqual({ ok: false })+ expect(await answerHeldPermission({ answer: { kind: 'nope' } }, x)).toEqual({ ok: false })+ expect(await answerHeldPermission({}, x)).toEqual({ ok: false })+ expect(x.writes).toEqual([])+ })+ it('a failed write reports false; a throwing reader fails soft', async () => {+ expect(+ await answerHeldPermission({ decision: 'deny' }, { readPending: async () => null, write: async () => false })+ ).toEqual({ ok: false })+ expect(+ await answerHeldPermission(+ { decision: 'deny' },+ {+ readPending: async () => {+ throw new Error('ssh down')+ },+ write: async () => true+ }+ )+ ).toEqual({ ok: true, decision: 'deny' })+ })+})diff --git a/src/core/agents/permission-decision.ts b/src/core/agents/permission-decision.tsnew file mode 100644index 000000000..46579992e--- /dev/null+++ b/src/core/agents/permission-decision.ts@@ -0,0 +1,307 @@+// Structured hook-reply decisions — the core half of answering a HELD Claude PermissionRequest with+// more than a bare allow/deny (docs/hook-reply-approvals.md, research:+// docs/superpowers/plans/2026-09-26-answer-paths-research.md).+//+// Division of labour, and why it is this way round:+// - CORE (here) builds and validates the decision. It reads the pending request file the hook+// wrote (`~/.nodeterm/pending/<pendingId>.json`) and treats it as the ONLY source of truth for+// the tool being held and — for a question — the exact `questions` array to echo. Nothing the+// renderer sends is echoed without being checked against that file: the question keys must be+// question texts from it, the labels must be its option labels (unless the answer marks the+// entry as free text), every enum is re-checked, every string is capped.+// - The HOOK SCRIPT (managed-script.ts) stays trivial sh: it prints a JSON answer verbatim only+// after a strict prefix/shape/size test (`isBoundedAnswerContent` is the same rule in TS).+//+// Pure except `answerHeldPermission`, which takes its two I/O legs (read the request, write the+// answer) as injected functions so desktop-local, desktop-SSH and Server Edition share ONE body.++import {+ ASK_USER_QUESTION_TOOL,+ EXIT_PLAN_MODE_TOOL,+ isSafeToolName,+ type PermissionAnswer+} from '../../shared/agents/permission-answer'++/**+ * Every JSON answer core writes starts with exactly these bytes, followed by `"allow"` or `"deny"`.+ * The hook script matches this literal before printing anything, so a stray or hostile file+ * cannot put some other hook's output (or free-form text) on Claude's stdout. Pinned byte-for-byte+ * in managed-script.ts — change both together.+ */+export const PERMISSION_DECISION_PREFIX =+ '{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":'++/** Largest JSON answer core will write and the script will print. A question echo carries the+ * request's own questions (option descriptions, previews), so it is generous; anything larger is+ * refused rather than truncated (a truncated decision is invalid JSON). */+export const PERMISSION_DECISION_MAX_BYTES = 64 * 1024++/** How much of the pending request file a reader takes. The file is the raw hook payload; a plan+ * can be long. Past this the request is treated as unreadable (structured answers refuse). */+export const PENDING_REQUEST_MAX_BYTES = 512 * 1024++/**+ * Seconds the hook holds an ExitPlanMode / AskUserQuestion request (other tools keep+ * PERM_WAIT_SECS_DEFAULT). People read a plan for minutes. Bounded by Claude's command-hook+ * timeout: our installers write NO `timeout` on the PermissionRequest entry, so Claude's default of+ * 600 s applies (hooks docs; pinned in install-helper.test.ts) — 540 leaves a 60 s margin so the+ * hook always exits on its own terms. On the main thread the dialog is painted CONCURRENTLY with+ * the hook (research §1), so a long hold blocks nothing; a subagent's request is awaited before+ * its dialog, which is why the script keeps the default hold whenever the payload names an agent_id.+ */+export const PERM_WAIT_SECS_INTERACTIVE = 540++/** Caps on user-typed text. Generous for a person, small against the decision budget. */+export const PLAN_REVISE_MAX_CHARS = 8000+export const FREE_TEXT_MAX_CHARS = 8000++const PLAN_REVISE_PREFIX = 'The user reviewed the plan and wants changes before you proceed: '++/** The two fields of the held request core needs. */+export interface PendingRequest {+ toolName: string+ toolInput: Record<string, unknown>+}++export type DecisionResult =+ | { ok: true; content: string; decision: 'allow' | 'deny' }+ | { ok: false; reason: string }++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v)+}++/** Parse the pending request file (the raw PermissionRequest hook payload). Null = not usable. */+export function parsePendingRequest(text: string): PendingRequest | null {+ if (typeof text !== 'string' || !text || text.length > PENDING_REQUEST_MAX_BYTES) return null+ let raw: unknown+ try {+ raw = JSON.parse(text)+ } catch {+ return null+ }+ if (!isPlainObject(raw) || raw.hook_event_name !== 'PermissionRequest') return null+ if (!isSafeToolName(raw.tool_name) || !isPlainObject(raw.tool_input)) return null+ return { toolName: raw.tool_name, toolInput: raw.tool_input }+}++/**+ * Narrow an untrusted value (IPC / WS-RPC payload) to a `PermissionAnswer`. Shape only — the+ * semantic checks against the pending request are `buildPermissionDecision`'s. Null = refuse.+ */+export function parsePermissionAnswer(v: unknown): PermissionAnswer | null {+ if (!isPlainObject(v) || typeof v.kind !== 'string') return null+ switch (v.kind) {+ case 'allow':+ return { kind: 'allow' }+ case 'deny':+ return { kind: 'deny' }+ case 'plan':+ return v.mode === 'restore' || v.mode === 'acceptEdits' || v.mode === 'manual'+ ? { kind: 'plan', mode: v.mode }+ : null+ case 'plan-revise':+ return typeof v.message === 'string' ? { kind: 'plan-revise', message: v.message } : null+ case 'question': {+ if (!isPlainObject(v.answers)) return null+ const answers: Record<string, string | string[]> = Object.create(null)+ for (const [k, a] of Object.entries(v.answers)) {+ if (typeof a === 'string') answers[k] = a+ else if (Array.isArray(a) && a.every((x) => typeof x === 'string')) answers[k] = [...(a as string[])]+ else return null+ }+ if (v.freeText === undefined) return { kind: 'question', answers: { ...answers } }+ if (!Array.isArray(v.freeText) || !v.freeText.every((x) => typeof x === 'string')) return null+ return { kind: 'question', answers: { ...answers }, freeText: [...(v.freeText as string[])] }+ }+ default:+ return null+ }+}++/** The decision JSON Claude reads from the hook's stdout. */+function decisionJson(decision: Record<string, unknown>): string {+ return JSON.stringify({ hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } })+}++function capped(content: string, decision: 'allow' | 'deny'): DecisionResult {+ // Belt and braces: everything built here must pass the same test the script applies, or the+ // script would silently ignore it and the user would think they answered.+ if (!isBoundedAnswerContent(content)) return { ok: false, reason: 'decision exceeds the answer bounds' }+ return { ok: true, content, decision }+}++interface QuestionShape {+ labels: Set<string>+ multiSelect: boolean+}++/** Index the request's own questions by their exact text. Null = not a shape we can answer. */+function questionIndex(toolInput: Record<string, unknown>): Map<string, QuestionShape> | null {+ const qs = toolInput.questions+ if (!Array.isArray(qs) || qs.length === 0) return null+ const index = new Map<string, QuestionShape>()+ for (const q of qs) {+ if (!isPlainObject(q) || typeof q.question !== 'string' || !q.question) return null+ const labels = new Set<string>()+ if (Array.isArray(q.options)) {+ for (const o of q.options) if (isPlainObject(o) && typeof o.label === 'string') labels.add(o.label)+ }+ // The "extended" variant (kind: text|number) has no options — only free text can answer it.+ index.set(q.question, { labels, multiSelect: q.multiSelect === true })+ }+ return index+}++function buildQuestionDecision(+ pending: PendingRequest,+ answers: Record<string, string | string[]>,+ freeText: readonly string[] | undefined+): DecisionResult {+ const index = questionIndex(pending.toolInput)+ if (!index) return { ok: false, reason: 'the held question has no readable questions' }+ const entries = Object.entries(answers)+ if (entries.length === 0) return { ok: false, reason: 'no answers' }+ const free = new Set(freeText ?? [])+ for (const k of free) if (!Object.prototype.hasOwnProperty.call(answers, k)) {+ return { ok: false, reason: 'freeText names a question that is not answered' }+ }+ // Null prototype: a question text of "__proto__" must become an own key, not a prototype write.+ const out: Record<string, string> = Object.create(null)+ for (const [question, answer] of entries) {+ const shape = index.get(question)+ if (!shape) return { ok: false, reason: 'unknown question' }+ if (free.has(question)) {+ const text = typeof answer === 'string' ? answer.trim() : ''+ if (!text || text.length > FREE_TEXT_MAX_CHARS) return { ok: false, reason: 'invalid free-text answer' }+ out[question] = text+ } else if (typeof answer === 'string') {+ if (!shape.labels.has(answer)) return { ok: false, reason: 'unknown option label' }+ out[question] = answer+ } else {+ if (!shape.multiSelect) return { ok: false, reason: 'several labels for a single-select question' }+ if (answer.length === 0 || new Set(answer).size !== answer.length) {+ return { ok: false, reason: 'empty or duplicate labels' }+ }+ if (!answer.every((l) => shape.labels.has(l))) return { ok: false, reason: 'unknown option label' }+ // The TUI's own transcript format for a multi-select answer (hooks docs: "Multi-select+ // answers join labels with commas").+ out[question] = answer.join(', ')+ }+ }+ // `updatedInput` REPLACES the whole input, so everything the request carried (questions,+ // title/metadata on the extended variant) is echoed from the PENDING FILE, never from the renderer.+ const updatedInput = { ...pending.toolInput, answers: out }+ return capped(decisionJson({ behavior: 'allow', updatedInput }), 'allow')+}++/**+ * Build the answer-file content for a held request. `content` is either a legacy verb+ * (`allow` | `deny`, which the script already understands — and maps, for ExitPlanMode) or a JSON+ * decision starting with `PERMISSION_DECISION_PREFIX`. `decision` is the verb the optimistic+ * "answered" event and the script's own answered POST report.+ *+ * `pending === null` (request file missing/unreadable): the legacy verbs are written anyway — that+ * is exactly today's behavior, and the script is the one that knows the tool. A structured answer+ * refuses, because it cannot be validated (and a missing file usually means the hold is over).+ */+export function buildPermissionDecision(pending: PendingRequest | null, answer: PermissionAnswer): DecisionResult {+ switch (answer.kind) {+ case 'deny':+ return { ok: true, content: 'deny', decision: 'deny' }+ case 'allow':+ // Claude drops a bare allow on AskUserQuestion, and the script keeps holding on one; saying+ // "answered" here would flip the badge for an answer that did nothing.+ if (pending?.toolName === ASK_USER_QUESTION_TOOL) {+ return { ok: false, reason: 'a question needs answers, not a plain allow' }+ }+ return { ok: true, content: 'allow', decision: 'allow' }+ case 'plan': {+ if (pending?.toolName !== EXIT_PLAN_MODE_TOOL) return { ok: false, reason: 'the held request is not a plan' }+ // `updatedInput:{}` — NOT the echoed input, whose `plan` would read as "edited by user".+ // No setMode `auto` exists in this table on purpose (research §2(A)).+ const setMode = answer.mode === 'acceptEdits' ? 'acceptEdits' : answer.mode === 'manual' ? 'default' : null+ if (answer.mode !== 'restore' && !setMode) return { ok: false, reason: 'unknown plan mode' }+ return capped(+ decisionJson({+ behavior: 'allow',+ updatedInput: {},+ ...(setMode ? { updatedPermissions: [{ type: 'setMode', mode: setMode, destination: 'session' }] } : {})+ }),+ 'allow'+ )+ }+ case 'plan-revise': {+ if (pending?.toolName !== EXIT_PLAN_MODE_TOOL) return { ok: false, reason: 'the held request is not a plan' }+ const text = typeof answer.message === 'string' ? answer.message.trim() : ''+ if (!text || text.length > PLAN_REVISE_MAX_CHARS) return { ok: false, reason: 'invalid feedback' }+ // No `interrupt`: the turn continues in plan mode and Claude revises (= "No, keep planning").+ return capped(decisionJson({ behavior: 'deny', message: `${PLAN_REVISE_PREFIX}${text}` }), 'deny')+ }+ case 'question':+ if (pending?.toolName !== ASK_USER_QUESTION_TOOL) return { ok: false, reason: 'the held request is not a question' }+ return buildQuestionDecision(pending, answer.answers, answer.freeText)+ default:+ return { ok: false, reason: 'unknown answer' }+ }+}++/**+ * The bound the hook script applies before printing an answer file, in TS: a legacy verb, or a+ * single-line JSON decision with the exact prefix, a `"allow"`/`"deny"` behavior, a closing brace,+ * no control characters and at most PERMISSION_DECISION_MAX_BYTES. Both writers refuse anything+ * else, so a file the script would ignore is never reported as answered.+ */+export function isBoundedAnswerContent(content: string): boolean {+ if (content === 'allow' || content === 'deny') return true+ if (typeof content !== 'string') return false+ if (Buffer.byteLength(content, 'utf8') > PERMISSION_DECISION_MAX_BYTES) return false+ // JSON.stringify escapes every U+0000–U+001F, so a raw one means the file is not ours.+ // eslint-disable-next-line no-control-regex+ if (/[\u0000-\u001f]/.test(content)) return false+ if (!content.endsWith('}')) return false+ return (+ content.startsWith(`${PERMISSION_DECISION_PREFIX}"allow"`) ||+ content.startsWith(`${PERMISSION_DECISION_PREFIX}"deny"`)+ )+}++/** The I/O legs of one answer: read the pending request text (null = missing), write the answer. */+export interface HeldPermissionIo {+ readPending(): Promise<string | null>+ write(content: string): Promise<boolean>+}++/**+ * Answer a held request: pick the answer (a structured `answer` wins over the legacy `decision`),+ * read the pending request, build + validate, write. Both shells call this — desktop with a local+ * or ControlMaster I/O pair, the Server Edition with the local one — so the rules live once.+ * Resolves `{ok:false}` without writing on any refusal; never throws.+ */+export async function answerHeldPermission(+ payload: { decision?: unknown; answer?: unknown },+ io: HeldPermissionIo+): Promise<{ ok: boolean; decision?: 'allow' | 'deny' }> {+ const answer =+ payload.answer !== undefined+ ? parsePermissionAnswer(payload.answer)+ : payload.decision === 'allow' || payload.decision === 'deny'+ ? ({ kind: payload.decision } as PermissionAnswer)+ : null+ if (!answer) return { ok: false }+ let text: string | null = null+ try {+ text = await io.readPending()+ } catch {+ text = null+ }+ const built = buildPermissionDecision(text === null ? null : parsePendingRequest(text), answer)+ if (!built.ok) return { ok: false }+ let written = false+ try {+ written = await io.write(built.content)+ } catch {+ written = false+ }+ return written ? { ok: true, decision: built.decision } : { ok: false }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 7b45cefbd..0fdfdde67 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -127,11 +127,13 @@ import { projectCapabilityGrantedFor } from '../shared/project-capability-consenimport { askpassServer, ensureAskpassScript } from './remote-ssh/ssh-askpass'import { appSshAgent } from './remote-ssh/ssh-agent'import {- writePendingAnswerLocal,+ localHeldPermissionIo,startPendingSweep,isValidPendingId,syntheticAnsweredEvent} from '../core/agents/pending-approvals'+import { answerHeldPermission, type HeldPermissionIo } from '../core/agents/permission-decision'+import type { AnswerPermissionPayload } from '../shared/agents/permission-answer'import { setMainWindow, getMainWindow, sendToMain, closeAction, createCrashReloadPolicy } from './main-window'import {MENU_ITEM_ID_CLOSE,@@ -2786,28 +2788,31 @@ app.whenReady().then(async () => {// project: an SSH project's hook runs on the REMOTE host (write over its ControlMaster), a local// project's on THIS machine (write under os.homedir() — the hook uses $HOME, which may differ from// the project cwd). pendingId is validated before it is interpolated into any path/command.- corePlatform.handle(- IPC.agentAnswerPermission,- async (payload: { nodeId: string; pendingId: string; decision: 'allow' | 'deny' }) => {- const { nodeId, pendingId, decision } = payload ?? ({} as typeof payload)- if (!isValidPendingId(pendingId)) return false- if (decision !== 'allow' && decision !== 'deny') return false- const sshProjectId = workspaceStore.sshProjectIdForNode(nodeId)- const ok =- sshProjectId && sshProjectManager- ? await sshProjectManager.writePendingAnswer(sshProjectId, pendingId, decision)- : await writePendingAnswerLocal(pendingId, decision, homedir())- // Optimistic flip: on a successful write, emit the same synthetic "answered" transition the- // held hook's second POST will produce, so the NEEDS YOU badge clears instantly instead of- // waiting for that POST to round-trip. The later hook POST is an idempotent duplicate (a- // same-state working re-assert is a no-op). See docs/hook-reply-approvals.md.- if (ok) {- const ev = syntheticAnsweredEvent(nodeId, pendingId, decision)- if (ev) emitAgentStatus(ev)- }- return ok+ corePlatform.handle(IPC.agentAnswerPermission, async (payload: AnswerPermissionPayload) => {+ const { nodeId, pendingId } = payload ?? ({} as AnswerPermissionPayload)+ if (typeof nodeId !== 'string' || !isValidPendingId(pendingId)) return false+ const sshProjectId = workspaceStore.sshProjectIdForNode(nodeId)+ // The ONE answer body both shells share (core/agents/permission-decision.ts): read the held+ // request on the host the agent runs on, validate + build the decision there, write it back.+ // A structured answer is refused without a readable request; the legacy words are not.+ const io: HeldPermissionIo =+ sshProjectId && sshProjectManager+ ? {+ readPending: () => sshProjectManager!.readPendingRequest(sshProjectId, pendingId),+ write: (content) => sshProjectManager!.writePendingAnswer(sshProjectId, pendingId, content)+ }+ : localHeldPermissionIo(pendingId, homedir())+ const res = await answerHeldPermission({ decision: payload.decision, answer: payload.answer }, io)+ // Optimistic flip: on a successful write, emit the same synthetic "answered" transition the+ // held hook's second POST will produce, so the NEEDS YOU badge clears instantly instead of+ // waiting for that POST to round-trip. The later hook POST is an idempotent duplicate (a+ // same-state working re-assert is a no-op). See docs/hook-reply-approvals.md.+ if (res.ok && res.decision) {+ const ev = syntheticAnsweredEvent(nodeId, pendingId, res.decision)+ if (ev) emitAgentStatus(ev)}- )+ return res.ok+ })// Read-a-finished-session ack (this feature): the renderer's unread-clear funnel calls it when the// just-read node's latest state is `done`. The mirror resolves the node's done inbox event(s)// (phone Inbox archives the card) and re-sends an 'end' live-update so the paired phone dismissesdiff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex 570eaf4f5..a2ab07ffe 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -157,6 +157,39 @@ describe('SshProjectManager', () => {}})+ it('writePendingAnswer puts a structured decision on STDIN, never in the remote command', async () => {+ const { mgr, run } = makeMgr()+ await mgr.connect('p1', conn)+ const json =+ '{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny","message":"it\'s $(rm -rf ~)"}}}'+ expect(await mgr.writePendingAnswer('p1', 'node-1-2', json)).toBe(true)+ const call = run.mock.calls.find((c) => (c[0] as string[]).join(' ').includes('.answer'))!+ expect(call[1]).toBe(json)+ expect((call[0] as string[]).join(' ')).not.toContain('hookSpecificOutput')+ expect((call[0] as string[]).join(' ')).not.toContain('rm -rf')+ })++ it('readPendingRequest reads the held request over the master, bounded, and null on any failure', async () => {+ const { mgr, run } = makeMgr()+ expect(await mgr.readPendingRequest('p1', 'node-1-2')).toBeNull() // not connected+ await mgr.connect('p1', conn)+ const req = '{"hook_event_name":"PermissionRequest","tool_name":"ExitPlanMode","tool_input":{}}'+ run.mockImplementation(async (args: string[]) =>+ args.join(' ').includes('pending/node-1-2.json') ? { code: 0, stdout: req } : { code: 0, stdout: '' }+ )+ expect(await mgr.readPendingRequest('p1', 'node-1-2')).toBe(req)+ const cmd = (run.mock.calls.at(-1)![0] as string[]).join(' ')+ expect(cmd).toContain('head -c')+ expect(cmd).toContain('exit 3') // a missing file is an answer, reported as null+ run.mockImplementation(async () => ({ code: 3, stdout: '' }))+ expect(await mgr.readPendingRequest('p1', 'node-1-2')).toBeNull()+ run.mockImplementation(async () => { throw new Error('master down') })+ expect(await mgr.readPendingRequest('p1', 'node-1-2')).toBeNull()+ const before = run.mock.calls.length+ expect(await mgr.readPendingRequest('p1', '../x')).toBeNull()+ expect(run.mock.calls.length).toBe(before)+ })+it('writePendingAnswer refuses an invalid pendingId and a disconnected project (no run)', async () => {const { mgr, run } = makeMgr()// Not connected → false, no ssh command issued.@@ -164,8 +197,9 @@ describe('SshProjectManager', () => {await mgr.connect('p1', conn)const before = run.mock.calls.lengthexpect(await mgr.writePendingAnswer('p1', '../evil', 'allow')).toBe(false)- // @ts-expect-error, runtime guard against a bad decision value+ // Content the hook script would not print is refused before any ssh (same bound as the script).expect(await mgr.writePendingAnswer('p1', 'ok-id', 'always')).toBe(false)+ expect(await mgr.writePendingAnswer('p1', 'ok-id', '{"hookSpecificOutput":{"hookEventName":"PreToolUse"}}')).toBe(false)expect(run.mock.calls.length).toBe(before) // neither refusal touched ssh})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 70fa83645..0ef27e261 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -74,6 +74,7 @@ import { appSshAgent } from './ssh-agent'import { probeAgentSockToPin } from '../../core/remote-ssh/agent-probe'import { sessionName } from '../../core/tmux-naming'import { remoteAtomicWrite } from '../remote-atomic-write'+import { isBoundedAnswerContent, PENDING_REQUEST_MAX_BYTES } from '../../core/agents/permission-decision'import { buildCodexLauncherScript } from '../../core/codex-identity-proxy'import {ACCOUNT_ID_RE,@@ -1884,24 +1885,26 @@ export class SshProjectManager {}/**- * Deterministic hook-reply approvals (docs/hook-reply-approvals.md): write the one-line answer- * file for a held REMOTE permission hook, on the project's host over its ControlMaster (atomic- * tmp+mv, 0600 via umask). The hook is polling `~/.nodeterm/pending/<pendingId>.answer` on that- * host. `pendingId` is validated by the caller (main) before it reaches here; this method also- * refuses anything but the safe charset as defense-in-depth, since it interpolates into a remote- * shell command. No-ops (false) when the project isn't connected or the write fails.+ * Deterministic hook-reply approvals (docs/hook-reply-approvals.md): write the answer file for a+ * held REMOTE permission hook, on the project's host over its ControlMaster (atomic tmp+mv, 0600+ * via umask). The hook is polling `~/.nodeterm/pending/<pendingId>.answer` on that host.+ * `content` is a legacy word or a core-built JSON decision; it travels on STDIN, never in the+ * remote command line (argv on both ends — a structured answer carries user text), and anything+ * the hook script would not print is refused here too (`isBoundedAnswerContent`). `pendingId` is+ * validated by the caller (main) before it reaches here; this method also refuses anything but the+ * safe charset as defense-in-depth, since it interpolates into a remote shell command. No-ops+ * (false) when the project isn't connected or the write fails.*/async writePendingAnswer(projectId: string,pendingId: string,- decision: 'allow' | 'deny'+ content: string): Promise<boolean> {const c = this.conns.get(projectId)if (!c) return falseif (!/^[A-Za-z0-9_-]+$/.test(pendingId)) return false- if (decision !== 'allow' && decision !== 'deny') return false- const dir = c.remoteHome ? `${c.remoteHome}/.nodeterm/pending` : '~/.nodeterm/pending'- const file = `${dir}/${pendingId}.answer`+ if (typeof content !== 'string' || !isBoundedAnswerContent(content)) return false+ const file = `${this.pendingDirFor(c)}/${pendingId}.answer`const { code } = await this.r.run(childArgs(@@ -1909,12 +1912,36 @@ export class SshProjectManager {c.controlPath,remoteAtomicWrite(file, { restrictPermissions: true }).command),- decision+ content).catch(() => ({ code: 1, stdout: '' }))return code === 0}+ /**+ * Read the request file a held REMOTE permission hook wrote (`<pendingId>.json`, the raw+ * PermissionRequest payload) — the source of truth a structured answer is validated against.+ * Bounded (`head -c`), and null for every failure: not connected, the file is gone (the hold+ * ended — `exit 3`), a dead master, an over-long file. The caller then refuses a structured+ * answer and keeps the legacy words working exactly as before.+ */+ async readPendingRequest(projectId: string, pendingId: string): Promise<string | null> {+ const c = this.conns.get(projectId)+ if (!c) return null+ if (!/^[A-Za-z0-9_-]+$/.test(pendingId)) return null+ const f = quoteRemotePath(`${this.pendingDirFor(c)}/${pendingId}.json`)+ const cmd = `if [ -f ${f} ]; then head -c ${PENDING_REQUEST_MAX_BYTES + 1} ${f}; else exit 3; fi`+ const { code, stdout } = await this.r+ .run(childArgs(c.conn, c.controlPath, cmd))+ .catch(() => ({ code: 1, stdout: '' }))+ if (code !== 0 || typeof stdout !== 'string' || stdout.length > PENDING_REQUEST_MAX_BYTES) return null+ return stdout+ }++ private pendingDirFor(c: { remoteHome?: string }): string {+ return c.remoteHome ? `${c.remoteHome}/.nodeterm/pending` : '~/.nodeterm/pending'+ }+/*** The resolved remote `$HOME` for the project owning this `controlPath`, if known. The hook* raw-listener only has the node's `{ controlPath, conn }` (from `sshRemoteForNode`), so itdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 08d6d0184..1e38d0665 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -13337,7 +13337,8 @@ export function Canvas() {e.newTurn,e.pendingId,e.verified,- e.errored+ e.errored,+ e.held)// A genuine new turn drops the previous fan-out — but only the cards that FINISHED// (issue #547). Claude launches subagents async, so "waiting for N background agents todiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 13cd51d26..936c3945a 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -5691,19 +5691,25 @@ export function TerminalNode({state leaves `blocked` (the store clears pendingId). */}{status?.state === 'blocked' && status?.pendingId && (<span className="term-node__approve nodrag">- <button- className="term-node__approve-btn term-node__approve-btn--allow"- title="Approve this permission request"- onClick={() =>- void window.nodeTerminal.answerPermission({- nodeId: id,- pendingId: status.pendingId!,- decision: 'allow'- })- }- >- ✓ Approve- </button>+ {/* A plain allow cannot answer a question (Claude drops it and the hook keeps holding),+ so Approve is hidden when THIS ticket is a held AskUserQuestion (a concurrent child+ approval keeps its own Approve); Deny still declines it. A held ExitPlanMode keeps Approve: the hook maps a plain allow to "restore the pre-plan+ mode" (docs/hook-reply-approvals.md). */}+ {!(status.held?.toolName === 'AskUserQuestion' && status.held.pendingId === status.pendingId) && (+ <button+ className="term-node__approve-btn term-node__approve-btn--allow"+ title="Approve this permission request"+ onClick={() =>+ void window.nodeTerminal.answerPermission({+ nodeId: id,+ pendingId: status.pendingId!,+ decision: 'allow'+ })+ }+ >+ ✓ Approve+ </button>+ )}<buttonclassName="term-node__approve-btn term-node__approve-btn--deny"title="Deny this permission request"diff --git a/src/renderer/nodes/approve-button-gate.test.ts b/src/renderer/nodes/approve-button-gate.test.tsnew file mode 100644index 000000000..793b32037--- /dev/null+++ b/src/renderer/nodes/approve-button-gate.test.ts@@ -0,0 +1,21 @@+// The header ✓ Approve writes a plain `allow`. For a held AskUserQuestion that is not an answer —+// Claude drops a bare allow on that tool, and the managed hook consumes it and keeps holding — so+// the button must not render for that ticket. Source-level pin: the header is a large component+// with no render harness, and the condition is exactly the kind of line a refactor drops silently.+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { describe, expect, it } from 'vitest'++describe('TerminalNode header Approve gate', () => {+ const src = readFileSync(resolve(__dirname, 'TerminalNode.tsx'), 'utf8')+ it('hides Approve only when THIS ticket is a held AskUserQuestion', () => {+ expect(src).toContain(+ "{!(status.held?.toolName === 'AskUserQuestion' && status.held.pendingId === status.pendingId) && ("+ )+ })+ it('Approve and Deny still speak the legacy decision words (the hook maps a plan allow)', () => {+ const block = src.slice(src.indexOf('term-node__approve nodrag'), src.indexOf('✕ Deny'))+ expect(block).toContain("decision: 'allow'")+ expect(block).toContain("decision: 'deny'")+ })+})diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.tsindex 08f9ae0f0..302c0dece 100644--- a/src/renderer/state/agentStatus.test.ts+++ b/src/renderer/state/agentStatus.test.ts@@ -305,7 +305,7 @@ describe('the verified evidence for a transition', () => {// argument list: nothing else in the suite would notice if the last argument disappeared.const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/canvas/Canvas.tsx'), 'utf8')expect(src).toMatch(- /cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified,\s*e\.errored\s*\)/+ /cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified,\s*e\.errored,\s*e\.held\s*\)/)})@@ -350,3 +350,33 @@ describe('the verified evidence for a transition', () => {}})})++describe('held permission request (structured answers)', () => {+ const plan = { pendingId: 'n-1-1', toolName: 'ExitPlanMode' }+ const question = { pendingId: 'n-2-2', toolName: 'AskUserQuestion' }++ it('is kept on blocked AND on waiting (a held picker is broadcast as waiting), cleared on leaving', () => {+ const s = useAgentStatus.getState()+ const id = nid()+ s.setState(id, 'blocked', 'claude', false, 'n-1-1', true, false, plan)+ expect(useAgentStatus.getState().byId[id].held).toEqual(plan)+ const q = nid()+ s.setState(q, 'waiting', 'claude', false, undefined, true, false, question)+ expect(useAgentStatus.getState().byId[q].held).toEqual(question)+ expect(useAgentStatus.getState().byId[q].pendingId).toBeUndefined() // approve/deny stays off+ s.setState(id, 'working', 'claude', false)+ expect(useAgentStatus.getState().byId[id].held).toBeUndefined()+ })++ it('a NEW held request on a same-state re-assert retargets (breaks the in-place fast path)', () => {+ const s = useAgentStatus.getState()+ const id = nid()+ s.setState(id, 'waiting', 'claude', false, undefined, true, false, question)+ const again = { pendingId: 'n-3-3', toolName: 'AskUserQuestion' }+ s.setState(id, 'waiting', 'claude', false, undefined, true, false, again)+ expect(useAgentStatus.getState().byId[id].held).toEqual(again)+ // A re-assert with no held info keeps the current one.+ s.setState(id, 'waiting', 'claude', false)+ expect(useAgentStatus.getState().byId[id].held).toEqual(again)+ })+})diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 6ef7f0856..00e6f3ab7 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -2,6 +2,7 @@ import { create, type StoreApi, type UseBoundStore } from 'zustand'import { WORKING_STALE_MS } from '@shared/agents/stale'import type { AgentId } from '@shared/agents/config'import type { AgentState } from '@shared/agents/normalize'+import type { HeldPermission } from '@shared/agents/permission-answer'import type { NodeTerminalApi, ObservedClaudeAccount } from '@shared/types'import type { WakeContext } from '../terminal/wake-identity'@@ -193,6 +194,17 @@ export interface AgentNodeStatus {* leaves `blocked` (so the buttons vanish once the decision lands). Absent = legacy prompt path.*/pendingId?: string+ /**+ * The request the node's managed hook is HOLDING (answer-file ticket + tool name), so a surface+ * can offer controls that fit it — approve a plan with a follow-on mode, answer a question —+ * through a structured `answerPermission`. Unlike `pendingId` it survives the mirror's question+ * classification (which strips `pendingId` from a picker so approve/deny never lights there), and+ * it is kept while the node is in EITHER needs-you state (`blocked` or `waiting`; a held picker is+ * broadcast as `waiting`). TRANSIENT, cleared as soon as the node leaves needs-you. It can outlive+ * the hold itself (the hook times out with no event), which is why an answer to a stale one is+ * simply refused by core (`answerPermission` resolves false).+ */+ held?: HeldPermission/*** The station's LAST turn ended on an API/model error (issue #521) — set from the agent's own* `StopFailure` hook, cleared by the next genuine new turn.@@ -258,7 +270,8 @@ export interface AgentStatusStore {newTurn?: boolean,pendingId?: string,verified?: boolean,- errored?: boolean+ errored?: boolean,+ held?: HeldPermission): void/** Clear `working` entries whose last event is older than `staleMs` (lost-Stop safety net). */sweepStaleWorking(staleMs?: number): void@@ -504,7 +517,7 @@ export function createAgentStatusSession(return s.activeId === id ? { activeId: null } : s}),- setState: (id, state, agentId, newTurn, pendingId, verified, errored) =>+ setState: (id, state, agentId, newTurn, pendingId, verified, errored, held) =>set((s) => {const prev = s.byId[id] ?? EMPTYconst now = Date.now()@@ -529,10 +542,14 @@ export function createAgentStatusSession(// a freshness-only refresh.const samePendingWhileBlocked =state !== 'blocked' || (pendingId ?? prev.pendingId) === prev.pendingId+ // Same for a NEW held request (a held picker re-asserts `waiting`, where pendingId is absent).+ const needsYou = state === 'blocked' || state === 'waiting'+ const sameHeld = !needsYou || !held || held.pendingId === prev.held?.pendingIdif (prev.state === state &&(agentId === undefined || prev.agentId === agentId) &&samePendingWhileBlocked &&+ sameHeld &&!turnErrorMoves) {// Same-state event: refresh freshness in place — stateAt is never rendered, and a@@ -556,6 +573,8 @@ export function createAgentStatusSession(if (agentId !== undefined) next.agentId = agentId// Retain the approval ticket only while blocked; any other state clears it (transient).next.pendingId = state === 'blocked' ? (pendingId ?? prev.pendingId) : undefined+ // The held request rides both needs-you states (see `held`); anything else ends the hold.+ next.held = needsYou ? (held ?? prev.held) : undefined// The last-turn verdict (issue #521). A genuine new turn retires it — the station is being// asked something else, and the old failure no longer describes what it is doing. Anything// else LEAVES IT STANDING (it rides the spread): the intermediate transitions between thediff --git a/src/server/index.ts b/src/server/index.tsindex 836a8be6b..2cf5276cd 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -55,11 +55,13 @@ import { refreshNodeTokens } from '../core/agents/node-token-service'import { armServerNodeIdentity } from './node-identity-arm'import { wireServerCodexSharedIdentity } from './codex-shared-identity'import {- writePendingAnswerLocal,+ localHeldPermissionIo,startPendingSweep,isValidPendingId,syntheticAnsweredEvent} from '../core/agents/pending-approvals'+import { answerHeldPermission } from '../core/agents/permission-decision'+import type { AnswerPermissionPayload } from '../shared/agents/permission-answer'import { installManagedAgentHooks } from '../core/agents/hooks'import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'import {@@ -506,28 +508,28 @@ export async function startServer(// answer file is written right there (under os.homedir(), which the hook uses as $HOME). SSH// projects are v1-unsupported server-side (no ControlMaster manager here) → false, a documented// three-surfaces degrade. pendingId is validated before it becomes a path.- platform.handle(- IPC.agentAnswerPermission,- async (payload: { nodeId: string; pendingId: string; decision: 'allow' | 'deny' }) => {- const { nodeId, pendingId, decision } = payload ?? ({} as typeof payload)- if (!isValidPendingId(pendingId)) return false- if (decision !== 'allow' && decision !== 'deny') return false- // An SSH-project node has no reachable ControlMaster here (v1): answer only local nodes.- if (workspaceStore.sshProjectIdForNode(nodeId)) return false- const ok = await writePendingAnswerLocal(pendingId, decision, os.homedir())- // Optimistic flip (parity with desktop): emit the synthetic "answered" transition so the- // browser canvas NEEDS YOU badge clears instantly, ahead of the held hook's second POST (an- // idempotent duplicate). See docs/hook-reply-approvals.md.- if (ok) {- const ev = syntheticAnsweredEvent(nodeId, pendingId, decision)- if (ev) {- platform.broadcast(IPC.agentStatus, ev)- recordAgentEvent(ev)- }+ platform.handle(IPC.agentAnswerPermission, async (payload: AnswerPermissionPayload) => {+ const { nodeId, pendingId } = payload ?? ({} as AnswerPermissionPayload)+ if (typeof nodeId !== 'string' || !isValidPendingId(pendingId)) return false+ // An SSH-project node has no reachable ControlMaster here (v1): answer only local nodes.+ if (workspaceStore.sshProjectIdForNode(nodeId)) return false+ // Same shared body as the desktop (core/agents/permission-decision.ts), local fs only.+ const res = await answerHeldPermission(+ { decision: payload.decision, answer: payload.answer },+ localHeldPermissionIo(pendingId, os.homedir())+ )+ // Optimistic flip (parity with desktop): emit the synthetic "answered" transition so the+ // browser canvas NEEDS YOU badge clears instantly, ahead of the held hook's second POST (an+ // idempotent duplicate). See docs/hook-reply-approvals.md.+ if (res.ok && res.decision) {+ const ev = syntheticAnsweredEvent(nodeId, pendingId, res.decision)+ if (ev) {+ platform.broadcast(IPC.agentStatus, ev)+ recordAgentEvent(ev)}- return ok}- )+ return res.ok+ })// Read-a-finished-session ack (parity with desktop): the browser canvas's unread-clear funnel// calls it when the just-read node's latest state is `done`. The mirror resolves the node's done// inbox event(s) + re-sends an 'end' live-update so the paired phone dismisses its lingering DONEdiff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsindex 650905b87..3b61bc1df 100644--- a/src/shared/agents/normalize.test.ts+++ b/src/shared/agents/normalize.test.ts@@ -121,6 +121,32 @@ describe('normalizeClaude — PermissionRequest (deterministic approvals)', () =})})+describe('normalizeClaude — held tool (structured answers)', () => {+ it('names the held tool beside the ticket, for plans, questions and ordinary tools alike', () => {+ for (const tool of ['ExitPlanMode', 'AskUserQuestion', 'Bash', 'mcp__srv__do']) {+ const e = normalizeClaude(+ env({ hook_event_name: 'PermissionRequest', tool_name: tool, nodeterm_pending_id: 'n1-1-1' })+ )+ expect(e).toMatchObject({ state: 'blocked', held: { pendingId: 'n1-1-1', toolName: tool } })+ }+ })+ it('no held request without a ticket, and an unsafe tool name is dropped rather than carried', () => {+ const none = normalizeClaude(env({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode' }))+ expect(none && 'held' in none).toBe(false)+ const bad = normalizeClaude(+ env({ hook_event_name: 'PermissionRequest', tool_name: 'a b<script>', nodeterm_pending_id: 'n1-1-1' })+ )+ expect(bad && 'held' in bad).toBe(false)+ expect(bad).toMatchObject({ pendingId: 'n1-1-1' }) // the approval ticket itself is untouched+ })+ it('the answered signal carries no held request (the hold is over)', () => {+ const e = normalizeClaude(+ env({ hook_event_name: 'PermissionRequest', tool_name: 'ExitPlanMode', nodeterm_pending_id: 'n1-1-1', nodeterm_answered: 'allow' })+ )+ expect(e && 'held' in e).toBe(false)+ })+})+describe('normalizeClaude — deterministic-approval "answered" signal', () => {// The signal rides ALONGSIDE the original PermissionRequest payload, so it must be matched BEFORE// hook_event_name (which would otherwise map to blocked) and yield a synthetic working transition.diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex a189440b4..072f60899 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -1,5 +1,6 @@import type { AgentId } from './config'import type { ObservedClaudeAccount } from '../types'+import { isSafeToolName, type HeldPermission } from './permission-answer'export type AgentState = 'working' | 'waiting' | 'blocked' | 'done'@@ -69,6 +70,13 @@ export interface NormalizedAgentEvent {// concurrent parent picker cannot hide their approval tickets. The canvas keys the approve/deny// buttons off `pendingId`, which is now absent on a question. */askKind?: 'question' | 'approval'+ /** blocked (Claude PermissionRequest with a held hook) only: the answer-file ticket PLUS the tool+ * being asked about, so a surface can tell a plan (ExitPlanMode) or question (AskUserQuestion)+ * hold from an ordinary permission and offer the right controls (a structured+ * `answerPermission`). Deliberately separate from `pendingId`, which the mirror STRIPS from a+ * question so no approve/deny button lights on a picker — this field lights nothing by itself.+ * Additive and optional: an older consumer ignores it. See docs/hook-reply-approvals.md. */+ held?: HeldPermission// sessionsessionTitle?: string// session lifecycle phase: 'start' resets to idle, 'end' resets + clears loop/fan-out@@ -318,7 +326,10 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu...(tool && tool !== 'AskUserQuestion' ? { askKind: 'approval' as const } : {}),lastMessage: p.last_assistant_message,// Deterministic-approval ticket (present only when the wait-branch of the managed hook ran).- ...(p.nodeterm_pending_id ? { pendingId: p.nodeterm_pending_id } : {})+ ...(p.nodeterm_pending_id ? { pendingId: p.nodeterm_pending_id } : {}),+ ...(p.nodeterm_pending_id && isSafeToolName(tool)+ ? { held: { pendingId: p.nodeterm_pending_id, toolName: tool } }+ : {})}}if (ev === 'Notification') {diff --git a/src/shared/agents/permission-answer.ts b/src/shared/agents/permission-answer.tsnew file mode 100644index 000000000..4e0c97ad3--- /dev/null+++ b/src/shared/agents/permission-answer.ts@@ -0,0 +1,71 @@+// Structured answers to a HELD Claude PermissionRequest (docs/hook-reply-approvals.md).+//+// The managed hook holds a PermissionRequest open and polls an answer file. The legacy answer is+// one word, `allow` | `deny`. That cannot answer the two tools that set `requiresUserInteraction`:+// Claude Code DROPS a bare allow for them (`if(!I.updatedInput&&e.requiresUserInteraction?.())+// return null` — docs/superpowers/plans/2026-09-26-answer-paths-research.md §2), so approving a plan+// or answering a question needs a decision that carries `updatedInput`. These are the shapes the+// renderer may ask for; core (`core/agents/permission-decision.ts`) validates every field against the+// pending request file and builds the JSON the hook prints. The renderer never builds hook JSON.+//+// Shared (not core) because the renderer and both shells' IPC types name it.++/** Claude's plan-approval tool. Its hold is long, and a plain `allow` maps to "restore the mode+ * that preceded plan mode" (`updatedInput:{}`) inside the hook script itself. */+export const EXIT_PLAN_MODE_TOOL = 'ExitPlanMode'+/** Claude's question picker. A plain `allow` cannot answer it; only `{kind:'question'}` can. */+export const ASK_USER_QUESTION_TOOL = 'AskUserQuestion'++/** The two tools a person reads for minutes rather than seconds — the hook holds them for+ * `PERM_WAIT_SECS_INTERACTIVE` instead of the 45 s default. */+export const INTERACTIVE_HOLD_TOOLS: readonly string[] = [EXIT_PLAN_MODE_TOOL, ASK_USER_QUESTION_TOOL]++/**+ * What an answerer may send. `allow` / `deny` are the legacy verbs (phone, older desktop, the header+ * buttons) and still travel as the one-word answer file.+ *+ * - `plan` — approve an ExitPlanMode. `restore` = the mode that preceded plan mode (no+ * `updatedPermissions`; the tool's own call() restores it, including auto's dangerous-rule+ * strip). `acceptEdits` / `manual` add a session `setMode`. There is deliberately no `auto`:+ * a hook `setMode auto` skips that strip (research §2(A)).+ * - `plan-revise` — "No, keep planning": a deny whose message is the user's feedback.+ * - `question` — answer an AskUserQuestion. Keys are the EXACT question texts; a string is one+ * option label, a string[] is several labels of a multiSelect question. A key listed in+ * `freeText` carries typed text (the picker's "Other") instead of a label — that is the ONLY way+ * an answer may be something other than an existing label.+ */+export type PermissionAnswer =+ | { kind: 'allow' }+ | { kind: 'deny' }+ | { kind: 'plan'; mode: 'restore' | 'acceptEdits' | 'manual' }+ | { kind: 'plan-revise'; message: string }+ | { kind: 'question'; answers: Record<string, string | string[]>; freeText?: string[] }++/** The payload of `window.nodeTerminal.answerPermission`. `decision` is the pre-structured+ * contract and still works alone; when `answer` is present it wins. */+export interface AnswerPermissionPayload {+ nodeId: string+ pendingId: string+ decision?: 'allow' | 'deny'+ answer?: PermissionAnswer+}++/**+ * The request a node's managed hook is currently holding: its answer-file ticket plus the tool it+ * is asking about. Lets the renderer tell a plan / question hold from an ordinary permission and+ * render the right controls. Deliberately SEPARATE from the approve/deny `pendingId`, which the+ * mirror strips from a question (approve/deny is the wrong UX for a picker) — so adding this lights+ * no existing button.+ */+export interface HeldPermission {+ pendingId: string+ toolName: string+}++/** Tool names are agent-controlled text (MCP tools are `mcp__<server>__<tool>`); only a plain+ * identifier ever rides an event. Anything else is dropped, never repaired. */+const TOOL_NAME_RE = /^[A-Za-z0-9_.:-]{1,128}$/++export function isSafeToolName(name: unknown): name is string {+ return typeof name === 'string' && TOOL_NAME_RE.test(name)+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 3dc67e013..52c6fdccf 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -7,6 +7,7 @@ import type { CloneProgress } from './clone-url'import type { KeybindingOverrides, TerminalShortcutPolicy } from './keybindings'import type { NormalizedAgentEvent } from './agents/normalize'import type { PaneOwner } from './agents/pane-owner-predicate'+import type { AnswerPermissionPayload } from './agents/permission-answer'import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'import type { ControlConfirmWaivers } from './control-confirm'import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'@@ -3749,8 +3750,14 @@ export interface NodeTerminalApi {* (`~/.nodeterm/pending/<pendingId>.answer`) on the host the agent runs on — the LOCAL fs for a* local project, or the remote host over the project's ControlMaster for an SSH project. Resolves* `true` when the file was written, `false` on any failure (invalid pendingId, unknown node,- * unsupported project, fs/exec error). */- answerPermission(payload: { nodeId: string; pendingId: string; decision: 'allow' | 'deny' }): Promise<boolean>+ * unsupported project, fs/exec error).+ *+ * `decision` is the original contract and still works alone. An optional structured `answer`+ * (`PermissionAnswer`: approve a plan with a follow-on mode, send plan feedback, answer an+ * AskUserQuestion) wins over it; core validates it against the held request file on the agent's+ * host and refuses (`false`) when that request is gone or the answer does not fit it. A plain+ * `allow` on a held AskUserQuestion is refused too — Claude would drop it. */+ answerPermission(payload: AnswerPermissionPayload): Promise<boolean>/** Notify the core that the user READ a finished (done) session on this surface (the unread-clear* funnel calls it when the node's latest state is `done`). The core marks the node's done inbox* event(s) resolved (phone Inbox archives the card) and re-sends an 'end' live-update so the