@glassbox-ai/engine 0.1.1 → 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.
@@ -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
@@ -3,9 +3,10 @@
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
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"];
@@ -565,6 +567,10 @@ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, un
565
567
  }
566
568
  if (lower === "claude" || lower === "claude.exe")
567
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);
568
574
  if (lower === "reg" || lower === "reg.exe") {
569
575
  const flat = args.map((a) => (a.value ?? a.word.raw)).join(" ").toLowerCase().replace(/[\\/"']/g, "");
570
576
  if (flat.includes("policiesclaudecode")) {
@@ -572,8 +578,15 @@ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, un
572
578
  return;
573
579
  }
574
580
  const sub = (args[0]?.value ?? "").toLowerCase();
575
- if (["add", "delete", "import", "restore", "load", "copy"].includes(sub))
581
+ if (["add", "delete", "import", "restore", "load", "copy"].includes(sub)) {
576
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
+ }
577
590
  return;
578
591
  }
579
592
  // ── Shells and interpreters ────────────────────────────────────────────
@@ -787,6 +800,13 @@ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, un
787
800
  }
788
801
  }
789
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
+ }
790
810
  function claudeCommand(args, c) {
791
811
  const { acc } = c;
792
812
  const vals = args.map((a) => a.value);
@@ -825,9 +845,9 @@ function claudeCommand(args, c) {
825
845
  }
826
846
  if (args.length === 1 && ["--version", "-v", "--help", "-h"].includes(vals[0] ?? ""))
827
847
  return;
848
+ // An argument that isn't known statically could be --dangerously-skip-permissions (rev 11).
828
849
  if (vals.some((v) => v === null)) {
829
- acc.tag("high-risk", "exec.nested-agent");
830
- acc.reason("starts a nested agent");
850
+ acc.unanalyzable("claude with arguments that aren't known statically");
831
851
  return;
832
852
  }
833
853
  acc.tag("high-risk", "exec.nested-agent");
@@ -1035,6 +1055,15 @@ function projectTool(rest, c, unwrapDepth) {
1035
1055
  glassboxCli(rest.slice(1), c.acc);
1036
1056
  return;
1037
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
+ }
1038
1067
  if (PROJECT.has(n) || READ.has(n)) {
1039
1068
  c.acc.tag("write-reversible", "exec.project-code");
1040
1069
  return;
@@ -1388,7 +1417,8 @@ function uploadFile(file, c, loop) {
1388
1417
  return;
1389
1418
  const np = typeof file === "string" ? normalizePath(file, c.pctx) : npOf(file, c.pctx);
1390
1419
  const label = typeof file === "string" ? file : (file.pathValue ?? file.suffix ?? "?");
1391
- 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));
1392
1422
  }
1393
1423
  function network(lower, args, c) {
1394
1424
  const { acc, pctx } = c;
@@ -1997,7 +2027,10 @@ function jsPm(lower, args, c) {
1997
2027
  }
1998
2028
  if (["dlx", "x", "exec", "create"].includes(sub)) {
1999
2029
  acc.tags.add("net.fetch.package-manager");
2000
- 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);
2001
2034
  }
2002
2035
  acc.tag("write-reversible", "exec.project-code");
2003
2036
  }
