@agent-corpus/policy-manager 0.8.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/profile.d.ts CHANGED
@@ -16,6 +16,15 @@ export interface Profile {
16
16
  * last segment ends in `*` (`mcp__github__get_*`). Unlisted MCP tools are left to the harness.
17
17
  */
18
18
  mcpReadOnly: string[];
19
+ /**
20
+ * Harness tools, per harness, that are not approved by default and keep the classification
21
+ * path. Every other harness tool that is not a shell, file, patch or MCP tool is approved.
22
+ */
23
+ toolsDeny: {
24
+ claude: string[];
25
+ codex: string[];
26
+ copilot: string[];
27
+ };
19
28
  /** SHA-256 of the file the profile came from, for the audit log. */
20
29
  digest?: string;
21
30
  }
@@ -23,6 +32,7 @@ export declare const strictProfile: Profile;
23
32
  export declare const MAX_MCP_READ_ONLY = 200;
24
33
  /** Whether `tool` is listed in the profile's `mcpReadOnly`. */
25
34
  export declare function mcpReadOnly(profile: Profile, tool: string): boolean;
35
+ export declare const MAX_TOOLS_DENY = 100;
26
36
  export declare function defaultProfilePath(): string;
27
37
  export declare class ProfileError extends Error {
28
38
  }
package/dist/profile.js CHANGED
@@ -3,12 +3,14 @@ import { lstatSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, isAbsolute, join } from "node:path";
5
5
  import { canonical, git } from "./evidence.js";
6
+ import { TOOL_NAME } from "./tools.js";
6
7
  export const strictProfile = {
7
8
  mode: "strict",
8
9
  cloudWrites: "human",
9
10
  humanPatterns: [],
10
11
  scratchRoots: [],
11
12
  mcpReadOnly: [],
13
+ toolsDeny: { claude: [], codex: [], copilot: [] },
12
14
  };
13
15
  export const MAX_MCP_READ_ONLY = 200;
14
16
  /**
@@ -28,6 +30,24 @@ export function mcpReadOnly(profile, tool) {
28
30
  return tool.startsWith(entry.slice(0, -1)) && !tool.slice(server.length).includes("__");
29
31
  });
30
32
  }
33
+ export const MAX_TOOLS_DENY = 100;
34
+ function parseToolsDeny(raw) {
35
+ const result = { claude: [], codex: [], copilot: [] };
36
+ if (raw === undefined)
37
+ return result;
38
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
39
+ throw new ProfileError("toolsDeny must be an object of per-harness tool name lists");
40
+ for (const [harness, names] of Object.entries(raw)) {
41
+ if (!(harness in result))
42
+ throw new ProfileError(`toolsDeny has an unknown harness: ${harness}`);
43
+ if (!Array.isArray(names) ||
44
+ names.length > MAX_TOOLS_DENY ||
45
+ names.some((name) => typeof name !== "string" || !TOOL_NAME.test(name)))
46
+ throw new ProfileError(`toolsDeny.${harness} must list at most ${MAX_TOOLS_DENY} tool names`);
47
+ result[harness] = [...new Set(names)];
48
+ }
49
+ return result;
50
+ }
31
51
  export function defaultProfilePath() {
32
52
  const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
33
53
  return join(base, "agent-corpus", "policy-manager", "policy.json");
@@ -75,6 +95,7 @@ export function parseProfile(text) {
75
95
  "humanPatterns",
76
96
  "scratchRoots",
77
97
  "mcpReadOnly",
98
+ "toolsDeny",
78
99
  "description",
79
100
  ]);
80
101
  for (const key of Object.keys(value))
@@ -98,6 +119,7 @@ export function parseProfile(text) {
98
119
  mcp.length > MAX_MCP_READ_ONLY ||
99
120
  mcp.some((entry) => typeof entry !== "string" || entry.length > 128 || !MCP_ENTRY.test(entry)))
100
121
  throw new ProfileError(`mcpReadOnly must list at most ${MAX_MCP_READ_ONLY} names like mcp__server__tool, optionally ending in *`);
122
+ const toolsDeny = parseToolsDeny(value.toolsDeny);
101
123
  let humanPatterns;
102
124
  try {
103
125
  humanPatterns = patterns.map((p) => new RegExp(p));
@@ -120,6 +142,7 @@ export function parseProfile(text) {
120
142
  humanPatterns,
121
143
  scratchRoots: value.mode === "permissive" ? [...scratchRoots] : [],
122
144
  mcpReadOnly: [...new Set(mcp)],
145
+ toolsDeny,
123
146
  digest: createHash("sha256").update(text).digest("hex"),
124
147
  };
125
148
  }
package/dist/review.d.ts CHANGED
@@ -48,6 +48,15 @@ export interface ClassificationReview {
48
48
  reclassified: ClassifiedRequest[];
49
49
  /** Requests the AI denied and later approved. */
