@agent-corpus/policy-manager 0.3.0 → 0.5.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/service.d.ts CHANGED
@@ -5,6 +5,7 @@ interface Message {
5
5
  request?: Request;
6
6
  classification?: Classification;
7
7
  report?: OutcomeReport;
8
+ phase?: string;
8
9
  }
9
10
  export declare function serve(harness: string, sessionId: string): Promise<void>;
10
11
  export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
package/dist/service.js CHANGED
@@ -64,7 +64,7 @@ export async function serve(harness, sessionId) {
64
64
  server.close();
65
65
  }
66
66
  else if (message.action === "review" && message.request)
67
- result = session.review(message.request);
67
+ result = session.review(message.request, undefined, message.phase);
68
68
  else if (message.action === "classify" && message.classification)
69
69
  result = session.classify(message.classification);
70
70
  else if (message.action === "record" && message.report) {
package/dist/session.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type Profile } from "./profile.js";
2
2
  import type { Classification, Decision, OutcomeReport, Request } from "./types.js";
3
+ /** AI approvals per session; beyond this, ambiguous requests go to a human. */
4
+ export declare const MAX_AI_APPROVALS = 50;
3
5
  export declare class PolicySession {
4
6
  readonly directory: string;
5
7
  readonly harness: string;
@@ -7,8 +9,18 @@ export declare class PolicySession {
7
9
  readonly profile: Profile;
8
10
  private cache;
9
11
  private pending;
12
+ private states;
13
+ /** Requests the AI approved, counted once each however often they are retried. */
14
+ private approvedByAi;
10
15
  constructor(directory: string, harness: string, sessionId: string, profile?: Profile);
11
- review(request: Request, ai?: Classification): Decision;
16
+ private state;
17
+ private remember;
18
+ /**
19
+ * `phase` is the hook event. Only `PreToolUse` runs the classification flow: the first time an
20
+ * ambiguous request arrives it is blocked with an instruction to classify and retry; the next
21
+ * time, with no usable classification, a human is asked and the reason is recorded.
22
+ */
23
+ review(request: Request, ai?: Classification, phase?: string): Decision;
12
24
  record(report: OutcomeReport): void;
13
25
  classify(classification: Classification): Decision;
14
26
  }
package/dist/session.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { audit, requestSummary } from "./audit.js";
2
2
  import { evaluate, hash } from "./policy.js";
3
3
  import { strictProfile } from "./profile.js";
4
+ import { redactText } from "./redact.js";
5
+ /** How long a classification outcome for one exact request is remembered. */
6
+ const CLASSIFICATION_TTL_MS = 5 * 60_000;
7
+ /** AI approvals per session; beyond this, ambiguous requests go to a human. */
8
+ export const MAX_AI_APPROVALS = 50;
4
9
  export class PolicySession {
5
10
  directory;
6
11
  harness;
@@ -8,13 +13,42 @@ export class PolicySession {
8
13
  profile;
9
14
  cache = new Map();
10
15
  pending = new Map();
16
+ states = new Map();
17
+ /** Requests the AI approved, counted once each however often they are retried. */
18
+ approvedByAi = new Set();
11
19
  constructor(directory, harness, sessionId, profile = strictProfile) {
12
20
  this.directory = directory;
13
21
  this.harness = harness;
14
22
  this.sessionId = sessionId;
15
23
  this.profile = profile;
16
24
  }
17
- review(request, ai) {
25
+ state(requestHash) {
26
+ const state = this.states.get(requestHash);
27
+ if (state && state.expires <= Date.now()) {
28
+ this.states.delete(requestHash);
29
+ return undefined;
30
+ }
31
+ return state;
32
+ }
33
+ remember(requestHash, change) {
34
+ if (this.states.size >= 512)
35
+ this.states.clear();
36
+ this.states.set(requestHash, {
37
+ requested: false,
38
+ invalid: false,
39
+ fallback: false,
40
+ limited: false,
41
+ ...this.states.get(requestHash),
42
+ ...change,
43
+ expires: Date.now() + CLASSIFICATION_TTL_MS,
44
+ });
45
+ }
46
+ /**
47
+ * `phase` is the hook event. Only `PreToolUse` runs the classification flow: the first time an
48
+ * ambiguous request arrives it is blocked with an instruction to classify and retry; the next
49
+ * time, with no usable classification, a human is asked and the reason is recorded.
50
+ */
51
+ review(request, ai, phase) {
18
52
  if (request.sessionId !== this.sessionId || request.harness !== this.harness)
19
53
  throw new Error("Session mismatch");
20
54
  audit(this.directory, { event: "request", ...requestSummary(request) });
@@ -31,6 +65,8 @@ export class PolicySession {
31
65
  ].includes(ai.category) ||
32
66
  typeof ai.confidence !== "number" ||
33
67
  !Number.isFinite(ai.confidence) ||
68
+ (ai.recoverable !== undefined && typeof ai.recoverable !== "boolean") ||
69
+ (ai.rationale !== undefined && typeof ai.rationale !== "string") ||
34
70
  !/^[a-f0-9]{64}$/.test(ai.requestHash))) {
35
71
  audit(this.directory, {
36
72
  event: "decision",
@@ -44,14 +80,72 @@ export class PolicySession {
44
80
  const key = hash([hash(request), "policy-v1", this.profile.digest ?? this.profile.mode]);
45
81
  const entry = this.cache.get(key);
46
82
  const cachedAi = entry && entry.expires > Date.now() ? entry.ai : undefined;
83
+ const requestHash = hash(request);
84
+ const known = ai ? undefined : this.state(requestHash);
47
85
  if (ai)
48
86
  audit(this.directory, {
49
87
  event: "classification",
50
- requestHash: hash(request),
88
+ requestHash,
51
89
  category: ai.category,
52
90
  confidence: ai.confidence,
91
+ ...(ai.recoverable === undefined ? {} : { recoverable: ai.recoverable }),
92
+ ...(ai.rationale ? { rationale: redactText(ai.rationale, 200) } : {}),
53
93
  });
54
- const decision = evaluate(request, ai ?? cachedAi, this.profile);
94
+ let decision = evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile);
95
+ if (decision.tier === "ambiguous") {
96
+ if (ai && !decision.classification)
97
+ this.remember(requestHash, { invalid: true });
98
+ else if (ai) {
99
+ // The cap is checked when the approval is first given and stored with the outcome, so a
100
+ // retry cannot turn a limited request into an approval.
101
+ if (decision.classification === "approved" &&
102
+ !this.approvedByAi.has(requestHash) &&
103
+ this.approvedByAi.size >= MAX_AI_APPROVALS) {
104
+ decision = {
105
+ ...decision,
106
+ decision: "human",
107
+ classification: "fallback",
108
+ fallbackReason: "limit",
109
+ reason: "Session limit on AI approvals reached; a human decides",
110
+ };
111
+ this.remember(requestHash, { limited: true });
112
+ }
113
+ else {
114
+ if (decision.classification === "approved")
115
+ this.approvedByAi.add(requestHash);
116
+ this.remember(requestHash, { ai });
117
+ }
118
+ }
119
+ if (decision.needsClassification && !ai && phase === "PreToolUse") {
120
+ if (!known?.requested) {
121
+ this.remember(requestHash, { requested: true });
122
+ audit(this.directory, {
123
+ event: "classification-requested",
124
+ requestHash,
125
+ tier: "ambiguous",
126
+ reason: decision.reason,
127
+ redactedCommand: redactText(String(request.input.command ?? request.input.cmd ?? request.tool), 300),
128
+ });
129
+ decision = { ...decision, decision: "deny", classification: "requested" };
130
+ }
131
+ else {
132
+ const fallbackReason = known.limited
133
+ ? "limit"
134
+ : known.invalid
135
+ ? "invalid-result"
136
+ : "unavailable";
137
+ if (!known.fallback) {
138
+ this.remember(requestHash, { fallback: true });
139
+ audit(this.directory, {
140
+ event: "classification-fallback",
141
+ requestHash,
142
+ fallbackReason,
143
+ });
144
+ }
145
+ decision = { ...decision, classification: "fallback", fallbackReason };
146
+ }
147
+ }
148
+ }
55
149
  if (decision.decision === "human")
56
150
  this.cache.delete(key);
57
151
  // Evaluation always precedes lookup. Filesystem evidence is never cached.
@@ -66,8 +160,10 @@ export class PolicySession {
66
160
  });
67
161
  }
68
162
  }
69
- if (decision.decision === "human" &&
70
- ["unknown", "cloud-read"].includes(decision.category) &&
163
+ // A denied request is final for its remembered state: only a human decision or a request
164
+ // still waiting for its first classification can be classified.
165
+ if ((decision.decision === "human" || decision.classification === "requested") &&
166
+ (["unknown", "cloud-read"].includes(decision.category) || decision.needsClassification) &&
71
167
  !ai) {
72
168
  if (this.pending.size >= 64)
73
169
  this.pending.delete(this.pending.keys().next().value ?? "");
@@ -103,7 +199,7 @@ export class PolicySession {
103
199
  });
104
200
  }
105
201
  else if (report.event === "execution-result") {
106
- if (!["completed", "succeeded", "failed", "cancelled"].includes(report.status ?? ""))
202
+ if (!["completed", "succeeded", "failed", "cancelled", "unknown"].includes(report.status ?? ""))
107
203
  throw new Error("Invalid execution status");
108
204
  if (report.exitCode !== undefined &&
109
205
  (!Number.isSafeInteger(report.exitCode) || Math.abs(report.exitCode) > 2147483647))
@@ -127,8 +223,19 @@ export class PolicySession {
127
223
  const request = this.pending.get(classification.requestHash);
128
224
  if (!request)
129
225
  throw new Error("No pending request matches the classification");
226
+ // One classification per request: a verdict, deny or approve, cannot be replaced.
227
+ if (this.state(classification.requestHash)?.ai)
228
+ throw new Error("The request is already classified");
130
229
  this.pending.delete(classification.requestHash);
131
- return this.review(request, classification);
230
+ try {
231
+ return this.review(request, classification);
232
+ }
233
+ catch (error) {
234
+ // A malformed result is not an approval; the retry will fall back to a human, with the
235
+ // reason recorded for the review.
236
+ this.remember(classification.requestHash, { invalid: true });
237
+ throw error;
238
+ }
132
239
  }
133
240
  }
134
241
  //# sourceMappingURL=session.js.map
package/dist/setup.js CHANGED
@@ -127,7 +127,9 @@ export function setupHook(harness, cliPath, options = {}) {
127
127
  "Start a new harness session to load the hooks.",
128
128
  ...(harness === "codex"
129
129
  ? [
130
- "Open /hooks and explicitly review and trust the installed hooks. Setup does not grant hook trust.",
130
+ "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
+ "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.",
131
133
  ]
132
134
  : []),
133
135
  "Native sandbox controls and existing permission rules remain in effect.",
package/dist/shell.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- /** Stands for the unknown output of a command substitution inside a word. */
2
- export declare const SUBSTITUTION = "\uE000";
1
+ export { SUBSTITUTION } from "./script.js";
3
2
  export interface Redirect {
4
3
  fd: string;
5
4
  op: ">" | ">>" | "<" | ">&";
@@ -9,8 +8,12 @@ export interface SimpleCommand {
9
8
  env: Array<[string, string]>;
10
9
  argv: string[];
11
10
  redirects: Redirect[];
12
- /** Inner commands of `$(...)` and backticks in this command's words, in order. */
11
+ /** Inner commands of `$(...)`, backticks and process substitutions in this command's words. */
13
12
  subs: string[];
13
+ /** For each argv word, whether it contains an unquoted unknown value (it could split). */
14
+ loose?: boolean[];
15
+ /** Literal text fed to standard input by a heredoc or here-string, when there is one. */
16
+ stdin?: string;
14
17
  }
15
18
  export type Pipeline = SimpleCommand[];
16
19
  export declare function parseShell(command: string): Pipeline[] | undefined;