@@ -4,6 +4,7 @@ import { coversProtectedRead, globCoversProtectedRead, isProtected, isProtectedR
4
4
  import { builtinCategory } from "./builtin-tools.js";
5
5
  import { analyzePowerShell } from "./powershell.js";
6
6
  import { isProtectedWrite } from "./protected-write.js";
7
+ import { agentConfigWrite } from "./agent-clis.js";
7
8
  import { analyzeShellCommand } from "./shell/analyze.js";
8
9
  import { analyzeSql } from "./sql.js";
9
10
  const READ_TOOLS = new Set(["read", "glob", "grep", "ls", "lsp", "websearch", "todowrite", "todoread", "askuserquestion", "exitplanmode", "notebookread", "bashoutput", "taskoutput", "listmcpresourcestool", "readmcpresourcetool", "toolsearch"]);
@@ -14,6 +15,7 @@ export function writePath(path, acc, t) {
14
15
  acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
15
16
  acc.persist(persistenceHit(np, t.pctx), "changes", np.path);
16
17
  acc.wrote(np.path);
18
+ agentConfigWrite(np, t.pctx, acc);
17
19
  const p = (np.path ?? np.suffix ?? "").toLowerCase();
18
20
  if (p.includes("/.git/hooks/") || p.endsWith("/.git/config") || p.includes("/.husky/") || p.endsWith("/.envrc") || p.endsWith("/.bashrc") || p.endsWith("/.zshrc") || p.endsWith("/.profile") || p.endsWith("/.bash_profile") || p.endsWith("/.pre-commit-config.yaml") || p.endsWith("profile.ps1") || p.includes("/library/launchagents/") || p.includes("/.config/systemd/user/")) {
19
21
  acc.tag("high-risk", "config.agent");
@@ -10,8 +10,12 @@ export declare function isLoopbackHost(host: string): boolean;
10
10
  export declare function hostOf(v: string): string | null;
11
11
  /** Destinations are known and all on this machine. */
12
12
  export declare function allLoopback(destinations: readonly (string | null)[]): boolean;
13
- /** Classifies an uploaded file. `projectDir` is the session's project directory. */
14
- export declare function classifyUpload(np: NormPath | null, pctx: PathCtx, projectDir: string | null): UploadKind;
13
+ /**
14
+ * Classifies an uploaded file. `projectDir` is the session's project directory (raw, as the
15
+ * caller gave it); `raw` is the file argument as written. Since 0.1.2 the project directory is
16
+ * normalized like the file path (before, on Windows every upload counted as "outside").
17
+ */
18
+ export declare function classifyUpload(np: NormPath | null, pctx: PathCtx, projectDir: string | null, raw?: string | null): UploadKind;
15
19
  /** Records one uploaded file (the caller has checked the destination isn't loopback). */
16
20
  export declare function recordUpload(acc: Acc, kind: UploadKind, what: string): void;
17
21
  //# sourceMappingURL=upload.d.ts.map
@@ -1,4 +1,4 @@
1
- import { isProtectedRead, sensitiveLabel } from "./paths.js";
1
+ import { isProtectedRead, normalizeFull, normalizePath, sensitiveLabel } from "./paths.js";
2
2
  /** True for loopback host names and addresses. */
3
3
  export function isLoopbackHost(host) {
4
4
  const h = host.toLowerCase().replace(/^\[|\]$/g, "");
@@ -39,8 +39,20 @@ export function allLoopback(destinations) {
39
39
  return false;
40
40
  return destinations.every((d) => d !== null && (() => { const h = hostOf(d); return h !== null && isLoopbackHost(h); })());
41
41
  }
42
- /** Classifies an uploaded file. `projectDir` is the session's project directory. */
43
- export function classifyUpload(np, pctx, projectDir) {
42
+ /**
43
+ * Windows paths whose meaning differs from their lexical form: UNC shares (also \\localhost\C$),
44
+ * and the \\?\ (literal: ".." is not collapsed) and \\.\ (device) namespaces. An upload from
45
+ * such a path is never shown to be a project file.
46
+ */
47
+ const WIN_SPECIAL_PREFIX = /^[\\/]{2}/;
48
+ /** `C:notes.txt` is relative to drive C's own current directory, not to the project. */
49
+ const WIN_DRIVE_RELATIVE = /^[A-Za-z]:(?![\\/])/;
50
+ /**
51
+ * Classifies an uploaded file. `projectDir` is the session's project directory (raw, as the
52
+ * caller gave it); `raw` is the file argument as written. Since 0.1.2 the project directory is
53
+ * normalized like the file path (before, on Windows every upload counted as "outside").
54
+ */
55
+ export function classifyUpload(np, pctx, projectDir, raw) {
44
56
  if (np === null || np.path === null) {
45
57
  if (np !== null && sensitiveLabel(np, pctx))
46
58
  return "sensitive";
@@ -48,12 +60,25 @@ export function classifyUpload(np, pctx, projectDir) {
48
60
  }
49
61
  if (isProtectedRead(np, pctx) || sensitiveLabel(np, pctx))
50
62
  return "sensitive";
63
+ // Where the path really leads, when the caller resolved it (junctions, symlinks).
64
+ const resolved = pctx.resolved?.[np.path];
65
+ const real = resolved === undefined ? null : normalizePath(resolved, { ...pctx, cwd: null, resolved: undefined });
66
+ if (real !== null && real.path !== null && (isProtectedRead(real, pctx) || sensitiveLabel(real, pctx)))
67
+ return "sensitive";
51
68
  if (projectDir === null)
52
69
  return "outside";
53
- const fold = (s) => (pctx.caseInsensitive ? s.toLowerCase() : s);
54
- const root = fold(projectDir.endsWith("/") ? projectDir.slice(0, -1) : projectDir);
55
- const p = fold(np.path);
56
- return p === root || p.startsWith(root + "/") ? "project" : "outside";
70
+ if (pctx.platform === "win32" && typeof raw === "string" && (WIN_SPECIAL_PREFIX.test(raw.trim()) || WIN_DRIVE_RELATIVE.test(raw.trim())))
71
+ return "outside";
72
+ const rootFull = normalizeFull(projectDir, { ...pctx, cwd: null });
73
+ if (rootFull === null)
74
+ return "outside";
75
+ const root = rootFull.length > 1 && rootFull.endsWith("/") ? rootFull.slice(0, -1) : rootFull;
76
+ const inside = (p) => p === root || p.startsWith(root.endsWith("/") ? root : root + "/");
77
+ if (!inside(np.path))
78
+ return "outside";
79
+ if (real !== null && (real.path === null || !inside(real.path)))
80
+ return "outside";
81
+ return "project";
57
82
  }
58
83
  /** Records one uploaded file (the caller has checked the destination isn't loopback). */
59
84
  export function recordUpload(acc, kind, what) {
@@ -28,5 +28,12 @@ export interface DecideOutput {
28
28
  }
29
29
  /** Fixed in the engine, not in the ruleset: no ruleset can remove a tag from the hard floor. */
30
30
  export declare const HARD_FLOOR_TAGS: readonly ActionTag[];
31
+ /**
32
+ * Persistence outside the project (rev 11, engine 0.1.2): startup files and profiles
33
+ * (CP-SELF-005) and scheduled jobs and autostart, including Windows Run keys (CP-SELF-006).
34
+ * A session grant covering the call may lift these findings; a remembered rule never does, so
35
+ * "Allow & remember" can't silence them for good. Fixed in the engine, like the hard floor.
36
+ */
37
+ export declare const GRANT_LIFTABLE_FINDINGS: readonly string[];
31
38
  export declare function decide(d: DecideInput): DecideOutput;
32
39
  //# sourceMappingURL=decide.d.ts.map
@@ -22,6 +22,20 @@ export const HARD_FLOOR_TAGS = Object.freeze(["vcs.force-push", "vcs.history-rew
22
22
  // and changing anything a caller can reach doesn't change the floor.
23
23
  const HARD_FLOOR = new Set(HARD_FLOOR_TAGS);
24
24
  const str = (x) => typeof x === "string" && x.length > 0;
25
+ /**
26
+ * Persistence outside the project (rev 11, engine 0.1.2): startup files and profiles
27
+ * (CP-SELF-005) and scheduled jobs and autostart, including Windows Run keys (CP-SELF-006).
28
+ * A session grant covering the call may lift these findings; a remembered rule never does, so
29
+ * "Allow & remember" can't silence them for good. Fixed in the engine, like the hard floor.
30
+ */
31
+ export const GRANT_LIFTABLE_FINDINGS = Object.freeze(["CP-SELF-005", "CP-SELF-006"]);
32
+ const GRANT_LIFTABLE = new Set(GRANT_LIFTABLE_FINDINGS);
33
+ /** A session grant (this session only, never a remembered rule) covering (server, tool, tag). */
34
+ function grantCovers(d, tag) {
35
+ const own = (m, k, want) => Object.hasOwn(m, k) && m[k] === want;
36
+ return str(d.sessionId) && d.sessionGrants.some((g) => typeof g === "object" && g !== null &&
37
+ own(g, "serverId", d.serverId) && own(g, "toolName", d.toolName) && own(g, "actionTag", tag) && own(g, "sessionId", d.sessionId));
38
+ }
25
39
  /** A remembered rule (this project) or session grant (this session) covering (server, tool, tag). */
26
40
  function lifted(d, tag) {
27
41
  // Own string properties only: a field inherited through a prototype doesn't count.
@@ -36,6 +50,8 @@ export function decide(d) {
36
50
  const mode = d.policy.mode;
37
51
  let v = "allow";
38
52
  const irreversible = new Set(d.ruleset.irreversibleTags);
53
+ // Set in R3: a session grant covers every liftable tag of this call (used for persistence findings below).
54
+ let grantLiftsPersistence = false;
39
55
  // R3 (calls only): high-risk action, by mode, then tagOverrides, then remembered rules and
40
56
  // session grants (mode-driven asks only, never the hard floor).
41
57
  if (d.kind === "call" && d.risk.level === "high-risk") {
@@ -63,13 +79,19 @@ export function decide(d) {
63
79
  }
64
80
  if (r3 === "ask" && !floorAsk && liftable.length > 0 && liftable.every((t) => lifted(d, t)))
65
81
  r3 = "allow";
82
+ grantLiftsPersistence = !floorAsk && liftable.length > 0 && liftable.every((t) => grantCovers(d, t));
66
83
  v = vmax(v, r3);
67
84
  }
68
- // R4–R7: findings (confidence ≥ threshold).
85
+ // R4–R7: findings (confidence ≥ threshold). Persistence outside the project (high, not
86
+ // critical) is skipped only when a session grant covers the call; every other finding counts.
69
87
  let top = -1;
70
- for (const f of d.findings)
71
- if (f.confidence >= d.minConfidence)
72
- top = Math.max(top, SEV.indexOf(f.severity));
88
+ for (const f of d.findings) {
89
+ if (f.confidence < d.minConfidence)
90
+ continue;
91
+ if (grantLiftsPersistence && f.severity === "high" && GRANT_LIFTABLE.has(f.ruleId))
92
+ continue;
93
+ top = Math.max(top, SEV.indexOf(f.severity));
94
+ }
73
95
  if (top === 2)
74
96
  v = vmax(v, mode === "strict" ? "ask" : "warn");
75
97
  if (top === 3)
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const ENGINE_VERSION = "0.1.1";
1
+ export declare const ENGINE_VERSION = "0.1.2";
2
2
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const ENGINE_VERSION = "0.1.1";
1
+ export const ENGINE_VERSION = "0.1.2";
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glassbox-ai/engine",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Glassbox security engine: pure, deterministic analysis of MCP metadata and agent tool calls.",
5
5
  "keywords": [
6
6
  "mcp",