@agent-corpus/policy-manager 0.7.0 → 0.9.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/dist/session.js CHANGED
@@ -1,6 +1,7 @@
1
- import { isClassifyRecord, looksLikeClassifyRecord } from "./adapters.js";
1
+ import { isClassifyRecord, looksLikeApproveGrant, looksLikeClassifyRecord } from "./adapters.js";
2
2
  import { audit, requestSummary } from "./audit.js";
3
3
  import { creationTargets, pathKey, settle, withCreated, } from "./created.js";
4
+ import { grantScope, scopeLabel } from "./grants.js";
4
5
  import { evaluate, hash, requestHash as requestHashOf, result, SHELL_TOOLS } from "./policy.js";
5
6
  import { strictProfile } from "./profile.js";
6
7
  import { redactText } from "./redact.js";
@@ -11,6 +12,26 @@ const CLASSIFICATION_TTL_MS = 5 * 60_000;
11
12
  export const MAX_AI_APPROVALS = 50;
12
13
  /** How long after its approval an execution report may still record the files a tool created. */
13
14
  const CREATION_REPORT_MS = 15 * 60_000;
15
+ export const APPROVE_GUARD = "Only the user may approve a request, by running approve in their own terminal";
16
+ /** How long after a human decision the user may still approve that exact request once. */
17
+ export const GRANT_WINDOW_MS = 15 * 60_000;
18
+ /** A grant the service refuses; its message is safe to show the user. */
19
+ export class GrantError extends Error {
20
+ }
21
+ function grantDetail(request) {
22
+ const command = request.input.command ?? request.input.cmd;
23
+ if (typeof command === "string")
24
+ return redactText(command, 300);
25
+ const file = request.input.file_path ?? request.input.path;
26
+ if (typeof file === "string")
27
+ return redactText(file, 300);
28
+ if (typeof request.input.patch === "string" || typeof request.input.input === "string")
29
+ return redactText(String(request.input.patch ?? request.input.input)
30
+ .split("\n")
31
+ .filter((line) => /^\*\*\* (?:Add|Update|Delete) File:/.test(line))
32
+ .join("; "), 300);
33
+ return request.tool;
34
+ }
14
35
  export class PolicySession {
15
36
  directory;
16
37
  harness;
@@ -25,6 +46,12 @@ export class PolicySession {
25
46
  /** Files this session created, and the paths each approved request may create. */
26
47
  created = new Map();
27
48
  creating = new Map();
49
+ /** Requests this session sent to a person, which the user may approve once. */
50
+ humanDecisions = new Map();
51
+ /** One-time user approvals, each usable once per hook phase. */
52
+ grants = new Map();
53
+ /** Session grants: hashes of a human rule and the scope the user approved it for. */
54
+ sessionGrants = new Set();
28
55
  constructor(directory, harness, sessionId, profile = strictProfile,
29
56
  /** This package's `cli.js`: the path in the record command the hook gives the model. */
30
57
  cliPath) {
@@ -60,6 +87,117 @@ export class PolicySession {
60
87
  return result(request, "temp-write", "Records a classification for this session", true);
61
88
  return result(request, "unknown", "A classification record for another session or CLI, or with anything added, requires human review");
62
89
  }
90
+ /**
91
+ * Only the user approves a request once, from their own terminal. A shell command that runs a
92
+ * policy-manager `approve`, in any form or nesting, is never approved for the agent.
93
+ */
94
+ approveGrant(request) {
95
+ const command = request.input.command ?? request.input.cmd;
96
+ if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
97
+ return undefined;
98
+ if (!looksLikeApproveGrant(command))
99
+ return undefined;
100
+ return result(request, "sensitive", APPROVE_GUARD);
101
+ }
102
+ /**
103
+ * A user approval that covers this human decision: a one-time grant for this exact request
104
+ * (used once per hook phase), or a session grant for its rule and scope. Each use is audited.
105
+ */
106
+ granted(request, decision, phase) {
107
+ const once = this.grants.get(decision.requestHash);
108
+ const slot = phase ?? "review";
109
+ if (once && !once.phases.has(slot)) {
110
+ once.phases.add(slot);
111
+ // PreToolUse runs before PermissionRequest; once both have allowed the tool, it is spent.
112
+ if (once.phases.has("PreToolUse") && once.phases.has("PermissionRequest"))
113
+ this.grants.delete(decision.requestHash);
114
+ audit(this.directory, {
115
+ event: "human-grant-use",
116
+ requestHash: decision.requestHash,
117
+ scope: "once",
118
+ phase: slot,
119
+ });
120
+ return {
121
+ ...result(request, decision.category, "Approved once by the user", true),
122
+ };
123
+ }
124
+ const scope = grantScope(request, decision, this.profile);
125
+ if (scope === undefined)
126
+ return undefined;
127
+ const key = hash([decision.reason, scope]);
128
+ if (!this.sessionGrants.has(key))
129
+ return undefined;
130
+ audit(this.directory, {
131
+ event: "human-grant-use",
132
+ requestHash: decision.requestHash,
133
+ scope: "session",
134
+ scopeHash: key,
135
+ phase: slot,
136
+ });
137
+ return {
138
+ ...result(request, decision.category, "Approved for this session by the user", true),
139
+ };
140
+ }
141
+ /** The newest request this session sent to a person that the user may still approve. */
142
+ latestHumanDecision() {
143
+ let latest;
144
+ for (const [requestHash, entry] of this.humanDecisions)
145
+ if (Date.now() - entry.at <= GRANT_WINDOW_MS && (!latest || entry.at >= latest.at))
146
+ latest = { requestHash, at: entry.at };
147
+ return latest && { ...latest, harness: this.harness, sessionId: this.sessionId };
148
+ }
149
+ /**
150
+ * Looks up, and with `confirm` grants, a user approval of a request this session sent to a
151
+ * person within the last GRANT_WINDOW_MS. Without `session` the next review of that exact
152
+ * request is approved once per hook phase; with it, every later request in this session that
153
+ * hits the same rule for the same scope is approved. A request with no session scope (credential
154
+ * reads, possible unrecoverable loss) is approved once only, and the result says so.
155
+ */
156
+ grant(requestHash, confirm, session = false) {
157
+ if (!/^[a-f0-9]{64}$/.test(requestHash))
158
+ throw new GrantError("Not a request hash");
159
+ const pending = this.humanDecisions.get(requestHash);
160
+ if (!pending || Date.now() - pending.at > GRANT_WINDOW_MS) {
161
+ this.humanDecisions.delete(requestHash);
162
+ throw new GrantError("No request in this session needed a person with that hash in the last 15 minutes. Retry the request so it is blocked again, then approve the new hash.");
163
+ }
164
+ const { at: _at, sessionScope, ...rest } = pending;
165
+ const scope = session && sessionScope !== undefined ? "session" : "once";
166
+ const preview = {
167
+ ...rest,
168
+ ...(scope === "session" && sessionScope !== undefined
169
+ ? { sessionScope: scopeLabel(sessionScope, this.profile) }
170
+ : {}),
171
+ };
172
+ if (!confirm)
173
+ return { ...preview, granted: false, scope };
174
+ this.humanDecisions.delete(requestHash);
175
+ if (scope === "session" && sessionScope !== undefined) {
176
+ if (this.sessionGrants.size >= 64)
177
+ this.sessionGrants.clear();
178
+ this.sessionGrants.add(hash([preview.reason, sessionScope]));
179
+ }
180
+ if (this.grants.size >= 64)
181
+ this.grants.delete(this.grants.keys().next().value ?? "");
182
+ this.grants.set(requestHash, { phases: new Set() });
183
+ audit(this.directory, {
184
+ event: "human-grant",
185
+ requestHash,
186
+ category: preview.category,
187
+ scope,
188
+ ...(scope === "session" ? { scopeHash: hash([preview.reason, sessionScope]) } : {}),
189
+ summary: scope === "session"
190
+ ? "User approved the rule for this session"
191
+ : "User approved the request once",
192
+ });
193
+ audit(this.directory, {
194
+ event: "human-response",
195
+ requestHash,
196
+ response: "approved",
197
+ summary: "User approved the request from the terminal",
198
+ });
199
+ return { ...preview, granted: true, scope };
200
+ }
63
201
  state(requestHash) {
64
202
  const state = this.states.get(requestHash);
65
203
  if (state && state.expires <= Date.now()) {
@@ -124,7 +262,8 @@ export class PolicySession {
124
262
  ...(ai.recoverable === undefined ? {} : { recoverable: ai.recoverable }),
125
263
  ...(ai.rationale ? { rationale: redactText(ai.rationale, 200) } : {}),
126
264
  });
127
- let decision = this.classifyRecord(request) ??
265
+ let decision = this.approveGrant(request) ??
266
+ this.classifyRecord(request) ??
128
267
  withCreated(this.created, () => evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile));
129
268
  if (decision.tier === "ambiguous") {
130
269
  if (ai && !decision.classification)
@@ -160,7 +299,11 @@ export class PolicySession {
160
299
  reason: decision.reason,
161
300
  redactedCommand: redactText(String(request.input.command ?? request.input.cmd ?? request.tool), 300),
162
301
  });
163
- decision = { ...decision, decision: "deny", classification: "requested" };
302
+ decision = {
303
+ ...decision,
304
+ decision: "deny",
305
+ classification: "requested",
306
+ };
164
307
  }
165
308
  else {
166
309
  const fallbackReason = known.limited
@@ -176,12 +319,46 @@ export class PolicySession {
176
319
  fallbackReason,
177
320
  });
178
321
  }
179
- decision = { ...decision, classification: "fallback", fallbackReason };
322
+ decision = {
323
+ ...decision,
324
+ classification: "fallback",
325
+ fallbackReason,
326
+ };
180
327
  }
