passcontrol 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/sidecar.mjs CHANGED
@@ -7,8 +7,10 @@ import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./pro
7
7
  import { createVisaClient } from "./visa-client.mjs";
8
8
  import { declaredLineage, declaredSession } from "./declared-session.mjs";
9
9
  import { defaultJournalDir, openJournal } from "./journal.mjs";
10
+ import { heldUnderTaint } from "./injection-hold.mjs";
11
+ import { findingsFromHook } from "./injection-sidecar.mjs";
10
12
  import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
11
- import { createStopGate, HOOK_PATH, selfAnswerState } from "./subscription-gate.mjs";
13
+ import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
12
14
  import { createToolGate } from "./tool-gate.mjs";
13
15
  import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
14
16
  import { CLIENT_EVENTS_PATH, CLIENT_EVENTS_SOURCE, createCallUploader } from "./client-events-upload.mjs";
@@ -67,6 +69,12 @@ function hookTimeoutS(url) {
67
69
  const t = new URL(url ?? "/", "http://127.0.0.1").searchParams.get("t");
68
70
  return t !== null && /^\d{1,4}$/.test(t) && Number(t) > 0 ? Number(t) : null;
69
71
  }
72
+ // The agent's opt-in note (1.6.0): `?note=1` on subscription mode's prompt hook,
73
+ // `?note=only` on API mode's, which only ever adds the note.
74
+ function hookNote(url) {
75
+ const note = new URL(url ?? "/", "http://127.0.0.1").searchParams.get("note");
76
+ return note === "1" ? "subscription" : note === "only" ? "api" : null;
77
+ }
70
78
  // A usage window is two numbers and two times.
71
79
  const WINDOW_BODY_LIMIT = 4 * 1024;
72
80
 
