@noppu-labs/opencode-permission-reviewer 0.0.0-stage → 2.4.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,4422 @@
1
+ #!/usr/bin/env bun
2
+
3
+ // src/cli/explain.ts
4
+ import { parseArgs as parseArgs2 } from "util";
5
+ import { createHash as createHash6 } from "crypto";
6
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
7
+ import { mkdir as mkdir2, open as open2 } from "fs/promises";
8
+ import { dirname as dirname3, join as join4 } from "path";
9
+
10
+ // src/config.ts
11
+ var DEFAULT_RISK_POLICY = {
12
+ allow: {
13
+ low: ["high", "medium", "low", "unknown"],
14
+ medium: ["high", "medium", "low"],
15
+ high: ["high", "medium"],
16
+ critical: []
17
+ },
18
+ minimumConfidence: 0.7,
19
+ onInvalidDecision: "manual",
20
+ onReviewerFailure: "manual"
21
+ };
22
+ var DEFAULT_CONFIG = {
23
+ model: "openai/gpt-6-luna",
24
+ variant: "medium",
25
+ outputFormat: "json_schema",
26
+ timeoutMs: 12e4,
27
+ maxContextChars: 32e3,
28
+ maxPartChars: 8e3,
29
+ maxEnrichmentChars: 24e3,
30
+ maxIntentChars: 8e3,
31
+ transcriptMessages: 12,
32
+ intentMessages: 8,
33
+ historyMessages: 200,
34
+ confidenceThreshold: 0.7,
35
+ systemOneConfidenceThreshold: 0.4,
36
+ systemOneReasoningThreshold: 0.38,
37
+ retainReviewSessions: false,
38
+ audit: true,
39
+ debug: false,
40
+ enforcementMode: "observe",
41
+ escalationMode: "manual",
42
+ maxSessionDepth: 8,
43
+ maxParentSessions: 8,
44
+ actorProfiles: {},
45
+ riskPolicy: DEFAULT_RISK_POLICY,
46
+ repositoryTrust: "unknown",
47
+ policyRules: [],
48
+ askDecisions: true
49
+ };
50
+ function boundedInteger(value, fallback, min, max) {
51
+ if (typeof value !== "number" || !Number.isInteger(value)) return fallback;
52
+ return Math.min(max, Math.max(min, value));
53
+ }
54
+ function boundedNumber(value, fallback, min, max) {
55
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
56
+ return Math.min(max, Math.max(min, value));
57
+ }
58
+ var ACTOR_PROFILES = /* @__PURE__ */ new Set([
59
+ "read-only",
60
+ "validation",
61
+ "workspace",
62
+ "operator",
63
+ "reviewer",
64
+ "unknown"
65
+ ]);
66
+ var ACTION_CLASS_MEMBERS = {
67
+ "read-only": true,
68
+ "workspace-write": true,
69
+ "temporary-write": true,
70
+ "external-write": true,
71
+ destruction: true,
72
+ "code-execution": true,
73
+ "package-management": true,
74
+ "git-mutation": true,
75
+ network: true,
76
+ "remote-operation": true,
77
+ "service-management": true,
78
+ persistence: true,
79
+ "privilege-escalation": true,
80
+ unknown: true
81
+ };
82
+ var VALID_ACTION_CLASS = new Set(Object.keys(ACTION_CLASS_MEMBERS));
83
+ var VALID_REPOSITORY_TRUST = /* @__PURE__ */ new Set(["trusted", "untrusted", "unknown"]);
84
+ function resolveActorProfiles(value) {
85
+ if (typeof value !== "object" || value === null) return {};
86
+ const out = {};
87
+ for (const [name, profile] of Object.entries(value)) {
88
+ if (typeof profile === "string" && ACTOR_PROFILES.has(profile)) {
89
+ out[name] = profile;
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+ var VALID_AUTH = /* @__PURE__ */ new Set(["high", "medium", "low", "unknown"]);
95
+ function resolveRiskPolicy(value) {
96
+ if (typeof value !== "object" || value === null)
97
+ return { ...DEFAULT_RISK_POLICY, allow: { ...DEFAULT_RISK_POLICY.allow } };
98
+ const src = value;
99
+ const allowSrc = typeof src.allow === "object" && src.allow !== null ? src.allow : {};
100
+ const merged = {
101
+ allow: { ...DEFAULT_RISK_POLICY.allow },
102
+ minimumConfidence: DEFAULT_RISK_POLICY.minimumConfidence,
103
+ // Prefer an explicit deny from either the field or a pre-clamped trusted
104
+ // baseline (loader may have already hardened the knob).
105
+ onInvalidDecision: src.onInvalidDecision === "deny" ? "deny" : DEFAULT_RISK_POLICY.onInvalidDecision,
106
+ onReviewerFailure: src.onReviewerFailure === "deny" ? "deny" : DEFAULT_RISK_POLICY.onReviewerFailure
107
+ };
108
+ for (const risk of ["low", "medium", "high", "critical"]) {
109
+ const cell = allowSrc[risk];
110
+ if (!Array.isArray(cell)) continue;
111
+ const auths = cell.filter(
112
+ (a) => typeof a === "string" && VALID_AUTH.has(a)
113
+ );
114
+ merged.allow[risk] = auths;
115
+ }
116
+ if (typeof src.minimumConfidence === "number" && Number.isFinite(src.minimumConfidence)) {
117
+ merged.minimumConfidence = Math.min(1, Math.max(0.5, src.minimumConfidence));
118
+ }
119
+ return merged;
120
+ }
121
+ function resolveEscalationMode(value) {
122
+ return value === "deny" ? "deny" : "manual";
123
+ }
124
+ function resolveRepositoryTrust(value) {
125
+ if (value === "trusted") return "trusted";
126
+ if (value === "untrusted") return "untrusted";
127
+ return "unknown";
128
+ }
129
+ var VALID_EFFECTS = /* @__PURE__ */ new Set(["review", "manual", "deny", "allow"]);
130
+ var VALID_SOURCES = /* @__PURE__ */ new Set(["builtin", "global", "project", "inline"]);
131
+ function parsePolicyRule(raw) {
132
+ if (typeof raw !== "object" || raw === null) return null;
133
+ const r = raw;
134
+ if (typeof r.id !== "string" || r.id.length === 0) return null;
135
+ if (typeof r.source !== "string" || !VALID_SOURCES.has(r.source)) return null;
136
+ if (typeof r.effect !== "string" || !VALID_EFFECTS.has(r.effect)) return null;
137
+ if (typeof r.reason !== "string" || r.reason.length === 0) return null;
138
+ if (r.when !== void 0) {
139
+ if (typeof r.when !== "object" || r.when === null) return null;
140
+ const when = validateCondition(r.when);
141
+ if (when === null) return null;
142
+ return {
143
+ id: r.id,
144
+ source: r.source,
145
+ when,
146
+ effect: r.effect,
147
+ reason: r.reason
148
+ };
149
+ }
150
+ return {
151
+ id: r.id,
152
+ source: r.source,
153
+ effect: r.effect,
154
+ reason: r.reason
155
+ };
156
+ }
157
+ function resolvePolicyRules(value) {
158
+ if (!Array.isArray(value)) return [];
159
+ const out = [];
160
+ for (const raw of value) {
161
+ const rule = parsePolicyRule(raw);
162
+ if (rule !== null) out.push(rule);
163
+ }
164
+ return out;
165
+ }
166
+ function countInvalidPolicyRules(value) {
167
+ if (value === void 0) return 0;
168
+ if (!Array.isArray(value)) return 1;
169
+ return value.filter((raw) => parsePolicyRule(raw) === null).length;
170
+ }
171
+ var CONDITION_LIST_KEYS = ["actionClass", "actorProfile", "repositoryTrust"];
172
+ var CONDITION_FLAG_KEYS = [
173
+ "writesWorkspace",
174
+ "writesExternal",
175
+ "writesTemporary",
176
+ "deletion",
177
+ "executesCode",
178
+ "createsAdHocCode",
179
+ "packageManagement",
180
+ "gitMutation",
181
+ "networkObserved",
182
+ "credentialRead",
183
+ "privilegeEscalation",
184
+ "remoteEnabled",
185
+ "persistence"
186
+ ];
187
+ function validateCondition(value) {
188
+ const knownKeys = /* @__PURE__ */ new Set(["always", ...CONDITION_LIST_KEYS, ...CONDITION_FLAG_KEYS]);
189
+ for (const key of Object.keys(value)) {
190
+ if (!knownKeys.has(key)) return null;
191
+ }
192
+ if (value.always !== void 0) {
193
+ if (value.always !== true || Object.keys(value).length !== 1) return null;
194
+ return { always: true };
195
+ }
196
+ const out = {};
197
+ if (value.actionClass !== void 0) {
198
+ if (!isClosedSetMemberArray(value.actionClass, VALID_ACTION_CLASS)) return null;
199
+ out.actionClass = value.actionClass;
200
+ }
201
+ if (value.actorProfile !== void 0) {
202
+ if (!isClosedSetMemberArray(value.actorProfile, ACTOR_PROFILES))
203
+ return null;
204
+ out.actorProfile = value.actorProfile;
205
+ }
206
+ if (value.repositoryTrust !== void 0) {
207
+ if (!isClosedSetMemberArray(value.repositoryTrust, VALID_REPOSITORY_TRUST)) return null;
208
+ out.repositoryTrust = value.repositoryTrust;
209
+ }
210
+ for (const flag of CONDITION_FLAG_KEYS) {
211
+ if (value[flag] !== void 0) {
212
+ if (typeof value[flag] !== "boolean") return null;
213
+ if (value[flag] === false) return null;
214
+ out[flag] = value[flag];
215
+ }
216
+ }
217
+ if (Object.keys(out).length === 0) return null;
218
+ return out;
219
+ }
220
+ function isStringArray(value) {
221
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
222
+ }
223
+ function isClosedSetMemberArray(value, valid) {
224
+ return Array.isArray(value) && value.length > 0 && value.every((v) => typeof v === "string" && valid.has(v));
225
+ }
226
+ function resolveConfig(options) {
227
+ const source = options ?? {};
228
+ const model = typeof source.model === "string" && source.model.includes("/") ? source.model : DEFAULT_CONFIG.model;
229
+ const variant = typeof source.variant === "string" && source.variant.length > 0 ? source.variant : DEFAULT_CONFIG.variant;
230
+ const outputFormat = source.outputFormat === "text" ? "text" : "json_schema";
231
+ const escalationReviewer = resolveEscalationReviewer(source.escalationReviewer);
232
+ const policy = typeof source.policy === "string" && source.policy.trim().length > 0 ? source.policy.trim() : void 0;
233
+ const auditPath = typeof source.auditPath === "string" && source.auditPath.trim().length > 0 ? source.auditPath.trim() : void 0;
234
+ return {
235
+ model,
236
+ variant,
237
+ outputFormat,
238
+ ...escalationReviewer === void 0 ? {} : { escalationReviewer },
239
+ timeoutMs: boundedInteger(source.timeoutMs, DEFAULT_CONFIG.timeoutMs, 5e3, 6e5),
240
+ ...source.reviewBudgetMs === void 0 ? {} : { reviewBudgetMs: boundedInteger(source.reviewBudgetMs, 18e4, 5e3, 9e5) },
241
+ maxContextChars: boundedInteger(
242
+ source.maxContextChars,
243
+ DEFAULT_CONFIG.maxContextChars,
244
+ 4e3,
245
+ 2e5
246
+ ),
247
+ maxPartChars: boundedInteger(source.maxPartChars, DEFAULT_CONFIG.maxPartChars, 500, 5e4),
248
+ maxEnrichmentChars: boundedInteger(
249
+ source.maxEnrichmentChars,
250
+ DEFAULT_CONFIG.maxEnrichmentChars,
251
+ 1e3,
252
+ 1e5
253
+ ),
254
+ maxIntentChars: boundedInteger(
255
+ source.maxIntentChars,
256
+ DEFAULT_CONFIG.maxIntentChars,
257
+ 1e3,
258
+ 5e4
259
+ ),
260
+ transcriptMessages: boundedInteger(
261
+ source.transcriptMessages,
262
+ DEFAULT_CONFIG.transcriptMessages,
263
+ 1,
264
+ 100
265
+ ),
266
+ intentMessages: boundedInteger(source.intentMessages, DEFAULT_CONFIG.intentMessages, 1, 50),
267
+ historyMessages: boundedInteger(
268
+ source.historyMessages,
269
+ DEFAULT_CONFIG.historyMessages,
270
+ 20,
271
+ 500
272
+ ),
273
+ confidenceThreshold: boundedNumber(
274
+ source.confidenceThreshold,
275
+ DEFAULT_CONFIG.confidenceThreshold,
276
+ 0.5,
277
+ 1
278
+ ),
279
+ systemOneConfidenceThreshold: boundedNumber(
280
+ source.systemOneConfidenceThreshold,
281
+ DEFAULT_CONFIG.systemOneConfidenceThreshold,
282
+ 0.3,
283
+ 1
284
+ ),
285
+ systemOneReasoningThreshold: boundedNumber(
286
+ source.systemOneReasoningThreshold,
287
+ DEFAULT_CONFIG.systemOneReasoningThreshold,
288
+ 0,
289
+ 1
290
+ ),
291
+ retainReviewSessions: typeof source.retainReviewSessions === "boolean" ? source.retainReviewSessions : DEFAULT_CONFIG.retainReviewSessions,
292
+ audit: typeof source.audit === "boolean" ? source.audit : DEFAULT_CONFIG.audit,
293
+ ...auditPath === void 0 ? {} : { auditPath },
294
+ ...policy === void 0 ? {} : { policy },
295
+ debug: typeof source.debug === "boolean" ? source.debug : DEFAULT_CONFIG.debug,
296
+ enforcementMode: source.enforcementMode === "enforce" ? "enforce" : DEFAULT_CONFIG.enforcementMode,
297
+ escalationMode: resolveEscalationMode(source.escalationMode),
298
+ maxSessionDepth: boundedInteger(source.maxSessionDepth, DEFAULT_CONFIG.maxSessionDepth, 1, 32),
299
+ maxParentSessions: boundedInteger(
300
+ source.maxParentSessions,
301
+ DEFAULT_CONFIG.maxParentSessions,
302
+ 0,
303
+ 32
304
+ ),
305
+ actorProfiles: resolveActorProfiles(source.actorProfiles),
306
+ riskPolicy: resolveRiskPolicy(source.riskPolicy),
307
+ repositoryTrust: resolveRepositoryTrust(source.repositoryTrust),
308
+ policyRules: resolvePolicyRules(source.policyRules),
309
+ askDecisions: typeof source.askDecisions === "boolean" ? source.askDecisions : DEFAULT_CONFIG.askDecisions,
310
+ ...isStringArray(source.configDegraded) && source.configDegraded.length > 0 ? { configDegraded: source.configDegraded } : {}
311
+ };
312
+ }
313
+ function resolveEscalationReviewer(value) {
314
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
315
+ const source = value;
316
+ if (typeof source.model !== "string" || !source.model.includes("/") || isSystemOneReviewerModel(source.model))
317
+ return;
318
+ return {
319
+ model: source.model,
320
+ variant: typeof source.variant === "string" && source.variant.length > 0 ? source.variant : DEFAULT_CONFIG.variant,
321
+ outputFormat: source.outputFormat === "text" ? "text" : "json_schema",
322
+ timeoutMs: boundedInteger(source.timeoutMs, DEFAULT_CONFIG.timeoutMs, 5e3, 6e5)
323
+ };
324
+ }
325
+ function isValidEscalationReviewer(value) {
326
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
327
+ const source = value;
328
+ if (typeof source.model !== "string" || !source.model.includes("/") || isSystemOneReviewerModel(source.model))
329
+ return false;
330
+ if (source.variant !== void 0 && (typeof source.variant !== "string" || !source.variant))
331
+ return false;
332
+ if (source.outputFormat !== void 0 && source.outputFormat !== "text" && source.outputFormat !== "json_schema")
333
+ return false;
334
+ if (source.timeoutMs !== void 0 && (typeof source.timeoutMs !== "number" || !Number.isInteger(source.timeoutMs)))
335
+ return false;
336
+ return true;
337
+ }
338
+ function splitModel(model) {
339
+ const slash = model.indexOf("/");
340
+ if (slash <= 0 || slash === model.length - 1) {
341
+ throw new Error(`Invalid reviewer model "${model}"; expected provider/model`);
342
+ }
343
+ return {
344
+ providerID: model.slice(0, slash),
345
+ modelID: model.slice(slash + 1)
346
+ };
347
+ }
348
+ function isSystemOneReviewerModel(model) {
349
+ let parsed;
350
+ try {
351
+ parsed = splitModel(model);
352
+ } catch {
353
+ return false;
354
+ }
355
+ return (parsed.providerID === "opencode" || parsed.providerID === "typesafe-ai") && /^jev(?:-|$)/.test(parsed.modelID) || parsed.providerID === "commandcode" && parsed.modelID === "typesafe/jev";
356
+ }
357
+
358
+ // src/config/loader.ts
359
+ import { closeSync, constants as fsConstants, fstatSync, openSync, readSync } from "fs";
360
+ import { homedir } from "os";
361
+ import { join } from "path";
362
+
363
+ // src/config/jsonc.ts
364
+ function parseJsoncStrict(text) {
365
+ const stripped = stripCommentsAndTrailingCommas(text);
366
+ const parsed = JSON.parse(stripped);
367
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
368
+ throw new Error("top-level value is not a JSON object");
369
+ }
370
+ return parsed;
371
+ }
372
+ function stripCommentsAndTrailingCommas(input) {
373
+ let out = "";
374
+ let i = 0;
375
+ const len = input.length;
376
+ let lastReal = "";
377
+ const append = (ch) => {
378
+ out += ch;
379
+ if (ch !== " " && ch !== " " && ch !== "\n" && ch !== "\r") lastReal = ch;
380
+ };
381
+ while (i < len) {
382
+ const ch = input[i];
383
+ const next = input[i + 1];
384
+ if (ch === '"') {
385
+ append(ch);
386
+ i += 1;
387
+ while (i < len) {
388
+ const c = input[i];
389
+ append(c);
390
+ if (c === "\\" && i + 1 < len) {
391
+ append(input[i + 1]);
392
+ i += 2;
393
+ continue;
394
+ }
395
+ i += 1;
396
+ if (c === '"') break;
397
+ }
398
+ continue;
399
+ }
400
+ if (ch === "/" && next === "/") {
401
+ i += 2;
402
+ while (i < len && input[i] !== "\n") i += 1;
403
+ continue;
404
+ }
405
+ if (ch === "/" && next === "*") {
406
+ i += 2;
407
+ while (i < len && !(input[i] === "*" && input[i + 1] === "/")) i += 1;
408
+ i += 2;
409
+ continue;
410
+ }
411
+ if ((ch === "}" || ch === "]") && lastReal === ",") {
412
+ let j = out.length - 1;
413
+ while (j >= 0 && out[j] !== ",") j -= 1;
414
+ if (j >= 0) out = out.slice(0, j);
415
+ lastReal = "";
416
+ }
417
+ append(ch);
418
+ i += 1;
419
+ }
420
+ return out;
421
+ }
422
+
423
+ // src/config/loader.ts
424
+ var O_RDONLY = typeof fsConstants.O_RDONLY === "number" ? fsConstants.O_RDONLY : 0;
425
+ var O_NOFOLLOW = typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0;
426
+ var O_NONBLOCK = typeof fsConstants.O_NONBLOCK === "number" ? fsConstants.O_NONBLOCK : 0;
427
+ var CONFIG_READ_CAP_BYTES = 1024 * 1024;
428
+ function readConfigLayer(path) {
429
+ const read = readLayerText(path);
430
+ if (!("text" in read)) return read;
431
+ try {
432
+ return { raw: parseJsoncStrict(read.text), status: "ok" };
433
+ } catch (error) {
434
+ return {
435
+ raw: {},
436
+ status: "malformed",
437
+ warning: `permission-reviewer config at ${path} is malformed and was ignored (${error instanceof Error ? error.message : String(error)})`
438
+ };
439
+ }
440
+ }
441
+ function readLayerText(path) {
442
+ const readError = (warning) => ({ raw: {}, status: "read-error", warning });
443
+ let fd;
444
+ try {
445
+ try {
446
+ fd = openSync(path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW);
447
+ } catch (error) {
448
+ const code = error.code;
449
+ if (code === "ENOENT") return { raw: {}, status: "missing" };
450
+ return readError(
451
+ `permission-reviewer config at ${path} exists but could not be read (${code ?? "unknown error"}); the layer was ignored`
452
+ );
453
+ }
454
+ const info = fstatSync(fd);
455
+ if (!info.isFile()) {
456
+ return readError(
457
+ `permission-reviewer config at ${path} is not a regular file and was ignored`
458
+ );
459
+ }
460
+ if (info.size > CONFIG_READ_CAP_BYTES) {
461
+ return readError(
462
+ `permission-reviewer config at ${path} exceeds the size limit (${CONFIG_READ_CAP_BYTES} bytes) and was ignored`
463
+ );
464
+ }
465
+ const length = info.size;
466
+ const buffer = Buffer.alloc(length);
467
+ let read = 0;
468
+ while (read < length) {
469
+ const count = readSync(fd, buffer, read, length - read, read);
470
+ if (count === 0) break;
471
+ read += count;
472
+ }
473
+ const text = (read < length ? buffer.subarray(0, read) : buffer).toString("utf8");
474
+ return { status: "ok", text };
475
+ } catch (error) {
476
+ const code = error.code;
477
+ return readError(
478
+ `permission-reviewer config at ${path} exists but could not be read (${code ?? "unknown error"}); the layer was ignored`
479
+ );
480
+ } finally {
481
+ if (fd !== void 0) {
482
+ try {
483
+ closeSync(fd);
484
+ } catch {
485
+ }
486
+ }
487
+ }
488
+ }
489
+ var globalConfigPathOverride;
490
+ function globalConfigPath() {
491
+ return globalConfigPathOverride ?? join(homedir(), ".config", "opencode", "permission-reviewer.jsonc");
492
+ }
493
+ function projectConfigPath(directory) {
494
+ return join(directory, ".opencode", "permission-reviewer.jsonc");
495
+ }
496
+ var TRUST_BOUNDARY_KEYS = /* @__PURE__ */ new Set([
497
+ "confidenceThreshold",
498
+ "systemOneConfidenceThreshold",
499
+ "systemOneReasoningThreshold",
500
+ "audit",
501
+ "auditPath",
502
+ "model",
503
+ "escalationReviewer",
504
+ "policy",
505
+ "repositoryTrust",
506
+ "actorProfiles",
507
+ "enforcementMode",
508
+ "riskPolicy",
509
+ "escalationMode",
510
+ "policyRules",
511
+ "variant",
512
+ "outputFormat",
513
+ "retainReviewSessions",
514
+ "timeoutMs",
515
+ "reviewBudgetMs",
516
+ "maxContextChars",
517
+ "maxPartChars",
518
+ "maxEnrichmentChars",
519
+ "maxIntentChars",
520
+ "transcriptMessages",
521
+ "intentMessages",
522
+ "historyMessages",
523
+ "maxSessionDepth",
524
+ "maxParentSessions",
525
+ "askDecisions",
526
+ "debug"
527
+ ]);
528
+ var TRUSTED_ONLY_RESOURCE_KEYS = [
529
+ "timeoutMs",
530
+ "reviewBudgetMs",
531
+ "maxContextChars",
532
+ "maxPartChars",
533
+ "maxEnrichmentChars",
534
+ "maxIntentChars",
535
+ "transcriptMessages",
536
+ "intentMessages",
537
+ "historyMessages",
538
+ "maxSessionDepth",
539
+ "maxParentSessions"
540
+ ];
541
+ function loadResolvedConfig(inlineOptions, directory, inlineTrust = "trusted") {
542
+ const globalLayer = readConfigLayer(globalConfigPath());
543
+ const projectLayer = directory !== void 0 ? readConfigLayer(projectConfigPath(directory)) : { raw: {}, status: "missing" };
544
+ for (const layer of [globalLayer, projectLayer]) {
545
+ if (layer.warning !== void 0) console.warn(layer.warning);
546
+ }
547
+ const degraded = [];
548
+ if (globalLayer.status === "malformed") {
549
+ degraded.push("global config file is malformed and was ignored");
550
+ } else if (globalLayer.status === "read-error") {
551
+ degraded.push("global config file exists but could not be read");
552
+ } else if (globalLayer.status === "ok") {
553
+ if (globalLayer.raw.escalationReviewer !== void 0 && !isValidEscalationReviewer(globalLayer.raw.escalationReviewer)) {
554
+ degraded.push("global config escalationReviewer is invalid and was ignored");
555
+ console.warn(
556
+ "permission-reviewer: global config escalationReviewer is invalid and was ignored; automatic approval stays disabled until it is fixed"
557
+ );
558
+ }
559
+ const invalidRules = countInvalidPolicyRules(globalLayer.raw.policyRules);
560
+ if (invalidRules > 0) {
561
+ degraded.push(
562
+ `${invalidRules} policy rule(s) from the global config were dropped by validation`
563
+ );
564
+ console.warn(
565
+ `permission-reviewer: ${invalidRules} policy rule(s) in the global config are invalid and were dropped; automatic approval stays disabled until they are fixed`
566
+ );
567
+ }
568
+ const globalEnforcement = globalLayer.raw.enforcementMode;
569
+ if (globalEnforcement !== void 0 && globalEnforcement !== "enforce" && globalEnforcement !== "observe") {
570
+ degraded.push(
571
+ `global config enforcementMode ${JSON.stringify(globalEnforcement)} is invalid and was ignored`
572
+ );
573
+ console.warn(
574
+ `permission-reviewer: global config enforcementMode ${JSON.stringify(globalEnforcement)} is invalid and was ignored; automatic approval stays disabled until it is fixed`
575
+ );
576
+ }
577
+ const globalEscalation = globalLayer.raw.escalationMode;
578
+ if (globalEscalation !== void 0 && globalEscalation !== "manual" && globalEscalation !== "deny") {
579
+ degraded.push(
580
+ `global config escalationMode ${JSON.stringify(globalEscalation)} is invalid and was ignored`
581
+ );
582
+ console.warn(
583
+ `permission-reviewer: global config escalationMode ${JSON.stringify(globalEscalation)} is invalid and was ignored; automatic approval stays disabled until it is fixed`
584
+ );
585
+ }
586
+ }
587
+ const invalidInlineRules = inlineTrust === "trusted" ? countInvalidPolicyRules(inlineOptions?.policyRules) : 0;
588
+ if (invalidInlineRules > 0) {
589
+ degraded.push(
590
+ `${invalidInlineRules} policy rule(s) from inline config were dropped by validation`
591
+ );
592
+ }
593
+ if (inlineTrust === "trusted" && inlineOptions !== void 0) {
594
+ if (inlineOptions.escalationReviewer !== void 0 && !isValidEscalationReviewer(inlineOptions.escalationReviewer)) {
595
+ degraded.push("inline config escalationReviewer is invalid and was ignored");
596
+ }
597
+ const inlineEnforcement = inlineOptions.enforcementMode;
598
+ if (inlineEnforcement !== void 0 && inlineEnforcement !== "enforce" && inlineEnforcement !== "observe") {
599
+ degraded.push(
600
+ `inline config enforcementMode ${JSON.stringify(inlineEnforcement)} is invalid and was ignored`
601
+ );
602
+ }
603
+ const inlineEscalation = inlineOptions.escalationMode;
604
+ if (inlineEscalation !== void 0 && inlineEscalation !== "manual" && inlineEscalation !== "deny") {
605
+ degraded.push(
606
+ `inline config escalationMode ${JSON.stringify(inlineEscalation)} is invalid and was ignored`
607
+ );
608
+ }
609
+ }
610
+ const invalidProjectRules = countInvalidPolicyRules(projectLayer.raw.policyRules);
611
+ if (invalidProjectRules > 0) {
612
+ console.warn(
613
+ `permission-reviewer: ${invalidProjectRules} policy rule(s) in the project config are invalid and were dropped`
614
+ );
615
+ }
616
+ const trusted = {
617
+ ...DEFAULT_CONFIG,
618
+ ...globalLayer.raw,
619
+ ...inlineTrust === "trusted" ? inlineOptions ?? {} : {}
620
+ };
621
+ let merged = mergeWithTrustBoundary(trusted, projectLayer.raw);
622
+ if (inlineTrust !== "trusted") {
623
+ const restrictions = Object.fromEntries(
624
+ Object.entries(inlineOptions ?? {}).filter(([key]) => TRUST_BOUNDARY_KEYS.has(key))
625
+ );
626
+ merged = mergeWithTrustBoundary(merged, restrictions);
627
+ }
628
+ const out = { ...merged };
629
+ for (const [key, value] of Object.entries(inlineOptions ?? {})) {
630
+ if (inlineTrust === "trusted" && !TRUST_BOUNDARY_KEYS.has(key)) out[key] = value;
631
+ }
632
+ if (degraded.length > 0) out.configDegraded = degraded;
633
+ return resolveConfig(out);
634
+ }
635
+ function hasKey(object, key) {
636
+ return Object.prototype.hasOwnProperty.call(object, key);
637
+ }
638
+ function isPlainObject(value) {
639
+ return typeof value === "object" && value !== null && !Array.isArray(value);
640
+ }
641
+ function mergeWithTrustBoundary(trusted, project) {
642
+ const clamped = { ...project };
643
+ delete clamped.configDegraded;
644
+ for (const key of [
645
+ "confidenceThreshold",
646
+ "systemOneConfidenceThreshold",
647
+ "systemOneReasoningThreshold"
648
+ ]) {
649
+ if (hasKey(clamped, key)) {
650
+ if (typeof clamped[key] !== "number" || !Number.isFinite(clamped[key])) {
651
+ delete clamped[key];
652
+ } else {
653
+ const floor = typeof trusted[key] === "number" ? trusted[key] : DEFAULT_CONFIG[key];
654
+ if (clamped[key] < floor) clamped[key] = floor;
655
+ }
656
+ }
657
+ }
658
+ for (const key of TRUSTED_ONLY_RESOURCE_KEYS) {
659
+ delete clamped[key];
660
+ }
661
+ if (clamped.audit === false && trusted.audit !== false) {
662
+ delete clamped.audit;
663
+ }
664
+ delete clamped.askDecisions;
665
+ delete clamped.auditPath;
666
+ delete clamped.model;
667
+ delete clamped.escalationReviewer;
668
+ delete clamped.policy;
669
+ delete clamped.variant;
670
+ delete clamped.outputFormat;
671
+ delete clamped.retainReviewSessions;
672
+ delete clamped.debug;
673
+ if (clamped.repositoryTrust !== "untrusted") {
674
+ delete clamped.repositoryTrust;
675
+ }
676
+ delete clamped.actorProfiles;
677
+ if (clamped.enforcementMode !== void 0) {
678
+ if (clamped.enforcementMode === "enforce" || trusted.enforcementMode === "enforce") {
679
+ delete clamped.enforcementMode;
680
+ }
681
+ }
682
+ if (hasKey(clamped, "riskPolicy")) {
683
+ if (isPlainObject(clamped.riskPolicy)) {
684
+ const trustedPolicy = isPlainObject(trusted.riskPolicy) ? trusted.riskPolicy : DEFAULT_RISK_POLICY;
685
+ clamped.riskPolicy = clampRiskPolicy(clamped.riskPolicy, trustedPolicy);
686
+ } else {
687
+ delete clamped.riskPolicy;
688
+ }
689
+ }
690
+ if (clamped.escalationMode !== void 0) {
691
+ if (clamped.escalationMode !== "manual" && clamped.escalationMode !== "deny") {
692
+ delete clamped.escalationMode;
693
+ } else if (clamped.escalationMode === "manual" && trusted.escalationMode === "deny") {
694
+ delete clamped.escalationMode;
695
+ }
696
+ }
697
+ if (Array.isArray(clamped.policyRules)) {
698
+ const projectRules = clamped.policyRules.map((rule) => ({
699
+ ...rule,
700
+ source: "project"
701
+ }));
702
+ const trustedRules = Array.isArray(trusted.policyRules) ? trusted.policyRules : [];
703
+ clamped.policyRules = [...trustedRules, ...projectRules];
704
+ } else if (Array.isArray(trusted.policyRules)) {
705
+ clamped.policyRules = trusted.policyRules;
706
+ }
707
+ return { ...trusted, ...clamped };
708
+ }
709
+ function clampRiskPolicy(project, trusted) {
710
+ const projectAllow = typeof project.allow === "object" && project.allow !== null ? project.allow : void 0;
711
+ const trustedAllow = typeof trusted.allow === "object" && trusted.allow !== null ? trusted.allow : {};
712
+ const clampedAllow = {};
713
+ for (const risk of ["low", "medium", "high", "critical"]) {
714
+ const trustedCell = Array.isArray(trustedAllow[risk]) ? trustedAllow[risk] : [];
715
+ if (projectAllow === void 0) {
716
+ clampedAllow[risk] = trustedCell;
717
+ continue;
718
+ }
719
+ const projectCell = Array.isArray(projectAllow[risk]) ? projectAllow[risk] : [];
720
+ clampedAllow[risk] = trustedCell.filter((auth) => projectCell.includes(auth));
721
+ }
722
+ const out = {
723
+ ...trusted,
724
+ allow: clampedAllow
725
+ };
726
+ if (project.onInvalidDecision === "deny" || trusted.onInvalidDecision === "deny") {
727
+ out.onInvalidDecision = "deny";
728
+ } else if (project.onInvalidDecision === "manual" || project.onInvalidDecision === void 0) {
729
+ out.onInvalidDecision = trusted.onInvalidDecision ?? "manual";
730
+ }
731
+ if (project.onReviewerFailure === "deny" || trusted.onReviewerFailure === "deny") {
732
+ out.onReviewerFailure = "deny";
733
+ } else if (project.onReviewerFailure === "manual" || project.onReviewerFailure === void 0) {
734
+ out.onReviewerFailure = trusted.onReviewerFailure ?? "manual";
735
+ }
736
+ const trustedMin = typeof trusted.minimumConfidence === "number" && Number.isFinite(trusted.minimumConfidence) ? trusted.minimumConfidence : DEFAULT_RISK_POLICY.minimumConfidence;
737
+ if (typeof project.minimumConfidence === "number" && Number.isFinite(project.minimumConfidence)) {
738
+ out.minimumConfidence = Math.max(trustedMin, project.minimumConfidence);
739
+ } else {
740
+ out.minimumConfidence = trustedMin;
741
+ }
742
+ return out;
743
+ }
744
+
745
+ // src/shell-lexer.ts
746
+ var SEPARATORS = /* @__PURE__ */ new Set([";", "|", "&", "\n", "\r", "(", ")"]);
747
+ var WHITESPACE = /* @__PURE__ */ new Set([" ", " "]);
748
+ var TRANSPARENT_WRAPPERS = /* @__PURE__ */ new Set([
749
+ "sudo",
750
+ "doas",
751
+ "pkexec",
752
+ "env",
753
+ "command",
754
+ "nice",
755
+ "nohup",
756
+ "time",
757
+ "stdbuf",
758
+ "ionice",
759
+ "fakeroot",
760
+ "setsid",
761
+ "setpriv",
762
+ "unshare",
763
+ "run0",
764
+ "systemd-run",
765
+ "strace",
766
+ "ltrace",
767
+ "watch",
768
+ "xargs",
769
+ "timeout",
770
+ "exec"
771
+ ]);
772
+ var VALUE_OPTIONS = {
773
+ sudo: /* @__PURE__ */ new Set([
774
+ "-u",
775
+ "--user",
776
+ "-g",
777
+ "--group",
778
+ "-C",
779
+ "-p",
780
+ "--prompt",
781
+ "-R",
782
+ "-T",
783
+ "-U",
784
+ "-D",
785
+ "--chdir",
786
+ "-r",
787
+ "-t"
788
+ ]),
789
+ doas: /* @__PURE__ */ new Set(["-u", "--user", "-a"]),
790
+ pkexec: /* @__PURE__ */ new Set(["--user", "--session"]),
791
+ env: /* @__PURE__ */ new Set(["-u", "--unset", "-S", "--split-string", "-C", "--chdir"]),
792
+ nice: /* @__PURE__ */ new Set(["-n", "--adjustment"]),
793
+ time: /* @__PURE__ */ new Set(["-o", "--output", "-f"]),
794
+ ionice: /* @__PURE__ */ new Set(["-c", "-n"]),
795
+ setpriv: /* @__PURE__ */ new Set([
796
+ "--ruid",
797
+ "--euid",
798
+ "--rgid",
799
+ "--egid",
800
+ "--reuid",
801
+ "--regid",
802
+ "--inh-caps",
803
+ "--bounding-set",
804
+ "--ambient-caps",
805
+ "--groups",
806
+ "--securebits",
807
+ "--pdeathsig",
808
+ "--selinux-label",
809
+ "--apparmor-profile"
810
+ ]),
811
+ command: /* @__PURE__ */ new Set(),
812
+ nohup: /* @__PURE__ */ new Set(),
813
+ // stdbuf's -i/-o/-e take the buffer TYPE either attached (`-oL`) or as the
814
+ // next token; both forms skip exactly one value.
815
+ stdbuf: /* @__PURE__ */ new Set(["-i", "-o", "-e", "--input", "--output", "--error"]),
816
+ fakeroot: /* @__PURE__ */ new Set(),
817
+ setsid: /* @__PURE__ */ new Set(),
818
+ unshare: /* @__PURE__ */ new Set([
819
+ "--propagation",
820
+ "--setgroups",
821
+ "-R",
822
+ "--root",
823
+ "-w",
824
+ "--wd",
825
+ "-S",
826
+ "--setuid",
827
+ "-G",
828
+ "--setgid",
829
+ "--monotonic",
830
+ "--boottime"
831
+ ]),
832
+ run0: /* @__PURE__ */ new Set(["--unit", "--service", "--slice", "--setenv", "--chdir"]),
833
+ // systemd-run mostly uses = forms (self-contained tokens); the flags listed
834
+ // here also accept a separate value token that must not be mistaken for the
835
+ // wrapped command.
836
+ "systemd-run": /* @__PURE__ */ new Set([
837
+ "-p",
838
+ "-E",
839
+ "-H",
840
+ "--host",
841
+ "-M",
842
+ "--property",
843
+ "-u",
844
+ "--unit",
845
+ "--description",
846
+ "--slice",
847
+ "--uid",
848
+ "--gid",
849
+ "--nice",
850
+ "--expand-environment",
851
+ "--service-type",
852
+ "--working-directory",
853
+ "--setenv",
854
+ "--machine",
855
+ "--job-mode",
856
+ "--on-active",
857
+ "--on-boot",
858
+ "--on-startup",
859
+ "--on-calendar",
860
+ "--on-unit-active",
861
+ "--on-unit-inactive",
862
+ "--timer-property",
863
+ "--path-property",
864
+ "--socket-property"
865
+ ]),
866
+ // strace/ltrace: -o/-e/-s take a separate value; their long forms are
867
+ // = only. Tracing without a command (`strace -p PID`) has nothing to peel
868
+ // after the PID is consumed.
869
+ strace: /* @__PURE__ */ new Set(["-o", "-e", "-s", "-a", "-b", "-p", "-u"]),
870
+ ltrace: /* @__PURE__ */ new Set(["-o", "-e", "-s", "-a", "-l", "-u"]),
871
+ // watch's interval and equexit flags consume separate values; its pure flags
872
+ // (-d, -g, -t, -b, -c, -e, …) stay absent like the other wrappers above.
873
+ watch: /* @__PURE__ */ new Set(["-n", "--interval", "-q", "--equexit"]),
874
+ // xargs value-taking options with a separate argument: without these the
875
+ // generic peel would mistake the option's argument for the command. Pure
876
+ // flags (-0, -r, -t, …) stay absent, as do options with optional arguments
877
+ // (-e, -l, --replace), where skipping a following token could swallow the
878
+ // real executable instead.
879
+ xargs: /* @__PURE__ */ new Set([
880
+ "-I",
881
+ "-a",
882
+ "-d",
883
+ "-E",
884
+ "-n",
885
+ "-P",
886
+ "-s",
887
+ "-L",
888
+ "--arg-file",
889
+ "--delimiter",
890
+ "--max-args",
891
+ "--max-chars",
892
+ "--max-procs",
893
+ "--max-lines",
894
+ "--process-slot-var"
895
+ ]),
896
+ // timeout value options; the DURATION operand itself is skipped by dedicated
897
+ // handling in walk(), not by the generic loop.
898
+ timeout: /* @__PURE__ */ new Set(["-k", "-s", "--kill-after", "--signal"]),
899
+ exec: /* @__PURE__ */ new Set(["-a"])
900
+ };
901
+ var SHELL_BINARIES = /* @__PURE__ */ new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "fish"]);
902
+ var SU_BINARIES = /* @__PURE__ */ new Set(["su", "runuser", "super"]);
903
+ var MAX_WALK_DEPTH = 32;
904
+ var MAX_EFFECTIVE_COMMANDS = 4096;
905
+ var MAX_ANALYSIS_INPUT_CHARS = 131072;
906
+ var MAX_LEX_TOKENS = 16384;
907
+ var MAX_REANALYSIS_CHARS = 262144;
908
+ function newAnalysisBudget() {
909
+ return {
910
+ remainingCommands: MAX_EFFECTIVE_COMMANDS,
911
+ remainingReanalysisChars: MAX_REANALYSIS_CHARS
912
+ };
913
+ }
914
+ var SSH_VALUE_OPTIONS = /* @__PURE__ */ new Set([
915
+ "-i",
916
+ "-l",
917
+ "-p",
918
+ "-o",
919
+ "-F",
920
+ "-J",
921
+ "-b",
922
+ "-c",
923
+ "-e",
924
+ "-m",
925
+ "-w",
926
+ "-W",
927
+ "-D",
928
+ "-L",
929
+ "-R",
930
+ "-I",
931
+ "-Q",
932
+ "-O",
933
+ "-E"
934
+ ]);
935
+ function sshValueOption(token) {
936
+ if (!token.startsWith("-") || token.startsWith("--") || token.length <= 1) return;
937
+ for (let position = 1; position < token.length; position += 1) {
938
+ const option = `-${token[position]}`;
939
+ if (!SSH_VALUE_OPTIONS.has(option)) continue;
940
+ const attached = token.slice(position + 1);
941
+ return attached ? { option, attached } : { option };
942
+ }
943
+ return;
944
+ }
945
+ var SHELL_KEYWORDS = /* @__PURE__ */ new Set(["{", "}", "(", ")", "then", "else", "do", "elif", "!"]);
946
+ function basename(exe) {
947
+ const slash = exe.lastIndexOf("/");
948
+ return slash >= 0 ? exe.slice(slash + 1) : exe;
949
+ }
950
+ function tokenCharIsQuoted(token, index) {
951
+ const spans = token.spans;
952
+ if (spans === void 0) return token.raw !== token.value;
953
+ let offset = 0;
954
+ for (const span of spans) {
955
+ if (index < offset + span.text.length) return span.quoted;
956
+ offset += span.text.length;
957
+ }
958
+ return false;
959
+ }
960
+ function lexSegments(command, state) {
961
+ const segments = [];
962
+ let tokens = [];
963
+ let value = "";
964
+ let raw = "";
965
+ let hasToken = false;
966
+ let spans = [];
967
+ let inSingle = false;
968
+ let inDouble = false;
969
+ let lastSeparator;
970
+ let outOfTokens = false;
971
+ const appendValue = (text, quoted) => {
972
+ if (text.length === 0) return;
973
+ const last = spans.at(-1);
974
+ if (last !== void 0 && last.quoted === quoted) last.text += text;
975
+ else spans.push({ text, quoted });
976
+ value += text;
977
+ };
978
+ const flushToken = () => {
979
+ if (hasToken) {
980
+ tokens.push({ raw, value, spans });
981
+ value = "";
982
+ raw = "";
983
+ spans = [];
984
+ hasToken = false;
985
+ if (state !== void 0) {
986
+ state.tokensRemaining -= 1;
987
+ if (state.tokensRemaining <= 0) outOfTokens = true;
988
+ }
989
+ }
990
+ };
991
+ const flushSegment = (endedBy) => {
992
+ flushToken();
993
+ if (tokens.length > 0 || endedBy === "(" || endedBy === ")") {
994
+ segments.push({
995
+ tokens,
996
+ ...endedBy === void 0 ? {} : { endedBy },
997
+ ...lastSeparator === void 0 ? {} : { precededBy: lastSeparator }
998
+ });
999
+ tokens = [];
1000
+ }
1001
+ };
1002
+ let i = 0;
1003
+ while (i < command.length) {
1004
+ if (outOfTokens) break;
1005
+ const c = command[i];
1006
+ if (inSingle) {
1007
+ raw += c;
1008
+ if (c === "'") inSingle = false;
1009
+ else appendValue(c, true);
1010
+ i += 1;
1011
+ continue;
1012
+ }
1013
+ if (inDouble) {
1014
+ raw += c;
1015
+ if (c === '"') {
1016
+ inDouble = false;
1017
+ } else if (c === "\\" && i + 1 < command.length) {
1018
+ const next = command[i + 1];
1019
+ raw += next;
1020
+ if (next === "\n" || next === "\r") {
1021
+ i += 2;
1022
+ continue;
1023
+ }
1024
+ if ('$`"\\'.includes(next)) {
1025
+ appendValue(next, true);
1026
+ i += 2;
1027
+ continue;
1028
+ }
1029
+ appendValue("\\", true);
1030
+ i += 1;
1031
+ continue;
1032
+ } else {
1033
+ appendValue(c, true);
1034
+ }
1035
+ i += 1;
1036
+ continue;
1037
+ }
1038
+ if (c === "'") {
1039
+ inSingle = true;
1040
+ raw += c;
1041
+ hasToken = true;
1042
+ i += 1;
1043
+ continue;
1044
+ }
1045
+ if (c === '"') {
1046
+ inDouble = true;
1047
+ raw += c;
1048
+ hasToken = true;
1049
+ i += 1;
1050
+ continue;
1051
+ }
1052
+ if (c === "&" && (command[i + 1] === ">" || value.endsWith(">") && !tokenCharIsQuoted({ raw, value, spans }, value.length - 1)) || c === "|" && value.endsWith(">") && !tokenCharIsQuoted({ raw, value, spans }, value.length - 1)) {
1053
+ appendValue(c, false);
1054
+ raw += c;
1055
+ hasToken = true;
1056
+ i += 1;
1057
+ continue;
1058
+ }
1059
+ if (SEPARATORS.has(c)) {
1060
+ let endedBy = c === "\n" || c === "\r" ? ";" : c;
1061
+ if ((c === "|" || c === "&") && command[i + 1] === c) {
1062
+ endedBy = `${c}${c}`;
1063
+ i += 1;
1064
+ }
1065
+ flushSegment(endedBy);
1066
+ lastSeparator = endedBy;
1067
+ i += 1;
1068
+ continue;
1069
+ }
1070
+ if (WHITESPACE.has(c)) {
1071
+ flushToken();
1072
+ i += 1;
1073
+ continue;
1074
+ }
1075
+ if (c === "#" && !hasToken) {
1076
+ while (i < command.length && command[i] !== "\n") i += 1;
1077
+ continue;
1078
+ }
1079
+ if (c === "\\" && i + 1 < command.length) {
1080
+ const next = command[i + 1];
1081
+ raw += "\\" + next;
1082
+ if (next !== "\n" && next !== "\r") {
1083
+ appendValue(next, true);
1084
+ hasToken = true;
1085
+ }
1086
+ i += 2;
1087
+ continue;
1088
+ }
1089
+ appendValue(c, false);
1090
+ raw += c;
1091
+ hasToken = true;
1092
+ i += 1;
1093
+ }
1094
+ if (!outOfTokens) flushSegment();
1095
+ return segments;
1096
+ }
1097
+ function lexSegmentsBounded(command) {
1098
+ if (command.length > MAX_ANALYSIS_INPUT_CHARS) return { segments: [], truncated: true };
1099
+ const state = { tokensRemaining: MAX_LEX_TOKENS };
1100
+ const segments = lexSegments(command, state);
1101
+ return { segments, truncated: state.tokensRemaining <= 0 };
1102
+ }
1103
+ function analyzeEffectiveCommands(segment, budget) {
1104
+ const out = [];
1105
+ const redirections = [];
1106
+ const state = { truncated: false };
1107
+ const b = budget ?? newAnalysisBudget();
1108
+ walk(segment.tokens, out, redirections, [], 0, state, b);
1109
+ return { commands: out, redirections, truncated: state.truncated };
1110
+ }
1111
+ function walk(tokens, out, redirectionOut, inheritedRedirections, depth, state, budget) {
1112
+ if (depth > MAX_WALK_DEPTH || out.length >= MAX_EFFECTIVE_COMMANDS || budget.remainingCommands <= 0) {
1113
+ state.truncated = true;
1114
+ return;
1115
+ }
1116
+ const normalized = normalizeShellRedirections(tokens);
1117
+ tokens = normalized.tokens;
1118
+ const commandRedirections = [...inheritedRedirections, ...normalized.redirections];
1119
+ let i = 0;
1120
+ while (i < tokens.length && SHELL_KEYWORDS.has(tokens[i].value)) i += 1;
1121
+ while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i].value)) i += 1;
1122
+ while (i < tokens.length) {
1123
+ const tok = tokens[i];
1124
+ if (tok.value === "--") {
1125
+ break;
1126
+ }
1127
+ const base = basename(tok.value);
1128
+ if (base === "env") {
1129
+ const s = findEnvSCommand(tokens, i + 1);
1130
+ if (s !== null && s.script.length > 0) {
1131
+ const tail = tokens.slice(s.tailIndex).map((t) => t.value).join(" ");
1132
+ const reanalyzed = tail ? `${s.script} ${tail}` : s.script;
1133
+ budget.remainingReanalysisChars -= reanalyzed.length;
1134
+ if (budget.remainingReanalysisChars < 0) {
1135
+ state.truncated = true;
1136
+ return;
1137
+ }
1138
+ for (const sub of lexSegments(reanalyzed))
1139
+ walk(sub.tokens, out, redirectionOut, commandRedirections, depth + 1, state, budget);
1140
+ return;
1141
+ }
1142
+ }
1143
+ if (base === "timeout") {
1144
+ const valueOpts = VALUE_OPTIONS.timeout ?? /* @__PURE__ */ new Set();
1145
+ let j = i + 1;
1146
+ while (j < tokens.length) {
1147
+ const opt = tokens[j].value;
1148
+ if (opt === "--") {
1149
+ j += 1;
1150
+ break;
1151
+ }
1152
+ if (opt.startsWith("-") && opt.length > 1) {
1153
+ j = skipWrapperOption(tokens, j, valueOpts);
1154
+ continue;
1155
+ }
1156
+ break;
1157
+ }
1158
+ if (j < tokens.length) j += 1;
1159
+ if (j < tokens.length)
1160
+ walk(tokens.slice(j), out, redirectionOut, commandRedirections, depth + 1, state, budget);
1161
+ return;
1162
+ }
1163
+ if (TRANSPARENT_WRAPPERS.has(base)) {
1164
+ const valueOpts = VALUE_OPTIONS[base] ?? /* @__PURE__ */ new Set();
1165
+ i += 1;
1166
+ while (i < tokens.length) {
1167
+ const opt = tokens[i].value;
1168
+ if (opt === "--") {
1169
+ i += 1;
1170
+ break;
1171
+ }
1172
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(opt)) {
1173
+ i += 1;
1174
+ continue;
1175
+ }
1176
+ if (opt.startsWith("-") && opt.length > 1) {
1177
+ i = skipWrapperOption(tokens, i, valueOpts);
1178
+ continue;
1179
+ }
1180
+ break;
1181
+ }
1182
+ continue;
1183
+ }
1184
+ if (base === "script") {
1185
+ const command = findCommandString(tokens, i + 1);
1186
+ if (command !== null) {
1187
+ budget.remainingReanalysisChars -= command.length;
1188
+ if (budget.remainingReanalysisChars < 0) {
1189
+ state.truncated = true;
1190
+ return;
1191
+ }
1192
+ for (const sub of lexSegments(command))
1193
+ walk(sub.tokens, out, redirectionOut, commandRedirections, depth + 1, state, budget);
1194
+ return;
1195
+ }
1196
+ }
1197
+ if (SHELL_BINARIES.has(base) || SU_BINARIES.has(base)) {
1198
+ const script = findCommandString(tokens, i + 1, SHELL_BINARIES.has(base) && base !== "fish");
1199
+ if (script !== null) {
1200
+ budget.remainingReanalysisChars -= script.length;
1201
+ if (budget.remainingReanalysisChars < 0) {
1202
+ state.truncated = true;
1203
+ return;
1204
+ }
1205
+ for (const sub of lexSegments(script))
1206
+ walk(sub.tokens, out, redirectionOut, commandRedirections, depth + 1, state, budget);
1207
+ return;
1208
+ }
1209
+ }
1210
+ if (base === "ssh") {
1211
+ const rest = consumeSshRemote(tokens, i + 1);
1212
+ if (rest.length > 0) {
1213
+ const remote = rest.map((t) => t.value).join(" ");
1214
+ budget.remainingReanalysisChars -= remote.length;
1215
+ if (budget.remainingReanalysisChars < 0) {
1216
+ state.truncated = true;
1217
+ return;
1218
+ }
1219
+ for (const sub of lexSegments(remote))
1220
+ walk(sub.tokens, out, redirectionOut, commandRedirections, depth + 1, state, budget);
1221
+ }
1222
+ return;
1223
+ }
1224
+ if (base === "busybox") {
1225
+ if (i + 1 < tokens.length)
1226
+ walk(
1227
+ tokens.slice(i + 1),
1228
+ out,
1229
+ redirectionOut,
1230
+ commandRedirections,
1231
+ depth + 1,
1232
+ state,
1233
+ budget
1234
+ );
1235
+ return;
1236
+ }
1237
+ if (base === "chroot") {
1238
+ let j = i + 1;
1239
+ while (j < tokens.length) {
1240
+ const opt = tokens[j].value;
1241
+ if (opt === "--") {
1242
+ j += 1;
1243
+ break;
1244
+ }
1245
+ if (opt.startsWith("-") && opt.length > 1) {
1246
+ j += 1;
1247
+ continue;
1248
+ }
1249
+ break;
1250
+ }
1251
+ if (j + 1 < tokens.length)
1252
+ walk(
1253
+ tokens.slice(j + 1),
1254
+ out,
1255
+ redirectionOut,
1256
+ commandRedirections,
1257
+ depth + 1,
1258
+ state,
1259
+ budget
1260
+ );
1261
+ return;
1262
+ }
1263
+ out.push(tokens.slice(i));
1264
+ redirectionOut.push(commandRedirections);
1265
+ budget.remainingCommands -= 1;
1266
+ return;
1267
+ }
1268
+ }
1269
+ function sliceToken(token, start, end = token.value.length) {
1270
+ const value = token.value.slice(start, end);
1271
+ const spans = [];
1272
+ let offset = 0;
1273
+ for (const span of token.spans ?? [{ text: token.value, quoted: token.raw !== token.value }]) {
1274
+ const spanStart = offset;
1275
+ const spanEnd = offset + span.text.length;
1276
+ const from = Math.max(start, spanStart);
1277
+ const to = Math.min(end, spanEnd);
1278
+ if (from < to) {
1279
+ const text = span.text.slice(from - spanStart, to - spanStart);
1280
+ const previous = spans.at(-1);
1281
+ if (previous?.quoted === span.quoted) previous.text += text;
1282
+ else spans.push({ text, quoted: span.quoted });
1283
+ }
1284
+ offset = spanEnd;
1285
+ }
1286
+ return { raw: value, value, spans };
1287
+ }
1288
+ function redirectionOperatorAt(token, index) {
1289
+ const value = token.value;
1290
+ const live = (offset) => offset < value.length && !tokenCharIsQuoted(token, offset) ? value[offset] : void 0;
1291
+ const first = live(index);
1292
+ const tail = `${first ?? ""}${live(index + 1) ?? ""}${live(index + 2) ?? ""}`;
1293
+ if (tail.startsWith("&>>")) return "&>>";
1294
+ if (tail.startsWith("<<<")) return "<<<";
1295
+ if (tail.startsWith("<<-")) return "<<-";
1296
+ for (const operator of ["&>", ">>", ">|", ">&", "<<", "<&", "<>"]) {
1297
+ if (tail.startsWith(operator)) return operator;
1298
+ }
1299
+ if (first === ">" || first === "<") return first;
1300
+ return void 0;
1301
+ }
1302
+ function nextRedirection(token, start) {
1303
+ for (let index = start; index < token.value.length; index += 1) {
1304
+ const operator = redirectionOperatorAt(token, index);
1305
+ if (operator !== void 0) return { index, operator };
1306
+ }
1307
+ return void 0;
1308
+ }
1309
+ function normalizeShellRedirections(tokens) {
1310
+ const words = [];
1311
+ const redirections = [];
1312
+ for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex += 1) {
1313
+ const token = tokens[tokenIndex];
1314
+ if (/^<HEREDOC:sha256:[a-f0-9]+>$/.test(token.value)) {
1315
+ words.push(token);
1316
+ continue;
1317
+ }
1318
+ let cursor = 0;
1319
+ let found = nextRedirection(token, cursor);
1320
+ if (found === void 0) {
1321
+ words.push(token);
1322
+ continue;
1323
+ }
1324
+ while (found !== void 0) {
1325
+ let wordEnd = found.index;
1326
+ let operator = found.operator;
1327
+ const prefix = token.value.slice(cursor, found.index);
1328
+ if (cursor === 0 && /^[0-9]+$/.test(prefix)) {
1329
+ operator = `${prefix}${operator}`;
1330
+ wordEnd = cursor;
1331
+ }
1332
+ if (wordEnd > cursor) words.push(sliceToken(token, cursor, wordEnd));
1333
+ const targetStart = found.index + found.operator.length;
1334
+ const following = nextRedirection(token, targetStart);
1335
+ let targetToken;
1336
+ if (targetStart < (following?.index ?? token.value.length)) {
1337
+ targetToken = sliceToken(token, targetStart, following?.index);
1338
+ } else if (following === void 0) {
1339
+ const candidate = tokens[tokenIndex + 1];
1340
+ if (candidate !== void 0 && nextRedirection(candidate, 0)?.index !== 0) {
1341
+ tokenIndex += 1;
1342
+ targetToken = candidate;
1343
+ }
1344
+ }
1345
+ if (targetToken !== void 0) {
1346
+ redirections.push({
1347
+ operator,
1348
+ target: targetToken.value,
1349
+ quoted: targetToken.value.length > 0 && Array.from({ length: targetToken.value.length }, (_, index) => index).some(
1350
+ (index) => tokenCharIsQuoted(targetToken, index)
1351
+ )
1352
+ });
1353
+ }
1354
+ cursor = following?.index ?? token.value.length;
1355
+ found = following;
1356
+ }
1357
+ }
1358
+ return { tokens: words, redirections };
1359
+ }
1360
+ function skipWrapperOption(tokens, index, valueOpts) {
1361
+ const opt = tokens[index].value;
1362
+ if (valueOpts.has(opt)) return index + 2;
1363
+ if (opt.startsWith("--")) return index + 1;
1364
+ const letters = opt.slice(1);
1365
+ for (let position = 0; position < letters.length; position += 1) {
1366
+ if (valueOpts.has(`-${letters[position]}`)) {
1367
+ return position === letters.length - 1 ? index + 2 : index + 1;
1368
+ }
1369
+ }
1370
+ return index + 1;
1371
+ }
1372
+ function findCommandString(tokens, start, shellFlags = false) {
1373
+ let i = start;
1374
+ let endOfFlags = false;
1375
+ let shellCommandPending = false;
1376
+ while (i < tokens.length) {
1377
+ const t = tokens[i].value;
1378
+ if (!endOfFlags && t === "--") {
1379
+ if (shellFlags && shellCommandPending) {
1380
+ return i + 1 < tokens.length ? tokens[i + 1].value : null;
1381
+ }
1382
+ endOfFlags = true;
1383
+ i += 1;
1384
+ continue;
1385
+ }
1386
+ if (!endOfFlags && t === "-c") {
1387
+ if (shellFlags) {
1388
+ shellCommandPending = true;
1389
+ i += 1;
1390
+ continue;
1391
+ }
1392
+ return i + 1 < tokens.length ? tokens[i + 1].value : null;
1393
+ }
1394
+ if (!endOfFlags && t === "--command") {
1395
+ return i + 1 < tokens.length ? tokens[i + 1].value : null;
1396
+ }
1397
+ if (!endOfFlags && t.startsWith("--command=")) {
1398
+ return t.slice("--command=".length);
1399
+ }
1400
+ if (shellFlags && shellCommandPending) {
1401
+ if (!endOfFlags && (t === "-o" || t === "-O")) {
1402
+ i += 2;
1403
+ continue;
1404
+ }
1405
+ if (!endOfFlags && (t.startsWith("-") || t.startsWith("+")) && t.length > 1) {
1406
+ i += 1;
1407
+ continue;
1408
+ }
1409
+ return t;
1410
+ }
1411
+ if (!endOfFlags && t.startsWith("-") && !t.startsWith("--") && t.length > 1) {
1412
+ const cPosition = t.indexOf("c");
1413
+ if (cPosition === -1) {
1414
+ i += 1;
1415
+ continue;
1416
+ }
1417
+ if (shellFlags) {
1418
+ shellCommandPending = true;
1419
+ i += 1;
1420
+ continue;
1421
+ }
1422
+ if (cPosition === t.length - 1) {
1423
+ return i + 1 < tokens.length ? tokens[i + 1].value : null;
1424
+ }
1425
+ return t.slice(cPosition + 1);
1426
+ }
1427
+ i += 1;
1428
+ }
1429
+ return null;
1430
+ }
1431
+ function findEnvSCommand(tokens, start) {
1432
+ for (let i = start; i < tokens.length; i += 1) {
1433
+ const value = tokens[i].value;
1434
+ if (value === "--") return null;
1435
+ if (value.startsWith("--")) {
1436
+ if (value === "--split-string") {
1437
+ const script = tokens[i + 1];
1438
+ if (script === void 0) return null;
1439
+ return { script: script.value, tailIndex: i + 2 };
1440
+ }
1441
+ if (value.startsWith("--split-string=")) {
1442
+ return { script: value.slice("--split-string=".length), tailIndex: i + 1 };
1443
+ }
1444
+ if (VALUE_OPTIONS.env.has(value)) i += 1;
1445
+ continue;
1446
+ }
1447
+ if (!value.startsWith("-") || value.length <= 1) return null;
1448
+ const letters = value.slice(1);
1449
+ for (let position = 0; position < letters.length; position += 1) {
1450
+ const letter = letters[position];
1451
+ if (letter === "S") {
1452
+ if (position === letters.length - 1) {
1453
+ const script = tokens[i + 1];
1454
+ if (script === void 0) return null;
1455
+ return { script: script.value, tailIndex: i + 2 };
1456
+ }
1457
+ return { script: letters.slice(position + 1), tailIndex: i + 1 };
1458
+ }
1459
+ if (letter === "u" || letter === "C" || letter === "P") {
1460
+ if (position === letters.length - 1) i += 1;
1461
+ break;
1462
+ }
1463
+ }
1464
+ }
1465
+ return null;
1466
+ }
1467
+ function consumeSshRemote(tokens, start) {
1468
+ let i = start;
1469
+ let hostSeen = false;
1470
+ while (i < tokens.length) {
1471
+ const t = tokens[i].value;
1472
+ if (t === "--") {
1473
+ i += 1;
1474
+ break;
1475
+ }
1476
+ if (t.startsWith("-") && t.length > 1) {
1477
+ const valued = sshValueOption(t);
1478
+ i += valued !== void 0 && valued.attached === void 0 ? 2 : 1;
1479
+ continue;
1480
+ }
1481
+ if (!hostSeen) {
1482
+ hostSeen = true;
1483
+ i += 1;
1484
+ continue;
1485
+ }
1486
+ break;
1487
+ }
1488
+ return tokens.slice(i);
1489
+ }
1490
+
1491
+ // src/capability/heredoc-extractor.ts
1492
+ import { createHash } from "crypto";
1493
+ var MAX_BODY_BYTES = 4096;
1494
+ var BARE_WORD_STOP = /* @__PURE__ */ new Set([
1495
+ " ",
1496
+ " ",
1497
+ "\n",
1498
+ "\r",
1499
+ "|",
1500
+ "&",
1501
+ ";",
1502
+ "<",
1503
+ ">",
1504
+ "(",
1505
+ ")",
1506
+ "\\",
1507
+ "'",
1508
+ '"'
1509
+ ]);
1510
+ function parseDelimiterWord(command, start) {
1511
+ let index = start;
1512
+ let delimiter = "";
1513
+ let quoted = false;
1514
+ let resolved = true;
1515
+ let sawAny = false;
1516
+ while (index < command.length) {
1517
+ const c = command[index];
1518
+ if (c === "'") {
1519
+ const end = command.indexOf("'", index + 1);
1520
+ if (end === -1) {
1521
+ resolved = false;
1522
+ break;
1523
+ }
1524
+ delimiter += command.slice(index + 1, end);
1525
+ quoted = true;
1526
+ sawAny = true;
1527
+ index = end + 1;
1528
+ continue;
1529
+ }
1530
+ if (c === "$" && (command[index + 1] === "'" || command[index + 1] === '"')) {
1531
+ quoted = true;
1532
+ sawAny = true;
1533
+ if (command[index + 1] === "'") {
1534
+ const parsed = unescapeAnsiC(command, index + 2);
1535
+ if (!parsed.closed) {
1536
+ resolved = false;
1537
+ break;
1538
+ }
1539
+ delimiter += parsed.text;
1540
+ index = parsed.end;
1541
+ } else {
1542
+ index += 1;
1543
+ }
1544
+ continue;
1545
+ }
1546
+ if (c === '"') {
1547
+ index += 1;
1548
+ let closed = false;
1549
+ while (index < command.length) {
1550
+ const d = command[index];
1551
+ if (d === '"') {
1552
+ closed = true;
1553
+ index += 1;
1554
+ break;
1555
+ }
1556
+ if (d === "\\" && index + 1 < command.length) {
1557
+ const escaped = command[index + 1];
1558
+ if ('$`"\\'.includes(escaped)) delimiter += escaped;
1559
+ else delimiter += `\\${escaped}`;
1560
+ index += 2;
1561
+ continue;
1562
+ }
1563
+ delimiter += d;
1564
+ index += 1;
1565
+ }
1566
+ if (!closed) {
1567
+ resolved = false;
1568
+ break;
1569
+ }
1570
+ quoted = true;
1571
+ sawAny = true;
1572
+ continue;
1573
+ }
1574
+ if (c === "\\" && index + 1 < command.length) {
1575
+ delimiter += command[index + 1];
1576
+ quoted = true;
1577
+ sawAny = true;
1578
+ index += 2;
1579
+ continue;
1580
+ }
1581
+ if (BARE_WORD_STOP.has(c)) break;
1582
+ delimiter += c;
1583
+ sawAny = true;
1584
+ index += 1;
1585
+ }
1586
+ if (!sawAny) return { wordEnd: start, delimiter: "", quoted: false, resolved: false };
1587
+ return { wordEnd: index, delimiter, quoted, resolved };
1588
+ }
1589
+ function unescapeAnsiC(command, start) {
1590
+ let text = "";
1591
+ let index = start;
1592
+ while (index < command.length) {
1593
+ const c = command[index];
1594
+ if (c === "'") return { text, end: index + 1, closed: true };
1595
+ if (c !== "\\") {
1596
+ text += c;
1597
+ index += 1;
1598
+ continue;
1599
+ }
1600
+ const escaped = command[index + 1];
1601
+ if (escaped === void 0) break;
1602
+ if (escaped === "x") {
1603
+ const hex = /^[0-9a-fA-F]{1,2}/.exec(command.slice(index + 2));
1604
+ if (hex === null) {
1605
+ text += "x";
1606
+ index += 2;
1607
+ continue;
1608
+ }
1609
+ text += String.fromCharCode(Number.parseInt(hex[0], 16));
1610
+ index += 2 + hex[0].length;
1611
+ continue;
1612
+ }
1613
+ if (/^[0-7]/.test(escaped)) {
1614
+ const octal = /^[0-7]{1,3}/.exec(command.slice(index + 1));
1615
+ text += String.fromCharCode(Number.parseInt(octal[0], 8));
1616
+ index += 1 + octal[0].length;
1617
+ continue;
1618
+ }
1619
+ const simple = {
1620
+ a: "\x07",
1621
+ b: "\b",
1622
+ e: "\x1B",
1623
+ E: "\x1B",
1624
+ f: "\f",
1625
+ n: "\n",
1626
+ r: "\r",
1627
+ t: " ",
1628
+ v: "\v",
1629
+ "\\": "\\",
1630
+ "'": "'",
1631
+ '"': '"'
1632
+ };
1633
+ text += simple[escaped] ?? escaped;
1634
+ index += 2;
1635
+ }
1636
+ return { text, end: index, closed: false };
1637
+ }
1638
+ function extractHeredocs(command) {
1639
+ const heredocs = [];
1640
+ let hasDynamicConstructs = false;
1641
+ let out = "";
1642
+ let cursor = 0;
1643
+ let i = 0;
1644
+ let lineStart = 0;
1645
+ let inSingle = false;
1646
+ let inDouble = false;
1647
+ let arithmeticDepth = 0;
1648
+ const pending = [];
1649
+ let pieces = [];
1650
+ const appendText = (text) => {
1651
+ if (text.length === 0) return;
1652
+ const last = pieces.at(-1);
1653
+ if (last !== void 0 && "text" in last) last.text += text;
1654
+ else pieces.push({ text });
1655
+ };
1656
+ const consumeBodies = (bodyStart, lineEnd) => {
1657
+ let position = bodyStart;
1658
+ const records = [];
1659
+ for (const start of pending) {
1660
+ let body;
1661
+ let truncated;
1662
+ if (start.resolved) {
1663
+ const collected = collectBody(command, position, start.delimiter, start.operator === "<<-");
1664
+ body = collected.body;
1665
+ truncated = collected.truncated;
1666
+ position = collected.endIndex + 1;
1667
+ } else {
1668
+ body = command.slice(position);
1669
+ truncated = true;
1670
+ position = command.length;
1671
+ }
1672
+ const sha256hex2 = createHash("sha256").update(body).digest("hex");
1673
+ const dynamic = start.resolved ? containsDynamic(body, start.quoted) : true;
1674
+ const { bounded, wasTruncated } = boundBody(body, truncated);
1675
+ if (dynamic) hasDynamicConstructs = true;
1676
+ const outputTarget = findOutputTarget(command.slice(start.lineStart, start.opStart)) ?? findOutputTarget(command.slice(start.wordEnd, lineEnd));
1677
+ records.push({
1678
+ bounded,
1679
+ sha256: sha256hex2,
1680
+ truncated: wasTruncated,
1681
+ dynamic,
1682
+ ...outputTarget === void 0 ? {} : { outputTarget }
1683
+ });
1684
+ }
1685
+ let assembled = "";
1686
+ for (const piece of pieces) {
1687
+ if ("text" in piece) {
1688
+ assembled += piece.text;
1689
+ continue;
1690
+ }
1691
+ const start = pending[piece.pendingIndex];
1692
+ const record = records[piece.pendingIndex];
1693
+ const shown = start.resolved ? start.delimiter : "<unresolved>";
1694
+ const safe = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(shown) ? shown : `'${shown.replace(/'/g, "'\\''")}'`;
1695
+ assembled += `${start.operator}${safe} <HEREDOC:sha256:${record.sha256.slice(0, 12)}>`;
1696
+ }
1697
+ out += assembled;
1698
+ for (let index = 0; index < pending.length; index += 1) {
1699
+ const start = pending[index];
1700
+ const record = records[index];
1701
+ heredocs.push({
1702
+ delimiter: start.resolved ? start.delimiter : start.rawWord,
1703
+ operator: start.operator,
1704
+ expansionDisabled: start.quoted,
1705
+ bodyBounded: record.bounded,
1706
+ bodySha256: record.sha256,
1707
+ truncated: record.truncated,
1708
+ ...record.outputTarget === void 0 ? {} : { outputTarget: record.outputTarget },
1709
+ dynamic: record.dynamic
1710
+ });
1711
+ }
1712
+ pending.length = 0;
1713
+ pieces = [];
1714
+ return position;
1715
+ };
1716
+ while (i < command.length) {
1717
+ const c = command[i];
1718
+ if (inSingle) {
1719
+ if (c === "'") inSingle = false;
1720
+ i += 1;
1721
+ continue;
1722
+ }
1723
+ if (inDouble) {
1724
+ if (c === "\\") i += 1;
1725
+ else if (c === '"') inDouble = false;
1726
+ i += 1;
1727
+ continue;
1728
+ }
1729
+ if (c === "'") {
1730
+ inSingle = true;
1731
+ i += 1;
1732
+ continue;
1733
+ }
1734
+ if (c === '"') {
1735
+ inDouble = true;
1736
+ i += 1;
1737
+ continue;
1738
+ }
1739
+ if (c === "\\" && i + 1 < command.length) {
1740
+ i += 2;
1741
+ continue;
1742
+ }
1743
+ if (c === "#" && (i === 0 || /[\s;&|()]/.test(command[i - 1]))) {
1744
+ while (i < command.length && command[i] !== "\n") i += 1;
1745
+ continue;
1746
+ }
1747
+ if (arithmeticDepth > 0) {
1748
+ if (c === "(") arithmeticDepth += 1;
1749
+ else if (c === ")") arithmeticDepth -= 1;
1750
+ i += 1;
1751
+ continue;
1752
+ }
1753
+ if (c === "$" && command[i + 1] === "(" && command[i + 2] === "(" || c === "(" && command[i + 1] === "(" && (i === 0 || /[\s;&|()]/.test(command[i - 1]))) {
1754
+ arithmeticDepth = 2;
1755
+ i += c === "$" ? 3 : 2;
1756
+ continue;
1757
+ }
1758
+ if (c === "\n") {
1759
+ if (pending.length > 0) {
1760
+ appendText(command.slice(cursor, i));
1761
+ const resume = consumeBodies(i + 1, i);
1762
+ out += "\n";
1763
+ cursor = i = resume;
1764
+ lineStart = resume;
1765
+ continue;
1766
+ }
1767
+ lineStart = i + 1;
1768
+ i += 1;
1769
+ continue;
1770
+ }
1771
+ if (c === "<" && command[i + 1] === "<") {
1772
+ let j = i + 2;
1773
+ const operator = command[j] === "-" ? "<<-" : "<<";
1774
+ if (operator === "<<-") j += 1;
1775
+ if (command[j] === "<") {
1776
+ i = j + 1;
1777
+ continue;
1778
+ }
1779
+ while (j < command.length && (command[j] === " " || command[j] === " ")) j += 1;
1780
+ const word = parseDelimiterWord(command, j);
1781
+ appendText(command.slice(cursor, i));
1782
+ pending.push({
1783
+ operator,
1784
+ delimiter: word.delimiter,
1785
+ rawWord: command.slice(j, word.wordEnd),
1786
+ quoted: word.quoted,
1787
+ resolved: word.resolved,
1788
+ opStart: i,
1789
+ wordEnd: word.wordEnd,
1790
+ lineStart
1791
+ });
1792
+ pieces.push({ pendingIndex: pending.length - 1 });
1793
+ cursor = i = word.wordEnd;
1794
+ continue;
1795
+ }
1796
+ i += 1;
1797
+ }
1798
+ if (pending.length > 0) {
1799
+ appendText(command.slice(cursor, command.length));
1800
+ consumeBodies(command.length, command.length);
1801
+ cursor = command.length;
1802
+ }
1803
+ out += command.slice(cursor);
1804
+ return { sanitizedCommand: out, heredocs, hasDynamicConstructs };
1805
+ }
1806
+ function findOutputTarget(beforeOperator) {
1807
+ const trimmed = beforeOperator.replace(/\s+$/, "");
1808
+ const match = />>?\s*([^\s|;&<>]+)\s*$/.exec(trimmed);
1809
+ return match === null ? void 0 : stripQuotes(match[1]);
1810
+ }
1811
+ function stripQuotes(token) {
1812
+ if (token.length >= 2) {
1813
+ const head = token[0];
1814
+ const tail = token[token.length - 1];
1815
+ if ((head === "'" || head === '"') && head === tail) return token.slice(1, -1);
1816
+ }
1817
+ return token;
1818
+ }
1819
+ function collectBody(source, start, delimiter, tabStripped) {
1820
+ let i = start;
1821
+ let body = "";
1822
+ let truncated = false;
1823
+ while (i < source.length) {
1824
+ let lineEnd = source.indexOf("\n", i);
1825
+ if (lineEnd === -1) lineEnd = source.length;
1826
+ const line = source.slice(i, lineEnd);
1827
+ const candidate = tabStripped ? line.replace(/^\t+/, "") : line;
1828
+ if (candidate === delimiter) {
1829
+ return { body, endIndex: lineEnd, truncated };
1830
+ }
1831
+ body += line + "\n";
1832
+ if (body.length > MAX_BODY_BYTES * 4) truncated = true;
1833
+ i = lineEnd + 1;
1834
+ }
1835
+ truncated = true;
1836
+ return { body, endIndex: source.length, truncated };
1837
+ }
1838
+ function boundBody(fullBody, alreadyTruncated) {
1839
+ const bytes = Buffer.byteLength(fullBody, "utf8");
1840
+ if (bytes <= MAX_BODY_BYTES) return { bounded: fullBody, wasTruncated: alreadyTruncated };
1841
+ let cut = 0;
1842
+ let len = 0;
1843
+ while (cut < fullBody.length && len < MAX_BODY_BYTES) {
1844
+ len += Buffer.byteLength(fullBody[cut], "utf8");
1845
+ cut += 1;
1846
+ }
1847
+ return { bounded: fullBody.slice(0, cut) + "\n\u2026[truncated]", wasTruncated: true };
1848
+ }
1849
+ function containsDynamic(body, expansionDisabled) {
1850
+ if (expansionDisabled) return false;
1851
+ return /\$\(?|`/.test(body);
1852
+ }
1853
+
1854
+ // src/capability/command-parser.ts
1855
+ var REDIRECTION_OPS = /* @__PURE__ */ new Set([">", ">>", "<", "<<", ">&", "2>", "&>", "1>", "2>>", "&>>"]);
1856
+ function parseCommand(rawCommand) {
1857
+ const { sanitizedCommand, heredocs, hasDynamicConstructs } = extractHeredocs(rawCommand);
1858
+ const lex = lexSegmentsBounded(sanitizedCommand);
1859
+ const segments = lex.segments;
1860
+ const effective = [];
1861
+ const redirections = [];
1862
+ let analysisTruncated = lex.truncated;
1863
+ const budget = newAnalysisBudget();
1864
+ for (const segment of segments) {
1865
+ const analysis = analyzeEffectiveCommands(segment, budget);
1866
+ analysisTruncated = analysisTruncated || analysis.truncated;
1867
+ for (let index = 0; index < analysis.commands.length; index += 1) {
1868
+ const cmd = analysis.commands[index];
1869
+ effective.push(cmd);
1870
+ redirections.push(analysis.redirections[index] ?? extractRedirections(cmd));
1871
+ }
1872
+ }
1873
+ const dyn = looksDynamic(sanitizedCommand);
1874
+ const dynamic = hasDynamicConstructs || dyn || segments.some((segment) => segmentHasDynamic(segment.tokens));
1875
+ return {
1876
+ sanitizedCommand,
1877
+ segments,
1878
+ effective,
1879
+ redirections,
1880
+ heredocs,
1881
+ hasDynamicConstructs: dynamic,
1882
+ analysisTruncated
1883
+ };
1884
+ }
1885
+ function extractRedirections(tokens) {
1886
+ const out = [];
1887
+ for (let i = 0; i < tokens.length; i += 1) {
1888
+ const tok = tokens[i];
1889
+ const value = tok.value;
1890
+ const combined = /^([0-9]?>>?)\s*(.+)$/.exec(value);
1891
+ if (combined) {
1892
+ out.push({
1893
+ operator: combined[1],
1894
+ target: combined[2],
1895
+ quoted: isQuoted(combined[2], tok.raw)
1896
+ });
1897
+ continue;
1898
+ }
1899
+ if (REDIRECTION_OPS.has(value) && i + 1 < tokens.length) {
1900
+ const next = tokens[i + 1];
1901
+ out.push({ operator: value, target: next.value, quoted: isQuoted(next.value, next.raw) });
1902
+ i += 1;
1903
+ continue;
1904
+ }
1905
+ if (value.startsWith(">") || value.startsWith("<")) {
1906
+ const op = value.startsWith(">>") ? ">>" : value[0];
1907
+ out.push({
1908
+ operator: op,
1909
+ target: value.slice(op === ">>" ? 2 : 1),
1910
+ quoted: isQuoted(value, tok.raw)
1911
+ });
1912
+ }
1913
+ }
1914
+ return out;
1915
+ }
1916
+ function isQuoted(value, raw) {
1917
+ if (raw.length < value.length) return true;
1918
+ const head = raw[0];
1919
+ const tail = raw[raw.length - 1];
1920
+ return (head === "'" || head === '"') && head === tail;
1921
+ }
1922
+ function looksDynamic(command) {
1923
+ const literal = command.replace(/'[^']*'/g, "");
1924
+ return /\$\(|`|\$\{|\$[A-Za-z_]|[?*]\s|<\(|>\(|\[\[/.test(literal);
1925
+ }
1926
+ function segmentHasDynamic(tokens) {
1927
+ return tokens.some((tok) => /\$|[*?]/.test(tok.value) && !isAllLiteral(tok.raw));
1928
+ }
1929
+ function isAllLiteral(raw) {
1930
+ return /^'[^']*'$/.test(raw);
1931
+ }
1932
+
1933
+ // src/capability/bash-analyzer.ts
1934
+ import { homedir as homedir2 } from "os";
1935
+ import { normalize, resolve, sep } from "path";
1936
+
1937
+ // src/capability/sensitive-paths.ts
1938
+ var SENSITIVE_PATH = /(?:^|\/)(?:\.env(?:\.|$)|\.ssh(?:\/|$)|\.aws(?:\/|$)|\.config\/gcloud(?:\/|$)|\.config\/gh\/hosts\.yml$|id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$|credentials(?:\.json)?$|authorized_keys$|known_hosts$|\.npmrc$|\.pypirc$|\.netrc$)/i;
1939
+ var NON_SECRET_SUFFIX = /\.(?:example|sample|template|dist|pub)$/i;
1940
+ function isSensitivePathToken(path) {
1941
+ if (!path) return false;
1942
+ if (NON_SECRET_SUFFIX.test(path)) return false;
1943
+ return SENSITIVE_PATH.test(path);
1944
+ }
1945
+
1946
+ // src/capability/bash-analyzer.ts
1947
+ var INTERPRETERS = /* @__PURE__ */ new Set([
1948
+ "sh",
1949
+ "bash",
1950
+ "zsh",
1951
+ "dash",
1952
+ "ksh",
1953
+ "ash",
1954
+ "mksh",
1955
+ "fish",
1956
+ "python",
1957
+ "python2",
1958
+ "python3",
1959
+ "py",
1960
+ "node",
1961
+ "nodejs",
1962
+ "bun",
1963
+ "deno",
1964
+ "tsx",
1965
+ "ruby",
1966
+ "rb",
1967
+ "perl",
1968
+ "php",
1969
+ "lua",
1970
+ "tclsh",
1971
+ "wish",
1972
+ "java",
1973
+ "javac",
1974
+ "dotnet",
1975
+ "Rscript",
1976
+ "julia",
1977
+ "awk",
1978
+ "gawk",
1979
+ "nawk"
1980
+ ]);
1981
+ var TEST_RUNNERS = /* @__PURE__ */ new Set([
1982
+ "pytest",
1983
+ "py.test",
1984
+ "unittest",
1985
+ "jest",
1986
+ "vitest",
1987
+ "mocha",
1988
+ "ava",
1989
+ "karma",
1990
+ "jasmine",
1991
+ "cypress",
1992
+ "playwright",
1993
+ "nx",
1994
+ "rake",
1995
+ "rspec",
1996
+ "minitest",
1997
+ "go",
1998
+ // `go test`
1999
+ "cargo",
2000
+ // `cargo test`
2001
+ "gradle",
2002
+ // `gradle test`
2003
+ "mvn",
2004
+ // `mvn test`
2005
+ "make",
2006
+ // often runs a test target
2007
+ "cmake",
2008
+ "ctest",
2009
+ "tap",
2010
+ "tape",
2011
+ "nu"
2012
+ ]);
2013
+ var PACKAGE_MANAGERS = /* @__PURE__ */ new Set([
2014
+ "npm",
2015
+ "pnpm",
2016
+ "yarn",
2017
+ "bun",
2018
+ // also an interpreter; dual-classified below
2019
+ "pip",
2020
+ "pip3",
2021
+ "pipx",
2022
+ "poetry",
2023
+ "uv",
2024
+ "conda",
2025
+ "mamba",
2026
+ "gem",
2027
+ "bundle",
2028
+ "cargo",
2029
+ "go",
2030
+ // `go get` / `go install`
2031
+ "composer",
2032
+ "mvn",
2033
+ "gradle",
2034
+ "apt",
2035
+ "apt-get",
2036
+ "apk",
2037
+ "dnf",
2038
+ "yum",
2039
+ "zypper",
2040
+ "pacman",
2041
+ "brew",
2042
+ "port",
2043
+ "nix",
2044
+ "flatpak",
2045
+ "snap",
2046
+ "choco",
2047
+ "scoop",
2048
+ "winget"
2049
+ ]);
2050
+ var PACKAGE_SUBCOMMANDS = {
2051
+ npm: /* @__PURE__ */ new Set(["install", "i", "add", "ci", "update", "upgrade", "run", "exec", "x"]),
2052
+ pnpm: /* @__PURE__ */ new Set(["install", "add", "update", "upgrade", "exec", "run", "dlx"]),
2053
+ yarn: /* @__PURE__ */ new Set(["add", "install", "upgrade", "remove", "run", "exec"]),
2054
+ bun: /* @__PURE__ */ new Set(["add", "install", "update", "upgrade", "remove", "run", "x"]),
2055
+ pip: /* @__PURE__ */ new Set(["install", "download"]),
2056
+ pip3: /* @__PURE__ */ new Set(["install", "download"]),
2057
+ poetry: /* @__PURE__ */ new Set(["install", "add", "update", "upgrade"]),
2058
+ uv: /* @__PURE__ */ new Set(["pip install", "add", "sync"]),
2059
+ pipx: /* @__PURE__ */ new Set(["install", "inject", "upgrade"]),
2060
+ conda: /* @__PURE__ */ new Set(["install", "create", "update"]),
2061
+ gem: /* @__PURE__ */ new Set(["install", "update"]),
2062
+ bundle: /* @__PURE__ */ new Set(["install", "update"]),
2063
+ cargo: /* @__PURE__ */ new Set(["install", "add", "update", "fetch"]),
2064
+ go: /* @__PURE__ */ new Set(["get", "install", "mod download", "mod tidy"]),
2065
+ composer: /* @__PURE__ */ new Set(["install", "update", "require"]),
2066
+ apt: /* @__PURE__ */ new Set(["install", "upgrade", "update", "remove", "purge"]),
2067
+ "apt-get": /* @__PURE__ */ new Set(["install", "upgrade", "update", "remove", "purge"]),
2068
+ apk: /* @__PURE__ */ new Set(["add", "upgrade", "del"]),
2069
+ dnf: /* @__PURE__ */ new Set(["install", "upgrade", "remove"]),
2070
+ yum: /* @__PURE__ */ new Set(["install", "upgrade", "remove"]),
2071
+ pacman: /* @__PURE__ */ new Set(["-S", "-Sy", "-Syu", "-R", "-Rs"]),
2072
+ brew: /* @__PURE__ */ new Set(["install", "upgrade", "reinstall"])
2073
+ };
2074
+ var NETWORK_CLIENTS = /* @__PURE__ */ new Set([
2075
+ "curl",
2076
+ "wget",
2077
+ "nc",
2078
+ "ncat",
2079
+ "netcat",
2080
+ "socat",
2081
+ "ftp",
2082
+ "sftp",
2083
+ "scp",
2084
+ "rsync",
2085
+ "telnet",
2086
+ "dig",
2087
+ "nslookup",
2088
+ "host",
2089
+ "ping",
2090
+ "traceroute",
2091
+ "openssl",
2092
+ "httpie",
2093
+ "http",
2094
+ "aria2c",
2095
+ "axon"
2096
+ ]);
2097
+ var FILE_WRITE_TOOLS = /* @__PURE__ */ new Set(["tee", "dd", "install", "truncate", "shred"]);
2098
+ var FILE_MUTATION_TOOLS = /* @__PURE__ */ new Set(["cp", "mv", "rename", "ln", "link", "symlink", "rsync"]);
2099
+ var MUTATION_VALUE_OPTIONS = {
2100
+ cp: /* @__PURE__ */ new Set(["-t", "--target-directory", "-S", "--suffix"]),
2101
+ mv: /* @__PURE__ */ new Set(["-t", "--target-directory", "-S", "--suffix"]),
2102
+ ln: /* @__PURE__ */ new Set(["-t", "--target-directory", "-S", "--suffix"]),
2103
+ rsync: /* @__PURE__ */ new Set([
2104
+ "--backup-dir",
2105
+ "-e",
2106
+ "--rsh",
2107
+ "--rsync-path",
2108
+ "--exclude-from",
2109
+ "--include-from",
2110
+ "--files-from",
2111
+ "--suffix",
2112
+ "--password-file",
2113
+ "--log-file",
2114
+ "--out-format"
2115
+ ])
2116
+ };
2117
+ function isRemoteMutationOperand(value) {
2118
+ if (/^[a-z][a-z0-9+.-]*:\/\//.test(value)) return true;
2119
+ const colon = value.indexOf(":");
2120
+ return colon > 0 && !value.slice(0, colon).includes("/");
2121
+ }
2122
+ function mutationOperands(base, cmd) {
2123
+ const valueOpts = MUTATION_VALUE_OPTIONS[base] ?? /* @__PURE__ */ new Set();
2124
+ const operands = [];
2125
+ let targetDirectory;
2126
+ let endOfOptions = false;
2127
+ for (let i = 1; i < cmd.length; i += 1) {
2128
+ const v = cmd[i].value;
2129
+ if (!endOfOptions && v === "--") {
2130
+ endOfOptions = true;
2131
+ continue;
2132
+ }
2133
+ if (!endOfOptions && v.startsWith("--")) {
2134
+ if (valueOpts.has(v)) {
2135
+ if (v === "--target-directory") targetDirectory = cmd[i + 1]?.value;
2136
+ i += 1;
2137
+ } else if (valueOpts.has("--target-directory") && v.startsWith("--target-directory=")) {
2138
+ targetDirectory = v.slice("--target-directory=".length);
2139
+ }
2140
+ continue;
2141
+ }
2142
+ if (!endOfOptions && v.startsWith("-") && v.length > 1) {
2143
+ for (let position = 1; position < v.length; position += 1) {
2144
+ const option = `-${v[position]}`;
2145
+ if (!valueOpts.has(option)) continue;
2146
+ const attached = v.slice(position + 1);
2147
+ const value = attached || cmd[++i]?.value;
2148
+ if (option === "-t") targetDirectory = value;
2149
+ break;
2150
+ }
2151
+ continue;
2152
+ }
2153
+ operands.push(v);
2154
+ }
2155
+ if (targetDirectory !== void 0) {
2156
+ return { sources: operands, destinations: [targetDirectory], sawOperand: operands.length > 0 };
2157
+ }
2158
+ if (base === "rename") {
2159
+ return { sources: [], destinations: operands, sawOperand: operands.length > 0 };
2160
+ }
2161
+ if (base === "ln" && operands.length === 1) {
2162
+ return { sources: operands, destinations: ["."], sawOperand: true };
2163
+ }
2164
+ const destinations = [];
2165
+ if (operands.length > 0) destinations.push(operands[operands.length - 1]);
2166
+ const sources = operands.length > 1 ? operands.slice(0, -1) : [];
2167
+ return { sources, destinations, sawOperand: operands.length > 0 };
2168
+ }
2169
+ var READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
2170
+ "cat",
2171
+ "less",
2172
+ "more",
2173
+ "ls",
2174
+ "head",
2175
+ "tail",
2176
+ "wc",
2177
+ "file",
2178
+ "stat",
2179
+ "pwd",
2180
+ "echo",
2181
+ "printf",
2182
+ "date",
2183
+ "whoami",
2184
+ "id",
2185
+ "uname",
2186
+ "hostname",
2187
+ "who",
2188
+ "w",
2189
+ "uptime",
2190
+ "which",
2191
+ "type",
2192
+ "printenv",
2193
+ "grep",
2194
+ "egrep",
2195
+ "fgrep",
2196
+ "rg",
2197
+ "find",
2198
+ "du",
2199
+ "df",
2200
+ "tree",
2201
+ "jq",
2202
+ "yq",
2203
+ "sort",
2204
+ "uniq",
2205
+ "cut",
2206
+ "column",
2207
+ "tr",
2208
+ "diff",
2209
+ "cmp",
2210
+ "comm",
2211
+ "md5sum",
2212
+ "sha1sum",
2213
+ "sha256sum",
2214
+ "sha512sum",
2215
+ "cksum",
2216
+ "base64",
2217
+ "xxd",
2218
+ "od",
2219
+ "strings",
2220
+ "nl",
2221
+ "tac",
2222
+ "rev",
2223
+ "fold",
2224
+ "fmt",
2225
+ "expand",
2226
+ "unexpand",
2227
+ "seq",
2228
+ "true",
2229
+ "false",
2230
+ "sleep",
2231
+ "clear",
2232
+ "test",
2233
+ "[",
2234
+ "basename",
2235
+ "dirname",
2236
+ "realpath",
2237
+ "readlink",
2238
+ "man",
2239
+ "info",
2240
+ "tput"
2241
+ ]);
2242
+ var NO_EFFECT_BUILTINS = /* @__PURE__ */ new Set([
2243
+ "cd",
2244
+ "pushd",
2245
+ "popd",
2246
+ "dirs",
2247
+ "export",
2248
+ "unset",
2249
+ "set",
2250
+ "shopt",
2251
+ "alias",
2252
+ "unalias",
2253
+ "exit",
2254
+ "return",
2255
+ "shift",
2256
+ "wait",
2257
+ "jobs",
2258
+ "fg",
2259
+ "bg",
2260
+ "read",
2261
+ "local",
2262
+ "declare",
2263
+ "readonly",
2264
+ "getopts",
2265
+ "hash",
2266
+ "help",
2267
+ "let",
2268
+ "trap",
2269
+ "ulimit",
2270
+ "umask",
2271
+ "builtin",
2272
+ "command"
2273
+ ]);
2274
+ var DELETION_TOOLS = /* @__PURE__ */ new Set(["rm", "rmdir", "unlink", "shred", "truncate"]);
2275
+ var GIT_MUTATION_SUBCOMMANDS = /* @__PURE__ */ new Set([
2276
+ "add",
2277
+ "am",
2278
+ "apply",
2279
+ "bisect",
2280
+ "branch",
2281
+ "checkout",
2282
+ "cherry-pick",
2283
+ "clean",
2284
+ "clone",
2285
+ "commit",
2286
+ "config",
2287
+ "fetch",
2288
+ "filter-branch",
2289
+ "gc",
2290
+ "init",
2291
+ "maintenance",
2292
+ "merge",
2293
+ "mv",
2294
+ "notes",
2295
+ "prune",
2296
+ "pull",
2297
+ "push",
2298
+ "rebase",
2299
+ "remote",
2300
+ "repack",
2301
+ "replace",
2302
+ "reset",
2303
+ "restore",
2304
+ "revert",
2305
+ "rm",
2306
+ "stash",
2307
+ "submodule",
2308
+ "switch",
2309
+ "symbolic-ref",
2310
+ "tag",
2311
+ "update-ref",
2312
+ "worktree"
2313
+ ]);
2314
+ var GIT_NETWORK_SUBCOMMANDS = /* @__PURE__ */ new Set(["clone", "fetch", "ls-remote", "pull", "push"]);
2315
+ var PRIVILEGE_WRAPPERS = /* @__PURE__ */ new Set([
2316
+ "sudo",
2317
+ "doas",
2318
+ "pkexec",
2319
+ "su",
2320
+ "runuser",
2321
+ "super",
2322
+ "setpriv",
2323
+ "setcap",
2324
+ "capsh"
2325
+ ]);
2326
+ var SERVICE_MANAGERS = /* @__PURE__ */ new Set([
2327
+ "systemctl",
2328
+ "service",
2329
+ "rc-service",
2330
+ "rc-update",
2331
+ "initctl",
2332
+ "launchctl",
2333
+ "supervisorctl",
2334
+ "pm2",
2335
+ "forever",
2336
+ "nodemon",
2337
+ "god",
2338
+ "circus"
2339
+ ]);
2340
+ var PERSISTENCE_WRAPPERS = /* @__PURE__ */ new Set(["nohup", "setsid", "disown"]);
2341
+ var PERSISTENCE_TOOLS = /* @__PURE__ */ new Set(["at", "atq", "atrm", "cron", "crontab"]);
2342
+ var SSH_TOOLS = /* @__PURE__ */ new Set(["ssh", "mosh", "autossh"]);
2343
+ var CREDENTIAL_READERS = /* @__PURE__ */ new Set([
2344
+ "cat",
2345
+ "head",
2346
+ "tail",
2347
+ "less",
2348
+ "more",
2349
+ "grep",
2350
+ "rg",
2351
+ "sed",
2352
+ "awk",
2353
+ "base64",
2354
+ "xxd",
2355
+ "od",
2356
+ "strings",
2357
+ "source",
2358
+ "."
2359
+ ]);
2360
+ var SHELL_KEYWORDS2 = /* @__PURE__ */ new Set(["{", "}", "(", ")", "then", "else", "do", "elif", "!"]);
2361
+ var directoryFallback = ".";
2362
+ function readOnlyToolMutation(cmd, base) {
2363
+ if (base === "find") {
2364
+ let index = 1;
2365
+ while (index < cmd.length) {
2366
+ const value = cmd[index].value;
2367
+ if (value === "--") {
2368
+ index += 1;
2369
+ break;
2370
+ }
2371
+ if (value === "-D") {
2372
+ index += 2;
2373
+ continue;
2374
+ }
2375
+ if (value === "-H" || value === "-L" || value === "-P" || /^-O\d+$/.test(value)) {
2376
+ index += 1;
2377
+ continue;
2378
+ }
2379
+ break;
2380
+ }
2381
+ const roots = [];
2382
+ while (index < cmd.length && !cmd[index].value.startsWith("-") && cmd[index].value !== "!" && cmd[index].value !== "(") {
2383
+ roots.push(cmd[index].value);
2384
+ index += 1;
2385
+ }
2386
+ const result = { writeTargets: [] };
2387
+ for (; index < cmd.length; index += 1) {
2388
+ const value = cmd[index].value;
2389
+ if (value === "-delete") {
2390
+ result.deletion = true;
2391
+ result.writeTargets.push(...roots);
2392
+ } else if (value.startsWith("-exec") || value.startsWith("-ok")) {
2393
+ result.executesCode = true;
2394
+ } else if (value === "-fls" || value.startsWith("-fprint")) {
2395
+ const target = cmd[index + 1]?.value;
2396
+ if (target !== void 0 && !target.startsWith("-")) result.writeTargets.push(target);
2397
+ }
2398
+ }
2399
+ return result.deletion || result.executesCode || result.writeTargets.length > 0 ? result : void 0;
2400
+ }
2401
+ if (base === "sort") {
2402
+ const result = { writeTargets: [] };
2403
+ for (let index = 1; index < cmd.length; index += 1) {
2404
+ const value = cmd[index].value;
2405
+ if (value === "-o" || value === "--output") {
2406
+ const target = cmd[index + 1]?.value;
2407
+ if (target !== void 0 && !target.startsWith("-")) result.writeTargets.push(target);
2408
+ } else if (value.startsWith("--output=")) {
2409
+ result.writeTargets.push(value.slice("--output=".length));
2410
+ } else if (value.startsWith("-o") && value.length > 2) {
2411
+ result.writeTargets.push(value.slice(2));
2412
+ }
2413
+ }
2414
+ return result.writeTargets.length > 0 ? result : void 0;
2415
+ }
2416
+ if (base === "yq") {
2417
+ if (!cmd.some((token) => token.value === "-i" || token.value === "--inplace")) return void 0;
2418
+ const targets = cmd.slice(1).map((token) => token.value).filter((value) => !value.startsWith("-"));
2419
+ return targets.length > 0 ? { writeTargets: targets } : { writeTargets: [directoryFallback] };
2420
+ }
2421
+ return void 0;
2422
+ }
2423
+ function hasCommandSubstitution(command) {
2424
+ return /\$\(|`/.test(command);
2425
+ }
2426
+ function staticFact(value, notes) {
2427
+ return {
2428
+ value,
2429
+ source: "static-analysis",
2430
+ confidence: value === "unknown" ? "unknown" : "high",
2431
+ ...notes === void 0 || notes.length === 0 ? {} : { notes }
2432
+ };
2433
+ }
2434
+ function heuristicFact(value, notes) {
2435
+ return {
2436
+ value,
2437
+ source: "heuristic",
2438
+ confidence: value === "unknown" ? "unknown" : "medium",
2439
+ ...notes === void 0 || notes.length === 0 ? {} : { notes }
2440
+ };
2441
+ }
2442
+ function hasInlineCodeOption(tokens) {
2443
+ if (tokens.length === 0) return { interpreter: "", inline: false };
2444
+ const base = basename(tokens[0].value);
2445
+ if (!INTERPRETERS.has(base)) return { interpreter: base, inline: false };
2446
+ for (let i = 1; i < tokens.length; i += 1) {
2447
+ const v = tokens[i].value;
2448
+ if (v === "-c" || v === "--command" || v === "-e" || v.startsWith("--command=")) {
2449
+ return { interpreter: base, inline: true };
2450
+ }
2451
+ }
2452
+ return { interpreter: base, inline: false };
2453
+ }
2454
+ function hasWriteRedirect(redirections) {
2455
+ return redirections.some(redirectionWritesPath);
2456
+ }
2457
+ function redirectionWritesPath(redirection) {
2458
+ const operator = redirection.operator.replace(/^\d+/, "");
2459
+ if ([">", ">>", ">|", "&>", "&>>", "<>"].includes(operator)) return true;
2460
+ return operator === ">&" && !/^\d/.test(redirection.operator) && redirection.target !== "-" && !/^\d+$/.test(redirection.target);
2461
+ }
2462
+ function classifyPath(target, directory, worktree) {
2463
+ if (!target || target.startsWith("&"))
2464
+ return { temporary: false, workspace: false, external: false };
2465
+ let temp = false;
2466
+ let external = false;
2467
+ let absolute;
2468
+ if (target === "~" || target.startsWith("~/")) {
2469
+ absolute = resolve(homedir2(), target.slice(target === "~" ? 1 : 2));
2470
+ } else if (!target.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(target)) {
2471
+ absolute = resolve(directory, target);
2472
+ } else {
2473
+ absolute = normalize(target);
2474
+ }
2475
+ const absolutePath = absolute.startsWith("/") || /^[A-Za-z]:[\\/]/.test(absolute);
2476
+ const within = (root) => {
2477
+ const normalizedRoot = normalize(root);
2478
+ return absolute === normalizedRoot || absolute.startsWith(`${normalizedRoot}${sep}`);
2479
+ };
2480
+ if (!absolutePath) {
2481
+ return { temporary: temp, workspace: false, external };
2482
+ }
2483
+ const workspace = within(directory) || within(worktree);
2484
+ temp = absolute === "/tmp" || absolute.startsWith("/tmp/") || absolute === "/var/tmp" || absolute.startsWith("/var/tmp/") || absolute === "/dev/shm" || absolute.startsWith("/dev/shm/") || absolute === "/dev/null";
2485
+ external = !workspace && !temp;
2486
+ return { temporary: temp, workspace, external };
2487
+ }
2488
+ function destinationFromTokens(tokens) {
2489
+ const out = [];
2490
+ for (let i = 1; i < tokens.length; i += 1) {
2491
+ const v = tokens[i].value;
2492
+ if (/^[a-z][a-z0-9+.-]*:\/\/[^\s]+/.test(v)) out.push(v);
2493
+ else if (/^[a-z0-9.-]+\.[a-z]{2,}(:[0-9]+)?(\/[^\s]*)?$/i.test(v)) out.push(v);
2494
+ }
2495
+ return out;
2496
+ }
2497
+ function gitSubcommandOf(cmd) {
2498
+ let index = 1;
2499
+ while (index < cmd.length) {
2500
+ const value = cmd[index].value;
2501
+ if (value === "-C" || value === "-c" || value === "--git-dir" || value === "--work-tree" || value === "--namespace" || value === "--exec-path" || value === "--super-prefix") {
2502
+ index += 2;
2503
+ continue;
2504
+ }
2505
+ if (value.startsWith("-") && value.length > 1) {
2506
+ index += 1;
2507
+ continue;
2508
+ }
2509
+ return { sub: value, index };
2510
+ }
2511
+ return {};
2512
+ }
2513
+ function gitSubcommandMutates(cmd, sub, index) {
2514
+ if (!GIT_MUTATION_SUBCOMMANDS.has(sub)) return false;
2515
+ const args = cmd.slice(index + 1).map((token) => token.value);
2516
+ const positional = args.filter((value) => value !== "--" && !value.startsWith("-"));
2517
+ if (sub === "branch") {
2518
+ if (args.length === 0) return false;
2519
+ if (args.some(
2520
+ (value) => [
2521
+ "-a",
2522
+ "--all",
2523
+ "-r",
2524
+ "--remotes",
2525
+ "-l",
2526
+ "--list",
2527
+ "-v",
2528
+ "-vv",
2529
+ "--show-current",
2530
+ "--contains",
2531
+ "--no-contains",
2532
+ "--merged",
2533
+ "--no-merged",
2534
+ "--points-at",
2535
+ "--format",
2536
+ "--sort",
2537
+ "--column"
2538
+ ].includes(value)
2539
+ ))
2540
+ return false;
2541
+ }
2542
+ if (sub === "tag") {
2543
+ if (args.length === 0) return false;
2544
+ if (args.some(
2545
+ (value) => [
2546
+ "-l",
2547
+ "--list",
2548
+ "--contains",
2549
+ "--no-contains",
2550
+ "--merged",
2551
+ "--no-merged",
2552
+ "--points-at",
2553
+ "--format",
2554
+ "--sort",
2555
+ "--column"
2556
+ ].includes(value)
2557
+ ))
2558
+ return false;
2559
+ }
2560
+ if (sub === "remote") {
2561
+ return positional.length > 0 && !["show", "get-url"].includes(positional[0]);
2562
+ }
2563
+ if (sub === "config") {
2564
+ if (args.some(
2565
+ (value) => [
2566
+ "--list",
2567
+ "-l",
2568
+ "--get",
2569
+ "--get-all",
2570
+ "--get-regexp",
2571
+ "--get-urlmatch",
2572
+ "--show-origin",
2573
+ "--show-scope",
2574
+ "get",
2575
+ "get-all",
2576
+ "get-regexp",
2577
+ "get-urlmatch",
2578
+ "list"
2579
+ ].includes(value)
2580
+ ))
2581
+ return false;
2582
+ return positional.length >= 2 || args.some((value) => /(?:add|set|unset|remove|rename)/.test(value));
2583
+ }
2584
+ if (sub === "worktree" && (positional.length === 0 || positional[0] === "list")) return false;
2585
+ if (sub === "notes" && (positional.length === 0 || ["list", "show"].includes(positional[0])))
2586
+ return false;
2587
+ if (sub === "submodule" && (positional.length === 0 || ["status", "summary"].includes(positional[0])))
2588
+ return false;
2589
+ if (sub === "symbolic-ref") {
2590
+ return args.includes("--delete") || positional.length >= 2;
2591
+ }
2592
+ return true;
2593
+ }
2594
+ function isLiteralPathValue(value) {
2595
+ if (!value) return false;
2596
+ if (/[$`*?[\]{}]/.test(value)) return false;
2597
+ return true;
2598
+ }
2599
+ function analyzeCapability(parsed, directory, worktree) {
2600
+ const warnings = [];
2601
+ let executesCode = false;
2602
+ let executesRepositoryCode = false;
2603
+ let createsAdHocCode = false;
2604
+ let invokesTestRunner = false;
2605
+ let invokesPackageLifecycle = false;
2606
+ let temporaryWrite = false;
2607
+ let workspaceWrite = false;
2608
+ let externalWrite = false;
2609
+ let deletion = false;
2610
+ let networkObserved = false;
2611
+ let networkPossible = false;
2612
+ let childProcesses = false;
2613
+ let persistence = false;
2614
+ let privilegeEscalation = false;
2615
+ let remoteEnabled = false;
2616
+ let remoteMutation = false;
2617
+ let gitObserved = false;
2618
+ let gitMutation = false;
2619
+ let credentialRead = false;
2620
+ let sawReadOnlyExecutable = false;
2621
+ let sawUnknownExecutable = false;
2622
+ const destinations = [];
2623
+ let dominantClass = "unknown";
2624
+ let classConfidence = "low";
2625
+ const heredocOutputs = new Set(
2626
+ parsed.heredocs.map((h) => h.outputTarget).filter(Boolean)
2627
+ );
2628
+ for (const segment of parsed.segments) {
2629
+ let k = 0;
2630
+ while (k < segment.tokens.length && SHELL_KEYWORDS2.has(segment.tokens[k].value)) k += 1;
2631
+ while (k < segment.tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(segment.tokens[k].value)) {
2632
+ k += 1;
2633
+ }
2634
+ if (k < segment.tokens.length) {
2635
+ const head = basename(segment.tokens[k].value);
2636
+ if (PRIVILEGE_WRAPPERS.has(head)) {
2637
+ privilegeEscalation = true;
2638
+ childProcesses = true;
2639
+ }
2640
+ if (PERSISTENCE_WRAPPERS.has(head)) {
2641
+ persistence = true;
2642
+ childProcesses = true;
2643
+ }
2644
+ if (SSH_TOOLS.has(head)) {
2645
+ remoteEnabled = true;
2646
+ childProcesses = true;
2647
+ const tail = segment.tokens.slice(k + 1).flatMap((t) => t.value.split(/\s+/));
2648
+ if (tail.some((v) => GIT_MUTATION_SUBCOMMANDS.has(v) || v === "rm")) {
2649
+ remoteMutation = true;
2650
+ }
2651
+ if (dominantClass === "unknown") {
2652
+ dominantClass = "remote-operation";
2653
+ classConfidence = "high";
2654
+ }
2655
+ }
2656
+ }
2657
+ }
2658
+ for (const cmd of parsed.effective) {
2659
+ if (cmd.length === 0) continue;
2660
+ const base = basename(cmd[0].value);
2661
+ const roMutation = readOnlyToolMutation(cmd, base);
2662
+ if (roMutation !== void 0) {
2663
+ if (roMutation.deletion === true) deletion = true;
2664
+ if (roMutation.executesCode === true) {
2665
+ executesCode = true;
2666
+ childProcesses = true;
2667
+ }
2668
+ for (const target of roMutation.writeTargets) {
2669
+ const cls = classifyPath(target, directory, worktree);
2670
+ if (cls.temporary) temporaryWrite = true;
2671
+ if (cls.workspace) workspaceWrite = true;
2672
+ if (cls.external) externalWrite = true;
2673
+ }
2674
+ }
2675
+ if ((READ_ONLY_TOOLS.has(base) || NO_EFFECT_BUILTINS.has(base)) && roMutation === void 0 && !INTERPRETERS.has(base) && !PACKAGE_MANAGERS.has(base) && !NETWORK_CLIENTS.has(base) && !FILE_WRITE_TOOLS.has(base) && !FILE_MUTATION_TOOLS.has(base) && !DELETION_TOOLS.has(base) && !SERVICE_MANAGERS.has(base) && !PERSISTENCE_TOOLS.has(base) && !PRIVILEGE_WRAPPERS.has(base)) {
2676
+ sawReadOnlyExecutable = true;
2677
+ } else if (base !== "git" && !INTERPRETERS.has(base) && !TEST_RUNNERS.has(base) && !PACKAGE_MANAGERS.has(base) && !NETWORK_CLIENTS.has(base) && !SSH_TOOLS.has(base) && !FILE_WRITE_TOOLS.has(base) && !FILE_MUTATION_TOOLS.has(base) && !DELETION_TOOLS.has(base) && !SERVICE_MANAGERS.has(base) && !PERSISTENCE_TOOLS.has(base) && !PERSISTENCE_WRAPPERS.has(base) && !PRIVILEGE_WRAPPERS.has(base)) {
2678
+ sawUnknownExecutable = true;
2679
+ }
2680
+ if (INTERPRETERS.has(base)) {
2681
+ executesCode = true;
2682
+ if (["bun", "node", "python", "python3", "deno", "tsx"].includes(base)) {
2683
+ childProcesses = true;
2684
+ }
2685
+ const { inline } = hasInlineCodeOption(cmd);
2686
+ if (inline) createsAdHocCode = true;
2687
+ for (let i = 1; i < cmd.length; i += 1) {
2688
+ const arg = cmd[i].value;
2689
+ if (heredocOutputs.has(arg)) createsAdHocCode = true;
2690
+ if (arg.startsWith(directory) || arg.startsWith(worktree)) executesRepositoryCode = true;
2691
+ }
2692
+ }
2693
+ if (TEST_RUNNERS.has(base)) {
2694
+ invokesTestRunner = true;
2695
+ executesCode = true;
2696
+ executesRepositoryCode = true;
2697
+ childProcesses = true;
2698
+ }
2699
+ if (INTERPRETERS.has(base) || PACKAGE_MANAGERS.has(base)) {
2700
+ const sub = cmd[1]?.value;
2701
+ if (sub === "test" || sub === "t" || sub === "check" || sub === "verify") {
2702
+ invokesTestRunner = true;
2703
+ executesCode = true;
2704
+ executesRepositoryCode = true;
2705
+ childProcesses = true;
2706
+ }
2707
+ }
2708
+ if (PACKAGE_MANAGERS.has(base)) {
2709
+ const sub = cmd[1]?.value;
2710
+ const subs = PACKAGE_SUBCOMMANDS[base];
2711
+ if (subs === void 0 || sub === void 0 || subs.has(sub)) {
2712
+ invokesPackageLifecycle = true;
2713
+ childProcesses = true;
2714
+ networkPossible = true;
2715
+ if (["run", "exec"].includes(sub ?? "")) {
2716
+ executesCode = true;
2717
+ if (sub === "run") executesRepositoryCode = true;
2718
+ }
2719
+ if (!["run", "exec"].includes(sub ?? "")) networkObserved = true;
2720
+ }
2721
+ }
2722
+ if (NETWORK_CLIENTS.has(base)) {
2723
+ networkObserved = true;
2724
+ destinations.push(...destinationFromTokens(cmd));
2725
+ dominantClass = "network";
2726
+ classConfidence = "high";
2727
+ }
2728
+ if (SSH_TOOLS.has(base)) {
2729
+ remoteEnabled = true;
2730
+ childProcesses = true;
2731
+ if (cmd.some((t) => GIT_MUTATION_SUBCOMMANDS.has(t.value) || t.value === "rm")) {
2732
+ remoteMutation = true;
2733
+ }
2734
+ dominantClass = "remote-operation";
2735
+ classConfidence = "high";
2736
+ }
2737
+ if (FILE_WRITE_TOOLS.has(base)) {
2738
+ const outputOperands = base === "dd" ? cmd.slice(1).map((token) => token.value).filter((value) => value.startsWith("of=")).map((value) => value.slice(3)) : cmd.slice(1).map((token) => token.value);
2739
+ for (const output of outputOperands) {
2740
+ const cls = classifyPath(output, directory, worktree);
2741
+ if (cls.temporary) temporaryWrite = true;
2742
+ if (cls.workspace) workspaceWrite = true;
2743
+ if (cls.external) externalWrite = true;
2744
+ }
2745
+ }
2746
+ if (FILE_MUTATION_TOOLS.has(base)) {
2747
+ const { sources, destinations: destinations2, sawOperand } = mutationOperands(base, cmd);
2748
+ const optionEnd = cmd.findIndex((token) => token.value === "--");
2749
+ const mutatesSources = base === "mv" || base === "rsync" && cmd.slice(1, optionEnd < 0 ? cmd.length : optionEnd).some((token) => token.value === "--remove-source-files");
2750
+ const writeOperands = mutatesSources ? [...destinations2, ...sources] : destinations2;
2751
+ for (const operand of writeOperands) {
2752
+ if (base === "rsync" && isRemoteMutationOperand(operand)) {
2753
+ externalWrite = true;
2754
+ continue;
2755
+ }
2756
+ const cls = classifyPath(operand, directory, worktree);
2757
+ if (cls.temporary) temporaryWrite = true;
2758
+ if (cls.workspace) workspaceWrite = true;
2759
+ if (cls.external) externalWrite = true;
2760
+ }
2761
+ if (!sawOperand) workspaceWrite = true;
2762
+ }
2763
+ if (DELETION_TOOLS.has(base)) {
2764
+ deletion = true;
2765
+ let anyTarget = false;
2766
+ for (let i = 1; i < cmd.length; i += 1) {
2767
+ const v = cmd[i].value;
2768
+ if (v.startsWith("-")) continue;
2769
+ anyTarget = true;
2770
+ const cls = classifyPath(v, directory, worktree);
2771
+ if (cls.temporary) temporaryWrite = true;
2772
+ if (cls.workspace) workspaceWrite = true;
2773
+ if (cls.external) externalWrite = true;
2774
+ }
2775
+ if (!anyTarget) workspaceWrite = true;
2776
+ }
2777
+ if (base === "git") {
2778
+ gitObserved = true;
2779
+ const { sub, index } = gitSubcommandOf(cmd);
2780
+ if (sub !== void 0 && GIT_NETWORK_SUBCOMMANDS.has(sub)) {
2781
+ networkObserved = true;
2782
+ }
2783
+ if (sub !== void 0 && index !== void 0 && gitSubcommandMutates(cmd, sub, index)) {
2784
+ gitMutation = true;
2785
+ if (sub === "push") externalWrite = true;
2786
+ else workspaceWrite = true;
2787
+ } else if (sub !== void 0 && GIT_NETWORK_SUBCOMMANDS.has(sub)) {
2788
+ dominantClass = "network";
2789
+ classConfidence = "high";
2790
+ }
2791
+ }
2792
+ if (PRIVILEGE_WRAPPERS.has(base)) {
2793
+ }
2794
+ if (SERVICE_MANAGERS.has(base)) {
2795
+ persistence = true;
2796
+ childProcesses = true;
2797
+ privilegeEscalation = true;
2798
+ if (dominantClass === "unknown") {
2799
+ dominantClass = "service-management";
2800
+ classConfidence = "high";
2801
+ }
2802
+ }
2803
+ if (PERSISTENCE_TOOLS.has(base)) {
2804
+ persistence = true;
2805
+ childProcesses = true;
2806
+ }
2807
+ }
2808
+ for (let index = 0; index < parsed.effective.length; index += 1) {
2809
+ const cmd = parsed.effective[index];
2810
+ if (cmd.length === 0) continue;
2811
+ const base = basename(cmd[0].value);
2812
+ const redirects = parsed.redirections[index] ?? [];
2813
+ for (const r of redirects) {
2814
+ if (r.operator !== "<") continue;
2815
+ if (!isLiteralPathValue(r.target)) continue;
2816
+ if (isSensitivePathToken(r.target)) credentialRead = true;
2817
+ }
2818
+ if (!CREDENTIAL_READERS.has(base)) continue;
2819
+ for (let i = 1; i < cmd.length; i += 1) {
2820
+ const value = cmd[i].value;
2821
+ const prev = cmd[i - 1].value;
2822
+ if (prev === "<" || prev === ">" || prev === ">>" || prev === "<<") continue;
2823
+ if (/^[0-9]*[<>]/.test(prev)) continue;
2824
+ if (value === "--") continue;
2825
+ if (value.startsWith("-") && value.length > 1) continue;
2826
+ if (value === "<" || value === ">" || value === ">>" || value === "<<") continue;
2827
+ if (value.startsWith("<") || value.startsWith(">")) continue;
2828
+ if (!isLiteralPathValue(value)) continue;
2829
+ if (isSensitivePathToken(value)) credentialRead = true;
2830
+ }
2831
+ }
2832
+ for (const segRedirects of parsed.redirections) {
2833
+ if (hasWriteRedirect(segRedirects)) {
2834
+ for (const r of segRedirects) {
2835
+ if (!redirectionWritesPath(r)) continue;
2836
+ const cls = classifyPath(r.target, directory, worktree);
2837
+ if (cls.temporary) temporaryWrite = true;
2838
+ if (cls.workspace) workspaceWrite = true;
2839
+ if (cls.external) externalWrite = true;
2840
+ }
2841
+ }
2842
+ }
2843
+ for (const h of parsed.heredocs) {
2844
+ if (h.outputTarget !== void 0) {
2845
+ const cls = classifyPath(h.outputTarget, directory, worktree);
2846
+ if (cls.temporary) temporaryWrite = true;
2847
+ if (cls.workspace) workspaceWrite = true;
2848
+ if (cls.external) externalWrite = true;
2849
+ }
2850
+ }
2851
+ if (dominantClass === "unknown") {
2852
+ if (deletion) {
2853
+ dominantClass = "destruction";
2854
+ classConfidence = "high";
2855
+ } else if (gitMutation) {
2856
+ dominantClass = "git-mutation";
2857
+ classConfidence = "high";
2858
+ } else if (externalWrite) {
2859
+ dominantClass = "external-write";
2860
+ classConfidence = "high";
2861
+ } else if (createsAdHocCode || executesCode) {
2862
+ dominantClass = "code-execution";
2863
+ classConfidence = createsAdHocCode ? "high" : "medium";
2864
+ } else if (invokesPackageLifecycle) {
2865
+ dominantClass = "package-management";
2866
+ classConfidence = "high";
2867
+ } else if (persistence) {
2868
+ dominantClass = "persistence";
2869
+ classConfidence = "high";
2870
+ } else if (privilegeEscalation) {
2871
+ dominantClass = "privilege-escalation";
2872
+ classConfidence = "high";
2873
+ } else if (workspaceWrite) {
2874
+ dominantClass = "workspace-write";
2875
+ classConfidence = "medium";
2876
+ } else if (temporaryWrite) {
2877
+ dominantClass = "temporary-write";
2878
+ classConfidence = "high";
2879
+ } else if (sawUnknownExecutable) {
2880
+ dominantClass = "unknown";
2881
+ classConfidence = "low";
2882
+ } else if (sawReadOnlyExecutable || gitObserved && !gitMutation) {
2883
+ dominantClass = "read-only";
2884
+ classConfidence = "medium";
2885
+ } else {
2886
+ dominantClass = "unknown";
2887
+ classConfidence = "low";
2888
+ }
2889
+ }
2890
+ if (parsed.hasDynamicConstructs) {
2891
+ warnings.push("command contains dynamic constructs (variables, substitution, or globs)");
2892
+ }
2893
+ if (parsed.heredocs.length > 0 && parsed.heredocs.some((h) => h.dynamic)) {
2894
+ warnings.push("one or more heredoc bodies have unresolvable expansion");
2895
+ }
2896
+ const heredocTruncated = parsed.heredocs.some((h) => h.truncated);
2897
+ if (parsed.heredocs.length > 0 && heredocTruncated) {
2898
+ warnings.push("one or more heredoc bodies were truncated or never terminated");
2899
+ }
2900
+ if (parsed.analysisTruncated) {
2901
+ warnings.push("command structure exceeded the static analysis depth or expansion budget");
2902
+ }
2903
+ const parserCompleteness = parsed.hasDynamicConstructs ? hasCommandSubstitution(parsed.sanitizedCommand) || parsed.heredocs.some((h) => h.dynamic) ? "opaque" : "partial" : parsed.analysisTruncated || heredocTruncated ? "partial" : "complete-for-supported-form";
2904
+ const summaryParts = [dominantClass];
2905
+ if (createsAdHocCode) summaryParts.push("ad-hoc code");
2906
+ if (executesRepositoryCode) summaryParts.push("repository code");
2907
+ if (invokesPackageLifecycle) summaryParts.push("package lifecycle scripts");
2908
+ if (gitMutation) summaryParts.push("git mutation");
2909
+ if (networkObserved) summaryParts.push("network");
2910
+ if (persistence) summaryParts.push("persistence");
2911
+ if (privilegeEscalation) summaryParts.push("privilege escalation");
2912
+ return {
2913
+ actionClass: {
2914
+ value: dominantClass,
2915
+ source: "static-analysis",
2916
+ confidence: classConfidence
2917
+ },
2918
+ summary: summaryParts.join(", "),
2919
+ executesCode: staticFact(executesCode ? true : "unknown"),
2920
+ executesRepositoryCode: staticFact(executesRepositoryCode ? true : "unknown"),
2921
+ createsAdHocCode: staticFact(createsAdHocCode ? true : "unknown"),
2922
+ invokesExistingTestRunner: staticFact(invokesTestRunner ? true : "unknown"),
2923
+ invokesPackageLifecycleScripts: staticFact(invokesPackageLifecycle ? true : "unknown"),
2924
+ credentialRead: staticFact(credentialRead ? true : "unknown"),
2925
+ writeEffects: {
2926
+ temporaryWrite: staticFact(temporaryWrite ? true : "unknown"),
2927
+ workspaceWrite: staticFact(workspaceWrite ? true : "unknown"),
2928
+ externalWrite: staticFact(externalWrite ? true : "unknown"),
2929
+ deletion: staticFact(deletion ? true : "unknown")
2930
+ },
2931
+ network: {
2932
+ observed: staticFact(networkObserved ? true : "unknown"),
2933
+ possible: heuristicFact(networkObserved || networkPossible ? true : "unknown"),
2934
+ destinations,
2935
+ observedAccess: staticFact(networkObserved ? true : "unknown"),
2936
+ possibleAccess: heuristicFact(networkObserved || networkPossible ? true : "unknown")
2937
+ },
2938
+ process: {
2939
+ childProcesses: staticFact(childProcesses ? true : "unknown"),
2940
+ persistence: staticFact(persistence ? true : "unknown"),
2941
+ privilegeEscalation: staticFact(privilegeEscalation ? true : "unknown")
2942
+ },
2943
+ remote: {
2944
+ enabled: staticFact(remoteEnabled ? true : "unknown"),
2945
+ mutationHint: staticFact(remoteMutation ? true : "unknown")
2946
+ },
2947
+ git: {
2948
+ observed: staticFact(gitObserved ? true : "unknown"),
2949
+ possible: heuristicFact(gitMutation ? true : "unknown"),
2950
+ observedAccess: staticFact(gitObserved ? true : "unknown"),
2951
+ possibleAccess: heuristicFact("unknown")
2952
+ },
2953
+ parserCompleteness,
2954
+ analysisWarnings: warnings
2955
+ };
2956
+ }
2957
+
2958
+ // src/policy/policy-engine.ts
2959
+ import { createHash as createHash2 } from "crypto";
2960
+ var EFFECT_SEVERITY = {
2961
+ deny: 3,
2962
+ manual: 2,
2963
+ review: 1,
2964
+ allow: 0
2965
+ };
2966
+ var EMPTY_TRACE_ROUTE = "review";
2967
+ function evaluatePolicy(capability, actor, config, rules = []) {
2968
+ const effectiveRules = filterProjectAllowRules(rules);
2969
+ const effectivePolicyHash = hashEffectivePolicy(effectiveRules, config);
2970
+ const matched = [];
2971
+ for (const rule of effectiveRules) {
2972
+ if (matches(rule.when, capability, actor, config)) {
2973
+ matched.push({
2974
+ id: rule.id,
2975
+ source: rule.source,
2976
+ effect: rule.effect,
2977
+ reason: rule.reason
2978
+ });
2979
+ }
2980
+ }
2981
+ let finalRoute = EMPTY_TRACE_ROUTE;
2982
+ if (matched.length > 0) {
2983
+ let bestEffect = matched[0].effect;
2984
+ let bestSev = EFFECT_SEVERITY[matched[0].effect] ?? 1;
2985
+ for (let i = 1; i < matched.length; i += 1) {
2986
+ const sev = EFFECT_SEVERITY[matched[i].effect] ?? 1;
2987
+ if (sev > bestSev) {
2988
+ bestEffect = matched[i].effect;
2989
+ bestSev = sev;
2990
+ }
2991
+ }
2992
+ finalRoute = bestEffect;
2993
+ }
2994
+ return {
2995
+ effectivePolicyHash,
2996
+ matchedRules: matched,
2997
+ finalRoute,
2998
+ mode: config.enforcementMode
2999
+ };
3000
+ }
3001
+ function filterProjectAllowRules(rules) {
3002
+ return rules.filter((r) => !(r.source === "project" && r.effect === "allow"));
3003
+ }
3004
+ function matches(cond, cap, actor, config) {
3005
+ if (cond === void 0 || cond.always === true) return true;
3006
+ if (cond.actionClass !== void 0) {
3007
+ if (!Array.isArray(cond.actionClass) || cap === void 0) return false;
3008
+ if (!cond.actionClass.includes(cap.actionClass.value)) return false;
3009
+ }
3010
+ if (cond.actorProfile !== void 0) {
3011
+ if (!Array.isArray(cond.actorProfile) || actor === void 0) return false;
3012
+ if (!cond.actorProfile.includes(actor.profile.value)) return false;
3013
+ }
3014
+ if (cond.writesWorkspace === true && cap?.writeEffects.workspaceWrite.value !== true) return false;
3015
+ if (cond.writesExternal === true && cap?.writeEffects.externalWrite.value !== true) return false;
3016
+ if (cond.writesTemporary === true && cap?.writeEffects.temporaryWrite.value !== true) return false;
3017
+ if (cond.deletion === true && cap?.writeEffects.deletion.value !== true) return false;
3018
+ if (cond.executesCode === true && cap?.executesCode.value !== true) return false;
3019
+ if (cond.createsAdHocCode === true && cap?.createsAdHocCode.value !== true) return false;
3020
+ if (cond.packageManagement === true && cap?.invokesPackageLifecycleScripts.value !== true)
3021
+ return false;
3022
+ if (cond.gitMutation === true && cap?.git.possible.value !== true) return false;
3023
+ if (cond.networkObserved === true && cap?.network.observed.value !== true) return false;
3024
+ if (cond.credentialRead === true && cap?.credentialRead.value !== true) return false;
3025
+ if (cond.privilegeEscalation === true && cap?.process.privilegeEscalation.value !== true)
3026
+ return false;
3027
+ if (cond.remoteEnabled === true && cap?.remote.enabled.value !== true) return false;
3028
+ if (cond.persistence === true && cap?.process.persistence.value !== true) return false;
3029
+ if (cond.repositoryTrust !== void 0) {
3030
+ if (!Array.isArray(cond.repositoryTrust)) return false;
3031
+ if (!cond.repositoryTrust.includes(config.repositoryTrust)) return false;
3032
+ }
3033
+ return true;
3034
+ }
3035
+ function hashEffectivePolicy(rules, config) {
3036
+ const rulesCanonical = rules.map((r) => `${r.id}:${r.effect}:${JSON.stringify(r.when ?? null)}`).sort().join("|");
3037
+ const decisionConfig = JSON.stringify({
3038
+ confidenceThreshold: config.confidenceThreshold,
3039
+ minimumConfidence: config.riskPolicy.minimumConfidence,
3040
+ riskPolicyAllow: config.riskPolicy.allow,
3041
+ onInvalidDecision: config.riskPolicy.onInvalidDecision,
3042
+ onReviewerFailure: config.riskPolicy.onReviewerFailure,
3043
+ repositoryTrust: config.repositoryTrust,
3044
+ enforcementMode: config.enforcementMode,
3045
+ escalationMode: config.escalationMode,
3046
+ configDegraded: config.configDegraded?.length ?? 0
3047
+ });
3048
+ return createHash2("sha256").update(`${rulesCanonical}#${decisionConfig}`).digest("hex").slice(0, 16);
3049
+ }
3050
+
3051
+ // src/audit.ts
3052
+ import { mkdir } from "fs/promises";
3053
+ import {
3054
+ closeSync as closeSync2,
3055
+ constants as fsConstants2,
3056
+ fchmodSync,
3057
+ fstatSync as fstatSync2,
3058
+ openSync as openSync2,
3059
+ readSync as readSync2,
3060
+ writeSync
3061
+ } from "fs";
3062
+ import { homedir as homedir3 } from "os";
3063
+ import { dirname, resolve as resolve2 } from "path";
3064
+
3065
+ // src/redact.ts
3066
+ var REDACT = (type) => `[REDACTED:${type}]`;
3067
+ var RULES = [
3068
+ // PEM private key blocks (bounded to avoid pathological backtracking). The
3069
+ // optional ` BLOCK` arm covers ASCII-armored GPG secret keys
3070
+ // (`-----BEGIN PGP PRIVATE KEY BLOCK-----`), which the simpler alternation
3071
+ // missed because of the trailing ` BLOCK`.
3072
+ {
3073
+ re: /-----BEGIN (?:[A-Z ]*PRIVATE KEY(?: BLOCK)?)-----[\s\S]{0,8192}?-----END (?:[A-Z ]*PRIVATE KEY(?: BLOCK)?)-----/g,
3074
+ replace: () => REDACT("pem")
3075
+ },
3076
+ // Truncated PEM (BEGIN with no matching END within the complete-block
3077
+ // window above): redact from the BEGIN marker to the end of the string so a
3078
+ // long private key whose END was chopped by an upstream truncation cannot
3079
+ // leak its tail. The `*` quantifier is a single greedy linear scan (no
3080
+ // alternation), so it is safe from pathological backtracking.
3081
+ {
3082
+ re: /-----BEGIN (?:[A-Z ]*PRIVATE KEY(?: BLOCK)?)-----[\s\S]*/g,
3083
+ replace: () => REDACT("pem")
3084
+ },
3085
+ // AWS access key ids: long-term (AKIA) and temporary/session (ASIA).
3086
+ { re: /\bA(?:KIA|SIA)[0-9A-Z]{16}\b/g, replace: () => REDACT("aws") },
3087
+ // GitHub tokens (ghu_ covers user-to-server OAuth tokens).
3088
+ { re: /\b(?:ghp|gho|ghs|ghr|ghu)_[A-Za-z0-9]{36,251}\b/g, replace: () => REDACT("github") },
3089
+ { re: /\bgithub_pat_[A-Za-z0-9_]{22,251}\b/g, replace: () => REDACT("github") },
3090
+ // OpenAI: project keys and long bare `sk-…` keys (excludes Anthropic).
3091
+ { re: /\bsk-proj-[A-Za-z0-9_-]{20,}\b/g, replace: () => REDACT("openai") },
3092
+ { re: /\bsk-(?!ant-)[A-Za-z0-9]{30,}\b/g, replace: () => REDACT("openai") },
3093
+ // Anthropic.
3094
+ { re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/g, replace: () => REDACT("anthropic") },
3095
+ // Slack tokens.
3096
+ { re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, replace: () => REDACT("slack") },
3097
+ // Google API key.
3098
+ { re: /\bAIza[0-9A-Za-z_-]{35}\b/g, replace: () => REDACT("google") },
3099
+ // Stripe live/test restricted/secret keys.
3100
+ { re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/g, replace: () => REDACT("stripe") },
3101
+ // GitLab, NVIDIA, Telegram bot tokens.
3102
+ { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/g, replace: () => REDACT("gitlab") },
3103
+ { re: /\bnvapi-[A-Za-z0-9_-]{20,}\b/g, replace: () => REDACT("nvidia") },
3104
+ { re: /\b\d{8,12}:AA[A-Za-z0-9_-]{30,}\b/g, replace: () => REDACT("telegram") },
3105
+ // JWT (three base64url segments).
3106
+ {
3107
+ re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,
3108
+ replace: () => REDACT("jwt")
3109
+ },
3110
+ // Credentials embedded in a URL userinfo component. A password is optional:
3111
+ // token-as-username URLs are credentials too, while SCP-style git@host paths
3112
+ // have no URL scheme and stay untouched.
3113
+ {
3114
+ re: /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@[\]]+)(?::[^\s/@[\]]*)?@/gi,
3115
+ replace: (_m, g) => `${g[0] ?? ""}${REDACT("userinfo")}@`
3116
+ },
3117
+ // Auth-scheme prefixes (Bearer / Basic / Token) followed by a token.
3118
+ // Case-insensitive so lowercase "bearer", "basic", "token" are caught too.
3119
+ {
3120
+ re: /\b(Bearer|Basic|Token)\s+(?!\[REDACTED)[A-Za-z0-9._~+/=-]{8,}/gi,
3121
+ replace: (_m, g) => {
3122
+ const scheme = g[0] ?? "";
3123
+ return `${scheme} ${REDACT(scheme.toLowerCase())}`;
3124
+ }
3125
+ },
3126
+ // Cookie headers.
3127
+ {
3128
+ re: /(^|[^A-Za-z0-9_])(Cookie|Set-Cookie)(\s*[:=]\s*)(["']?)(?!\[REDACTED)([A-Za-z0-9._~+/%=-]{8,})(["']?)/g,
3129
+ replace: (_m, g) => `${g[0] ?? ""}${g[1] ?? ""}${g[2] ?? ""}${g[3] ?? ""}${REDACT("credential")}${g[5] ?? ""}`
3130
+ },
3131
+ // Authorization-style headers and JSON/YAML keys.
3132
+ {
3133
+ re: /(^|[^A-Za-z0-9_])(authorization|proxy-authorization|x-api-key|x-auth-token)(\s*[:=]\s*)(["']?)(?!\[REDACTED)([A-Za-z0-9._~+/-]{8,})(["']?)/gi,
3134
+ replace: (_m, g) => `${g[0] ?? ""}${g[1] ?? ""}${g[2] ?? ""}${g[3] ?? ""}${REDACT("credential")}${g[5] ?? ""}`
3135
+ },
3136
+ // Generic credential assignments (covers compound env names like DB_PASSWORD,
3137
+ // AWS_SECRET_ACCESS_KEY, GITHUB_TOKEN via the underscore-tolerant prefix).
3138
+ // First, compound variable names whose identifier contains a credential word.
3139
+ // Case-insensitive so lowercase forms (ssh_private_key, passphrase,
3140
+ // service_credentials) are caught alongside their UPPER_CASE counterparts.
3141
+ {
3142
+ re: /(^|[^A-Za-z0-9_])([A-Za-z][A-Za-z0-9_]*(?:SECRET|PASSWORD|TOKEN|API_KEY|ACCESS_KEY|PRIVATE_KEY|CLIENT_SECRET|PASSPHRASE|CREDENTIALS?)[A-Za-z0-9_]*)(\s*[:=]\s*)(["']?)(?!\[REDACTED)([^$`{}()\s"'#[\]]{8,})(["']?)/gi,
3143
+ replace: (_m, g) => `${g[0] ?? ""}${g[1] ?? ""}${g[2] ?? ""}${g[3] ?? ""}${REDACT("credential")}${g[5] ?? ""}`
3144
+ },
3145
+ // Then lowercase credential keywords as standalone-ish keys (also catches the
3146
+ // bare forms private_key / passphrase / credential that the compound rule
3147
+ // above misses because it requires a leading identifier).
3148
+ {
3149
+ re: /(^|_|[^A-Za-z0-9_])(api[_-]?key|access[_-]?token|secret[_-]?key|client[_-]?secret|secret|password|passwd|token|cookie|csrf[_-]?token|session[_-]?id|sessionid|session|sid|private[_-]?key|passphrase|credentials?)(["']?\s*[:=]\s*["']?)(?!\[REDACTED)([^$`{}()\s"'#[\]]{8,})/gi,
3150
+ replace: (_m, g) => `${g[0] ?? ""}${g[1] ?? ""}${g[2] ?? ""}${REDACT("credential")}`
3151
+ }
3152
+ ];
3153
+ function redactSecrets(input) {
3154
+ let result = input;
3155
+ for (const rule of RULES) {
3156
+ rule.re.lastIndex = 0;
3157
+ result = result.replace(rule.re, (match, ...rest) => {
3158
+ const groups = rest.slice(0, rest.length - 2);
3159
+ return rule.replace(match, groups);
3160
+ });
3161
+ }
3162
+ return result;
3163
+ }
3164
+
3165
+ // src/audit.ts
3166
+ var DEFAULT_AUDIT_PATH = "~/.local/share/opencode/permission-reviewer-audit.jsonl";
3167
+ var O_RDONLY2 = typeof fsConstants2.O_RDONLY === "number" ? fsConstants2.O_RDONLY : 0;
3168
+ var O_WRONLY = typeof fsConstants2.O_WRONLY === "number" ? fsConstants2.O_WRONLY : 0;
3169
+ var O_CREAT = typeof fsConstants2.O_CREAT === "number" ? fsConstants2.O_CREAT : 0;
3170
+ var O_APPEND = typeof fsConstants2.O_APPEND === "number" ? fsConstants2.O_APPEND : 0;
3171
+ var O_NOFOLLOW2 = typeof fsConstants2.O_NOFOLLOW === "number" ? fsConstants2.O_NOFOLLOW : 0;
3172
+ var O_NONBLOCK2 = typeof fsConstants2.O_NONBLOCK === "number" ? fsConstants2.O_NONBLOCK : 0;
3173
+ function expandHome(path) {
3174
+ if (path === "~") return homedir3();
3175
+ if (path.startsWith("~/")) return resolve2(homedir3(), path.slice(2));
3176
+ return resolve2(path);
3177
+ }
3178
+ function resolveAuditPath(config) {
3179
+ return expandHome(config.auditPath ?? DEFAULT_AUDIT_PATH);
3180
+ }
3181
+ var REQUIRED_AUDIT_FIELDS = [
3182
+ "timestamp",
3183
+ "requestID",
3184
+ "sessionID",
3185
+ "permission",
3186
+ "outcome",
3187
+ "reason"
3188
+ ];
3189
+ function bump(map, key) {
3190
+ map[key] = (map[key] ?? 0) + 1;
3191
+ }
3192
+ var AUDIT_READ_CAP_BYTES = 64 * 1024 * 1024;
3193
+ function readTail(path) {
3194
+ let fd;
3195
+ try {
3196
+ fd = openSync2(path, O_RDONLY2 | O_NONBLOCK2 | O_NOFOLLOW2);
3197
+ const info = fstatSync2(fd);
3198
+ if (!info.isFile()) return void 0;
3199
+ const size = info.size;
3200
+ const truncated = size > AUDIT_READ_CAP_BYTES;
3201
+ const length = truncated ? AUDIT_READ_CAP_BYTES : size;
3202
+ const buffer = Buffer.alloc(length);
3203
+ const offset = truncated ? size - length : 0;
3204
+ let atLineBoundary = false;
3205
+ if (truncated && offset > 0) {
3206
+ try {
3207
+ const probe = Buffer.alloc(1);
3208
+ const seen = readSync2(fd, probe, 0, 1, offset - 1);
3209
+ atLineBoundary = seen === 1 && probe[0] === 10;
3210
+ } catch {
3211
+ atLineBoundary = false;
3212
+ }
3213
+ }
3214
+ let read = 0;
3215
+ while (read < length) {
3216
+ const count = readSync2(fd, buffer, read, length - read, offset + read);
3217
+ if (count === 0) break;
3218
+ read += count;
3219
+ }
3220
+ let text = (read < length ? buffer.subarray(0, read) : buffer).toString("utf8");
3221
+ if (truncated && !atLineBoundary) {
3222
+ text = text.replace(/^[^\n]*\n/, "");
3223
+ }
3224
+ return { text, truncated };
3225
+ } catch {
3226
+ return void 0;
3227
+ } finally {
3228
+ if (fd !== void 0) closeSyncSafe(fd);
3229
+ }
3230
+ }
3231
+ function closeSyncSafe(fd) {
3232
+ try {
3233
+ closeSync2(fd);
3234
+ } catch {
3235
+ }
3236
+ }
3237
+ function readAuditSummary(path) {
3238
+ const summary = {
3239
+ path,
3240
+ exists: false,
3241
+ truncated: false,
3242
+ totalLines: 0,
3243
+ validRecords: 0,
3244
+ invalidLines: 0,
3245
+ bySchemaVersion: {},
3246
+ byHostGeneration: {},
3247
+ byApplication: {},
3248
+ byOutcome: {},
3249
+ byRiskLevel: {},
3250
+ byDecisionSource: {},
3251
+ byPermission: {},
3252
+ unknownActorNames: [],
3253
+ missingRequiredFields: []
3254
+ };
3255
+ const read = readTail(path);
3256
+ if (read === void 0) return summary;
3257
+ summary.exists = true;
3258
+ summary.truncated = read.truncated;
3259
+ const lines = read.text.split("\n").filter((line) => line.trim().length > 0);
3260
+ summary.totalLines = lines.length;
3261
+ const actorCounts = /* @__PURE__ */ new Map();
3262
+ for (let i = 0; i < lines.length; i++) {
3263
+ const lineNo = i + 1;
3264
+ let parsed;
3265
+ try {
3266
+ parsed = JSON.parse(lines[i]);
3267
+ } catch {
3268
+ summary.invalidLines++;
3269
+ continue;
3270
+ }
3271
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
3272
+ summary.invalidLines++;
3273
+ continue;
3274
+ }
3275
+ const record = parsed;
3276
+ summary.validRecords++;
3277
+ bump(summary.bySchemaVersion, String(record.schemaVersion ?? 1));
3278
+ bump(
3279
+ summary.byHostGeneration,
3280
+ record.hostGeneration === "v1" || record.hostGeneration === "v2" ? record.hostGeneration : "legacy-unspecified"
3281
+ );
3282
+ if (typeof record.application === "string" && [
3283
+ "evaluation-returned",
3284
+ "reply-accepted",
3285
+ "human-pending",
3286
+ "superseded",
3287
+ "cancelled",
3288
+ "unknown"
3289
+ ].includes(record.application))
3290
+ bump(summary.byApplication, record.application);
3291
+ if (typeof record.outcome === "string") bump(summary.byOutcome, record.outcome);
3292
+ bump(summary.byRiskLevel, typeof record.riskLevel === "string" ? record.riskLevel : "(none)");
3293
+ if (typeof record.decisionSource === "string")
3294
+ bump(summary.byDecisionSource, record.decisionSource);
3295
+ if (typeof record.permission === "string") bump(summary.byPermission, record.permission);
3296
+ if (typeof record.timestamp === "string") {
3297
+ if (summary.firstTimestamp === void 0 || record.timestamp < summary.firstTimestamp) {
3298
+ summary.firstTimestamp = record.timestamp;
3299
+ }
3300
+ if (summary.lastTimestamp === void 0 || record.timestamp > summary.lastTimestamp) {
3301
+ summary.lastTimestamp = record.timestamp;
3302
+ }
3303
+ }
3304
+ const missing = REQUIRED_AUDIT_FIELDS.filter((f) => record[f] === void 0);
3305
+ if (missing.length > 0) summary.missingRequiredFields.push({ lineNo, missing });
3306
+ const actor = typeof record.actor === "object" && record.actor !== null ? record.actor : void 0;
3307
+ const isUnknown = actor === void 0 || actor.profile === void 0 || actor.profile === "unknown" || actor.name === void 0 || actor.name === "";
3308
+ if (isUnknown) {
3309
+ const rawName = actor?.name ?? (record.actor === void 0 ? "(no actor field)" : "(unnamed)");
3310
+ const name = typeof rawName === "string" ? rawName : JSON.stringify(rawName);
3311
+ actorCounts.set(name, (actorCounts.get(name) ?? 0) + 1);
3312
+ }
3313
+ }
3314
+ summary.unknownActorNames = [...actorCounts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
3315
+ return summary;
3316
+ }
3317
+
3318
+ // src/cli/init.ts
3319
+ import { parseArgs } from "util";
3320
+ import { homedir as homedir4 } from "os";
3321
+ import { createHash as createHash3 } from "crypto";
3322
+ import { satisfies } from "semver";
3323
+ import { applyEdits, modify } from "jsonc-parser";
3324
+ import {
3325
+ closeSync as closeSync3,
3326
+ constants as fsConstants3,
3327
+ existsSync,
3328
+ fstatSync as fstatSync3,
3329
+ ftruncateSync,
3330
+ fsyncSync,
3331
+ mkdirSync,
3332
+ openSync as openSync3,
3333
+ readFileSync,
3334
+ realpathSync,
3335
+ writeFileSync,
3336
+ writeSync as writeSync2
3337
+ } from "fs";
3338
+ import { dirname as dirname2, join as join2, resolve as resolve3 } from "path";
3339
+ import { fileURLToPath } from "url";
3340
+
3341
+ // src/opencode/host-guard.ts
3342
+ var SUPPORTED_V2_RANGE = ">=2.0.3 <3";
3343
+
3344
+ // src/cli/init.ts
3345
+ async function runInit(argv) {
3346
+ const { values } = parseArgs({
3347
+ args: argv,
3348
+ options: {
3349
+ project: { type: "string" },
3350
+ global: { type: "boolean" },
3351
+ tui: { type: "boolean" },
3352
+ host: { type: "string", default: "auto" },
3353
+ binary: { type: "string", default: "opencode" },
3354
+ "dry-run": { type: "boolean" },
3355
+ print: { type: "boolean" },
3356
+ yes: { type: "boolean" },
3357
+ json: { type: "boolean" },
3358
+ npm: { type: "boolean" },
3359
+ help: { type: "boolean", short: "h" }
3360
+ },
3361
+ strict: true,
3362
+ allowPositionals: false
3363
+ });
3364
+ if (values.help) {
3365
+ process.stderr.write(usage());
3366
+ return 0;
3367
+ }
3368
+ const directory = values.project ?? process.cwd();
3369
+ if (!existsSync(directory)) {
3370
+ console.error(`init: project directory does not exist: ${directory}`);
3371
+ return 1;
3372
+ }
3373
+ const pkg = readPackageInfo();
3374
+ if (!["auto", "v1", "v2"].includes(values.host)) {
3375
+ console.error("init: --host must be auto, v1, or v2");
3376
+ return 2;
3377
+ }
3378
+ const versionChecks = await runVersionChecks(pkg, values.binary);
3379
+ if (values.host === "auto" && !versionChecks.find((check) => check.name === "opencode")?.ok) {
3380
+ console.error("init: detected host is unavailable or unsupported; no configuration was written");
3381
+ return 2;
3382
+ }
3383
+ const version = versionChecks.find((check) => check.name === "opencode")?.version;
3384
+ const detected = version?.startsWith("1.") ? "v1" : version?.startsWith("2.") ? "v2" : void 0;
3385
+ const host = values.host === "auto" ? detected : values.host;
3386
+ if (!host) {
3387
+ console.error("init: cannot determine the host; pass --host v1 or --host v2");
3388
+ return 2;
3389
+ }
3390
+ const entry = buildEntry(pkg, Boolean(values.npm), host);
3391
+ const targets = resolveTargets(directory, Boolean(values.global), Boolean(values.tui), host);
3392
+ const existingSnapshot = readConfigFile(targets.config);
3393
+ const existingConfig = existingSnapshot.status === "read" ? existingSnapshot.config : void 0;
3394
+ if (values.host === "auto" && existingConfig && (host === "v1" && "plugins" in existingConfig || host === "v2" && "plugin" in existingConfig)) {
3395
+ console.error("init: binary version and config format disagree; select --host explicitly");
3396
+ return 2;
3397
+ }
3398
+ const plans = [targets.config, ...targets.tui ? [targets.tui] : []].map(
3399
+ (p) => planFileChange(p, pkg, host)
3400
+ );
3401
+ if (values.print) {
3402
+ console.log(JSON.stringify(entry, null, 2));
3403
+ return 0;
3404
+ }
3405
+ if (values.json) {
3406
+ console.log(
3407
+ JSON.stringify(
3408
+ {
3409
+ command: "init",
3410
+ host,
3411
+ dryRun: Boolean(values["dry-run"]),
3412
+ package: { name: pkg.name, version: pkg.version, root: pkg.root },
3413
+ versionChecks,
3414
+ targets: plans.map((p) => ({
3415
+ path: p.path,
3416
+ exists: existsSync(p.path),
3417
+ action: p.action,
3418
+ ...p.backup ? { backup: p.backup } : {}
3419
+ })),
3420
+ entry,
3421
+ writes: [],
3422
+ plannedWrites: plans.filter((p) => p.action === "append" || p.action === "create").map((p) => p.path)
3423
+ },
3424
+ null,
3425
+ 2
3426
+ )
3427
+ );
3428
+ return 0;
3429
+ }
3430
+ console.error(`init: opencode-permission-reviewer ${pkg.version}`);
3431
+ for (const c of versionChecks) {
3432
+ const tag = c.ok ? "ok" : "warning";
3433
+ console.error(` ${c.name}: ${c.version} (${c.range}) ${tag}`);
3434
+ }
3435
+ console.error(` entry: ${JSON.stringify(entry)}`);
3436
+ for (const plan of plans) {
3437
+ console.error(` ${plan.path}: ${plan.action}`);
3438
+ }
3439
+ if (values["dry-run"]) {
3440
+ console.error("init: dry-run, no files written");
3441
+ console.error("rollback: (nothing was changed)");
3442
+ return 0;
3443
+ }
3444
+ if (!values.yes) {
3445
+ if (!process.stdin.isTTY) {
3446
+ console.error("init: not a TTY; pass --yes to apply changes non-interactively");
3447
+ return 2;
3448
+ }
3449
+ process.stderr.write("Apply these changes? [y/N] ");
3450
+ const answer = (await readStdin()).trim().toLowerCase();
3451
+ if (answer !== "y" && answer !== "yes") {
3452
+ console.error("init: aborted, nothing changed");
3453
+ return 0;
3454
+ }
3455
+ }
3456
+ return applyPlannedWrites(plans, entry, pkg, host);
3457
+ }
3458
+ function applyPlannedWrites(plans, entry, pkg, host = "v1") {
3459
+ const written = [];
3460
+ for (const plan of plans) {
3461
+ if (plan.action === "noop") continue;
3462
+ const fresh = planFileChange(plan.path, pkg, host);
3463
+ if (fresh.action !== plan.action || plan.fingerprint !== void 0 && fresh.fingerprint !== plan.fingerprint) {
3464
+ console.error(
3465
+ `init: ${plan.path} changed since planning (was ${plan.action}, now ${fresh.action}); refusing to write`
3466
+ );
3467
+ return 1;
3468
+ }
3469
+ if (fresh.action === "error") {
3470
+ console.error(
3471
+ `init: ${plan.path} is malformed or has a non-array "plugin" key; refusing to write`
3472
+ );
3473
+ return 1;
3474
+ }
3475
+ if (fresh.backup !== void 0 && existsSync(plan.path)) {
3476
+ console.error(` backup: ${writeBackup(plan.path, fresh.backup)}`);
3477
+ }
3478
+ try {
3479
+ writeEntry(plan.path, entry, fresh.action === "create", host, fresh.fingerprint);
3480
+ } catch (error) {
3481
+ if (error.code !== "EEXIST") throw error;
3482
+ console.error(`init: ${plan.path} was created concurrently; refusing to overwrite`);
3483
+ return 1;
3484
+ }
3485
+ written.push(plan.path);
3486
+ }
3487
+ console.error("init: done");
3488
+ console.error("next: restart OpenCode to load the plugin");
3489
+ console.error(
3490
+ 'next: ensure at least one permission "ask" rule (e.g. bash), or the plugin is a no-op'
3491
+ );
3492
+ if (plans.some((p) => p.backup)) {
3493
+ console.error("rollback: restore from the .bak file above and restart OpenCode");
3494
+ }
3495
+ return 0;
3496
+ }
3497
+ function writeBackup(source, preferred) {
3498
+ let sourceFd;
3499
+ let data;
3500
+ try {
3501
+ sourceFd = openSync3(
3502
+ source,
3503
+ fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK
3504
+ );
3505
+ if (!fstatSync3(sourceFd).isFile()) throw new Error(`Config is not a regular file: ${source}`);
3506
+ data = readFileSync(sourceFd);
3507
+ } finally {
3508
+ if (sourceFd !== void 0) closeSync3(sourceFd);
3509
+ }
3510
+ let dest = preferred;
3511
+ for (; ; ) {
3512
+ try {
3513
+ writeFileSync(dest, data, { flag: "wx", mode: 384 });
3514
+ return dest;
3515
+ } catch (error) {
3516
+ if (error.code !== "EEXIST") throw error;
3517
+ dest = backupPath(source);
3518
+ }
3519
+ }
3520
+ }
3521
+ function usage() {
3522
+ return `Usage:
3523
+ opencode-permission-reviewer init [--project <dir>] [--global] [--tui]
3524
+ [--npm] [--dry-run] [--print] [--yes] [--json]
3525
+
3526
+ Register the permission-reviewer plugin in an OpenCode config file.
3527
+ Backs up the existing file before writing. Never overwrites an already-
3528
+ registered entry or a malformed config.
3529
+
3530
+ --project <dir> target project directory (default: cwd)
3531
+ --global target ~/.config/opencode/opencode.json
3532
+ --tui also register in tui.json
3533
+ --host <host> v1, v2, or auto (default); auto refuses uncertain detection
3534
+ --binary <path> OpenCode binary used for version detection
3535
+ --npm emit an npm spec entry instead of a path reference
3536
+ --dry-run print the plan, write nothing
3537
+ --print print only the plugin entry JSON to stdout
3538
+ --yes skip confirmation (required when stdin is not a TTY)
3539
+ --json print planned changes as JSON without writing files
3540
+ `;
3541
+ }
3542
+ function readPackageInfo() {
3543
+ let dir = import.meta.dirname ?? process.cwd();
3544
+ for (let depth = 0; depth < 8; depth++) {
3545
+ const candidate = join2(dir, "package.json");
3546
+ if (existsSync(candidate)) {
3547
+ const raw = JSON.parse(readFileSync(candidate, "utf8"));
3548
+ return {
3549
+ name: raw.name ?? "opencode-permission-reviewer",
3550
+ version: raw.version ?? "0.0.0",
3551
+ engines: raw.engines ?? {},
3552
+ root: dir
3553
+ };
3554
+ }
3555
+ const parent = dirname2(dir);
3556
+ if (parent === dir) break;
3557
+ dir = parent;
3558
+ }
3559
+ throw new Error("init: could not locate package.json");
3560
+ }
3561
+ function buildEntry(pkg, npm, host) {
3562
+ const fromNodeModules = pkg.root.includes(join2("node_modules", ""));
3563
+ if (npm || fromNodeModules) {
3564
+ const name = `${pkg.name}@^${pkg.version}`;
3565
+ return host === "v2" ? { package: name, options: {} } : name;
3566
+ }
3567
+ return host === "v2" ? { package: pkg.root, options: {} } : pkg.root;
3568
+ }
3569
+ function resolveTargets(directory, forceGlobal, wantTui, host) {
3570
+ const globalDir = join2(process.env.XDG_CONFIG_HOME ?? join2(homedir4(), ".config"), "opencode");
3571
+ const globalCfg = pickExisting([
3572
+ join2(globalDir, "opencode.json"),
3573
+ join2(globalDir, "opencode.jsonc")
3574
+ ]);
3575
+ const projectCfg = pickExisting([
3576
+ join2(directory, "opencode.json"),
3577
+ join2(directory, "opencode.jsonc"),
3578
+ join2(directory, ".opencode", "opencode.json"),
3579
+ join2(directory, ".opencode", "opencode.jsonc")
3580
+ ]);
3581
+ const configPath = forceGlobal ? globalCfg ?? join2(globalDir, "opencode.json") : projectCfg ?? globalCfg ?? join2(directory, "opencode.json");
3582
+ if (!wantTui) return { config: configPath };
3583
+ if (host === "v2") return { config: configPath, tui: join2(globalDir, "cli.json") };
3584
+ const tuiDir = forceGlobal ? globalDir : dirname2(configPath);
3585
+ const tuiPath = pickExisting([join2(tuiDir, "tui.json"), join2(tuiDir, "tui.jsonc")]) ?? join2(tuiDir, "tui.json");
3586
+ return { config: configPath, tui: tuiPath };
3587
+ }
3588
+ function pickExisting(candidates) {
3589
+ return candidates.find((p) => existsSync(p));
3590
+ }
3591
+ function readConfigFile(path) {
3592
+ let fd;
3593
+ try {
3594
+ fd = openSync3(path, fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK);
3595
+ if (!fstatSync3(fd).isFile()) return { status: "error" };
3596
+ const raw = readFileSync(fd);
3597
+ const config = parseConfigText(raw.toString("utf8"));
3598
+ if (config === null) return { status: "error" };
3599
+ return { status: "read", config, fingerprint: createHash3("sha256").update(raw).digest("hex") };
3600
+ } catch (error) {
3601
+ return { status: error.code === "ENOENT" ? "missing" : "error" };
3602
+ } finally {
3603
+ if (fd !== void 0) closeSync3(fd);
3604
+ }
3605
+ }
3606
+ function parseConfigText(raw) {
3607
+ if (raw.trim() === "") return {};
3608
+ try {
3609
+ const parsed = JSON.parse(stripCommentsAndTrailingCommas(raw));
3610
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
3611
+ return parsed;
3612
+ } catch {
3613
+ return null;
3614
+ }
3615
+ }
3616
+ function isOurEntry(entry, pkg, directory) {
3617
+ let head;
3618
+ if (typeof entry === "string") {
3619
+ head = entry;
3620
+ } else if (Array.isArray(entry) && typeof entry[0] === "string") {
3621
+ head = entry[0];
3622
+ } else if (typeof entry === "object" && entry !== null && "package" in entry && typeof entry.package === "string") {
3623
+ head = entry.package;
3624
+ }
3625
+ if (head === void 0) return false;
3626
+ if (head === pkg.root || head === pkg.name || head.startsWith(`${pkg.name}@`)) return true;
3627
+ try {
3628
+ const path = head.startsWith("file:") ? fileURLToPath(head) : resolve3(directory, head);
3629
+ return realpathSync(path) === realpathSync(pkg.root);
3630
+ } catch {
3631
+ return false;
3632
+ }
3633
+ }
3634
+ function planFileChange(path, pkg, host = "v1") {
3635
+ const snapshot = readConfigFile(path);
3636
+ if (snapshot.status === "missing") return { path, action: "create" };
3637
+ if (snapshot.status === "error") return { path, action: "error" };
3638
+ const { config: cfg, fingerprint } = snapshot;
3639
+ const plugin = cfg[host === "v2" ? "plugins" : "plugin"];
3640
+ if (plugin === void 0) {
3641
+ return { path, action: "append", backup: backupPath(path), fingerprint };
3642
+ }
3643
+ if (!Array.isArray(plugin)) {
3644
+ return { path, action: "error" };
3645
+ }
3646
+ const matching = plugin.filter((entry) => isOurEntry(entry, pkg, dirname2(path)));
3647
+ if (matching.length > 1) return { path, action: "error" };
3648
+ if (matching.length === 1) {
3649
+ const existing = matching[0];
3650
+ const isObject = typeof existing === "object" && existing !== null && !Array.isArray(existing);
3651
+ if (isObject !== (host === "v2")) return { path, action: "error" };
3652
+ const spec = typeof existing === "string" ? existing : Array.isArray(existing) ? existing[0] : existing.package;
3653
+ if (typeof spec === "string" && spec.startsWith(`${pkg.name}@`) && spec !== `${pkg.name}@${pkg.version}`)
3654
+ return { path, action: "error" };
3655
+ return { path, action: "noop" };
3656
+ }
3657
+ return { path, action: "append", backup: backupPath(path), fingerprint };
3658
+ }
3659
+ function backupPath(path) {
3660
+ const d = /* @__PURE__ */ new Date();
3661
+ const pad = (n) => String(n).padStart(2, "0");
3662
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
3663
+ let bak = `${path}.bak-${stamp}`;
3664
+ for (let i = 2; existsSync(bak); i++) bak = `${path}.bak-${stamp}-${i}`;
3665
+ return bak;
3666
+ }
3667
+ function writeEntry(path, entry, create, host = "v1", fingerprint) {
3668
+ const key = host === "v2" ? "plugins" : "plugin";
3669
+ if (create) {
3670
+ mkdirSync(dirname2(path), { recursive: true });
3671
+ const schema = path.includes("tui.json") || path.includes("tui.jsonc") ? "https://opencode.ai/tui.json" : "https://opencode.ai/config.json";
3672
+ const fresh = path.endsWith("cli.json") ? { [key]: [entry] } : { $schema: schema, [key]: [entry] };
3673
+ writeFileSync(path, `${JSON.stringify(fresh, null, 2)}
3674
+ `, { encoding: "utf8", flag: "wx" });
3675
+ return;
3676
+ }
3677
+ let fd;
3678
+ try {
3679
+ fd = openSync3(path, fsConstants3.O_RDWR | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK);
3680
+ if (!fstatSync3(fd).isFile()) throw new Error("Config is not a regular file");
3681
+ const raw = readFileSync(fd, "utf8");
3682
+ if (fingerprint !== void 0 && createHash3("sha256").update(raw).digest("hex") !== fingerprint) {
3683
+ throw new Error("Config changed after planning; refusing to overwrite");
3684
+ }
3685
+ const cfg = parseConfigText(raw);
3686
+ if (!cfg || cfg[key] !== void 0 && !Array.isArray(cfg[key]))
3687
+ throw new Error("Invalid plugin config");
3688
+ const edits = modify(
3689
+ raw.trim() ? raw : "{}",
3690
+ cfg[key] === void 0 ? [key] : [key, -1],
3691
+ cfg[key] === void 0 ? [entry] : entry,
3692
+ {
3693
+ formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" }
3694
+ }
3695
+ );
3696
+ const data = Buffer.from(applyEdits(raw.trim() ? raw : "{}", edits), "utf8");
3697
+ ftruncateSync(fd, 0);
3698
+ let written = 0;
3699
+ while (written < data.length) {
3700
+ written += writeSync2(fd, data, written, data.length - written, written);
3701
+ }
3702
+ fsyncSync(fd);
3703
+ } finally {
3704
+ if (fd !== void 0) closeSync3(fd);
3705
+ }
3706
+ }
3707
+ async function runVersionChecks(pkg, binary) {
3708
+ const checks = [];
3709
+ const bunVer = process.versions.bun ?? process.versions.node ?? "0.0.0";
3710
+ const bunRange = pkg.engines.bun ?? "(unstated)";
3711
+ checks.push({
3712
+ name: "bun",
3713
+ version: bunVer,
3714
+ range: bunRange,
3715
+ ok: !pkg.engines.bun || satisfies(bunVer, pkg.engines.bun)
3716
+ });
3717
+ const ocVersion = await probeOpencodeVersion(binary);
3718
+ const ocRange = pkg.engines.opencode ?? "(unstated)";
3719
+ checks.push({
3720
+ name: "opencode",
3721
+ version: ocVersion ?? "(not found)",
3722
+ range: ocRange,
3723
+ ok: ocVersion !== void 0 && (!pkg.engines.opencode || satisfies(ocVersion, pkg.engines.opencode)) && (!ocVersion.startsWith("2.") || satisfies(ocVersion, SUPPORTED_V2_RANGE))
3724
+ });
3725
+ return checks;
3726
+ }
3727
+ async function probeOpencodeVersion(binary = "opencode") {
3728
+ try {
3729
+ const proc = Bun.spawn({ cmd: [binary, "--version"], stdout: "pipe", stderr: "pipe" });
3730
+ const timer = setTimeout(() => proc.kill(), 2e3);
3731
+ const [code, out] = await Promise.all([proc.exited, new Response(proc.stdout).text()]);
3732
+ clearTimeout(timer);
3733
+ if (code !== 0) return void 0;
3734
+ return (out.match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/) ?? [])[0];
3735
+ } catch {
3736
+ return void 0;
3737
+ }
3738
+ }
3739
+ async function readStdin() {
3740
+ return new Response(await Bun.stdin.text()).text();
3741
+ }
3742
+
3743
+ // src/opencode/v2/permission-codec.ts
3744
+ function normalizeV2Permission(input, scope, actionInput) {
3745
+ const permission = input.action === "shell" ? "bash" : input.action === "subagent" ? "task" : input.action;
3746
+ const metadata = structuredClone(input.metadata ?? {});
3747
+ delete metadata.hostAgent;
3748
+ if (input.agent !== void 0) metadata.hostAgent = input.agent;
3749
+ const exactInput = typeof actionInput === "object" && actionInput !== null && !Array.isArray(actionInput) ? structuredClone(actionInput) : void 0;
3750
+ if (exactInput) {
3751
+ metadata.toolInput = exactInput;
3752
+ if (permission === "bash" && typeof exactInput.command === "string")
3753
+ metadata.command = exactInput.command;
3754
+ }
3755
+ const actionEvidenceComplete = permission === "bash" ? typeof metadata.command === "string" && metadata.command.trim().length > 0 : exactInput !== void 0;
3756
+ return {
3757
+ ...scope,
3758
+ host: "v2",
3759
+ nativeAction: input.action,
3760
+ actionEvidenceComplete,
3761
+ request: {
3762
+ id: scope.reviewID,
3763
+ sessionID: input.sessionID,
3764
+ permission,
3765
+ patterns: [...input.resources],
3766
+ metadata,
3767
+ always: [],
3768
+ ...input.source === void 0 ? {} : {
3769
+ tool: { messageID: input.source.messageID, callID: input.source.id }
3770
+ }
3771
+ }
3772
+ };
3773
+ }
3774
+
3775
+ // src/opencode/v2/connection.ts
3776
+ import { Buffer as Buffer2 } from "buffer";
3777
+ import { readFile } from "fs/promises";
3778
+ import { homedir as homedir5 } from "os";
3779
+ import { join as join3 } from "path";
3780
+ import { OpenCode } from "@opencode/client";
3781
+
3782
+ // src/ui/rpc.ts
3783
+ var ReviewerRpc = {
3784
+ id: "opencode-permission-reviewer",
3785
+ methods: {
3786
+ identity: {
3787
+ input: { type: "object", additionalProperties: false },
3788
+ output: { type: "string" }
3789
+ },
3790
+ status: { input: { type: "object", additionalProperties: false }, output: { type: "object" } },
3791
+ snapshot: {
3792
+ input: { type: "object", additionalProperties: false },
3793
+ output: { type: "object" }
3794
+ }
3795
+ },
3796
+ events: { "review.updated": { schema: { type: "object" } } }
3797
+ };
3798
+
3799
+ // src/opencode/v2/connection.ts
3800
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
3801
+ function validateHostEndpoint(url) {
3802
+ const endpoint = new URL(url);
3803
+ if (!["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password)
3804
+ throw new Error("Reviewer host URL must be HTTP(S) without embedded credentials");
3805
+ if (endpoint.protocol === "http:" && !LOOPBACK_HOSTS.has(endpoint.hostname))
3806
+ throw new Error("Reviewer host connections outside loopback require HTTPS");
3807
+ return endpoint;
3808
+ }
3809
+
3810
+ // src/cli/explain.ts
3811
+ import { OpenCode as OpenCode2 } from "@opencode/client";
3812
+
3813
+ // src/ssh-evidence.ts
3814
+ import { createHash as createHash4 } from "crypto";
3815
+ import { constants as fsConstants4 } from "fs";
3816
+ import { open, lstat, realpath, readlink } from "fs/promises";
3817
+ import { basename as basename2, isAbsolute, resolve as resolve4, sep as sep2 } from "path";
3818
+ var O_RDONLY3 = typeof fsConstants4.O_RDONLY === "number" ? fsConstants4.O_RDONLY : 0;
3819
+ var O_NOFOLLOW3 = typeof fsConstants4.O_NOFOLLOW === "number" ? fsConstants4.O_NOFOLLOW : 0;
3820
+ var O_NONBLOCK3 = typeof fsConstants4.O_NONBLOCK === "number" ? fsConstants4.O_NONBLOCK : 0;
3821
+ var SENSITIVE_PATH2 = /(?:^|\/)(?:\.env(?:\.|$)|\.ssh(?:\/|$)|\.aws(?:\/|$)|\.config\/(?:gh|gcloud)(?:\/|$)|id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?$|credentials(?:\.json)?$|authorized_keys$|known_hosts$|\.npmrc$|\.pypirc$|\.netrc$)/i;
3822
+ var SENSITIVE_CONTENT = /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:sk|nvapi)-[A-Za-z0-9_-]{16,}|\b(?:ghp|gho|ghs|ghr|ghu)_[A-Za-z0-9_-]{16,}|\bgithub_pat_[A-Za-z0-9_-]{16,}|\b(?:api[_-]?key|access[_-]?token|password)\s*[:=]\s*["'][^"'\n]{8,}["']/i;
3823
+ function sha256(value) {
3824
+ return createHash4("sha256").update(value).digest("hex");
3825
+ }
3826
+ function isWithinRoot(path, root) {
3827
+ return path === root || path.startsWith(`${root}${sep2}`);
3828
+ }
3829
+ async function approvedEvidenceRoots(rootDirectory, worktree, temporaryPath = "/tmp/opencode") {
3830
+ const [directoryRoot, worktreeRoot, temporaryRoot] = await Promise.all([
3831
+ realpath(rootDirectory).catch(() => resolve4(rootDirectory)),
3832
+ worktree === void 0 ? void 0 : realpath(worktree).catch(() => resolve4(worktree)),
3833
+ temporaryEvidenceRoot(temporaryPath)
3834
+ ]);
3835
+ return [
3836
+ directoryRoot,
3837
+ ...worktreeRoot === void 0 ? [] : [worktreeRoot],
3838
+ ...temporaryRoot === void 0 ? [] : [temporaryRoot]
3839
+ ];
3840
+ }
3841
+ async function temporaryEvidenceRoot(path) {
3842
+ try {
3843
+ const info = await lstat(path);
3844
+ if (info.isSymbolicLink() || !info.isDirectory()) return void 0;
3845
+ if (typeof process.getuid === "function") {
3846
+ const uid = process.getuid();
3847
+ if (typeof info.uid === "number" && info.uid !== uid) return void 0;
3848
+ }
3849
+ if (info.mode & 18) return void 0;
3850
+ return path;
3851
+ } catch {
3852
+ return void 0;
3853
+ }
3854
+ }
3855
+ async function descriptorRealPath(fd) {
3856
+ try {
3857
+ return await readlink(`/proc/self/fd/${fd}`);
3858
+ } catch {
3859
+ return void 0;
3860
+ }
3861
+ }
3862
+ async function includeFileOnce(source, directory, rootDirectory, worktree, maxChars) {
3863
+ const resolved = resolve4(directory, source);
3864
+ if (SENSITIVE_PATH2.test(resolved)) {
3865
+ return { source: "file", path: resolved, status: "blocked", reason: "sensitive path" };
3866
+ }
3867
+ try {
3868
+ const actual = await realpath(resolved);
3869
+ const roots = await approvedEvidenceRoots(rootDirectory, worktree);
3870
+ if (!roots.some((root) => isWithinRoot(actual, root))) {
3871
+ return {
3872
+ source: "file",
3873
+ path: resolved,
3874
+ status: "blocked",
3875
+ reason: "outside approved enrichment roots"
3876
+ };
3877
+ }
3878
+ if (SENSITIVE_PATH2.test(actual)) {
3879
+ return {
3880
+ source: "file",
3881
+ path: resolved,
3882
+ status: "blocked",
3883
+ reason: "sensitive resolved path"
3884
+ };
3885
+ }
3886
+ const limit = Math.max(1, maxChars);
3887
+ const handle = await open(actual, O_RDONLY3 | O_NOFOLLOW3 | O_NONBLOCK3);
3888
+ try {
3889
+ const info = await handle.stat();
3890
+ if (!info.isFile()) {
3891
+ return {
3892
+ source: "file",
3893
+ path: resolved,
3894
+ status: "unavailable",
3895
+ reason: "not a regular file"
3896
+ };
3897
+ }
3898
+ const fdPath = await descriptorRealPath(handle.fd);
3899
+ if (fdPath !== void 0) {
3900
+ if (!roots.some((root) => isWithinRoot(fdPath, root))) {
3901
+ return {
3902
+ source: "file",
3903
+ path: resolved,
3904
+ status: "blocked",
3905
+ reason: `open descriptor resolves outside approved enrichment roots (${fdPath})`
3906
+ };
3907
+ }
3908
+ if (SENSITIVE_PATH2.test(fdPath)) {
3909
+ return {
3910
+ source: "file",
3911
+ path: resolved,
3912
+ status: "blocked",
3913
+ reason: "sensitive resolved path"
3914
+ };
3915
+ }
3916
+ }
3917
+ const buffer = Buffer.alloc(Math.min(info.size, limit + 1));
3918
+ let bytesRead = 0;
3919
+ while (bytesRead < buffer.length) {
3920
+ const { bytesRead: count } = await handle.read(
3921
+ buffer,
3922
+ bytesRead,
3923
+ buffer.length - bytesRead,
3924
+ bytesRead
3925
+ );
3926
+ if (count === 0) break;
3927
+ bytesRead += count;
3928
+ }
3929
+ const shortRead = bytesRead < buffer.length;
3930
+ const included = buffer.subarray(0, Math.min(bytesRead, limit));
3931
+ const content = included.toString("utf8");
3932
+ const replacementCount = [...content].filter((character) => character === "\uFFFD").length;
3933
+ if (included.includes(0) || replacementCount > Math.max(2, content.length / 100)) {
3934
+ return {
3935
+ source: "file",
3936
+ path: resolved,
3937
+ status: "blocked",
3938
+ reason: "binary or non-text content",
3939
+ size: info.size
3940
+ };
3941
+ }
3942
+ if (SENSITIVE_CONTENT.test(content)) {
3943
+ return {
3944
+ source: "file",
3945
+ path: resolved,
3946
+ status: "blocked",
3947
+ reason: "possible literal credential or private key",
3948
+ size: info.size,
3949
+ includedSha256: sha256(included)
3950
+ };
3951
+ }
3952
+ return {
3953
+ source: "file",
3954
+ path: resolved,
3955
+ status: info.size > limit || shortRead ? "truncated" : "included",
3956
+ size: info.size,
3957
+ includedBytes: included.length,
3958
+ includedSha256: sha256(included),
3959
+ content
3960
+ };
3961
+ } finally {
3962
+ await handle.close();
3963
+ }
3964
+ } catch (error) {
3965
+ return {
3966
+ source: "file",
3967
+ path: isAbsolute(source) ? source : resolved,
3968
+ status: "unavailable",
3969
+ reason: error instanceof Error ? error.message : String(error)
3970
+ };
3971
+ }
3972
+ }
3973
+ function isMissingFile(result) {
3974
+ return result.status === "unavailable" && /\bENOENT\b|no such file or directory/i.test(result.reason ?? "");
3975
+ }
3976
+ async function includeEvidenceFile(source, directory, rootDirectory, worktree, maxChars) {
3977
+ const first = await includeFileOnce(source, directory, rootDirectory, worktree, maxChars);
3978
+ if (!isMissingFile(first)) return first;
3979
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
3980
+ return includeFileOnce(source, directory, rootDirectory, worktree, maxChars);
3981
+ }
3982
+
3983
+ // src/verified-ssh-script.ts
3984
+ import { createHash as createHash5 } from "crypto";
3985
+ var VERIFIED_SCRIPT_LIMIT = 64 * 1024;
3986
+ var RECEIPT_LIFETIME_MS = 60 * 60 * 1e3;
3987
+ function renderVerifiedSshScriptCommand(input) {
3988
+ const remote = `set -eu; f=$(mktemp /tmp/reviewer-script.XXXXXXXX); cleanup(){ rm -f -- $f; }; trap cleanup EXIT; cat >$f; sum=$(sha256sum $f); test \${sum%% *} = ${input.sha256}; ${input.shell} $f`;
3989
+ return `cat -- ${input.path} | ssh -T -o BatchMode=yes -o StrictHostKeyChecking=yes -o ConnectTimeout=5${input.port === void 0 ? "" : ` -p ${input.port}`} ${input.destination} '${remote}'`;
3990
+ }
3991
+
3992
+ // src/cli/explain.ts
3993
+ if (import.meta.main) {
3994
+ const code = await runCli(process.argv.slice(2));
3995
+ process.exit(code);
3996
+ }
3997
+ async function runCli(argv) {
3998
+ const first = argv[0];
3999
+ const explicit = first !== void 0 && !first.startsWith("-");
4000
+ const command = explicit ? first : "explain";
4001
+ const rest = explicit ? argv.slice(1) : argv;
4002
+ try {
4003
+ switch (command) {
4004
+ case "init":
4005
+ return await runInit(rest);
4006
+ case "explain":
4007
+ return await runExplain(rest);
4008
+ case "doctor":
4009
+ return await runDoctor(rest);
4010
+ case "config":
4011
+ return await runConfig(rest);
4012
+ case "audit":
4013
+ return await runAudit(rest);
4014
+ case "script":
4015
+ return await runScript(rest);
4016
+ default:
4017
+ console.error(`unknown command: ${command}
4018
+ ${usage2()}`);
4019
+ return 2;
4020
+ }
4021
+ } catch (error) {
4022
+ if (error?.code === "ERR_PARSE_ARGS_INVALID_OPTION") {
4023
+ console.error(String(error.message ?? error));
4024
+ return 2;
4025
+ }
4026
+ console.error(String(error?.message ?? error));
4027
+ return 2;
4028
+ }
4029
+ }
4030
+ function usage2() {
4031
+ return `Usage:
4032
+ opencode-permission-reviewer init [--project <dir>] [--global] [--tui] [--dry-run] [--print] [--yes]
4033
+ opencode-permission-reviewer explain [--event <file>] [--project <dir>]
4034
+ opencode-permission-reviewer doctor [--project <dir>] [--json]
4035
+ opencode-permission-reviewer config print-effective [--project <dir>]
4036
+ opencode-permission-reviewer audit report [--path <file>] [--project <dir>] [--json]
4037
+ opencode-permission-reviewer script command --file <path> --host <host> [--port <port>] [--shell bash|sh]`;
4038
+ }
4039
+ async function runScript(argv) {
4040
+ const { values, positionals } = parseArgs2({
4041
+ args: argv,
4042
+ options: {
4043
+ file: { type: "string" },
4044
+ host: { type: "string" },
4045
+ port: { type: "string" },
4046
+ shell: { type: "string" }
4047
+ },
4048
+ strict: true,
4049
+ allowPositionals: true
4050
+ });
4051
+ const file = values.file;
4052
+ const host = values.host;
4053
+ const shell = values.shell ?? "bash";
4054
+ const port = values.port === void 0 ? void 0 : Number(values.port);
4055
+ if (positionals.length !== 1 || positionals[0] !== "command" || !file || !/^[A-Za-z0-9_./-]+$/.test(file) || !host || !/^[A-Za-z0-9_.@-]+$/.test(host) || host.startsWith("-") || shell !== "bash" && shell !== "sh" || port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) {
4056
+ console.error(
4057
+ "Usage: script command --file <simple-path> --host <host> [--port <port>] [--shell bash|sh]"
4058
+ );
4059
+ return 2;
4060
+ }
4061
+ const directory = process.cwd();
4062
+ const evidence = await includeEvidenceFile(
4063
+ file,
4064
+ directory,
4065
+ directory,
4066
+ directory,
4067
+ VERIFIED_SCRIPT_LIMIT
4068
+ );
4069
+ if (evidence.status !== "included" || evidence.includedSha256 === void 0 || evidence.content === void 0 || redactSecrets(evidence.content) !== evidence.content) {
4070
+ console.error(
4071
+ `Script cannot be fully inspected (${evidence.status}). Use a text file of at most 64 KiB inside the workspace or /tmp/opencode, without secrets.`
4072
+ );
4073
+ return 1;
4074
+ }
4075
+ console.log(
4076
+ renderVerifiedSshScriptCommand({
4077
+ path: file,
4078
+ destination: host,
4079
+ ...port === void 0 ? {} : { port },
4080
+ sha256: evidence.includedSha256,
4081
+ shell
4082
+ })
4083
+ );
4084
+ return 0;
4085
+ }
4086
+ async function runExplain(argv) {
4087
+ const { values } = parseArgs2({
4088
+ args: argv,
4089
+ options: {
4090
+ event: { type: "string" },
4091
+ defaults: { type: "boolean" },
4092
+ project: { type: "string" },
4093
+ help: { type: "boolean", short: "h" }
4094
+ },
4095
+ strict: true,
4096
+ allowPositionals: false
4097
+ });
4098
+ if (values.help) {
4099
+ console.error(`Usage: explain --event <fixture.json> [--project <dir>]
4100
+ Reads a permission request JSON, runs the capability analyzer and policy engine
4101
+ (observe mode), and prints the result as JSON.`);
4102
+ return 0;
4103
+ }
4104
+ let raw;
4105
+ if (values.event) {
4106
+ raw = readFileSync2(values.event, "utf8");
4107
+ } else {
4108
+ raw = await readStdin2();
4109
+ }
4110
+ let parsed;
4111
+ try {
4112
+ parsed = JSON.parse(raw);
4113
+ } catch {
4114
+ console.error("explain: input is not valid JSON");
4115
+ return 2;
4116
+ }
4117
+ const normalized = normalizeRequest(parsed);
4118
+ if (normalized === void 0) {
4119
+ console.error('explain: input must have "permission" and "metadata.command" or "patterns"');
4120
+ return 2;
4121
+ }
4122
+ const request = normalized.request;
4123
+ const directory = values.project ?? process.cwd();
4124
+ const config = values.defaults ? resolveConfig(void 0) : loadResolvedConfig(void 0, directory);
4125
+ const worktree = directory;
4126
+ const nativeResources = normalized.nativeAction !== void 0;
4127
+ const command = typeof request.metadata?.command === "string" ? request.metadata.command : nativeResources ? "" : (request.patterns ?? []).filter((p) => typeof p === "string").join("\n");
4128
+ const result = {
4129
+ permission: request.permission,
4130
+ command,
4131
+ configuration: values.defaults ? "defaults" : "effective",
4132
+ model: config.model,
4133
+ ...nativeResources ? {
4134
+ resources: request.patterns,
4135
+ actionEvidenceComplete: normalized.actionEvidenceComplete,
4136
+ nativeAction: normalized.nativeAction
4137
+ } : {}
4138
+ };
4139
+ if (request.permission === "bash" && command.trim()) {
4140
+ const parsedCmd = parseCommand(command);
4141
+ const capability = analyzeCapability(parsedCmd, directory, worktree);
4142
+ const policyTrace = evaluatePolicy(capability, void 0, config, config.policyRules);
4143
+ result.capability = capability;
4144
+ result.policyTrace = policyTrace;
4145
+ } else {
4146
+ result.capability = null;
4147
+ result.policyTrace = evaluatePolicy(void 0, void 0, config, config.policyRules);
4148
+ }
4149
+ console.log(JSON.stringify(result, null, 2));
4150
+ return 0;
4151
+ }
4152
+ async function runDoctor(argv) {
4153
+ const { values } = parseArgs2({
4154
+ args: argv,
4155
+ options: {
4156
+ project: { type: "string" },
4157
+ binary: { type: "string" },
4158
+ endpoint: { type: "string" },
4159
+ json: { type: "boolean" },
4160
+ help: { type: "boolean", short: "h" }
4161
+ },
4162
+ strict: true,
4163
+ allowPositionals: false
4164
+ });
4165
+ if (values.help) {
4166
+ console.error("Usage: doctor [--project <dir>] [--json]");
4167
+ return 0;
4168
+ }
4169
+ const directory = values.project ?? process.cwd();
4170
+ const pkg = readPackageJson();
4171
+ const config = loadResolvedConfig(void 0, directory);
4172
+ const sources = inspectConfigSources(directory);
4173
+ const effectiveHash = hashEffectivePolicy(filterProjectAllowRules(config.policyRules), config);
4174
+ const auditPath = resolveAuditPath(config);
4175
+ const auditWritable = await checkWritable(auditPath);
4176
+ let connected;
4177
+ if (values.endpoint) {
4178
+ const password = process.env.OPENCODE_PASSWORD ?? process.env.OPENCODE_SERVER_PASSWORD;
4179
+ if (!password) throw new Error("Connected doctor requires OPENCODE_PASSWORD");
4180
+ const client = OpenCode2.make({
4181
+ baseUrl: validateHostEndpoint(values.endpoint).href,
4182
+ headers: { authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` }
4183
+ });
4184
+ connected = await client.rpc(ReviewerRpc).status({}, { location: { directory }, signal: AbortSignal.timeout(5e3) });
4185
+ }
4186
+ const report = {
4187
+ mode: values.endpoint ? "connected" : "local-only",
4188
+ host: {
4189
+ binaryVersion: values.binary ? await probeOpencodeVersion(values.binary) ?? null : null,
4190
+ runtime: connected ?? null
4191
+ },
4192
+ version: {
4193
+ package: pkg.version,
4194
+ opencodeRange: pkg.engines.opencode ?? "(unstated)",
4195
+ runtime: `bun/${process.versions.bun ?? "?"}`
4196
+ },
4197
+ config: {
4198
+ global: sources.global,
4199
+ project: sources.project,
4200
+ model: config.model,
4201
+ enforcementMode: config.enforcementMode,
4202
+ repositoryTrust: config.repositoryTrust,
4203
+ policyRuleCount: config.policyRules.length,
4204
+ effectivePolicyHash: effectiveHash
4205
+ },
4206
+ audit: {
4207
+ path: auditPath,
4208
+ writable: auditWritable.ok,
4209
+ ...auditWritable.error ? { error: auditWritable.error } : {}
4210
+ }
4211
+ };
4212
+ if (values.json) {
4213
+ console.log(JSON.stringify(report, null, 2));
4214
+ return 0;
4215
+ }
4216
+ console.error(`opencode-permission-reviewer doctor ${pkg.version}`);
4217
+ console.error(`diagnostic mode: ${report.mode}`);
4218
+ console.error(`version`);
4219
+ console.error(` package: ${report.version.package}`);
4220
+ console.error(` opencode: ${report.version.opencodeRange} (engines.opencode)`);
4221
+ console.error(` runtime: ${report.version.runtime}`);
4222
+ console.error(`config`);
4223
+ console.error(` global: ${fmtSource(sources.global)}`);
4224
+ console.error(` project: ${fmtSource(sources.project)}`);
4225
+ console.error(` model: ${report.config.model}`);
4226
+ const modeNote = report.config.enforcementMode === "observe" ? "declarative rules audited only; reviewer auto-allow/deny remains active" : "declarative rules enforced; reviewer decisions unchanged";
4227
+ console.error(` mode: ${report.config.enforcementMode} (${modeNote})`);
4228
+ console.error(` trust: ${report.config.repositoryTrust}`);
4229
+ console.error(
4230
+ ` rules: ${report.config.policyRuleCount} (effectivePolicyHash: ${effectiveHash})`
4231
+ );
4232
+ console.error(`audit`);
4233
+ console.error(` path: ${auditPath}`);
4234
+ console.error(
4235
+ ` writable: ${auditWritable.ok ? "yes" : "no"}${auditWritable.error ? ` (${auditWritable.error})` : ""}`
4236
+ );
4237
+ return 0;
4238
+ }
4239
+ async function runConfig(argv) {
4240
+ const { values, positionals } = parseArgs2({
4241
+ args: argv,
4242
+ options: { project: { type: "string" }, help: { type: "boolean", short: "h" } },
4243
+ strict: true,
4244
+ allowPositionals: true
4245
+ });
4246
+ if (values.help || positionals[0] !== "print-effective") {
4247
+ console.error("Usage: config print-effective [--project <dir>]");
4248
+ return 2;
4249
+ }
4250
+ const directory = values.project ?? process.cwd();
4251
+ const config = loadResolvedConfig(void 0, directory);
4252
+ const sources = inspectConfigSources(directory);
4253
+ const report = {
4254
+ command: "print-effective",
4255
+ directory,
4256
+ sources,
4257
+ config: redactConfig(config),
4258
+ policy: {
4259
+ ruleCount: config.policyRules.length,
4260
+ effectivePolicyHash: hashEffectivePolicy(filterProjectAllowRules(config.policyRules), config)
4261
+ }
4262
+ };
4263
+ console.log(JSON.stringify(report, null, 2));
4264
+ return 0;
4265
+ }
4266
+ async function runAudit(argv) {
4267
+ const { values, positionals } = parseArgs2({
4268
+ args: argv,
4269
+ options: {
4270
+ path: { type: "string" },
4271
+ project: { type: "string" },
4272
+ json: { type: "boolean" },
4273
+ help: { type: "boolean", short: "h" }
4274
+ },
4275
+ strict: true,
4276
+ allowPositionals: true
4277
+ });
4278
+ if (values.help || positionals[0] !== "report") {
4279
+ console.error("Usage: audit report [--path <file>] [--project <dir>] [--json]");
4280
+ return 2;
4281
+ }
4282
+ const directory = values.project ?? process.cwd();
4283
+ const config = loadResolvedConfig(void 0, directory);
4284
+ const auditPath = values.path ? expandHome(values.path) : resolveAuditPath(config);
4285
+ const summary = readAuditSummary(auditPath);
4286
+ if (!summary.exists) {
4287
+ console.error(`audit report: ${auditPath}: no such file`);
4288
+ return 1;
4289
+ }
4290
+ if (values.json) {
4291
+ console.log(JSON.stringify(summary, null, 2));
4292
+ return 0;
4293
+ }
4294
+ printAuditHuman(summary);
4295
+ return 0;
4296
+ }
4297
+ function printAuditHuman(s) {
4298
+ console.log(`audit report: ${s.path}`);
4299
+ if (s.truncated) {
4300
+ console.log(" NOTE: only the most recent 64 MiB were summarized; counts and");
4301
+ console.log(" timestamps describe that tail, not the whole file.");
4302
+ }
4303
+ console.log(` valid records: ${s.validRecords} (invalid lines: ${s.invalidLines})`);
4304
+ console.log(` schema versions: ${fmtCounts(s.bySchemaVersion)}`);
4305
+ console.log(` host generations: ${fmtCounts(s.byHostGeneration)}`);
4306
+ console.log(` application states:${fmtCounts(s.byApplication)}`);
4307
+ if (s.firstTimestamp || s.lastTimestamp) {
4308
+ console.log(` time range: ${s.firstTimestamp ?? "?"} \u2192 ${s.lastTimestamp ?? "?"}`);
4309
+ }
4310
+ console.log(` by outcome: ${fmtCounts(s.byOutcome)}`);
4311
+ console.log(` by risk level: ${fmtCounts(s.byRiskLevel)}`);
4312
+ if (Object.keys(s.byDecisionSource).length > 0) {
4313
+ console.log(` by decision source:${fmtCounts(s.byDecisionSource)}`);
4314
+ }
4315
+ if (Object.keys(s.byPermission).length > 0) {
4316
+ console.log(` by permission: ${fmtCounts(s.byPermission)}`);
4317
+ }
4318
+ if (s.unknownActorNames.length > 0) {
4319
+ console.log(` unknown actors: ${s.unknownActorNames.length}`);
4320
+ for (const a of s.unknownActorNames.slice(0, 10)) console.log(` ${a.name} (${a.count})`);
4321
+ }
4322
+ if (s.missingRequiredFields.length > 0) {
4323
+ console.log(` missing required fields: ${s.missingRequiredFields.length}`);
4324
+ for (const m of s.missingRequiredFields.slice(0, 10)) {
4325
+ console.log(` line ${m.lineNo}: missing ${m.missing.join(", ")}`);
4326
+ }
4327
+ }
4328
+ }
4329
+ function readPackageJson() {
4330
+ let dir = import.meta.dirname;
4331
+ for (let depth = 0; depth < 8; depth++) {
4332
+ const candidate = join4(dir, "package.json");
4333
+ if (existsSync2(candidate)) {
4334
+ const raw = JSON.parse(readFileSync2(candidate, "utf8"));
4335
+ return { version: raw.version, engines: raw.engines ?? {} };
4336
+ }
4337
+ const parent = dirname3(dir);
4338
+ if (parent === dir) break;
4339
+ dir = parent;
4340
+ }
4341
+ throw new Error("could not locate package.json");
4342
+ }
4343
+ function inspectConfigSources(directory) {
4344
+ return {
4345
+ global: inspectFile(globalConfigPath()),
4346
+ project: inspectFile(projectConfigPath(directory))
4347
+ };
4348
+ }
4349
+ function inspectFile(path) {
4350
+ try {
4351
+ const content = readFileSync2(path, "utf8");
4352
+ return { path, exists: true, sha256: sha256hex(content).slice(0, 16) };
4353
+ } catch {
4354
+ return { path, exists: false, sha256: null };
4355
+ }
4356
+ }
4357
+ function fmtSource(s) {
4358
+ return `${s.path} exists=${s.exists ? "yes" : "no"} sha256=${s.sha256 ?? "-"}`;
4359
+ }
4360
+ function fmtCounts(map) {
4361
+ const entries = Object.entries(map);
4362
+ if (entries.length === 0) return "(none)";
4363
+ return entries.sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`).join(" | ");
4364
+ }
4365
+ async function checkWritable(path) {
4366
+ try {
4367
+ await mkdir2(dirname3(path), { recursive: true });
4368
+ const fh = await open2(path, "a", 384);
4369
+ await fh.close();
4370
+ return { ok: true };
4371
+ } catch (error) {
4372
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
4373
+ }
4374
+ }
4375
+ function sha256hex(value) {
4376
+ return createHash6("sha256").update(value).digest("hex");
4377
+ }
4378
+ function redactConfig(config) {
4379
+ return config;
4380
+ }
4381
+ function readStdin2() {
4382
+ return new Promise((resolve5) => {
4383
+ let data = "";
4384
+ process.stdin.setEncoding("utf8");
4385
+ process.stdin.on("data", (chunk) => data += chunk);
4386
+ process.stdin.on("end", () => resolve5(data));
4387
+ });
4388
+ }
4389
+ function normalizeRequest(value) {
4390
+ if (typeof value !== "object" || value === null) return;
4391
+ const v = value;
4392
+ if (typeof v.action === "string" && Array.isArray(v.resources) && v.resources.every((resource) => typeof resource === "string")) {
4393
+ return normalizeV2Permission(
4394
+ {
4395
+ sessionID: typeof v.sessionID === "string" ? v.sessionID : "explain-session",
4396
+ action: v.action,
4397
+ resources: v.resources,
4398
+ effect: "ask",
4399
+ ...typeof v.agent === "string" ? { agent: v.agent } : {},
4400
+ metadata: typeof v.metadata === "object" && v.metadata !== null ? v.metadata : {}
4401
+ },
4402
+ { reviewID: "explain-dry-run", generation: "explain", directory: "", hostVersion: "2.0.3" },
4403
+ v.input
4404
+ );
4405
+ }
4406
+ if (typeof v.permission !== "string") return;
4407
+ const req = {
4408
+ id: typeof v.id === "string" ? v.id : "explain-dry-run",
4409
+ sessionID: typeof v.sessionID === "string" ? v.sessionID : "explain-session",
4410
+ permission: v.permission,
4411
+ patterns: Array.isArray(v.patterns) ? v.patterns : [],
4412
+ always: Array.isArray(v.always) ? v.always : [],
4413
+ metadata: typeof v.metadata === "object" && v.metadata !== null ? v.metadata : {}
4414
+ };
4415
+ if (typeof v.tool === "object" && v.tool !== null && typeof v.tool.messageID === "string") {
4416
+ req.tool = v.tool;
4417
+ }
4418
+ return { request: req };
4419
+ }
4420
+ export {
4421
+ runCli
4422
+ };