181
328
  }
182
329
  }
183
- if (decision.decision === "human")
330
+ if (decision.decision === "human") {
331
+ const allowed = this.granted(request, decision, phase);
332
+ if (allowed)
333
+ decision = allowed;
334
+ }
335
+ if (decision.decision === "human" && decision.reason === APPROVE_GUARD) {
336
+ this.cache.delete(key);
337
+ decision = { ...decision, userOnly: true, sessionGrantable: false };
338
+ }
339
+ else if (decision.decision === "human") {
184
340
  this.cache.delete(key);
341
+ const sessionScope = grantScope(request, decision, this.profile);
342
+ decision = {
343
+ ...decision,
344
+ sessionGrantable: sessionScope !== undefined,
345
+ ...(sessionScope === undefined
346
+ ? {}
347
+ : { sessionScopeLabel: scopeLabel(sessionScope, this.profile) }),
348
+ };
349
+ if (this.humanDecisions.size >= 256)
350
+ this.humanDecisions.delete(this.humanDecisions.keys().next().value ?? "");
351
+ this.humanDecisions.delete(requestHash);
352
+ this.humanDecisions.set(requestHash, {
353
+ requestHash,
354
+ tool: request.tool,
355
+ category: decision.category,
356
+ reason: decision.reason,
357
+ detail: grantDetail(request),
358
+ at: Date.now(),
359
+ ...(sessionScope === undefined ? {} : { sessionScope }),
360
+ });
361
+ }
185
362
  // Evaluation always precedes lookup. Filesystem evidence is never cached.