50
50
  deniedThenApproved: ClassifiedRequest[];
51
+ /**
52
+ * Harness tools approved by default (not shell, file, patch or MCP tools), newest first by when
53
+ * each was first seen, so a tool a harness newly added is noticed and can go into toolsDeny.
54
+ */
55
+ defaultTools: Array<{
56
+ tool: string;
57
+ firstSeen: string;
58
+ count: number;
59
+ }>;
51
60
  }
52
61
  export declare function sessionDirectories(extra?: string[]): string[];
53
62
  export declare function reviewClassifications(directories: string[], since?: string): Promise<ClassificationReview>;
package/dist/review.js CHANGED
@@ -30,6 +30,7 @@ const text = (value) => typeof value === "string" ? value : undefined;
30
30
  const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
31
31
  export async function reviewClassifications(directories, since) {
32
32
  const requests = [];
33
+ const defaultTools = new Map();
33
34
  let sessions = 0;
34
35
  for (const directory of directories) {
35
36
  const records = [];
@@ -72,6 +73,17 @@ export async function reviewClassifications(directories, since) {
72
73
  };
73
74
  for (const record of records) {
74
75
  const a = record.attributes;
76
+ const tool = text(a.defaultTool);
77
+ if (record.eventName === "decision" && tool) {
78
+ const seen = defaultTools.get(tool);
79
+ if (!seen)
80
+ defaultTools.set(tool, { tool, firstSeen: record.timestamp, count: 1 });
81
+ else {
82
+ seen.count++;
83
+ if (record.timestamp < seen.firstSeen)
84
+ seen.firstSeen = record.timestamp;
85
+ }
86
+ }
75
87
  // Only requests that entered the classification flow are reviewed.
76
88
  if (record.eventName !== "classification-requested" && !byRequest.has(record.requestId ?? ""))
77
89
  continue;
@@ -156,6 +168,7 @@ export async function reviewClassifications(directories, since) {
156
168
  fallbackReasons[key] = (fallbackReasons[key] ?? 0) + 1;
157
169
  }
158
170
  return {
171
+ defaultTools: [...defaultTools.values()].sort((x, y) => y.firstSeen.localeCompare(x.firstSeen)),
159
172
  sessions,
160
173
  requested: requests.length,
161
174
  approved: approved.length,
@@ -220,6 +233,9 @@ export function formatReview(review) {
220
233
  `Commands a person later denied (${review.humanDenied.length}):`,
221
234
  ...review.humanDenied.map(row),
222
235
  "",
236
+ `Harness tools approved by default, newest first (${review.defaultTools.length}):`,
237
+ ...review.defaultTools.map((t) => ` ${t.tool} first seen ${t.firstSeen} ${t.count}x`),
238
+ "",
223
239
  `All AI-approved commands (${review.aiApproved.length}):`,
224
240
  ...review.aiApproved.map(row),
225
241
  "",
package/dist/service.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Classification, OutcomeReport, Request } from "./types.js";
2
2
  interface Message {
3
3
  token: string;
4
- action: "ping" | "review" | "classify" | "record" | "grant" | "stop";
4
+ action: "ping" | "review" | "classify" | "record" | "grant" | "pending" | "stop";
5
5
  request?: Request;
6
6
  classification?: Classification;
7
7
  report?: OutcomeReport;
@@ -14,6 +14,19 @@ interface Message {
14
14
  }
15
15
  export declare function serve(harness: string, sessionId: string, cliPath?: string): Promise<void>;
16
16
  export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
17
+ /**
18
+ * The newest request waiting for a person across this user's running policy services, for
19
+ * `approve --last`. Only private session directories owned by this user are asked.
20
+ */
21
+ export declare function latestHumanDecision(): Promise<{
22
+ directory: string;
23
+ requestHash: string;
24
+ at: number;
25
+ harness: string;
26
+ sessionId: string;
27
+ } | undefined>;
28
+ /** Sends to the service of an existing session directory (see `approve --last`). */
29
+ export declare function sendTo(directory: string, message: Omit<Message, "token">): Promise<unknown>;
17
30
  /**
18
31
  * Stops a session's service. A session with no service (it never started, already ended, or the
19
32
  * harness fired SessionEnd outside a real session such as `claude update`) is not an error:
package/dist/service.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
- import { chmodSync, existsSync } from "node:fs";
2
+ import { chmodSync, existsSync, lstatSync, readdirSync } from "node:fs";
3
3
  import { createConnection, createServer } from "node:net";
4
+ import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { audit, sessionDirectory, sessionDirectoryPath, sessionToken } from "./audit.js";
6
7
  import { hash, requestHash } from "./policy.js";
@@ -52,7 +53,7 @@ export async function serve(harness, sessionId, cliPath) {
52
53
  : message.grant
53
54
  ? { requestHash: String(message.grant.requestHash) }
54
55
  : {}),
55
- action: ["ping", "review", "classify", "record", "grant", "stop"].includes(message.action)
56
+ action: ["ping", "review", "classify", "record", "grant", "pending", "stop"].includes(message.action)
56
57
  ? message.action
57
58
  : "invalid",
58
59
  });
@@ -60,6 +61,8 @@ export async function serve(harness, sessionId, cliPath) {
60
61
  let result;
61
62
  if (message.action === "ping")
62
63
  result = { ready: true };
64
+ else if (message.action === "pending")
65
+ result = session.latestHumanDecision() ?? null;
63
66
  else if (message.action === "stop") {
64
67
  audit(directory, { event: "session-end" });
65
68
  result = { stopped: true };
@@ -112,7 +115,11 @@ export async function serve(harness, sessionId, cliPath) {
112
115
  resolve();
113
116
  });
114
117
  });
115
- audit(directory, { event: "session-start", harness, sessionHash: hash(sessionId) });
118
+ audit(directory, {
119
+ event: "session-start",
120
+ harness,
121
+ sessionHash: hash(sessionId),
122
+ });
116
123
  audit(directory, {
117
124
  event: "profile",
118
125
  mode: profile.mode,
@@ -125,7 +132,51 @@ export async function serve(harness, sessionId, cliPath) {
125
132
  });
126
133
  }
127
134
  export function send(harness, sessionId, message) {
128
- const directory = sessionDirectory(harness, sessionId);
135
+ return sendTo(sessionDirectory(harness, sessionId), message);
136
+ }
137
+ /**
138
+ * The newest request waiting for a person across this user's running policy services, for
139
+ * `approve --last`. Only private session directories owned by this user are asked.
140
+ */
141
+ export async function latestHumanDecision() {
142
+ const root = tmpdir();
143
+ const prefix = `acp-${process.getuid?.() ?? "user"}-`;
144
+ let best;
145
+ for (const name of readdirSync(root)) {
146
+ if (!name.startsWith(prefix) || !/^[a-f0-9]{24}$/.test(name.slice(prefix.length)))
147
+ continue;
148
+ const directory = join(root, name);
149
+ try {
150
+ const stat = lstatSync(directory);
151
+ if (!stat.isDirectory() ||
152
+ stat.isSymbolicLink() ||
153
+ (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)) ||
154
+ !existsSync(join(directory, "token")))
155
+ continue;
156
+ const found = (await sendTo(directory, { action: "pending" }));
157
+ if (found &&
158
+ typeof found.requestHash === "string" &&
159
+ /^[a-f0-9]{64}$/.test(found.requestHash) &&
160
+ typeof found.at === "number" &&
161
+ typeof found.harness === "string" &&
162
+ typeof found.sessionId === "string" &&
163
+ (!best || found.at > best.at))
164
+ best = {
165
+ directory,
166
+ requestHash: found.requestHash,
167
+ at: found.at,
168
+ harness: found.harness,
169
+ sessionId: found.sessionId,
170
+ };
171
+ }
172
+ catch {
173
+ /* A stopped or unreachable service has nothing to approve. */
174
+ }
175
+ }
176
+ return best;
177
+ }
178
+ /** Sends to the service of an existing session directory (see `approve --last`). */
179
+ export function sendTo(directory, message) {
129
180
  return new Promise((resolve, reject) => {
130
181
  const socket = createConnection(endpoint(directory));
131
182
  let data = "";
package/dist/session.d.ts CHANGED
@@ -60,6 +60,13 @@ export declare class PolicySession {
60
60
  * (used once per hook phase), or a session grant for its rule and scope. Each use is audited.
61
61
  */
62
62
  private granted;
63
+ /** The newest request this session sent to a person that the user may still approve. */
64
+ latestHumanDecision(): {
65
+ requestHash: string;
66
+ at: number;
67
+ harness: string;
68
+ sessionId: string;
69
+ } | undefined;
63
70
  /**
64
71
  * Looks up, and with `confirm` grants, a user approval of a request this session sent to a
65
72
  * person within the last GRANT_WINDOW_MS. Without `session` the next review of that exact
package/dist/session.js CHANGED
@@ -117,7 +117,9 @@ export class PolicySession {
117
117
  scope: "once",
118
118
  phase: slot,
119
119
  });
120
- return { ...result(request, decision.category, "Approved once by the user", true) };
120
+ return {
121
+ ...result(request, decision.category, "Approved once by the user", true),
122
+ };
121
123
  }
122
124
  const scope = grantScope(request, decision, this.profile);
123
125
  if (scope === undefined)
@@ -136,6 +138,14 @@ export class PolicySession {
136
138
  ...result(request, decision.category, "Approved for this session by the user", true),
137
139
  };
138
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
+ }
139
149
  /**
140
150
  * Looks up, and with `confirm` grants, a user approval of a request this session sent to a
141
151
  * person within the last GRANT_WINDOW_MS. Without `session` the next review of that exact
@@ -289,7 +299,11 @@ export class PolicySession {
289
299
  reason: decision.reason,
290
300
  redactedCommand: redactText(String(request.input.command ?? request.input.cmd ?? request.tool), 300),
291
301
  });
292
- decision = { ...decision, decision: "deny", classification: "requested" };
302
+ decision = {
303
+ ...decision,
304
+ decision: "deny",
305
+ classification: "requested",
306
+ };
293
307
  }
294
308
  else {
295
309
  const fallbackReason = known.limited
@@ -305,7 +319,11 @@ export class PolicySession {
305
319
  fallbackReason,
306
320
  });
307
321
  }
308
- decision = { ...decision, classification: "fallback", fallbackReason };
322
+ decision = {
323
+ ...decision,
324
+ classification: "fallback",
325
+ fallbackReason,
326
+ };
309
327
  }
310
328
  }
311
329
  }
@@ -321,7 +339,13 @@ export class PolicySession {
321
339
  else if (decision.decision === "human") {
322
340
  this.cache.delete(key);
323
341
  const sessionScope = grantScope(request, decision, this.profile);
324
- decision = { ...decision, sessionGrantable: sessionScope !== undefined };
342
+ decision = {
343
+ ...decision,
344
+ sessionGrantable: sessionScope !== undefined,
345
+ ...(sessionScope === undefined
346
+ ? {}
347
+ : { sessionScopeLabel: scopeLabel(sessionScope, this.profile) }),
348
+ };
325
349
  if (this.humanDecisions.size >= 256)
326
350
  this.humanDecisions.delete(this.humanDecisions.keys().next().value ?? "");
327
351
  this.humanDecisions.delete(requestHash);
@@ -364,10 +388,14 @@ export class PolicySession {
364
388
  if (targets.length) {
365
389
  if (this.creating.size >= 256)
366
390
  this.creating.delete(this.creating.keys().next().value ?? "");
367
- this.creating.set(decision.requestHash, { targets, approvedAt: Date.now() });
391
+ this.creating.set(decision.requestHash, {
392
+ targets,
393
+ approvedAt: Date.now(),
394
+ });
368
395
  }
369
396
  }
370
- const { ai: classification, ...safe } = decision;
397
+ // The scope label names paths, which audit records never contain.
398
+ const { ai: classification, sessionScopeLabel: _label, ...safe } = decision;
371
399
  audit(this.directory, {
372
400
  event: "decision",
373
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