@@ -172,10 +180,24 @@ export function createSidecar({
172
180
  // Subscription mode's Stop (cli/subscription-gate.mjs): Claude Code's hooks ask
173
181
  // here, and the answer comes from the gateway's /api/v1/self, read with this
174
182
  // sidecar's visa and the session the hook names.
175
- const SELF_TIMEOUT_MS = 2_000;
183
+ let highVersion = 0;
184
+ let relayVersion = 0;
185
+ let readHighVersion = 0;
186
+ let readRelayVersion = 0;
187
+ let holdOptOutWarned = false;
176
188
  async function readSelf(session) {
189
+ const highAtStart = highVersion;
190
+ const relayAtStart = relayVersion;
191
+ // One deadline over the whole read, a visa mint included: past the hook's own
192
+ // timeout the action goes ahead with no warning. A mint cut short here is not
193
+ // aborted (the proxy shares it); it finishes and is cached for the next read.
194
+ const signal = AbortSignal.timeout(SELF_READ_TIMEOUT_MS);
195
+ const deadline = new Promise((_, reject) => {
196
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
197
+ });
198
+ deadline.catch(() => {});
177
199
  try {
178
- const response = await visas.fetchWithVisa((visa) => {
200
+ const response = await Promise.race([deadline, visas.fetchWithVisa((visa) => {
179
201
  // The tool rules ride on every gate read (Phase 2): no call of their own.
180
202
  const path = "/api/v1/self?include=tool_rules";
181
203
  const headers = {
@@ -186,9 +208,18 @@ export function createSidecar({
186
208
  "accept-encoding": "identity",
187
209
  };
188
210
  if (session) headers["x-claude-code-session-id"] = session;
189
- return fetch(`${origin}${path}`, { headers, signal: AbortSignal.timeout(SELF_TIMEOUT_MS) });
190
- });
191
- return await selfAnswerState(response);
211
+ return fetch(`${origin}${path}`, { headers, signal });
212
+ })]);
213
+ const answer = await Promise.race([deadline, selfAnswerState(response)]);
214
+ if (answer.state === "open") {
215
+ readHighVersion = Math.max(readHighVersion, highAtStart);
216
+ readRelayVersion = Math.max(readRelayVersion, relayAtStart);
217
+ if (answer.injection?.mode === "hold" && !reportCalls && !holdOptOutWarned) {
218
+ holdOptOutWarned = true;
219
+ warn("The injection guard's hold needs this sidecar to upload what it finds. --no-report-calls turns that off, so tools are held only for what the gateway itself saw.");
220
+ }
221
+ }
222
+ return answer;
192
223
  } catch (error) {
193
224
  return { state: "unknown", reason: error?.name === "TimeoutError" ? "the gateway did not answer in time" : (error?.message ?? "error") };
194
225
  }
@@ -259,14 +290,42 @@ export function createSidecar({
259
290
  const body = await response.json().catch(() => ({}));
260
291
  return { status: response.status, error: body?.error, retryAfterS: Number(response.headers.get("retry-after")) };
261
292
  }
293
+ const injectionSeen = new Set();
262
294
  const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
263
295
  // Its decisions reach the agent's page with the reported calls (same opt-out).
264
296
  const toolGate = createToolGate({
265
297
  askOwner,
266
298
  dashboardUrl: `${origin}/dashboard`,
267
299
  onDecision: (record) => uploader?.add({ kind: "tool_decision", at: Date.now(), ...record }),
300
+ onHold: (record) => feed.toolHold({ at: Date.now(), ...record }),
301
+ refresh: async () => {
302
+ await stopGate.refresh();
303
+ return { rulesEntry: stopGate.toolRules(), injection: stopGate.injection() };
304
+ },
268
305
  });
269
306
 
307
+ let injectionRefresh = null;
308
+ async function freshInjectionFor(tool) {
309
+ if (!heldUnderTaint(tool) || !stopGate.injectionHoldMode()) return;
310
+ if (injectionRefresh) return injectionRefresh;
311
+ if (highVersion <= readHighVersion && relayVersion <= readRelayVersion) return;
312
+ injectionRefresh = (async () => {
313
+ if (uploader && highVersion > readHighVersion) {
314
+ let timer;
315
+ try {
316
+ await Promise.race([
317
+ Promise.resolve().then(() => uploader.flush()),
318
+ new Promise((resolve) => { timer = setTimeout(resolve, 3_000); }),
319
+ ]);
320
+ } catch {
321
+ // A failed upload must not prevent the read or change the opt-out.
322
+ } finally { clearTimeout(timer); }
323
+ }
324
+ await stopGate.refresh();
325
+ })();
326
+ try { await injectionRefresh; } finally { injectionRefresh = null; }
327
+ }
328
+
270
329
  const relayedSessions = new Set();
271
330
  function rememberRelayed(headers) {
272
331
  const session = lineageOf(headers)?.session;
@@ -397,7 +456,8 @@ export function createSidecar({
397
456
  }
398
457
  let out;
399
458
  try {
400
- out = await stopGate.decide(input);
459
+ if (input.hook_event_name === "PreToolUse") await freshInjectionFor(input.tool_name);
460
+ out = await stopGate.decide(input, { note: hookNote(req.url) });
401
461
  } catch {
402
462
  out = {};
403
463
  }
@@ -406,7 +466,7 @@ export function createSidecar({
406
466
  if (out.continue !== false && input.hook_event_name === "PreToolUse") {
407
467
  let tool;
408
468
  try {
409
- tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url));
469
+ tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), stopGate.injection());
410
470
  } catch {
411
471
  tool = {};
412
472
  }
@@ -416,6 +476,23 @@ export function createSidecar({
416
476
  const body = JSON.stringify(out);
417
477
  res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
418
478
  res.end(body);
479
+ // Injection tells in what the tools returned (plans/injection-guard.md §2b): after
480
+ // the answer is written, so the scan never delays or changes it.
481
+ if (input.hook_event_name === "PostToolBatch" || input.hook_event_name === "PostToolUse") {
482
+ setImmediate(() => {
483
+ try {
484
+ for (const event of findingsFromHook(input, { seen: injectionSeen })) {
485
+ if (event.severity === "high") highVersion++;
486
+ feed.injection(event);
487
+ // With the reported calls (same opt-out). The gateway records it only while
488
+ // the owner has the guard on, and never says which.
489
+ uploader?.add(event);
490
+ }
491
+ } catch {
492
+ // Local telemetry must never change or delay the hook answer.
493
+ }
494
+ });
495
+ }
419
496
  });
420
497
  req.on("error", () => res.destroy());
421
498
  }
@@ -459,6 +536,13 @@ export function createSidecar({
459
536
  // from a capped peek at a CLONE of the body, so the client's bytes are untouched
460
537
  // and nothing here waits on the peek.
461
538
  function writeResponse(res, upstream, reqHeaders, watch = null) {
539
+ // Also mark streamed responses on completion: a /self read while the stream
540
+ // was open cannot cover a finding the gateway sees later in that stream.
541
+ if (watch) {
542
+ relayVersion++;
543
+ res.once("finish", () => { relayVersion++; });
544
+ res.once("close", () => { relayVersion++; });
545
+ }
462
546
  // At the headers, not at the end of the body: a streamed call whose client
463
547
  // disconnects mid-stream still produced a receipt, and the user's record of
464
548
  // it must not depend on how long they kept reading. With the session the call
@@ -14,7 +14,7 @@
14
14
  // older budget that might read as current.
15
15
  import fs from "node:fs";
16
16
  import path from "node:path";
17
- import { limitReached, panelRows, statusLine } from "./budget-format.mjs";
17
+ import { limitReached, panelRows, paused, statusLine } from "./budget-format.mjs";
18
18
  import { heldUsageWindow, readUsageWindow, usageWindowText, WINDOW_PATH } from "./usage-window.mjs";
19
19
 
20
20
  export const STATUSLINE_TTL_MS = 20_000;
@@ -292,7 +292,7 @@ export async function statusPanelText({
292
292
  }
293
293
  if (typeof self?.budget !== "object" || self.budget === null) return "PassControl · unreadable answer";
294
294
  const agentId = typeof self.agent_id === "string" && UUID.test(self.agent_id) ? self.agent_id : null;
295
- const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : ""}`;
295
+ const title = `PassControl${agentId ? ` · agent ${agentId.slice(0, 8)}` : ""}${limitReached(self) ? " · LIMIT REACHED" : paused(self) ? " · PAUSED" : ""}`;
296
296
  const window = subscription ? await readSidecarWindow({ host, port, fetch: fetchImpl, signal: controller.signal }) : "";
297
297
  return [
298
298
  title,
@@ -34,15 +34,30 @@
34
34
  // A refusal carries no rules, so a PreToolUse refreshes them with the agent-wide ask
35
35
  // once they are `freshMs` old.
36
36
  //
37
+ // The agent's own note (1.6.0, cli/agent-note.mjs) rides on the prompt hook when its
38
+ // URL opts in: `?note=1` in this mode, `?note=only` when Claude Code goes through the
39
+ // sidecar with an API key, where the gateway already enforces and the hook only ever
40
+ // adds the note. It is built from the latest answer and sent per session only when
41
+ // its signature changes; a stop always wins over it.
42
+ //
37
43
  // Honest limit: hooks run inside Claude Code, so this is a guard rail for the user's
38
44
  // own sessions, not a boundary against a client that skips them.
39
45
 
46
+ import { agentNote } from "./agent-note.mjs";
47
+
40
48
  export const HOOK_PATH = "/_passcontrol/hook";
41
49
 
42
50
  const GATED = new Set(["UserPromptSubmit", "PreToolUse", "PostToolBatch"]);
43
51
  // What the gateway accepts as a declared session (lib/client-lineage.ts).
44
52
  const DECLARED_SESSION = /^[A-Za-z0-9._:-]{1,128}$/;
45
53
 
54
+ // Claude Code's timeout on the prompt and next-model-call hooks (cli/claude-code.mjs).
55
+ // Past it the action goes ahead with no warning at all, so the sidecar's read of
56
+ // /api/v1/self ends a second earlier and says why. 2 s was too short: a Cloud answer
57
+ // on a cold start took longer, and a stop was missed with "did not answer in time".
58
+ export const GATE_HOOK_TIMEOUT_S = 5;
59
+ export const SELF_READ_TIMEOUT_MS = (GATE_HOOK_TIMEOUT_S - 1) * 1000;
60
+
46
61
  export const GATE_FRESH_MS = 5_000;
47
62
  export const GATE_SESSION_FRESH_MS = 15_000;
48
63
  export const GATE_MAX_STALE_MS = 60_000;
@@ -94,6 +109,10 @@ export function createStopGate({
94
109
  let agent = null;
95
110
  // The agent's tool rules as the last answer that carried them gave them.
96
111
  let rules = null;
112
+ let injectionEntry = null;
113
+ // The limits from the latest open answer, for the note; and each session's last note.
114
+ let latest = null;
115
+ const noted = new Map();
97
116
  const sessions = new Map();
98
117
  const inflight = new Map();
99
118
  const warnedAt = new Map();
@@ -124,7 +143,9 @@ export function createStopGate({
124
143
  answer = { state: "unknown", reason: error?.message ?? "error" };
125
144
  }
126
145
  answer ??= { state: "unknown", reason: "no answer" };
146
+ if (answer.state === "open" && answer.self) latest = { self: answer.self, at: now() };
127
147
  if (answer.state === "open") {
148
+ injectionEntry = { value: answer.injection, at: now() };
128
149
  rules = { read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" }, at: now() };
129
150
  }
130
151
  if (["open", "stopped"].includes(answer.state) || (session !== null && answer.state === "session_stopped")) {
@@ -151,8 +172,40 @@ export function createStopGate({
151
172
 
152
173
  const age = (entry) => (entry ? now() - entry.at : Infinity);
153
174
 
154
- async function decide(input) {
175
+ /** The note for this session's prompt, when it opted in and something changed since the last. */
176
+ function noteFor(sessionKey, mode) {
177
+ if (!latest || age(latest) > maxStaleMs) return null;
178
+ const freshRules = rules && age(rules) <= maxStaleMs ? rules.read : null;
179
+ const n = agentNote({ self: latest.self, rules: freshRules, mode, nowMs: now() });
180
+ if (!n || noted.get(sessionKey) === n.signature) return null;
181
+ remember(noted, sessionKey, n.signature);
182
+ return { hookEventName: "UserPromptSubmit", additionalContext: n.text };
183
+ }
184
+
185
+ /**
186
+ * @param {object} input Claude Code's hook input.
187
+ * @param {{ note?: "api" | "subscription" | null }} [options] the prompt hook's opt-in.
188
+ */
189
+ async function decide(input, { note = null } = {}) {
155
190
  const event = input?.hook_event_name;
191
+ if (note === "api") {
192
+ // Only the note, never a stop or a warning: the gateway refuses these calls itself.
193
+ if (event !== "UserPromptSubmit") return {};
194
+ if (age(latest) >= freshMs) await ask(null);
195
+ const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : "";
196
+ const out = noteFor(session, "api");
197
+ return out ? { hookSpecificOutput: out } : {};
198
+ }
199
+ const out = await gateDecision(input, event);
200
+ if (note === "subscription" && event === "UserPromptSubmit" && out.continue !== false) {
201
+ const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : "";
202
+ const extra = noteFor(session, "subscription");
203
+ if (extra) return { ...out, hookSpecificOutput: extra };
204
+ }
205
+ return out;
206
+ }
207
+
208
+ async function gateDecision(input, event) {
156
209
  if (!GATED.has(event)) return {};
157
210
  const session = typeof input.session_id === "string" && DECLARED_SESSION.test(input.session_id) ? input.session_id : null;
158
211
 
@@ -189,7 +242,21 @@ export function createStopGate({
189
242
  return rules && age(rules) <= maxStaleMs ? rules : null;
190
243
  }
191
244
 
192
- return { decide, toolRules };
245
+ function injection() {
246
+ if (!injectionEntry || injectionEntry.value === undefined) return "off";
247
+ if (age(injectionEntry) > maxStaleMs) return "unknown";
248
+ const value = injectionEntry.value;
249
+ if (!value || value.mode !== "hold" || value.readable !== true) return "unknown";
250
+ if (value.tainted_until === null) return "clear";
251
+ if (typeof value.tainted_until !== "string") return "unknown";
252
+ const until = Date.parse(value.tainted_until);
253
+ if (!Number.isFinite(until)) return "unknown";
254
+ return until > now() ? "tainted" : "clear";
255
+ }
256
+
257
+ // Keep the last known mode even after max-stale: a fresh read may recover it.
258
+ const injectionHoldMode = () => injectionEntry?.value?.mode === "hold";
259
+ return { decide, toolRules, injection, injectionHoldMode, refresh: () => ask(null) };
193
260
  }
194
261
 
195
262
  /**
@@ -201,7 +268,14 @@ export async function selfAnswerState(response) {
201
268
  if (response.ok) {
202
269
  const body = await response.json().catch(() => null);
203
270
  const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
204
- return toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
271
+ const answer = toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
272
+ if (body && typeof body === "object" && Object.hasOwn(body, "injection")) answer.injection = body.injection;
273
+ // The limits and the soft pause, for the agent's note; nothing else from the answer is kept.
274
+ if (body && typeof body === "object" && body.budget && typeof body.budget === "object") {
275
+ const kept = (v) => (v && typeof v === "object" ? v : null);
276
+ answer.self = { budget: body.budget, pace: kept(body.pace), pause: kept(body.pause) };
277
+ }
278
+ return answer;
205
279
  }
206
280
  if (response.status === 403) {
207
281
  const body = await response.json().catch(() => ({}));
package/cli/tool-gate.mjs CHANGED
@@ -25,6 +25,7 @@
25
25
  //
26
26
  // Each outcome that is not a plain pass is handed to `onDecision` for the agent's
27
27
  // page: tool name, decision, rule number and wait. Never the command, path or URL.
28
+ import { underTaint } from "./injection-hold.mjs";
28
29
  import { evaluateToolRules, parseToolRules } from "./tool-rules.mjs";
29
30
 
30
31
  /** The wait ends this long before Claude Code would give up on the hook. */
@@ -46,13 +47,23 @@ function verdict(permissionDecision, reason) {
46
47
  * askOwner: (input: object, ask: { ruleIndex: number, subject: string, session: string | null, waitMs: number }) =>
47
48
  * Promise<{ state: "approved" | "denied" | "timeout" | "unavailable" | "full" | "refused" | "too_large" }>,
48
49
  * onDecision?: (record: { session: string | null, agent: string | null, tool: string, decision: string, ruleIndex: number | null, waitMs: number }) => void,
50
+ * onHold?: (record: { tool: string, outcome: string }) => void,
51
+ * refresh?: () => Promise<object | null>,
49
52
  * now?: () => number,
50
53
  * dashboardUrl?: string,
51
54
  * }} options
52
55
  */
53
- export function createToolGate({ askOwner, onDecision = () => {}, now = () => Date.now(), dashboardUrl = "" }) {
56
+ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Date.now(), dashboardUrl = "", onHold = () => {}, refresh = async () => null }) {
54
57
  let warnedAt = null;
58
+ let injectionWarnedAt = null;
59
+ let needsRefresh = false;
60
+ let refreshing = null;
55
61
  const where = dashboardUrl ? ` on ${dashboardUrl}` : " on the agent's dashboard page";
62
+ // Said with every rule's refusal: told only "the tool rules refuse this", Claude
63
+ // Code went looking for the rule in the local PassControl config, which has none.
64
+ const rulesLive = dashboardUrl
65
+ ? `Tool rules are set on the agent's page at ${dashboardUrl}, not on this machine.`
66
+ : "Tool rules are set on the agent's dashboard page, not on this machine.";
56
67
 
57
68
  function record(input, decision, ruleIndex, waitMs) {
58
69
  try {
@@ -74,16 +85,24 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
74
85
  * @param {{ read: { state: string, document?: unknown }, at: number } | null} rulesEntry
75
86
  * The rules from the latest trusted /self read, or null.
76
87
  * @param {number | null} hookTimeoutS What the hook's URL says it waits; null when it does not say.
88
+ * @param {"off" | "clear" | "tainted" | "unknown"} injection
77
89
  */
78
- async function decide(input, rulesEntry, hookTimeoutS) {
90
+ async function decide(input, rulesEntry, hookTimeoutS, injection = "off") {
79
91
  if (input?.hook_event_name !== "PreToolUse") return {};
92
+ if (needsRefresh || refreshing) {
93
+ if (!refreshing) {
94
+ needsRefresh = false;
95
+ refreshing = Promise.resolve().then(refresh).finally(() => { refreshing = null; });
96
+ }
97
+ const fresh = await refreshing;
98
+ if (fresh) ({ rulesEntry, injection } = fresh);
99
+ }
80
100
  const read = rulesEntry?.read;
81
- if (read?.state === "none") return {};
82
101
  if (read?.state === "invalid") {
83
102
  record(input, "rules_invalid", null, 0);
84
103
  return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
85
104
  }
86
- const parsed = read?.state === "ok" ? parseToolRules(read.document) : null;
105
+ const parsed = read?.state === "none" ? parseToolRules({ rules: [] }) : read?.state === "ok" ? parseToolRules(read.document) : null;
87
106
  if (!parsed) {
88
107
  if (warnedAt !== null && now() - warnedAt < WARN_EVERY_MS) return {};
89
108
  warnedAt = now();
@@ -94,42 +113,83 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
94
113
  return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
95
114
  }
96
115
 
97
- const hit = evaluateToolRules(parsed, input);
98
- if (hit.effect === null) return {};
99
- const rule = `rule ${hit.ruleIndex + 1}`;
116
+ const original = evaluateToolRules(parsed, input);
117
+ const hit = injection === "tainted" ? underTaint(original, input.tool_name) : original;
118
+ const escalated = hit.reason === "injection_taint";
119
+ const guardText = "This tool was held by the injection guard because the agent recently read something that looked like a prompt injection.";
120
+ let warning = {};
121
+ if (injection === "unknown" && (injectionWarnedAt === null || now() - injectionWarnedAt >= WARN_EVERY_MS)) {
122
+ injectionWarnedAt = now();
123
+ warning = { systemMessage: "PassControl could not check this agent's injection guard, so this goes ahead." };
124
+ }
125
+ const withWarning = (out) => ({ ...out, ...warning });
126
+ function holdRecord(outcome) {
127
+ if (escalated) {
128
+ try { onHold({ tool: String(input.tool_name ?? "").slice(0, 128), outcome }); } catch {}
129
+ }
130
+ }
131
+ const ruleIndex = escalated ? null : hit.ruleIndex;
132
+ if (hit.effect === null) return withWarning({});
133
+ const rule = escalated ? "injection guard" : `rule ${hit.ruleIndex + 1}`;
100
134
  if (hit.effect === "deny") {
101
135
  record(input, "deny", hit.ruleIndex, 0);
102
- return verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}).`);
136
+ return withWarning(verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}). ${rulesLive}`));
103
137
  }
104
138
  if (hit.effect === "ask") {
105
139
  record(input, "ask", hit.ruleIndex, 0);
106
- return verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}).`);
140
+ return withWarning(verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}). ${rulesLive}`));
107
141
  }
108
142
 
109
143
  // ask_owner
110
144
  const waitS = hookTimeoutS === null ? 0 : Math.min(parsed.approvalWaitS, hookTimeoutS - HOOK_MARGIN_S);
145
+ if (waitS < MIN_WAIT_S && escalated) {
146
+ record(input, "owner_unavailable", null, 0);
147
+ holdRecord("unavailable");
148
+ return verdict("deny", `PassControl: ${guardText} The hook cannot wait for the owner. Run \`passcontrol configure claude-code --subscription --write\`, then try again.`);
149
+ }
111
150
  if (waitS < MIN_WAIT_S) {
112
151
  record(input, "owner_unavailable", hit.ruleIndex, 0);
113
- return verdict(
152
+ return withWarning(verdict(
114
153
  "deny",
115
154
  `PassControl: this needs the agent's owner to say yes (${rule}), and Claude Code's hook would give up before the answer. Run \`passcontrol configure claude-code --subscription --write\`, then try again.`
116
- );
155
+ ));
117
156
  }
118
157
  const started = now();
119
158
  let answer;
120
159
  try {
121
- answer = await askOwner(input, { ruleIndex: hit.ruleIndex, subject: hit.subject, session: declared(input.session_id), waitMs: waitS * 1000 });
160
+ answer = await askOwner(input, { ruleIndex, subject: escalated ? "injection guard" : hit.subject, session: declared(input.session_id), waitMs: waitS * 1000 });
122
161
  } catch {
123
162
  answer = { state: "unavailable" };
124
163
  }
125
164
  const waited = Math.max(0, now() - started);
126
- switch (answer?.state) {
165
+ if (escalated) {
166
+ const state = answer?.state;
167
+ if (state === "refused") {
168
+ // Not an owner outcome: the tool goes ahead on its own rules, so the agent's page
169
+ // gets the record those rules give (only an "ask"), never "owner unavailable".
170
+ needsRefresh = true;
171
+ holdRecord("through");
172
+ if (original.effect === "ask") {
173
+ record(input, "ask", original.ruleIndex, 0);
174
+ return verdict("ask", `PassControl: ${guardText} The gateway now sees no taint. The tool rules still ask you to confirm this (rule ${original.ruleIndex + 1}: ${short(original.subject)}). ${rulesLive}`);
175
+ }
176
+ return { systemMessage: `PassControl: ${guardText} The gateway now sees no taint, so this goes ahead.` };
177
+ }
178
+ const outcome = ["approved", "denied", "timeout"].includes(state) ? state : "unavailable";
179
+ holdRecord(outcome);
180
+ record(input, `owner_${outcome}`, null, waited);
181
+ if (outcome === "approved") return { systemMessage: `PassControl: ${guardText} The agent's owner approved it.` };
182
+ const ending = outcome === "denied" ? "The agent's owner said no." : outcome === "timeout" ? `The agent's owner did not answer within ${waitS} s, so this was not run.` : "The owner could not be asked, so this was not run.";
183
+ return verdict("deny", `PassControl: ${guardText} ${ending}`);
184
+ }
185
+ function ruleAnswer() {
186
+ switch (answer?.state) {
127
187
  case "approved":
128
188
  record(input, "owner_approved", hit.ruleIndex, waited);
129
189
  return {};
130
190
  case "denied":
131
191
  record(input, "owner_denied", hit.ruleIndex, waited);
132
- return verdict("deny", `PassControl: the agent's owner said no to this (${rule}).`);
192
+ return verdict("deny", `PassControl: the agent's owner said no to this (${rule}). ${rulesLive}`);
133
193
  case "timeout":
134
194
  record(input, "owner_timeout", hit.ruleIndex, waited);
135
195
  return verdict("deny", `PassControl: the agent's owner did not answer within ${waitS} s, so this was not run (${rule}).`);
@@ -145,7 +205,9 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
145
205
  default:
146
206
  record(input, "owner_unavailable", hit.ruleIndex, waited);
147
207
  return verdict("deny", `PassControl: this needs the agent's owner to say yes (${rule}), and they could not be reached, so it was not run.`);
208
+ }
148
209
  }
210
+ return withWarning(ruleAnswer());
149
211
  }
150
212
 
151
213
  return { decide };
@@ -21,6 +21,8 @@
21
21
  // cannot keep up is dropped rather than buffered for, and nothing on the proxy
22
22
  // path waits on a subscriber.
23
23
 
24
+ import { INJECTION_FAMILIES } from "./injection-scan.mjs";
25
+
24
26
  export const WATCH_PATH = "/_passcontrol/watch";
25
27
  /** Paths under this prefix are the sidecar's own and are never forwarded. */
26
28
  export const LOCAL_PREFIX = "/_passcontrol/";
@@ -270,6 +272,41 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
270
272
  }
271
273
  }
272
274
 
275
+ /** A local scan saw a tell; this says nothing about server recording. */
276
+ function injection(event) {
277
+ try {
278
+ const families = INJECTION_FAMILIES.filter((f) => Array.isArray(event.families) && event.families.includes(f));
279
+ if (!families.length) return;
280
+ const record = {
281
+ type: "injection_finding", seq: ++seq,
282
+ at: Number.isFinite(event.at) ? event.at : now(), source: "tool_result",
283
+ tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool), families,
284
+ };
285
+ remember(record);
286
+ broadcast(record);
287
+ } catch {
288
+ // Like calls, findings are best-effort metadata only.
289
+ }
290
+ }
291
+
292
+ /**
293
+ * One tool the injection guard held (Phase 2): tool name and outcome only, never
294
+ * its input. Not a call, so the board does not count it. Never throws.
295
+ */
296
+ function toolHold(event) {
297
+ try {
298
+ if (!["approved", "denied", "timeout", "unavailable", "through"].includes(event?.outcome)) return;
299
+ const record = {
300
+ type: "tool_hold", seq: ++seq,
301
+ at: Number.isFinite(event.at) ? event.at : now(),
302
+ tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool),
303
+ outcome: event.outcome,
304
+ };
305
+ remember(record);
306
+ broadcast(record);
307
+ } catch {}
308
+ }
309
+
273
310
  /**
274
311
  * The latest usage window, already held to its shape by the caller. Replaces the
275
312
  * last one and tells every board. Never throws.
@@ -335,6 +372,8 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
335
372
  begin,
336
373
  record,
337
374
  report,
375
+ injection,
376
+ toolHold,
338
377
  setWindow,
339
378
  window: () => usageWindow,
340
379
  serve,
package/cli/watch.mjs CHANGED
@@ -16,7 +16,8 @@
16
16
  // fields are held to the feed's own patterns on arrival, and every cell is stripped
17
17
  // of control characters again before it is drawn.
18
18
  import http from "node:http";
19
- import { formatUsd, limitReached, panelRows } from "./budget-format.mjs";
19
+ import { INJECTION_FAMILIES } from "./injection-scan.mjs";
20
+ import { formatUsd, limitReached, panelRows, paused } from "./budget-format.mjs";
20
21
  import { WATCH_PATH } from "./watch-feed.mjs";
21
22
  import { heldUsageWindow, resetTime, usageWindowText } from "./usage-window.mjs";
22
23
 
@@ -141,6 +142,29 @@ export function applyEvent(state, event) {
141
142
  state.feed = { state: "live" };
142
143
  return state;
143
144
  }
145
+ if (event.type === "tool_hold") {
146
+ if (!Number.isInteger(event.seq) || event.seq < 1 || !["approved", "denied", "timeout", "unavailable", "through"].includes(event.outcome)) return state;
147
+ const row = { type: "tool_hold", seq: event.seq, at: count(event.at), tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool), outcome: event.outcome };
148
+ const existing = state.rows.findIndex((r) => r.seq === row.seq);
149
+ if (existing === -1) state.rows.push(row);
150
+ else state.rows[existing] = row;
151
+ if (state.rows.length > MAX_ROWS) state.rows.splice(0, state.rows.length - MAX_ROWS);
152
+ return state;
153
+ }
154
+ if (event.type === "injection_finding") {
155
+ if (!Number.isInteger(event.seq) || event.seq < 1 || event.source !== "tool_result") return state;
156
+ const families = INJECTION_FAMILIES.filter((f) => Array.isArray(event.families) && event.families.includes(f));
157
+ if (!families.length) return state;
158
+ const row = {
159
+ type: "injection_finding", seq: event.seq, at: count(event.at), source: "tool_result",
160
+ tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool), families,
161
+ };
162
+ const existing = state.rows.findIndex((r) => r.seq === row.seq);
163
+ if (existing === -1) state.rows.push(row);
164
+ else state.rows[existing] = row;
165
+ if (state.rows.length > MAX_ROWS) state.rows.splice(0, state.rows.length - MAX_ROWS);
166
+ return state;
167
+ }
144
168
  if (event.type === "call") {
145
169
  if (!Number.isInteger(event.seq) || event.seq < 1) return state;
146
170
  const row = {
@@ -275,6 +299,17 @@ const BAR_STYLE = { boarded: "green", denied: "red", error: "yellow" };
275
299
 
276
300
  /** One board row, `width` wide at most. */
277
301
  function rowLine(row, cols, { run, now, formatTime, color }) {
302
+ if (row.type === "tool_hold") {
303
+ const tool = held(/^[A-Za-z0-9_.-]{1,128}$/, row.tool) ?? "—";
304
+ return paint(color, "yellow", clean(`${fit(row.at !== null ? formatTime(row.at) : "", cols.time)} HELD · injection guard · ${tool} · ${row.outcome}`));
305
+ }
306
+ if (row.type === "injection_finding") {
307
+ const families = INJECTION_FAMILIES.filter((f) => Array.isArray(row.families) && row.families.includes(f));
308
+ const tool = held(/^[A-Za-z0-9_.-]{1,128}$/, row.tool) ?? "—";
309
+ // The local scan saw it; whether the gateway recorded it is the owner's policy, unknown here.
310
+ const text = `${fit(row.at ? formatTime(row.at) : "", cols.time)} INJECTION? · tool_result · ${tool} · ${families.join("+")}`;
311
+ return paint(color, "yellow", clean(text));
312
+ }
278
313
  const cells = [fit(row.at !== null ? formatTime(row.at) : "", cols.time)];
279
314
  if (cols.withSession) cells.push(fit(sessionText(row, run), cols.session));
280
315
  cells.push(agentText(row, cols.agent));
@@ -313,7 +348,12 @@ function budgetLine(budget, width, { color, formatTime }) {
313
348
  const style = fraction >= 1 ? "red" : fraction >= 0.8 ? "yellow" : "green";
314
349
  bar = `[${paint(color, style, "█".repeat(filled))}${"░".repeat(barWidth - filled)}] `;
315
350
  }
316
- const reached = limitReached(budget.self) ? ` · ${paint(color, "red", "LIMIT REACHED")}` : "";
351
+ // A pause is the owner's line doing its job, so not the red of a spent limit.
352
+ const reached = limitReached(budget.self)
353
+ ? ` · ${paint(color, "red", "LIMIT REACHED")}`
354
+ : paused(budget.self)
355
+ ? ` · ${paint(color, "yellow", "PAUSED")}`
356
+ : "";
317
357
  const line = `${clean(label).padEnd(9)} ${bar}${clean(value)}${reached}`;
318
358
  // When it was asked is the first thing to go when the line is too long.
319
359
  const checked = budget.checkedAt ? ` · checked ${formatTime(budget.checkedAt)}` : "";
@@ -391,9 +431,10 @@ export function renderBoard(state, { width, height, port, now = Date.now(), form
391
431
  const cols = columns(w);
392
432
  const rows = state.rows;
393
433
  const tally = { boarded: 0, denied: 0, error: 0, seen: 0 };
394
- for (const r of rows) tally[r.outcome] += 1;
395
- const counts = rows.length
396
- ? `${rows.length} call${rows.length === 1 ? "" : "s"}: ${tally.seen ? `${tally.seen} seen, ` : ""}${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
434
+ const calls = rows.filter((r) => r.type !== "injection_finding" && r.type !== "tool_hold");
435
+ for (const r of calls) tally[r.outcome] += 1;
436
+ const counts = calls.length
437
+ ? `${calls.length} call${calls.length === 1 ? "" : "s"}: ${tally.seen ? `${tally.seen} seen, ` : ""}${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
397
438
  : "no calls yet";
398
439
  const lines = [
399
440
  `${paint(color, "bold", "PassControl watch")} · sidecar :${port} · ${feedText(state.feed, port)} · ${counts}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "1.5.1",
3
+ "version": "1.7.0",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",