186
363
  if (decision.decision === "approve" && decision.cache === "session") {
187
364
  decision.cached = entry !== undefined && entry.expires > Date.now() && ai === undefined;
@@ -211,10 +388,14 @@ export class PolicySession {
211
388
  if (targets.length) {
212
389
  if (this.creating.size >= 256)
213
390
  this.creating.delete(this.creating.keys().next().value ?? "");
214
- this.creating.set(decision.requestHash, { targets, approvedAt: Date.now() });
391
+ this.creating.set(decision.requestHash, {
392
+ targets,
393
+ approvedAt: Date.now(),
394
+ });
215
395
  }
216
396
  }
217
- const { ai: classification, ...safe } = decision;
397
+ // The scope label names paths, which audit records never contain.
398
+ const { ai: classification, sessionScopeLabel: _label, ...safe } = decision;
218
399
  audit(this.directory, {
219
400
  event: "decision",
220
401
  ...safe,
package/dist/setup.d.ts CHANGED
@@ -1,8 +1,11 @@
1
+ import { type ShimStatus } from "./shim.js";
1
2
  import type { Request } from "./types.js";
2
3
  type JsonObject = Record<string, unknown>;
3
4
  export interface SetupOptions {
4
5
  configDirectory?: string;
5
6
  dryRun?: boolean;
7
+ /** Where to put the `pm` launcher. Without it, a `configDirectory` run leaves the launcher alone. */
8
+ shimDirectory?: string;
6
9
  }
7
10
  export interface SetupResult {
8
11
  harness: Request["harness"];
@@ -11,6 +14,10 @@ export interface SetupResult {
11
14
  changed: boolean;
12
15
  backupPath?: string;
13
16
  managedHooks: JsonObject;
17
+ /** The `pm` launcher: its path, state after setup, whether setup changed it, whether it is on PATH. */
18
+ shim?: ShimStatus & {
19
+ changed: boolean;
20
+ };
14
21
  nextSteps: string[];
15
22
  }
16
23
  export declare class SetupError extends Error {
package/dist/setup.js CHANGED
@@ -3,6 +3,7 @@ import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdi
3
3
  import { homedir } from "node:os";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  import { hookConfig, managedHookFlag } from "./config.js";
6
+ import { cliVersion, installShim, shimDirectory } from "./shim.js";
6
7
  export class SetupError extends Error {
7
8
  }
8
9
  function object(value) {
@@ -129,11 +130,30 @@ export function setupHook(harness, cliPath, options = {}) {
129
130
  ? [
130
131
  "Open /hooks and explicitly review and trust the installed hooks. Setup does not grant hook trust, and Codex skips hooks it has not trusted.",
131
132
  "Codex trusts the command text, not the code behind it: an upgrade at the same CLI path keeps trust, so review a new version before upgrading in place. A changed command (a new install path or Node binary) is skipped until you trust it again.",
132
- "Codex does not support ask in PreToolUse, so a decision that needs a human is returned as a deny and the command does not run; approving it in chat does not unblock it.",
133
+ "Codex does not support ask in PreToolUse, so a decision that needs a human is returned as a deny and the command does not run, and approving it in chat does not unblock it: run `pm approve --last` (or the command in the deny reason) in your own terminal, then tell the agent to retry.",
133
134
  ]
134
135
  : []),
135
136
  "Native sandbox controls and existing permission rules remain in effect.",
136
137
  ];
138
+ const shimDir = options.shimDirectory ?? (options.configDirectory === undefined ? shimDirectory() : undefined);
139
+ const shim = (dry) => {
140
+ if (shimDir === undefined)
141
+ return undefined;
142
+ let status;
143
+ // The launcher is a convenience: its failure never fails the hook install.
144
+ try {
145
+ status = installShim(resolve(shimDir), installedCli, cliVersion(installedCli), dry);
146
+ }
147
+ catch (error) {
148
+ nextSteps.push(`The \`pm\` launcher was not installed: ${error instanceof Error ? error.message : String(error)}`);
149
+ return undefined;
150
+ }
151
+ if (!status.onPath && (status.state === "current" || status.changed))
152
+ nextSteps.push(`Add ${dirname(status.path)} to PATH to approve blocked requests with \`pm approve --last\`.`);
153
+ if (status.state === "foreign")
154
+ nextSteps.push(`${status.path} is not managed by this package; it was left unchanged.`);
155
+ return status;
156
+ };
137
157
  const prepare = () => {
138
158
  const original = readConfig(target);
139
159
  let config = {};
@@ -149,13 +169,15 @@ export function setupHook(harness, cliPath, options = {}) {
149
169
  const changed = JSON.stringify(config) !== JSON.stringify(result);
150
170
  return { original, text: `${JSON.stringify(result, null, 2)}\n`, changed };
151
171
  };
152
- if (dryRun)
172
+ if (dryRun) {
173
+ const launcher = shim(true);
153
174
  return {
154
175
  harness,
155
176
  configPath: target,
156
177
  dryRun,
157
- changed: prepare().changed,
178
+ changed: prepare().changed || launcher?.changed === true,
158
179
  managedHooks: desired.hooks,
180
+ ...(launcher ? { shim: launcher } : {}),
159
181
  nextSteps: [
160
182
  ...(inCheckout(installedCli)
161
183
  ? ["Install the reviewed package outside Git checkouts before applying this preview."]
@@ -163,6 +185,7 @@ export function setupHook(harness, cliPath, options = {}) {
163
185
  ...nextSteps,
164
186
  ],
165
187
  };
188
+ }
166
189
  const parent = dirname(target);
167
190
  mkdirSync(parent, { recursive: true, mode: 0o700 });
168
191
  const parentStat = lstatSync(parent);
@@ -183,15 +206,18 @@ export function setupHook(harness, cliPath, options = {}) {
183
206
  const temp = join(parent, `.${basename(target)}.${randomUUID()}.tmp`);
184
207
  try {
185
208
  const prepared = prepare();
186
- if (!prepared.changed)
209
+ if (!prepared.changed) {
210
+ const launcher = shim(false);
187
211
  return {
188
212
  harness,
189
213
  configPath: target,
190
214
  dryRun,
191
- changed: false,
215
+ changed: launcher?.changed === true,
192
216
  managedHooks: desired.hooks,
217
+ ...(launcher ? { shim: launcher } : {}),
193
218
  nextSteps,
194
219
  };
220
+ }
195
221
  writePrivate(temp, prepared.text);
196
222
  if (readConfig(target) !== prepared.original)
197
223
  throw new SetupError("The settings changed during setup. Retry without overwriting the concurrent edit.");
@@ -201,6 +227,7 @@ export function setupHook(harness, cliPath, options = {}) {
201
227
  writePrivate(backupPath, prepared.original);
202
228
  }
203
229
  renameSync(temp, target);
230
+ const launcher = shim(false);
204
231
  return {
205
232
  harness,
206
233
  configPath: target,
@@ -208,6 +235,7 @@ export function setupHook(harness, cliPath, options = {}) {
208
235
  changed: true,
209
236
  ...(backupPath ? { backupPath } : {}),
210
237
  managedHooks: desired.hooks,
238
+ ...(launcher ? { shim: launcher } : {}),
211
239
  nextSteps,
212
240
  };
213
241
  }
package/dist/shim.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /** Marks a `pm` launcher this package wrote, with the version that wrote it. */
2
+ export declare const SHIM_MARKER = "agent-corpus-policy-manager-shim";
3
+ export interface ShimStatus {
4
+ path: string;
5
+ /** `current`: managed and runs this CLI; `older`/`newer`: managed by another version;
6
+ * `foreign`: a `pm` this package did not write; `absent`. */
7
+ state: "current" | "older" | "newer" | "foreign" | "absent";
8
+ onPath: boolean;
9
+ }
10
+ /** The directory the launcher lives in: `~/.local/bin`, or `%LOCALAPPDATA%\agent-corpus\bin`. */
11
+ export declare function shimDirectory(): string;
12
+ export declare function shimPath(directory: string): string;
13
+ /** The package version of an installed CLI (`<package>/dist/cli.js`). */
14
+ export declare function cliVersion(cliPath: string): string;
15
+ export declare function shimText(cliPath: string, version: string): string;
16
+ export declare function inspectShim(directory: string, cliPath: string, version: string): ShimStatus;
17
+ /**
18
+ * Installs or updates the managed `pm` launcher. Never replaces a `pm` this package did not
19
+ * write, or one written by a newer version. Returns whether it changed anything.
20
+ */
21
+ export declare function installShim(directory: string, cliPath: string, version: string, dryRun: boolean): ShimStatus & {
22
+ changed: boolean;
23
+ };
24
+ //# sourceMappingURL=shim.d.ts.map
package/dist/shim.js ADDED
@@ -0,0 +1,114 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, dirname, join, resolve } from "node:path";
5
+ /** Marks a `pm` launcher this package wrote, with the version that wrote it. */
6
+ export const SHIM_MARKER = "agent-corpus-policy-manager-shim";
7
+ /** The directory the launcher lives in: `~/.local/bin`, or `%LOCALAPPDATA%\agent-corpus\bin`. */
8
+ export function shimDirectory() {
9
+ return process.platform === "win32"
10
+ ? join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "agent-corpus", "bin")
11
+ : join(homedir(), ".local", "bin");
12
+ }
13
+ export function shimPath(directory) {
14
+ return join(directory, process.platform === "win32" ? "pm.cmd" : "pm");
15
+ }
16
+ /** The package version of an installed CLI (`<package>/dist/cli.js`). */
17
+ export function cliVersion(cliPath) {
18
+ const pkg = JSON.parse(readFileSync(join(dirname(cliPath), "..", "package.json"), "utf8"));
19
+ if (typeof pkg.version !== "string" || !/^\d+\.\d+\.\d+$/.test(pkg.version))
20
+ throw new Error("The installed CLI has no readable version");
21
+ return pkg.version;
22
+ }
23
+ export function shimText(cliPath, version) {
24
+ if (process.platform === "win32")
25
+ return [
26
+ "@echo off",
27
+ `rem ${SHIM_MARKER} version=${version}`,
28
+ `"${process.execPath}" "${cliPath}" %*`,
29
+ "",
30
+ ].join("\r\n");
31
+ return [
32
+ "#!/usr/bin/env node",
33
+ `// ${SHIM_MARKER} version=${version}`,
34
+ // Works whether Node loads this extensionless file as CommonJS or as ESM (Node 20.16+).
35
+ 'const { spawnSync } = process.getBuiltinModule ? process.getBuiltinModule("node:child_process") : require("node:child_process");',
36
+ `const result = spawnSync(process.execPath, [${JSON.stringify(cliPath)}, ...process.argv.slice(2)], { stdio: "inherit" });`,
37
+ "process.exit(result.status ?? 1);",
38
+ "",
39
+ ].join("\n");
40
+ }
41
+ const compare = (a, b) => {
42
+ const x = a.split(".").map(Number);
43
+ const y = b.split(".").map(Number);
44
+ for (let i = 0; i < 3; i++)
45
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
46
+ return (x[i] ?? 0) - (y[i] ?? 0);
47
+ return 0;
48
+ };
49
+ function onPath(directory) {
50
+ const target = resolve(directory);
51
+ return (process.env.PATH ?? process.env.Path ?? "")
52
+ .split(delimiter)
53
+ .some((entry) => entry && resolve(entry) === target);
54
+ }
55
+ export function inspectShim(directory, cliPath, version) {
56
+ const path = shimPath(directory);
57
+ const status = (state) => ({
58
+ path,
59
+ state,
60
+ onPath: onPath(directory),
61
+ });
62
+ if (!existsSync(path))
63
+ return status("absent");
64
+ let text;
65
+ try {
66
+ if (!lstatSync(path).isFile())
67
+ return status("foreign");
68
+ text = readFileSync(path, "utf8");
69
+ }
70
+ catch {
71
+ return status("foreign");
72
+ }
73
+ const found = text.match(new RegExp(`${SHIM_MARKER} version=(\\d+\\.\\d+\\.\\d+)`))?.[1];
74
+ if (!found)
75
+ return status("foreign");
76
+ const order = compare(found, version);
77
+ if (order > 0)
78
+ return status("newer");
79
+ if (order < 0)
80
+ return status("older");
81
+ return status(text === shimText(cliPath, version) ? "current" : "older");
82
+ }
83
+ /**
84
+ * Installs or updates the managed `pm` launcher. Never replaces a `pm` this package did not
85
+ * write, or one written by a newer version. Returns whether it changed anything.
86
+ */
87
+ export function installShim(directory, cliPath, version, dryRun) {
88
+ const before = inspectShim(directory, cliPath, version);
89
+ if (before.state !== "absent" && before.state !== "older")
90
+ return { ...before, changed: false };
91
+ if (dryRun)
92
+ return { ...before, changed: true };
93
+ mkdirSync(directory, { recursive: true, mode: 0o755 });
94
+ const temp = join(directory, `.pm.${randomUUID()}.tmp`);
95
+ const fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o755);
96
+ try {
97
+ writeFileSync(fd, shimText(cliPath, version));
98
+ fsyncSync(fd);
99
+ }
100
+ finally {
101
+ closeSync(fd);
102
+ }
103
+ try {
104
+ if (process.platform !== "win32")
105
+ chmodSync(temp, 0o755);
106
+ renameSync(temp, before.path);
107
+ }
108
+ finally {
109
+ if (existsSync(temp))
110
+ unlinkSync(temp);
111
+ }
112
+ return { ...inspectShim(directory, cliPath, version), changed: true };
113
+ }
114
+ //# sourceMappingURL=shim.js.map
@@ -0,0 +1,23 @@
1
+ import type { Request } from "./types.js";
2
+ /**
3
+ * Tools the engine judges itself: shell, file, patch and command-running tools. They are never
4
+ * approved by default and always get the engine's checks. MCP tools (`mcp__*`) follow
5
+ * `mcpReadOnly` instead.
6
+ */
7
+ export declare const ENGINE_TOOLS: Set<string>;
8
+ /**
9
+ * Harness tools that are never approved by default and keep the classification path. Empty for
10
+ * now; a profile adds names through `toolsDeny`.
11
+ */
12
+ export declare const BUILTIN_TOOLS_DENY: Record<Request["harness"], ReadonlySet<string>>;
13
+ /**
14
+ * A name that suggests running code, feeding a running command, or touching files. Such a tool is
15
+ * never approved by default, even when ENGINE_TOOLS misses it, so a new or renamed one fails
16
+ * closed. A false positive (`BashOutput`, `SendUserFile`) only costs a classification.
17
+ */
18
+ export declare const COMMAND_TOOL: RegExp;
19
+ /** A harness tool name a profile may list. */
20
+ export declare const TOOL_NAME: RegExp;
21
+ /** Whether a tool is approved by default: not an engine or MCP tool, and not denied. */
22
+ export declare function defaultAllowed(harness: Request["harness"], tool: string, deny: readonly string[]): boolean;
23
+ //# sourceMappingURL=tools.d.ts.map
package/dist/tools.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Tools the engine judges itself: shell, file, patch and command-running tools. They are never
3
+ * approved by default and always get the engine's checks. MCP tools (`mcp__*`) follow
4
+ * `mcpReadOnly` instead.
5
+ */
6
+ export const ENGINE_TOOLS = new Set([
7
+ "Bash",
8
+ "bash",
9
+ "powershell",
10
+ "exec_command",
11
+ "shell",
12
+ "apply_patch",
13
+ "Read",
14
+ "view",
15
+ "read_file",
16
+ "Edit",
17
+ "Write",
18
+ "MultiEdit",
19
+ "NotebookEdit",
20
+ "edit",
21
+ "create",
22
+ "write_file",
23
+ "str_replace_editor",
24
+ // Read file contents or names, so they can reach credential paths.
25
+ "Grep",
26
+ "Glob",
27
+ "LS",
28
+ "NotebookRead",
29
+ "view_image",
30
+ // Runs a shell command in the background.
31
+ "Monitor",
32
+ // Run a command or feed a running one.
33
+ "shell_command",
34
+ "local_shell",
35
+ "unified_exec",
36
+ "write_stdin",
37
+ "write_bash",
38
+ "write_powershell",
39
+ ].map((name) => name.toLowerCase()));
40
+ /**
41
+ * Harness tools that are never approved by default and keep the classification path. Empty for
42
+ * now; a profile adds names through `toolsDeny`.
43
+ */
44
+ export const BUILTIN_TOOLS_DENY = {
45
+ claude: new Set(),
46
+ codex: new Set(),
47
+ copilot: new Set(),
48
+ };
49
+ /**
50
+ * A name that suggests running code, feeding a running command, or touching files. Such a tool is
51
+ * never approved by default, even when ENGINE_TOOLS misses it, so a new or renamed one fails
52
+ * closed. A false positive (`BashOutput`, `SendUserFile`) only costs a classification.
53
+ */
54
+ export const COMMAND_TOOL = /bash|shell|powershell|pwsh|exec|stdin|terminal|command|cmd|spawn|repl|eval|python|node|interpreter|script|computer|run|file|delete|remove|move|rename|patch|edit/i;
55
+ /** A harness tool name a profile may list. */
56
+ export const TOOL_NAME = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;
57
+ /** Whether a tool is approved by default: not an engine or MCP tool, and not denied. */
58
+ export function defaultAllowed(harness, tool, deny) {
59
+ return (TOOL_NAME.test(tool) &&
60
+ !ENGINE_TOOLS.has(tool.toLowerCase()) &&
61
+ !COMMAND_TOOL.test(tool) &&
62
+ !tool.toLowerCase().startsWith("mcp__") &&
63
+ !BUILTIN_TOOLS_DENY[harness]?.has(tool) &&
64
+ !deny.includes(tool));
65
+ }
66
+ //# sourceMappingURL=tools.js.map
package/dist/types.d.ts CHANGED
@@ -38,6 +38,14 @@ export interface Decision {
38
38
  /** Why a human was asked after classification could not decide. */
39
39
  fallbackReason?: "unavailable" | "invalid-result" | "limit";
40
40
  ai?: Classification;
41
+ /** A human decision the user may approve for the rest of the session (`approve --session`). */
42
+ sessionGrantable?: boolean;
43
+ /** What `approve --session` would cover, in words the user can check. */
44
+ sessionScopeLabel?: string;
45
+ /** A harness tool approved by default (not a shell, file, patch or MCP tool), by name. */
46
+ defaultTool?: string;
47
+ /** The agent tried to approve a request itself: no approval instruction is offered for it. */
48
+ userOnly?: boolean;
41
49
  }
42
50
  export interface OutcomeReport {
43
51
  requestHash: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",