@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/shell.js CHANGED
@@ -1,370 +1,92 @@
1
- // Parses a bounded subset of POSIX shell: simple commands joined by `;`, newlines, `&&`, `||`
2
- // and `|`, with quoting, leading VAR=value assignments and file redirections. Anything whose
3
- // effects depend on expansion is rejected so a caller can fall back to a human. Three kinds of
4
- // expansion are understood: `$HOME`, which is substituted because its value is known before
5
- // anything runs; command substitution (`$(...)` and backticks), whose inner command is returned in
6
- // `subs` for the caller to judge; and parameters whose value is unknown (`$?`, `$#`, `$$`,
7
- // `PIPESTATUS`). The output of the last two is represented in a word by SUBSTITUTION. Everything
8
- // else (other variables, arithmetic, braces, subshells, heredocs, background jobs, comments,
9
- // process substitution) is rejected.
10
- import { homedir } from "node:os";
11
- /** Stands for the unknown output of a command substitution inside a word. */
12
- export const SUBSTITUTION = "\uE000";
13
- const ASSIGNMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
- /** Index of the `)` that closes a `$(` whose body starts at `start`, honouring quotes and nesting. */
15
- function closingParen(command, start) {
16
- let depth = 1;
17
- let j = start;
18
- while (j < command.length) {
19
- const c = command[j];
20
- if (c === "\\")
21
- j += 2;
22
- else if (c === "'") {
23
- const end = command.indexOf("'", j + 1);
24
- if (end < 0)
25
- return undefined;
26
- j = end + 1;
27
- }
28
- else if (c === '"') {
29
- j++;
30
- while (j < command.length && command[j] !== '"') {
31
- const d = command[j];
32
- if (d === "\\")
33
- j += 2;
34
- else if (d === "$" && command[j + 1] === "(") {
35
- const end = closingParen(command, j + 2);
36
- if (end === undefined)
37
- return undefined;
38
- j = end + 1;
39
- }
40
- else if (d === "`") {
41
- const end = closingBacktick(command, j + 1);
42
- if (end === undefined)
43
- return undefined;
44
- j = end + 1;
45
- }
46
- else
47
- j++;
48
- }
49
- if (j >= command.length)
50
- return undefined;
51
- j++;
52
- }
53
- else if (c === "`") {
54
- const end = closingBacktick(command, j + 1);
55
- if (end === undefined)
56
- return undefined;
57
- j = end + 1;
58
- }
59
- else {
60
- if (c === "(")
61
- depth++;
62
- else if (c === ")" && --depth === 0)
63
- return j;
64
- j++;
65
- }
1
+ // Compatibility view of the script parser for callers that only handle plain commands: simple
2
+ // commands joined by `;`, newlines, `&&`, `||` and `|`, with literal words. Anything else
3
+ // (variables, compound commands, heredocs, background jobs) returns undefined. The evaluator uses
4
+ // `parseScript` directly.
5
+ import { parseScript, SUBSTITUTION, } from "./script.js";
6
+ export { SUBSTITUTION } from "./script.js";
7
+ /** Text of a word with no variable references; unknown parts become SUBSTITUTION. */
8
+ function literalText(word) {
9
+ let text = "";
10
+ for (const part of word.parts) {
11
+ if (typeof part === "string")
12
+ text += part;
13
+ else if ("unknown" in part)
14
+ text += SUBSTITUTION;
15
+ else
16
+ return undefined;
66
17
  }
67
- return undefined;
18
+ return text;
68
19
  }
69
- function closingBacktick(command, start) {
70
- for (let j = start; j < command.length; j++) {
71
- if (command[j] === "\\")
72
- j++;
73
- else if (command[j] === "`")
74
- return j;
75
- }
76
- return undefined;
20
+ function plainRedirect(redir) {
21
+ if (redir.op === "<<" || redir.op === "<<<" || !redir.target)
22
+ return undefined;
23
+ const target = literalText(redir.target);
24
+ return target === undefined ? undefined : { fd: redir.fd, op: redir.op, target };
77
25
  }
78
- // Only HOME has a value that is known before anything runs. The others are recognised so a
79
- // harmless read like `echo "exit: $?"` can be judged, but their value is unknown: `$?` and friends
80
- // change per run, and an array element such as `${PIPESTATUS[5]}` is empty when out of range.
81
- // They are therefore represented by SUBSTITUTION, never by a made-up value.
82
- const UNKNOWN_PARAMETER = /^(?:(?:PIPESTATUS|pipestatus)(?:\[[0-9@*]+\])?)$/;
83
- /**
84
- * Reads the expansion that starts at `command[at] === "$"`. Returns the text it stands for and the
85
- * index after it, any command substitution body, or undefined for an expansion that is not
86
- * understood.
87
- */
88
- function expansion(command, at) {
89
- const rest = command.slice(at + 1);
90
- const home = () => {
91
- const path = homedir();
92
- // The text is inserted as-is and never re-parsed, so a backslash (a Windows separator) is
93
- // harmless; whitespace and glob characters would split or expand when unquoted.
94
- return /[\s*?[\]'"$`]/.test(path) ? undefined : path;
95
- };
96
- if (rest[0] === "(") {
97
- if (rest[1] === "(")
98
- return undefined; // arithmetic expansion
99
- const end = closingParen(command, at + 2);
100
- if (end === undefined)
26
+ function plainSimple(command) {
27
+ if (command.kind !== "simple")
28
+ return undefined;
29
+ const simple = command;
30
+ if (!simple.argv.length)
31
+ return undefined;
32
+ const env = [];
33
+ const subs = [];
34
+ for (const { name, value } of simple.assigns) {
35
+ const text = literalText(value);
36
+ if (text === undefined)
101
37
  return undefined;
102
- return { text: SUBSTITUTION, next: end + 1, inner: command.slice(at + 2, end) };
38
+ env.push([name, text]);
39
+ subs.push(...value.subs);
103
40
  }
104
- if (rest[0] === "{") {
105
- const close = rest.indexOf("}");
106
- const name = close > 0 ? rest.slice(1, close) : "";
107
- const next = at + close + 2;
108
- if (name === "HOME") {
109
- const text = home();
110
- return text === undefined ? undefined : { text, next };
111
- }
112
- return UNKNOWN_PARAMETER.test(name) ? { text: SUBSTITUTION, next } : undefined;
41
+ const argv = [];
42
+ const loose = [];
43
+ for (const word of simple.argv) {
44
+ const text = literalText(word);
45
+ if (text === undefined)
46
+ return undefined;
47
+ argv.push(text);
48
+ loose.push(word.parts.some((p) => typeof p !== "string" && "unknown" in p && !p.quoted));
49
+ subs.push(...word.subs);
113
50
  }
114
- if (rest[0] && "?#$".includes(rest[0]))
115
- return { text: SUBSTITUTION, next: at + 2 };
116
- const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest)?.[0];
117
- const next = at + 1 + (name?.length ?? 0);
118
- if (name === "HOME") {
119
- const text = home();
120
- return text === undefined ? undefined : { text, next };
51
+ const redirects = [];
52
+ for (const redir of simple.redirects) {
53
+ const plain = plainRedirect(redir);
54
+ if (!plain)
55
+ return undefined;
56
+ redirects.push(plain);
57
+ subs.push(...(redir.target?.subs ?? []));
121
58
  }
122
- return name && UNKNOWN_PARAMETER.test(name) ? { text: SUBSTITUTION, next } : undefined;
59
+ return { env, argv, redirects, subs, loose };
123
60
  }
124
- /** Body of a backtick substitution: backslash escapes `\``, `\\` and `\$` are removed first. */
125
- function backtickBody(raw) {
126
- return raw.replace(/\\([`\\$])/g, "$1");
127
- }
128
- export function parseShell(command) {
129
- if (!command ||
130
- command.includes("\0") ||
131
- command.includes("\r") ||
132
- command.includes(SUBSTITUTION))
133
- return undefined;
61
+ function flatten(andOr) {
134
62
  const pipelines = [];
135
- let pipeline = [];
136
- let words = [];
137
- let redirects = [];
138
- let subs = [];
139
- let pendingRedirect;
140
- let current = "";
141
- let active = false;
142
- let quoted = false;
143
- // A word is an assignment only if its `NAME=` prefix was typed plainly. Quotes or escapes later,
144
- // in the value, are fine (`FOO="a b" cmd`); a quote or escape before the `=` is not an assignment.
145
- let plain = true;
146
- let eqAt = -1;
147
- let quote = "";
148
- let dangling = false;
149
- const endWord = () => {
150
- if (!active)
151
- return true;
152
- const word = { text: current, assignAt: plain ? eqAt : -1 };
153
- current = "";
154
- active = false;
155
- quoted = false;
156
- plain = true;
157
- eqAt = -1;
158
- if (pendingRedirect) {
159
- redirects.push({ ...pendingRedirect, target: word.text });
160
- pendingRedirect = undefined;
161
- }
162
- else {
163
- words.push(word);
164
- dangling = false;
165
- }
166
- return true;
167
- };
168
- const endSimple = () => {
169
- if (pendingRedirect)
170
- return false;
171
- if (!words.length && !redirects.length)
172
- return true;
173
- const env = [];
174
- let index = 0;
175
- while (index < words.length) {
176
- const word = words[index];
177
- if (!word || word.assignAt < 1 || !ASSIGNMENT_NAME.test(word.text.slice(0, word.assignAt)))
178
- break;
179
- env.push([word.text.slice(0, word.assignAt), word.text.slice(word.assignAt + 1)]);
180
- index++;
181
- }
182
- const argv = words.slice(index).map((word) => word.text);
183
- if (!argv.length)
184
- return false;
185
- // Bash also treats `FOO+=x`, `FOO[0]=x` and quoted or escaped forms as assignments and then runs
186
- // the next word. A program name never contains `=`, so a leading word that still has one is
187
- // an assignment this parser cannot represent: reject it instead of judging it as the program.
188
- if (argv[0]?.includes("="))
189
- return false;
190
- pipeline.push({ env, argv, redirects, subs });
191
- words = [];
192
- redirects = [];
193
- subs = [];
194
- return true;
195
- };
196
- const endPipeline = (allowEmpty) => {
197
- if (!endSimple())
198
- return false;
199
- if (!pipeline.length)
200
- return allowEmpty;
201
- pipelines.push(pipeline);
202
- pipeline = [];
203
- return true;
204
- };
205
- for (let i = 0; i < command.length; i++) {
206
- const char = command[i];
207
- if (quote) {
208
- if (quote === '"') {
209
- if (char === "\\") {
210
- // Inside double quotes a backslash only escapes `"`, `\`, `$` and a backtick; before any
211
- // other character it is literal. Either way nothing is expanded or executed.
212
- const next = command[i + 1];
213
- if (next === undefined || next === "\n")
214
- return undefined;
215
- if ('"\\$`'.includes(next)) {
216
- current += next;
217
- i++;
218
- }
219
- else
220
- current += char;
221
- continue;
222
- }
223
- if (char === "$") {
224
- const expanded = expansion(command, i);
225
- if (!expanded)
226
- return undefined;
227
- current += expanded.text;
228
- if (expanded.inner !== undefined)
229
- subs.push(expanded.inner);
230
- i = expanded.next - 1;
231
- continue;
232
- }
233
- if (char === "`") {
234
- const end = closingBacktick(command, i + 1);
235
- if (end === undefined)
236
- return undefined;
237
- subs.push(backtickBody(command.slice(i + 1, end)));
238
- current += SUBSTITUTION;
239
- i = end;
240
- continue;
241
- }
242
- }
243
- if (char === quote)
244
- quote = "";
245
- else
246
- current += char;
247
- continue;
248
- }
249
- if (char === "'" || char === '"') {
250
- quote = char;
251
- active = true;
252
- quoted = true;
253
- if (eqAt < 0)
254
- plain = false;
255
- continue;
256
- }
257
- if (char === "\\") {
258
- // An unquoted backslash makes the next character literal (`\.`, `\|`, `\ `).
259
- const next = command[i + 1];
260
- if (next === undefined || next === "\n")
261
- return undefined;
262
- current += next;
263
- active = true;
264
- quoted = true;
265
- if (eqAt < 0)
266
- plain = false;
267
- i++;
268
- continue;
269
- }
270
- if (char === "$") {
271
- const expanded = expansion(command, i);
272
- if (!expanded)
273
- return undefined;
274
- if (eqAt < 0)
275
- plain = false;
276
- current += expanded.text;
277
- active = true;
278
- if (expanded.inner !== undefined)
279
- subs.push(expanded.inner);
280
- i = expanded.next - 1;
281
- continue;
282
- }
283
- if (char === "`") {
284
- const end = closingBacktick(command, i + 1);
285
- if (end === undefined)
286
- return undefined;
287
- if (eqAt < 0)
288
- plain = false;
289
- subs.push(backtickBody(command.slice(i + 1, end)));
290
- current += SUBSTITUTION;
291
- active = true;
292
- i = end;
293
- continue;
294
- }
295
- if (/[(){}#!]/.test(char)) {
296
- // `#` only starts a comment at a word boundary, but rejecting it everywhere is simpler.
63
+ for (const node of [andOr.first, ...andOr.rest.map((r) => r.node)]) {
64
+ if (node.negated)
297
65
  return undefined;
298
- }
299
- if (char === " " || char === "\t") {
300
- endWord();
301
- continue;
302
- }
303
- if (char === "\n" || char === ";") {
304
- endWord();
305
- if (dangling || !endPipeline(true))
306
- return undefined;
307
- continue;
308
- }
309
- if (char === "&") {
310
- if (command[i + 1] !== "&")
311
- return undefined;
312
- endWord();
313
- if (!endPipeline(false))
314
- return undefined;
315
- dangling = true;
316
- i++;
317
- continue;
318
- }
319
- if (char === "|") {
320
- endWord();
321
- if (command[i + 1] === "|") {
322
- if (!endPipeline(false))
323
- return undefined;
324
- i++;
325
- }
326
- else if (!words.length || !endSimple())
66
+ const stages = [];
67
+ for (const stage of node.stages) {
68
+ const simple = plainSimple(stage);
69
+ if (!simple)
327
70
  return undefined;
328
- dangling = true;
329
- continue;
71
+ stages.push(simple);
330
72
  }
331
- if (char === ">" || char === "<") {
332
- if (command[i + 1] === "(" || (char === "<" && command[i + 1] === "<"))
333
- return undefined;
334
- let fd = char === ">" ? "1" : "0";
335
- if (active && !quoted && /^[0-9]$/.test(current)) {
336
- fd = current;
337
- current = "";
338
- active = false;
339
- }
340
- else
341
- endWord();
342
- let op = char;
343
- if (char === ">" && command[i + 1] === ">") {
344
- op = ">>";
345
- i++;
346
- }
347
- else if (char === ">" && command[i + 1] === "&") {
348
- op = ">&";
349
- i++;
350
- }
351
- else if (char === ">" && command[i + 1] === "|")
352
- return undefined;
353
- if (pendingRedirect)
354
- return undefined;
355
- pendingRedirect = { fd, op };
356
- continue;
357
- }
358
- if (plain && eqAt < 0 && char === "=")
359
- eqAt = current.length;
360
- current += char;
361
- active = true;
73
+ pipelines.push(stages);
362
74
  }
363
- if (quote)
364
- return undefined;
365
- endWord();
366
- if (dangling || !endPipeline(true))
75
+ return pipelines;
76
+ }
77
+ export function parseShell(command) {
78
+ const script = parseScript(command);
79
+ if (!script)
367
80
  return undefined;
81
+ const pipelines = [];
82
+ for (const item of script.items) {
83
+ if (item.background)
84
+ return undefined;
85
+ const flat = flatten(item.node);
86
+ if (!flat)
87
+ return undefined;
88
+ pipelines.push(...flat);
89
+ }
368
90
  return pipelines.length ? pipelines : undefined;
369
91
  }
370
92
  //# sourceMappingURL=shell.js.map
package/dist/types.d.ts CHANGED
@@ -10,22 +10,34 @@ export interface Classification {
10
10
  category: Category;
11
11
  confidence: number;
12
12
  requestHash: string;
13
+ /** Whether the action can be undone (merged work, tracked files, anything a backup restores). */
14
+ recoverable?: boolean;
15
+ /** Short free-text reason from the classifier; capped and redacted before it is logged. */
16
+ rationale?: string;
13
17
  }
18
+ /** Where an ambiguous request stands in the AI classification flow. */
19
+ export type ClassificationStage = "requested" | "approved" | "denied" | "fallback";
14
20
  export interface Decision {
15
- decision: "approve" | "human";
21
+ /** `deny` is a decision the model sees and works around; `human` asks the person. */
22
+ decision: "approve" | "human" | "deny";
16
23
  category: Category;
17
24
  reason: string;
18
25
  requestHash: string;
19
26
  cache: "none" | "session";
20
27
  cached: boolean;
21
28
  needsClassification?: boolean;
29
+ /** `ambiguous`: the deterministic engine could not decide and nothing in code forbids it. */
30
+ tier?: "ambiguous";
31
+ classification?: ClassificationStage;
32
+ /** Why a human was asked after classification could not decide. */
33
+ fallbackReason?: "unavailable" | "invalid-result" | "limit";
22
34
  ai?: Classification;
23
35
  }
24
36
  export interface OutcomeReport {
25
37
  requestHash: string;
26
38
  event: "human-response" | "execution-result";
27
39
  response?: "approved" | "denied";
28
- status?: "completed" | "succeeded" | "failed" | "cancelled";
40
+ status?: "completed" | "succeeded" | "failed" | "cancelled" | "unknown";
29
41
  exitCode?: number;
30
42
  durationMs?: number;
31
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",