@glassbox-ai/engine 0.1.0 → 0.1.2

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.
Files changed (48) hide show
  1. package/README.md +2 -0
  2. package/dist/action/acc.d.ts +1 -1
  3. package/dist/action/agent-clis.d.ts +44 -0
  4. package/dist/action/agent-clis.js +175 -0
  5. package/dist/action/builtin-tools.d.ts +5 -0
  6. package/dist/action/builtin-tools.js +74 -0
  7. package/dist/action/inline.js +2 -2
  8. package/dist/action/paths.js +1 -1
  9. package/dist/action/powershell.js +10 -4
  10. package/dist/action/schedule.d.ts +7 -0
  11. package/dist/action/schedule.js +10 -0
  12. package/dist/action/shell/analyze.js +75 -15
  13. package/dist/action/shell/parse.js +1 -1
  14. package/dist/action/shell/view.js +1 -1
  15. package/dist/action/sql.js +1 -1
  16. package/dist/action/tools.js +70 -3
  17. package/dist/action/upload.d.ts +6 -2
  18. package/dist/action/upload.js +32 -7
  19. package/dist/analysis/fields.js +3 -3
  20. package/dist/analysis/findings.js +1 -1
  21. package/dist/analysis/gate.js +8 -6
  22. package/dist/analysis/manifest.js +2 -2
  23. package/dist/analysis/match.js +2 -2
  24. package/dist/analysis/scan.js +1 -1
  25. package/dist/canon/decode.js +1 -1
  26. package/dist/canon/views.js +1 -1
  27. package/dist/evidence/evidence.js +1 -1
  28. package/dist/fingerprint/diff.js +1 -1
  29. package/dist/index.d.ts +5 -1
  30. package/dist/index.js +6 -2
  31. package/dist/intake/json.js +1 -1
  32. package/dist/intake/snapshot.js +1 -1
  33. package/dist/policy/decide.d.ts +14 -1
  34. package/dist/policy/decide.js +68 -15
  35. package/dist/ruleset/load.d.ts +2 -3
  36. package/dist/ruleset/load.js +20 -6
  37. package/dist/ruleset/schema.d.ts +1 -1
  38. package/dist/ruleset/schema.js +1 -1
  39. package/dist/ruleset-entry.js +1 -1
  40. package/dist/secrets/detect.js +2 -2
  41. package/dist/secrets/redact.js +1 -1
  42. package/dist/types.d.ts +21 -0
  43. package/dist/types.js +1 -1
  44. package/dist/util/jcs.js +1 -1
  45. package/dist/util/re.js +1 -1
  46. package/dist/version.d.ts +1 -1
  47. package/dist/version.js +1 -1
  48. package/package.json +7 -6
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # @glassbox-ai/engine
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@glassbox-ai/engine.svg)](https://www.npmjs.com/package/@glassbox-ai/engine)
4
+
3
5
  Checks what an AI agent is about to do and what it reads. For each step it answers allow,
4
6
  warn, ask or deny. It also grades MCP servers from their metadata. It's a library with no I/O;
5
7
  it is deterministic and never throws.
@@ -6,7 +6,7 @@ export interface CodeFinding {
6
6
  }
7
7
  export declare class Acc {
8
8
  level: ActionRiskLevel;
9
- tags: Set<"fs.read" | "fs.read.sensitive" | "fs.write" | "fs.delete" | "fs.destroy" | "fs.move" | "net.egress" | "net.fetch.package-manager" | "net.fetch.vcs" | "vcs.commit" | "vcs.push" | "vcs.force-push" | "vcs.history-rewrite" | "vcs.discard-changes" | "db.read" | "db.write" | "db.delete" | "db.ddl" | "db.unscoped-write" | "deploy.prod" | "deploy.other" | "infra.change" | "payment" | "publish.public" | "message.send" | "perm.change" | "exec.inline-code" | "exec.project-code" | "exec.unknown" | "exec.nested-agent" | "config.agent" | "self-protection">;
9
+ tags: Set<"self-protection" | "fs.read" | "fs.read.sensitive" | "fs.write" | "fs.delete" | "fs.destroy" | "fs.move" | "net.egress" | "net.fetch.package-manager" | "net.fetch.vcs" | "vcs.commit" | "vcs.push" | "vcs.force-push" | "vcs.history-rewrite" | "vcs.discard-changes" | "db.read" | "db.write" | "db.delete" | "db.ddl" | "db.unscoped-write" | "deploy.prod" | "deploy.other" | "infra.change" | "payment" | "publish.public" | "message.send" | "perm.change" | "exec.inline-code" | "exec.project-code" | "exec.unknown" | "exec.nested-agent" | "config.agent">;
10
10
  unanalyzableReasons: string[];
11
11
  selfProtection: boolean;
12
12
  findings: CodeFinding[];
@@ -0,0 +1,44 @@
1
+ import type { Acc } from "./acc.js";
2
+ import { type NormPath, type PathCtx } from "./paths.js";
3
+ /** A flag that takes a value: denied only for the listed values (or any value when `values` is "any"). */
4
+ interface ValueFlag {
5
+ flags: readonly string[];
6
+ values: readonly string[] | "any";
7
+ /** Only for these keys of a `key=value` setting (Codex `-c approval_policy=…`). */
8
+ keys?: readonly string[];
9
+ }
10
+ export interface AgentCli {
11
+ tool: string;
12
+ exes: readonly string[];
13
+ /** Boolean flags that turn off approvals or the sandbox. */
14
+ deny: readonly string[];
15
+ denyValues: readonly ValueFlag[];
16
+ /** Environment variables that are denied whatever their value. */
17
+ denyEnv: readonly string[];
18
+ /** Environment variables denied only for these values. */
19
+ denyEnvValues: Readonly<Record<string, readonly string[]>>;
20
+ }
21
+ export declare const AGENT_CLIS: readonly AgentCli[];
22
+ /** The agent CLI a command name starts, if any (case-insensitive, `.exe`/`.cmd` dropped). */
23
+ export declare function agentCliFor(commandName: string): AgentCli | undefined;
24
+ /**
25
+ * npm packages whose `bin` is an agent CLI (checked against the npm registry 2026-11-25), so a
26
+ * package runner (`npx @openai/codex --yolo`) is analyzed like the CLI itself.
27
+ */
28
+ export declare const AGENT_PACKAGES: Readonly<Record<string, string>>;
29
+ /** The CLI a package spec (`@openai/codex@1.2.3`, `opencode-ai@latest`) provides, if it is an agent. */
30
+ export declare function agentPackageBin(spec: string): string | undefined;
31
+ /**
32
+ * Analyze one agent CLI call. `vals` are the argument values (null = not known statically);
33
+ * `env` maps environment variables set for this command to their value (null = not literal).
34
+ */
35
+ export declare function agentCliCommand(a: AgentCli, vals: readonly (string | null)[], env: ReadonlyMap<string, string | null>, acc: Acc): void;
36
+ /**
37
+ * Is this normalized, lower-cased path another agent CLI's configuration or instruction file?
38
+ * `home` and `project` are normalized and lower-cased too (project may be null).
39
+ */
40
+ export declare function isAgentConfigPath(p: string, home: string, project: string | null): boolean;
41
+ /** A write (or move or delete) of another agent's config or instruction file: config.agent (a liftable ask). */
42
+ export declare function agentConfigWrite(np: NormPath | null, pctx: PathCtx, acc: Acc): void;
43
+ export {};
44
+ //# sourceMappingURL=agent-clis.d.ts.map
@@ -0,0 +1,175 @@
1
+ import { normalizeFull } from "./paths.js";
2
+ const cli = (c) => ({ deny: [], denyValues: [], denyEnv: [], denyEnvValues: {}, ...c });
3
+ export const AGENT_CLIS = [
4
+ cli({
5
+ tool: "OpenAI Codex", exes: ["codex"],
6
+ deny: ["--dangerously-bypass-approvals-and-sandbox", "--yolo", "--approve-for-me", "--not-so-yolo", "--dangerously-bypass-hook-trust", "--ignore-rules"],
7
+ denyValues: [
8
+ { flags: ["-a", "--ask-for-approval"], values: ["never"] },
9
+ { flags: ["-s", "--sandbox"], values: ["danger-full-access"] },
10
+ { flags: ["-c", "--config"], values: "any", keys: ["approval_policy", "sandbox_mode", "default_permissions"] },
11
+ ],
12
+ denyEnv: ["CODEX_HOME"],
13
+ }),
14
+ cli({
15
+ tool: "Gemini CLI", exes: ["gemini"],
16
+ deny: ["--yolo", "-y", "--skip-trust"],
17
+ denyValues: [{ flags: ["--approval-mode"], values: ["yolo"] }],
18
+ denyEnv: ["GEMINI_CLI_HOME", "SEATBELT_PROFILE"],
19
+ }),
20
+ cli({ tool: "Aider", exes: ["aider"], deny: ["--yes-always", "--yes"], denyEnv: ["AIDER_YES_ALWAYS", "AIDER_YES"] }),
21
+ cli({
22
+ tool: "Cursor CLI", exes: ["agent", "cursor-agent"],
23
+ deny: ["-f", "--force", "--yolo", "--approve-mcps", "--trust"],
24
+ denyValues: [{ flags: ["--sandbox"], values: ["disabled"] }],
25
+ denyEnv: ["CURSOR_CONFIG_DIR"],
26
+ }),
27
+ cli({
28
+ tool: "opencode", exes: ["opencode"],
29
+ deny: ["--auto", "--yolo", "--dangerously-skip-permissions"],
30
+ denyEnv: ["OPENCODE_PERMISSION", "OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "OPENCODE_CONFIG_CONTENT"],
31
+ }),
32
+ cli({ tool: "Goose", exes: ["goose"], deny: ["--dangerously-unauthenticated"], denyEnv: ["GOOSE_PATH_ROOT"], denyEnvValues: { GOOSE_MODE: ["auto"] } }),
33
+ cli({ tool: "Amp", exes: ["amp"], deny: ["--dangerously-allow-all"] }),
34
+ cli({ tool: "Crush", exes: ["crush"], deny: ["--yolo"] }),
35
+ cli({ tool: "GitHub Copilot CLI", exes: ["copilot"], deny: ["--allow-all-tools", "--allow-all", "--yolo", "--allow-all-paths", "--allow-all-urls"], denyEnv: ["COPILOT_HOME"] }),
36
+ cli({ tool: "Kiro CLI", exes: ["kiro-cli", "kiro"], deny: ["--trust-all-tools"], denyEnv: ["KIRO_HOME"] }),
37
+ cli({ tool: "Cline CLI", exes: ["cline"], deny: ["-y", "--yolo"] }),
38
+ cli({ tool: "Qwen Code", exes: ["qwen"] }), // no flag confirmed in official docs: launching asks
39
+ ];
40
+ const BY_EXE = new Map(AGENT_CLIS.flatMap((c) => c.exes.map((e) => [e, c])));
41
+ /** The agent CLI a command name starts, if any (case-insensitive, `.exe`/`.cmd` dropped). */
42
+ export function agentCliFor(commandName) {
43
+ const n = commandName.toLowerCase().replace(/\.(exe|cmd|bat|ps1)$/, "");
44
+ return BY_EXE.get(n.split(/[\\/]/).pop() ?? n);
45
+ }
46
+ /**
47
+ * npm packages whose `bin` is an agent CLI (checked against the npm registry 2026-11-25), so a
48
+ * package runner (`npx @openai/codex --yolo`) is analyzed like the CLI itself.
49
+ */
50
+ export const AGENT_PACKAGES = {
51
+ "@anthropic-ai/claude-code": "claude",
52
+ "@openai/codex": "codex",
53
+ "@google/gemini-cli": "gemini",
54
+ "opencode-ai": "opencode",
55
+ "@qwen-code/qwen-code": "qwen",
56
+ "@github/copilot": "copilot",
57
+ "@sourcegraph/amp": "amp",
58
+ "@charmland/crush": "crush",
59
+ cline: "cline",
60
+ };
61
+ /** The CLI a package spec (`@openai/codex@1.2.3`, `opencode-ai@latest`) provides, if it is an agent. */
62
+ export function agentPackageBin(spec) {
63
+ const s = spec.toLowerCase();
64
+ const at = s.indexOf("@", s.startsWith("@") ? 1 : 0);
65
+ const name = at > 0 ? s.slice(0, at) : s;
66
+ return Object.hasOwn(AGENT_PACKAGES, name) ? AGENT_PACKAGES[name] : undefined;
67
+ }
68
+ const matches = (v, flag) => v === flag || v.startsWith(flag + "=");
69
+ /**
70
+ * Analyze one agent CLI call. `vals` are the argument values (null = not known statically);
71
+ * `env` maps environment variables set for this command to their value (null = not literal).
72
+ */
73
+ export function agentCliCommand(a, vals, env, acc) {
74
+ const why = `starts ${a.tool} with approvals or its sandbox turned off`;
75
+ for (const [name, value] of env) {
76
+ if (a.denyEnv.includes(name)) {
77
+ acc.protect("CP-SELF-003", `starts ${a.tool} with a different configuration (${name})`);
78
+ return;
79
+ }
80
+ const bad = a.denyEnvValues[name];
81
+ if (bad && (value === null || bad.includes(value.toLowerCase()))) {
82
+ acc.protect("CP-SELF-003", `${why} (${name})`);
83
+ return;
84
+ }
85
+ }
86
+ for (let i = 0; i < vals.length; i++) {
87
+ const v = vals[i];
88
+ if (v === null || v === undefined)
89
+ continue;
90
+ if (a.deny.some((f) => matches(v, f))) {
91
+ acc.protect("CP-SELF-003", `${why} (${v.split("=")[0]})`);
92
+ return;
93
+ }
94
+ for (const vf of a.denyValues) {
95
+ for (const f of vf.flags) {
96
+ let value;
97
+ if (v === f)
98
+ value = vals[i + 1];
99
+ else if (v.startsWith(f + "="))
100
+ value = v.slice(f.length + 1);
101
+ else if (f.length === 2 && v.startsWith(f) && v.length > 2)
102
+ value = v.slice(2); // clap-style -anever
103
+ else
104
+ continue;
105
+ if (value === null || value === undefined) {
106
+ acc.unanalyzable(`${a.tool}: ${f} with a value that isn't known statically`);
107
+ return;
108
+ }
109
+ const val = value.replace(/^["']|["']$/g, "").toLowerCase();
110
+ const hit = vf.keys ? vf.keys.some((k) => val.startsWith(k + "=") || val.startsWith(k + ".") || val === k) : vf.values === "any" || vf.values.includes(val);
111
+ if (hit) {
112
+ acc.protect("CP-SELF-003", `${why} (${f} ${val.slice(0, 40)})`);
113
+ return;
114
+ }
115
+ }
116
+ }
117
+ }
118
+ // An argument that isn't known statically could be one of the flags above.
119
+ if (vals.some((v) => v === null)) {
120
+ acc.unanalyzable(`${a.tool} with arguments that aren't known statically`);
121
+ return;
122
+ }
123
+ if (vals.length === 1 && ["--help", "-h", "--version", "-v", "-V"].includes(vals[0] ?? ""))
124
+ return;
125
+ acc.tag("high-risk", "exec.nested-agent");
126
+ acc.reason(`starts a nested agent (${a.tool})`);
127
+ }
128
+ // ── Their configuration and instruction files (agent config) ────────────
129
+ const USER_DIRS = [".codex", ".gemini", ".cursor", ".config/opencode", ".config/goose", "appdata/roaming/block/goose", ".config/amp", ".qwen", ".config/crush", ".copilot", ".kiro"];
130
+ const USER_FILES = [".aider.conf.yml"];
131
+ const SYSTEM_DIRS = ["/etc/gemini-cli", "/library/application support/geminicli", "c:/programdata/gemini-cli", "c:/programdata/opencode", "c:/programdata/ampcode"];
132
+ const PROJECT_DIRS = [".codex", ".gemini", ".cursor", ".opencode", ".amp", ".qwen"];
133
+ const CLAUDE_FILES = ["claude.md", "claude.local.md"];
134
+ const CLAUDE_DIRS = ["/.claude/agents/", "/.claude/commands/", "/.claude/skills/"];
135
+ const PROJECT_FILES = ["opencode.json", "opencode.jsonc", ".aider.conf.yml", ".goosehints", ".crushrc", "crushrc", "agents.md", "gemini.md", "qwen.md", "crush.md"];
136
+ /**
137
+ * Is this normalized, lower-cased path another agent CLI's configuration or instruction file?
138
+ * `home` and `project` are normalized and lower-cased too (project may be null).
139
+ */
140
+ export function isAgentConfigPath(p, home, project) {
141
+ const under = (dir) => p === dir || p.startsWith(dir + "/");
142
+ // Claude Code's own instruction and extension files, at any level (owner decision 2026-11-25).
143
+ // Its settings files and .mcp.json are self-protected (deny) elsewhere, not here.
144
+ const base = p.slice(p.lastIndexOf("/") + 1);
145
+ if (CLAUDE_FILES.includes(base) || CLAUDE_DIRS.some((d) => p.includes(d)))
146
+ return true;
147
+ if (USER_DIRS.some((d) => under(`${home}/${d}`)) || USER_FILES.some((f) => p === `${home}/${f}`))
148
+ return true;
149
+ if (SYSTEM_DIRS.some((d) => under(d)))
150
+ return true;
151
+ if (project !== null && under(project)) {
152
+ const rel = p.slice(project.length + 1);
153
+ const segs = rel.split("/");
154
+ if (segs.some((s, i) => i < segs.length - 1 && PROJECT_DIRS.includes(s)))
155
+ return true;
156
+ if (PROJECT_FILES.includes(segs[segs.length - 1] ?? ""))
157
+ return true;
158
+ }
159
+ return false;
160
+ }
161
+ /** A write (or move or delete) of another agent's config or instruction file: config.agent (a liftable ask). */
162
+ export function agentConfigWrite(np, pctx, acc) {
163
+ if (np === null || np.path === null)
164
+ return;
165
+ const norm = (x) => (x === null ? null : normalizeFull(x, { ...pctx, cwd: null }));
166
+ const lower = (x) => (x === null ? null : (x.endsWith("/") && x.length > 1 ? x.slice(0, -1) : x).toLowerCase());
167
+ const home = lower(norm(pctx.homeDir));
168
+ if (home === null)
169
+ return;
170
+ if (isAgentConfigPath(np.path.toLowerCase(), home, lower(norm(pctx.cwd)))) {
171
+ acc.tag("high-risk", "config.agent");
172
+ acc.reason("writes another agent's configuration or instructions");
173
+ }
174
+ }
175
+ //# sourceMappingURL=agent-clis.js.map
@@ -0,0 +1,5 @@
1
+ import type { BuiltinToolCategory } from "../types.js";
2
+ export declare const BUILTIN_TOOLS: Readonly<Record<string, BuiltinToolCategory>>;
3
+ /** Category of a built-in tool, matched case-insensitively; undefined if unknown. */
4
+ export declare function builtinCategory(name: string): BuiltinToolCategory | undefined;
5
+ //# sourceMappingURL=builtin-tools.d.ts.map
@@ -0,0 +1,74 @@
1
+ export const BUILTIN_TOOLS = Object.freeze({
2
+ // Runs commands: full shell analysis.
3
+ Bash: "command",
4
+ PowerShell: "command",
5
+ Monitor: "command",
6
+ // Writes files.
7
+ Edit: "write",
8
+ Write: "write",
9
+ NotebookEdit: "write",
10
+ EnterWorktree: "write",
11
+ ExitWorktree: "write",
12
+ // Network: sends data off the machine.
13
+ WebFetch: "network",
14
+ WebSearch: "network",
15
+ Artifact: "network",
16
+ ShareOnboardingGuide: "network",
17
+ // Spawns agents or schedules agent work. Their tool calls are checked on their own.
18
+ Agent: "agent",
19
+ Workflow: "agent",
20
+ Skill: "agent",
21
+ SendMessage: "agent",
22
+ CronCreate: "agent",
23
+ ScheduleWakeup: "agent",
24
+ RemoteTrigger: "agent",
25
+ // Reads only.
26
+ Read: "read",
27
+ Glob: "read",
28
+ Grep: "read",
29
+ LSP: "read",
30
+ ListMcpResourcesTool: "read",
31
+ ReadMcpResourceTool: "read",
32
+ ToolSearch: "read",
33
+ TaskGet: "read",
34
+ TaskList: "read",
35
+ CronList: "read",
36
+ ListAgents: "read",
37
+ ListPlugins: "read",
38
+ ListSkills: "read",
39
+ SearchPlugins: "read",
40
+ SearchSkills: "read",
41
+ WaitForMcpServers: "read",
42
+ // Other: conversation, planning, task list and notification tools that act only inside the session.
43
+ AskUserQuestion: "other",
44
+ EndConversation: "other",
45
+ EnterPlanMode: "other",
46
+ ExitPlanMode: "other",
47
+ propose_skills: "other",
48
+ PushNotification: "other",
49
+ ReportFindings: "other",
50
+ SendFeedback: "other",
51
+ SendUserFile: "other",
52
+ SubagentHandback: "other",
53
+ SuggestPluginInstall: "other",
54
+ SuggestSkills: "other",
55
+ TaskCreate: "other",
56
+ TaskStop: "other",
57
+ TaskUpdate: "other",
58
+ TodoWrite: "other",
59
+ CronDelete: "other",
60
+ // Older names still accepted from earlier Claude Code versions.
61
+ Task: "agent",
62
+ MultiEdit: "write",
63
+ LS: "read",
64
+ NotebookRead: "read",
65
+ TodoRead: "other",
66
+ BashOutput: "read",
67
+ TaskOutput: "read",
68
+ });
69
+ const LOWER = new Map(Object.entries(BUILTIN_TOOLS).map(([k, v]) => [k.toLowerCase(), v]));
70
+ /** Category of a built-in tool, matched case-insensitively; undefined if unknown. */
71
+ export function builtinCategory(name) {
72
+ return LOWER.get(name.toLowerCase());
73
+ }
74
+ //# sourceMappingURL=builtin-tools.js.map
@@ -1,6 +1,6 @@
1
- // Interpreter inline code (engine-spec §7.3 interpreter row, Q6 rev 4).
1
+ // Interpreter inline code.
2
2
  // A token heuristic: obfuscation markers → unanalyzable; dangerous tokens → high-risk;
3
- // otherwise write-reversible. Bypassable by design (threat-model §7 #13).
3
+ // otherwise write-reversible. Bypassable by design.
4
4
  import { test } from "../util/re.js";
5
5
  const MARKERS = [
6
6
  ["__import__", "__import__"],
@@ -1,4 +1,4 @@
1
- // Path normalization and the protected / protected-read / sensitive sets (engine-spec §7.2, §7.6).
1
+ // Path normalization and the protected / protected-read / sensitive sets.
2
2
  // Purely lexical: the engine can't see the filesystem.
3
3
  import { trimEndChars } from "../util/misc.js";
4
4
  import { JOB_LABEL } from "./schedule.js";
@@ -1,11 +1,12 @@
1
- // PowerShell analysis (engine-spec §7.4, rev 3/4): hand-written tokenizer, alias table,
2
- // cmdlet classes; native programs go through the §7.3 command table.
1
+ // PowerShell analysis: hand-written tokenizer, alias table,
2
+ // cmdlet classes; native programs go through the shell command table.
3
3
  import { Acc } from "./acc.js";
4
4
  import { homeTopLevel, isProtected, isProtectedRead, normalizePath, persistenceHit, sensitiveLabel } from "./paths.js";
5
5
  import { isProtectedWrite } from "./protected-write.js";
6
+ import { agentConfigWrite } from "./agent-clis.js";
6
7
  import { classifyNative } from "./shell/analyze.js";
7
8
  import { allLoopback, classifyUpload, recordUpload } from "./upload.js";
8
- import { commandFiles } from "./schedule.js";
9
+ import { commandFiles, isRunKey } from "./schedule.js";
9
10
  import { litWord } from "./shell/parse.js";
10
11
  class PsUnanalyzable extends Error {
11
12
  reason;
@@ -684,6 +685,10 @@ function analyzeElement(el, st, acc, cwd, upstream = null) {
684
685
  }
685
686
  acc.tag("high-risk", "config.agent");
686
687
  acc.reason("changes the Windows registry");
688
+ // Run / RunOnce keys start programs at every login (rev 11): a scheduled job (CP-SELF-006).
689
+ if (pathTargets().some((t) => isRunKey(tokText(t).pathValue ?? ""))) {
690
+ acc.scheduleJob({ kind: "autostart", verb: cmdlet.startsWith("remove") ? "removes" : "changes", path: null, schedule: "at login (registry Run key)", files: [] });
691
+ }
687
692
  return;
688
693
  }
689
694
  if (cmdlet === "remove-item" || cmdlet === "clear-content" || cmdlet === "clear-item") {
@@ -775,6 +780,7 @@ function analyzeElement(el, st, acc, cwd, upstream = null) {
775
780
  acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
776
781
  acc.persist(persistenceHit(p, pctx), "changes", p.path);
777
782
  acc.wrote(p.path);
783
+ agentConfigWrite(p, pctx, acc);
778
784
  const lp = (p.path ?? "").toLowerCase();
779
785
  if (lp.endsWith("profile.ps1") || lp.includes("/.git/hooks/"))
780
786
  acc.tag("high-risk", "config.agent");
@@ -813,7 +819,7 @@ function analyzeElement(el, st, acc, cwd, upstream = null) {
813
819
  if (!loop) {
814
820
  for (const f of files) {
815
821
  const p = f === null ? null : np({ k: "word", v: f, dyn: false }, pctx);
816
- recordUpload(acc, classifyUpload(p, pctx, st.pctx.cwd), f ?? "a file named at run time");
822
+ recordUpload(acc, classifyUpload(p, pctx, st.pctx.cwd, f), f ?? "a file named at run time");
817
823
  }
818
824
  }
819
825
  return;
@@ -1,4 +1,11 @@
1
1
  export type JobKind = "cron" | "systemd" | "at" | "launchd" | "autostart" | "startup-folder" | "task-scheduler" | "service" | "boot-script";
2
+ /**
3
+ * Windows registry keys that start a program at login (rev 11): ...\CurrentVersion\Run, RunOnce,
4
+ * RunOnceEx, RunServices[Once], in HKCU/HKLM and the 32-bit view (WOW6432Node), and the Explorer
5
+ * policy Run key. Compared with separators, quotes and spaces removed, case-insensitively; any
6
+ * key whose name starts with "Run" right under CurrentVersion counts (conservative: ask).
7
+ */
8
+ export declare function isRunKey(text: string): boolean;
2
9
  export interface ScheduledJob {
3
10
  kind: JobKind;
4
11
  verb: "creates" | "changes" | "removes";
@@ -3,6 +3,16 @@
3
3
  // (CP-SELF-006, deny in autopilot) and the ask shows the schedule and the full command. The
4
4
  // files a job runs are recorded as a session signal; later agent edits, moves or deletes of
5
5
  // those files ask too (CP-SELF-007). String code only: no regex with nested quantifiers.
6
+ /**
7
+ * Windows registry keys that start a program at login (rev 11): ...\CurrentVersion\Run, RunOnce,
8
+ * RunOnceEx, RunServices[Once], in HKCU/HKLM and the 32-bit view (WOW6432Node), and the Explorer
9
+ * policy Run key. Compared with separators, quotes and spaces removed, case-insensitively; any
10
+ * key whose name starts with "Run" right under CurrentVersion counts (conservative: ask).
11
+ */
12
+ export function isRunKey(text) {
13
+ const s = text.toLowerCase().replace(/[\\/"'\s`]/g, "");
14
+ return /microsoftwindowscurrentversion(policiesexplorer)?run/.test(s);
15
+ }
6
16
  export const JOB_LABEL = {
7
17
  cron: "cron job",
8
18
  systemd: "systemd unit or timer",
@@ -1,12 +1,13 @@
1
- // Shell classification (engine-spec §7.3, Q5/Q6 rev 4) over the parsed AST.
1
+ // Shell classification over the parsed AST.
2
2
  import { Acc } from "../acc.js";
3
3
  import { allLoopback, classifyUpload, recordUpload } from "../upload.js";
4
- import { commandFiles, schtasksJob } from "../schedule.js";
4
+ import { commandFiles, isRunKey, schtasksJob } from "../schedule.js";
5
5
  import { trimEndChars } from "../../util/misc.js";
6
6
  import { analyzeInlineCode } from "../inline.js";
7
7
  import { coversProtectedRead, homeTopLevel, isProtected, isProtectedRead, normalizePath, persistenceHit, sensitiveLabel, suffixOnly, } from "../paths.js";
8
8
  import { analyzeSql } from "../sql.js";
9
9
  import { isProtectedWrite } from "../protected-write.js";
10
+ import { agentCliCommand, agentCliFor, agentConfigWrite, agentPackageBin } from "../agent-clis.js";
10
11
  import { parseShell, Unanalyzable } from "./parse.js";
11
12
  export function wordInfo(w) {
12
13
  let value = "";
@@ -277,6 +278,7 @@ function writeTarget(np, acc, pctx, isGlob = false) {
277
278
  acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
278
279
  acc.persist(persistenceHit(np, pctx), "changes", np.path);
279
280
  acc.wrote(np.path);
281
+ agentConfigWrite(np, pctx, acc);
280
282
  const p = (np.path ?? np.suffix ?? "").toLowerCase();
281
283
  const home = trimEndChars(pctx.homeDir.replace(/\\/g, "/"), "/").toLowerCase();
282
284
  const homeFiles = [".bashrc", ".zshrc", ".profile", ".bash_profile", ".bash_login", ".zprofile", ".zshenv", ".zlogin", ".config/fish/config.fish", ".ssh/rc", ".inputrc"];
@@ -560,14 +562,15 @@ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, un
560
562
  }
561
563
  // ── Self-protection commands ───────────────────────────────────────────
562
564
  if (lower === "glassbox" || lower === "glassbox.exe") {
563
- const sub = operands(args)[0]?.value ?? "";
564
- const mutating = ["mode", "allow", "uninstall", "logout", "login", "install", "pair", "unpair", "config", "set", "disable", "enable", "reset"].includes(sub) || (sub === "doctor" && hasFlag(args, "--fix"));
565
- if (mutating || args.some((a) => a.value === null))
566
- acc.protect("CP-SELF-003", "changes Glassbox protection settings");
565
+ glassboxCli(args, acc);
567
566
  return;
568
567
  }
569
568
  if (lower === "claude" || lower === "claude.exe")
570
569
  return claudeCommand(args, c);
570
+ // Other agent CLIs (rev 11, §7.10): nested agents; approval/sandbox-off flags are denied.
571
+ const agentCli = agentCliFor(lower);
572
+ if (agentCli)
573
+ return agentCliCommand(agentCli, args.map((a) => a.value), envOf(c.cmd), acc);
571
574
  if (lower === "reg" || lower === "reg.exe") {
572
575
  const flat = args.map((a) => (a.value ?? a.word.raw)).join(" ").toLowerCase().replace(/[\\/"']/g, "");
573
576
  if (flat.includes("policiesclaudecode")) {
@@ -575,8 +578,15 @@ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, un
575
578
  return;
576
579
  }
577
580
  const sub = (args[0]?.value ?? "").toLowerCase();
578
- if (["add", "delete", "import", "restore", "load", "copy"].includes(sub))
581
+ if (["add", "delete", "import", "restore", "load", "copy"].includes(sub)) {
579
582
  acc.tag("high-risk", "config.agent");
583
+ // Run / RunOnce keys start programs at every login (rev 11): a scheduled job (CP-SELF-006).
584
+ if (isRunKey(flat))
585
+ acc.scheduleJob({ kind: "autostart", verb: sub === "delete" ? "removes" : "changes", path: null, schedule: "at login (registry Run key)", files: [] });
586
+ // import/restore/load take a file whose keys aren't visible: they may write a Run key.
587
+ if (["import", "restore", "load"].includes(sub))
588
+ acc.reason("loads registry keys from a file");
589
+ }
580
590
  return;
581
591
  }
582
592
  // ── Shells and interpreters ────────────────────────────────────────────
@@ -790,6 +800,13 @@ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, un
790
800
  }
791
801
  }
792
802
  }
803
+ /** Environment variables set for this command (`VAR=value cmd`), with literal values (null = not literal). */
804
+ function envOf(cmd) {
805
+ const m = new Map();
806
+ for (const a of cmd.assigns)
807
+ m.set(a.name, a.value ? wordInfo(a.value).value : "");
808
+ return m;
809
+ }
793
810
  function claudeCommand(args, c) {
794
811
  const { acc } = c;
795
812
  const vals = args.map((a) => a.value);
@@ -828,9 +845,9 @@ function claudeCommand(args, c) {
828
845
  }
829
846
  if (args.length === 1 && ["--version", "-v", "--help", "-h"].includes(vals[0] ?? ""))
830
847
  return;
848
+ // An argument that isn't known statically could be --dangerously-skip-permissions (rev 11).
831
849
  if (vals.some((v) => v === null)) {
832
- acc.tag("high-risk", "exec.nested-agent");
833
- acc.reason("starts a nested agent");
850
+ acc.unanalyzable("claude with arguments that aren't known statically");
834
851
  return;
835
852
  }
836
853
  acc.tag("high-risk", "exec.nested-agent");
@@ -912,6 +929,13 @@ function interpreter(lower, args, c) {
912
929
  return;
913
930
  }
914
931
  }
932
+ // An interpreter running the Glassbox CLI script directly (node …/glassbox/dist/cli.js allow …).
933
+ const gbScript = args.findIndex((a) => a.value !== null && !a.value.startsWith("-") && a.value.toLowerCase().includes("glassbox"));
934
+ if (gbScript >= 0) {
935
+ glassboxCli(args.slice(gbScript + 1), acc);
936
+ if (acc.selfProtection)
937
+ return;
938
+ }
915
939
  const hereStr = cmd.redirects.find((r) => r.op === "<<<")?.target;
916
940
  const body = cmd.redirects.find((r) => r.heredoc)?.heredoc?.body ?? (hereStr ? wordInfo(hereStr).value ?? "" : "");
917
941
  if (body && protectedText(body, pctx)) {
@@ -927,7 +951,7 @@ function interpreter(lower, args, c) {
927
951
  acc.unanalyzable("inline code isn't a literal string");
928
952
  return;
929
953
  }
930
- // Protected paths inside the code → self-protection (spec §7.6.2).
954
+ // Protected paths inside the code → self-protection.
931
955
  if (protectedText(code.value, pctx)) {
932
956
  const lowerCode = code.value.toLowerCase();
933
957
  acc.protect(lowerCode.includes(".key") || lowerCode.includes("device") ? "CP-SELF-002" : "CP-SELF-001", "inline code refers to a protected agent or Glassbox file");
@@ -1008,6 +1032,17 @@ function protectedText(text, pctx) {
1008
1032
  needles.push(norm(sp));
1009
1033
  return needles.some((n) => n.length > 0 && t.includes(n));
1010
1034
  }
1035
+ /**
1036
+ * The Glassbox CLI: subcommands that change protection are self-protection (the agent may
1037
+ * never run them, however it launches the CLI). A non-literal argument counts as changing.
1038
+ */
1039
+ const GLASSBOX_MUTATING = new Set(["mode", "allow", "uninstall", "logout", "login", "install", "pair", "unpair", "config", "set", "disable", "enable", "reset", "deny", "forget", "revoke"]);
1040
+ function glassboxCli(args, acc) {
1041
+ const sub = (operands(args)[0]?.value ?? "").toLowerCase();
1042
+ const mutating = GLASSBOX_MUTATING.has(sub) || (sub === "doctor" && hasFlag(args, "--fix"));
1043
+ if (mutating || args.some((a) => a.value === null))
1044
+ acc.protect("CP-SELF-003", "changes Glassbox protection settings");
1045
+ }
1011
1046
  function projectTool(rest, c, unwrapDepth) {
1012
1047
  const h = rest[0];
1013
1048
  if (!h || h.value === null) {
@@ -1015,6 +1050,20 @@ function projectTool(rest, c, unwrapDepth) {
1015
1050
  return;
1016
1051
  }
1017
1052
  const n = (() => { const v = h.value; const slash = v.lastIndexOf("/"); const at = v.indexOf("@", slash + 1); return (at >= 0 ? v.slice(0, at) : v).split("/").pop() ?? ""; })();
1053
+ // A package runner launching the Glassbox CLI (npx glassbox allow …, pnpm dlx @glassbox-ai/…).
1054
+ if (h.value.toLowerCase().includes("glassbox")) {
1055
+ glassboxCli(rest.slice(1), c.acc);
1056
+ return;
1057
+ }
1058
+ // A package runner starting an agent CLI (npx @openai/codex --yolo, npx @anthropic-ai/claude-code …).
1059
+ const agentBin = agentPackageBin(h.value) ?? (agentCliFor(h.value) ? h.value : undefined);
1060
+ if (agentBin === "claude" || h.value.toLowerCase() === "claude")
1061
+ return claudeCommand(rest.slice(1), c);
1062
+ const agentCli = agentBin !== undefined ? agentCliFor(agentBin) : undefined;
1063
+ if (agentCli) {
1064
+ agentCliCommand(agentCli, rest.slice(1).map((a) => a.value), envOf(c.cmd), c.acc);
1065
+ return;
1066
+ }
1018
1067
  if (PROJECT.has(n) || READ.has(n)) {
1019
1068
  c.acc.tag("write-reversible", "exec.project-code");
1020
1069
  return;
@@ -1368,7 +1417,8 @@ function uploadFile(file, c, loop) {
1368
1417
  return;
1369
1418
  const np = typeof file === "string" ? normalizePath(file, c.pctx) : npOf(file, c.pctx);
1370
1419
  const label = typeof file === "string" ? file : (file.pathValue ?? file.suffix ?? "?");
1371
- recordUpload(c.acc, classifyUpload(np, c.pctx, c.st.pctx.cwd), label.slice(0, 80));
1420
+ const raw = typeof file === "string" ? file : file.pathValue;
1421
+ recordUpload(c.acc, classifyUpload(np, c.pctx, c.st.pctx.cwd, raw), label.slice(0, 80));
1372
1422
  }
1373
1423
  function network(lower, args, c) {
1374
1424
  const { acc, pctx } = c;
@@ -1918,9 +1968,16 @@ function gh(args, c) {
1918
1968
  acc.network = true;
1919
1969
  const vals = args.map((a) => a.value ?? "");
1920
1970
  const [a, b] = operands(args, new Set(["-R", "--repo", "-t", "--title", "-b", "--body", "-F", "--body-file", "-m", "--milestone", "-l", "--label", "-a", "--assignee", "-B", "--base", "-H", "--head", "-L", "--limit", "-q", "--jq", "--json", "-r", "--reviewer", "-n", "--notes"])).map((x) => x.value ?? "");
1921
- const publish = (a === "pr" && ["create", "comment", "merge", "review", "close", "reopen", "edit", "ready"].includes(b ?? "")) ||
1922
- (a === "issue" && ["create", "comment", "close", "reopen", "edit", "delete", "transfer", "lock"].includes(b ?? "")) ||
1923
- (a === "release" && ["create", "upload", "edit", "delete"].includes(b ?? "")) ||
1971
+ // Pull requests and issues are conversations with the repo's collaborators: message.send
1972
+ // (asks by default; can be remembered). Releases, gists, repos, secrets and workflows publish
1973
+ // or change what others get: publish.public (hard floor).
1974
+ const message = (a === "pr" && ["create", "comment", "merge", "review", "close", "reopen", "edit", "ready"].includes(b ?? "")) ||
1975
+ (a === "issue" && ["create", "comment", "close", "reopen", "edit", "delete", "transfer", "lock"].includes(b ?? ""));
1976
+ if (message) {
1977
+ acc.tags.add("message.send");
1978
+ acc.reason("posts or changes a pull request or issue on GitHub");
1979
+ }
1980
+ const publish = (a === "release" && ["create", "upload", "edit", "delete"].includes(b ?? "")) ||
1924
1981
  (a === "gist" && ["create", "edit", "delete"].includes(b ?? "")) ||
1925
1982
  (a === "repo" && ["create", "delete", "edit", "rename", "archive", "fork"].includes(b ?? "")) ||
1926
1983
  (a === "secret" && ["set", "delete"].includes(b ?? "")) || (a === "variable" && ["set", "delete"].includes(b ?? "")) ||
@@ -1970,7 +2027,10 @@ function jsPm(lower, args, c) {
1970
2027
  }
1971
2028
  if (["dlx", "x", "exec", "create"].includes(sub)) {
1972
2029
  acc.tags.add("net.fetch.package-manager");
1973
- return projectTool(ops.slice(1), c, 0);
2030
+ // Pass everything after the package, flags included (pnpm dlx @openai/codex --yolo): operands alone drop them.
2031
+ const pkg = ops[1];
2032
+ const at = pkg === undefined ? -1 : args.indexOf(pkg);
2033
+ return projectTool(at >= 0 ? args.slice(at) : ops.slice(1), c, 0);
1974
2034
  }
1975
2035
  acc.tag("write-reversible", "exec.project-code");
1976
2036
  }
@@ -1,4 +1,4 @@
1
- // Hand-written bash/sh parser (engine-spec §7.3, Q2). Recursive descent over a defined
1
+ // Hand-written bash/sh parser. Recursive descent over a defined
2
2
  // subset, bounded (bytes, nesting, tokens). Anything outside the subset → unanalyzable.
3
3
  export const MAX_NESTING = 8;
4
4
  export const MAX_TOKENS = 4096;
@@ -1,4 +1,4 @@
1
- // T-DIFF support (engine-spec §13): the parser's view of which commands a shell string
1
+ // T-DIFF support: the parser's view of which commands a shell string
2
2
  // runs, as argv lists. Unknown words are null (they match zero or more real words).
3
3
  import { analyzeShellCommand, wordInfo } from "./analyze.js";
4
4
  import { parseShell } from "./parse.js";
@@ -1,4 +1,4 @@
1
- // SQL tokenizer and classifier (engine-spec §7.5). Linear, no regex on input.
1
+ // SQL tokenizer and classifier. Linear, no regex on input.
2
2
  import { Acc } from "./acc.js";
3
3
  function tokenize(sql) {
4
4
  const stmts = [[]];