@noppu-labs/opencode-permission-reviewer 2.4.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +174 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/MIGRATION.md +2 -1
  5. package/NOTICE +14 -6
  6. package/README.md +109 -787
  7. package/SECURITY.md +41 -22
  8. package/dist/explain.d.ts +3 -4
  9. package/dist/explain.js +9708 -4298
  10. package/dist/index.d.ts +1096 -987
  11. package/dist/index.js +18646 -10575
  12. package/dist/rpc.d.ts +38 -38
  13. package/dist/rpc.js +30 -18
  14. package/dist/tui/config/jsonc.ts +71 -63
  15. package/dist/tui/config/layer-read.ts +120 -0
  16. package/dist/tui/config/loader.ts +73 -512
  17. package/dist/tui/config/risk-policy-clamp.ts +80 -0
  18. package/dist/tui/config/trust-boundary-keys.ts +102 -0
  19. package/dist/tui/config/trust-boundary.ts +148 -0
  20. package/dist/tui/config/trusted-degradation.ts +97 -0
  21. package/dist/tui/config-fields.ts +75 -0
  22. package/dist/tui/config-knobs.ts +119 -0
  23. package/dist/tui/config-policy-rules.ts +86 -0
  24. package/dist/tui/config-risk-policy.ts +59 -0
  25. package/dist/tui/config-rule-condition.ts +150 -0
  26. package/dist/tui/config.ts +72 -431
  27. package/dist/tui/descriptor-io.ts +42 -0
  28. package/dist/tui/failure-kind.ts +28 -0
  29. package/dist/tui/is-record.ts +13 -0
  30. package/dist/tui/opencode/event-normalizer.ts +41 -31
  31. package/dist/tui/reviewer-model.ts +87 -0
  32. package/dist/tui/system-one-routing.ts +110 -0
  33. package/dist/tui/tui.tsx +97 -99
  34. package/dist/tui/types.ts +206 -596
  35. package/dist/tui/ui/action-fit.ts +161 -0
  36. package/dist/tui/ui/action-spans.tsx +60 -0
  37. package/dist/tui/ui/attribution.ts +113 -0
  38. package/dist/tui/ui/components.tsx +69 -137
  39. package/dist/tui/ui/config-notices.ts +137 -0
  40. package/dist/tui/ui/fit-parts.ts +76 -0
  41. package/dist/tui/ui/manual-toast.ts +87 -0
  42. package/dist/tui/ui/review-connection.ts +32 -0
  43. package/dist/tui/ui/review-feed.ts +156 -0
  44. package/dist/tui/ui/review-overlay.tsx +111 -0
  45. package/dist/tui/ui/review-result.tsx +74 -0
  46. package/dist/tui/ui/review-store.ts +88 -0
  47. package/dist/tui/ui/review-theme.ts +70 -0
  48. package/dist/tui/ui/rpc.ts +5 -2
  49. package/dist/tui/ui/v1-host.ts +66 -0
  50. package/dist/tui/ui/v2.tsx +82 -220
  51. package/dist/tui/ui-protocol.ts +112 -124
  52. package/dist/tui/ui-state.ts +86 -64
  53. package/dist/tui/ui-status-extras.ts +165 -0
  54. package/dist/tui/ui-status-parse.ts +132 -0
  55. package/dist/tui/ui-text-elide.ts +89 -0
  56. package/package.json +24 -23
  57. package/rpc.js +2 -1
  58. package/server.js +2 -2
  59. package/tui.tsx +2 -1
package/dist/index.d.ts CHANGED
@@ -1,48 +1,246 @@
1
- import { Plugin as Plugin$1 } from '@opencode-ai/plugin';
2
- import { Plugin } from '@opencode/plugin';
3
-
1
+ import { TypeSafeClient } from "@typesafe-ai/sdk";
2
+ import "@opencode/client";
3
+ import { Plugin } from "@opencode-ai/plugin";
4
+ import { Plugin as Plugin$1 } from "@opencode/plugin";
5
+ import "@opencode/plugin/promise/permission";
6
+ //#region src/verified-ssh-script.d.ts
7
+ interface VerifiedScriptEvidence {
8
+ sha256: string;
9
+ destination: string;
10
+ port?: number;
11
+ shell: "bash" | "sh";
12
+ bytes?: number;
13
+ status: "full" | "reused" | "unavailable";
14
+ text: string;
15
+ cacheKey?: string;
16
+ }
17
+ //#endregion
18
+ //#region src/shell-token.d.ts
19
+ /** A run of a token's value that shares one quoting. `opaque` marks text the
20
+ * lexer kept whole from a substitution (an unquoted backtick form): it is
21
+ * the substitution's command, not the outer command's, so no operator in it
22
+ * acts on the outer command. It stays unquoted otherwise: a glob character
23
+ * in it reads as it did before. */
24
+ interface TokenSpan {
25
+ text: string;
26
+ quoted: boolean;
27
+ opaque?: true;
28
+ }
4
29
  interface ShellToken {
5
- /** Original text including any surrounding quotes. */
6
- raw: string;
7
- /** Unquoted/normalized value used for comparisons. */
8
- value: string;
9
- /** Value split into spans by quoting: every character of `value` appears
10
- * in exactly one span, marked `quoted` when it came from inside quotes
11
- * or from a backslash escape. An operator character (`>`, `*`, …) only
12
- * acts as an operator while it sits in an UNQUOTED span: a glued, partly
13
- * quoted `>"/dev/sda"` still redirects, while `'>/dev/sda'` is data. */
14
- spans?: Array<{
15
- text: string;
16
- quoted: boolean;
17
- }>;
30
+ /** Original text including any surrounding quotes. */
31
+ raw: string;
32
+ /** Unquoted/normalized value used for comparisons. */
33
+ value: string;
34
+ /** Value split into spans by quoting: every character of `value` appears
35
+ * in exactly one span, marked `quoted` when it came from inside quotes
36
+ * or from a backslash escape. An operator character (`>`, `*`, …) only
37
+ * acts as an operator while it sits in an UNQUOTED span: a glued, partly
38
+ * quoted `>"/dev/sda"` still redirects, while `'>/dev/sda'` is data.
39
+ * A zero-width quoted span can end a word: it marks an empty quote right
40
+ * after text that ends like a redirection operator (`<<<''`), and holds no
41
+ * character of `value`. */
42
+ spans?: TokenSpan[];
18
43
  }
19
44
  interface ShellSegment {
20
- tokens: ShellToken[];
21
- /** Separator that terminated this segment (`;`, `|`, `||`, `&`, `&&`, `(`,
22
- * `)`). Newlines and carriage returns are reported as `;`. Absent for the
23
- * final segment when the command does not end with a separator. A segment
24
- * with no tokens and `endedBy` `(` or `)` is a paren marker: it exists so
25
- * grouping events are never lost, and carries no command of its own. */
26
- endedBy?: string;
27
- /** The last separator seen before this segment's first token, counting
28
- * separators whose (empty) segment was dropped: in `( a ) | b`, segment
29
- * `b` ended up after a dropped empty segment, so its separator lineage is
30
- * `)` and then `|`, and `precededBy` reports `|`. Absent for the first
31
- * segment. */
32
- precededBy?: string;
45
+ tokens: ShellToken[];
46
+ /** Separator that terminated this segment (`;`, `|`, `||`, `&`, `&&`, `(`,
47
+ * `)`). Newlines and carriage returns are reported as `;`. Absent for the
48
+ * final segment when the command does not end with a separator. A segment
49
+ * with no tokens and `endedBy` `(` or `)` is a paren marker: it exists so
50
+ * grouping events are never lost, and carries no command of its own. */
51
+ endedBy?: string;
52
+ /** The last separator seen before this segment's first token, counting
53
+ * separators whose (empty) segment was dropped: in `( a ) | b`, segment
54
+ * `b` ended up after a dropped empty segment, so its separator lineage is
55
+ * `)` and then `|`, and `precededBy` reports `|`. Absent for the first
56
+ * segment. */
57
+ precededBy?: string;
33
58
  }
34
-
35
- interface VerifiedScriptEvidence {
36
- sha256: string;
37
- destination: string;
38
- port?: number;
39
- shell: "bash" | "sh";
40
- bytes?: number;
41
- status: "full" | "reused" | "unavailable";
42
- text: string;
43
- cacheKey?: string;
59
+ //#endregion
60
+ //#region src/walk-sink.d.ts
61
+ /** A command the walk resolves, wrapper or not: its basename, the words of
62
+ * its level and its index among them, and whether it runs inside the
63
+ * remote command of an ssh, mosh or autossh. */
64
+ interface PeeledHead {
65
+ head: string;
66
+ tokens: readonly ShellToken[];
67
+ index: number;
68
+ remote: boolean;
69
+ }
70
+ //#endregion
71
+ //#region src/capability/capability-types.d.ts
72
+ /** How completely the command could be statically analyzed. */
73
+ type ParserCompleteness =
74
+ /** Fully parsed: no variables, globs, substitutions, or heredoc bodies. */
75
+ "complete-for-supported-form" |
76
+ /** Some constructs could not be resolved (variables, partial heredoc). */
77
+ "partial" |
78
+ /** Heavy dynamic constructs (command substitution, eval, dynamic heredoc). */
79
+ "opaque";
80
+ /** A redirection extracted from a parsed command segment. */
81
+ interface Redirection {
82
+ /** `>` `>>` `<` `2>` `&>` etc. */
83
+ operator: string;
84
+ /** Target path (file descriptor targets normalized to a path when possible). */
85
+ target: string;
86
+ /** Whether the target was quoted in the source (affects literal-ness). */
87
+ quoted: boolean;
88
+ }
89
+ /** A heredoc extracted before lexing so its body never reaches the lexer/brake. */
90
+ interface HeredocRecord {
91
+ /** The literal delimiter token as it appeared (`EOF`, `END`, …). */
92
+ delimiter: string;
93
+ /** `<<` (expansion on) or `<<-` (tabs stripped) — normalized form. */
94
+ operator: string;
95
+ /** Whether the delimiter was quoted, disabling expansion (`<<'EOF'`). */
96
+ expansionDisabled: boolean;
97
+ /** Bounded + redacted body (truncated to a safe length). */
98
+ bodyBounded: string;
99
+ /** SHA-256 of the full, unredacted body (stable identity without leaking it). */
100
+ bodySha256: string;
101
+ /** Whether the body was truncated for storage. */
102
+ truncated: boolean;
103
+ /** Output path associated with the heredoc when a `> path` precedes it. */
104
+ outputTarget?: string;
105
+ /** Whether the body is dynamically constructed (unresolvable expansion). */
106
+ dynamic: boolean;
107
+ }
108
+ /** A command parsed into a reusable structure. Wraps the existing lexer output
109
+ * plus pre-extracted redirections and heredocs. */
110
+ interface ParsedCommand {
111
+ /** The command after heredoc bodies were replaced with placeholders. */
112
+ sanitizedCommand: string;
113
+ /** Lexed segments of the sanitized command. */
114
+ segments: ShellSegment[];
115
+ /** Effective commands (wrappers peeled) per segment. */
116
+ effective: ShellToken[][];
117
+ /** Redirections grouped by segment index. */
118
+ redirections: Redirection[][];
119
+ /** Heredocs extracted before lexing. */
120
+ heredocs: HeredocRecord[];
121
+ /** Whether the original command contained any dynamic constructs. */
122
+ hasDynamicConstructs: boolean;
123
+ /** True when the lexer's depth or expansion budget stopped command-string
124
+ * resolution early; `effective` is then a prefix of the real structure and
125
+ * deterministic facts do not cover the whole command. */
126
+ analysisTruncated: boolean;
127
+ /** The effective commands that run on the far side of an ssh with no
128
+ * remote command, from the script it reads. They are among `effective`
129
+ * too. */
130
+ remoteCommands?: ShellToken[][];
131
+ /** Every command the walk resolves, wrappers among them, at every level:
132
+ * command strings, `env -S`, `watch` and ssh remote commands. */
133
+ heads: readonly PeeledHead[];
134
+ /** The redirections each walked segment and command string carries
135
+ * itself, whether or not it yields an effective command: the shell
136
+ * opens them before it runs anything (`>f ssh h`). */
137
+ segmentRedirections: readonly (readonly Redirection[])[];
138
+ /** An interpreter among the commands runs code from a heredoc or
139
+ * here-string. */
140
+ stdinCode?: boolean;
141
+ }
142
+ /** What the action can do, what it appears to do, and analysis confidence. */
143
+ interface CapabilityAssessment {
144
+ /** Best single-label summary of the dominant capability. */
145
+ actionClass: Provenanced<CapabilityActionClass>;
146
+ /** Human-readable summary of the detected surface. */
147
+ summary: string;
148
+ /** Executes an interpreter or runtime (sh, python, node, bun, …). */
149
+ executesCode: Provenanced<boolean | "unknown">;
150
+ /** Executes code that lives in the repository (scripts, test files). */
151
+ executesRepositoryCode: Provenanced<boolean | "unknown">;
152
+ /** Executes ad-hoc code generated by the agent (heredoc/inline). */
153
+ createsAdHocCode: Provenanced<boolean | "unknown">;
154
+ /** Invokes a known test runner (pytest, jest, bun test, …). */
155
+ invokesExistingTestRunner: Provenanced<boolean | "unknown">;
156
+ /** Runs a package manager that may execute lifecycle scripts. */
157
+ invokesPackageLifecycleScripts: Provenanced<boolean | "unknown">;
158
+ /** Reads literal credential material through a known file reader. */
159
+ credentialRead: Provenanced<boolean | "unknown">;
160
+ /** Detected file-write surface. */
161
+ writeEffects: {
162
+ temporaryWrite: Provenanced<boolean | "unknown">;
163
+ workspaceWrite: Provenanced<boolean | "unknown">;
164
+ externalWrite: Provenanced<boolean | "unknown">;
165
+ deletion: Provenanced<boolean | "unknown">;
166
+ };
167
+ /** Detected network surface. */
168
+ network: {
169
+ observed: Provenanced<boolean | "unknown">;
170
+ possible: Provenanced<boolean | "unknown">;
171
+ /** Hosts/destinations observed literally in the command. */
172
+ destinations: string[];
173
+ observedAccess: Provenanced<boolean | "unknown">;
174
+ possibleAccess: Provenanced<boolean | "unknown">;
175
+ };
176
+ /** Detected process side-effects. */
177
+ process: {
178
+ childProcesses: Provenanced<boolean | "unknown">;
179
+ persistence: Provenanced<boolean | "unknown">;
180
+ privilegeEscalation: Provenanced<boolean | "unknown">;
181
+ };
182
+ /** Detected remote-operation surface (ssh, etc.). */
183
+ remote: {
184
+ enabled: Provenanced<boolean | "unknown">;
185
+ mutationHint: Provenanced<boolean | "unknown">;
186
+ };
187
+ /** Detected git mutation surface. */
188
+ git: {
189
+ observed: Provenanced<boolean | "unknown">;
190
+ possible: Provenanced<boolean | "unknown">;
191
+ observedAccess: Provenanced<boolean | "unknown">;
192
+ possibleAccess: Provenanced<boolean | "unknown">;
193
+ };
194
+ /** How completely the command could be analyzed. */
195
+ parserCompleteness: ParserCompleteness;
196
+ /** Free-form warnings about analysis limitations. */
197
+ analysisWarnings: string[];
198
+ }
199
+ //#endregion
200
+ //#region src/system-one/system-one-types.d.ts
201
+ declare const SYSTEM_ONE_BASES: readonly ["authorized_routine", "authorized_reversible_change", "insufficient_authorization", "scope_mismatch", "insufficient_evidence", "destructive_effect", "credential_or_private_data", "security_or_privilege_change", "external_or_remote_effect", "trusted_policy_restriction", "conflicting_evidence"];
202
+ type SystemOnePrimaryBasis = (typeof SYSTEM_ONE_BASES)[number];
203
+ interface SystemOneChoiceScore<T extends string> {
204
+ choice: T;
205
+ confidence: number;
206
+ }
207
+ /** Probability (0-1) that each safety question is true. */
208
+ interface SystemOneSignals {
209
+ materialAuthorization: number;
210
+ withinIntentScope: number;
211
+ unauthorizedDataLoss: number;
212
+ untrustedSensitiveDisclosure: number;
213
+ excessiveCredentialAccess: number;
214
+ unauthorizedSecurityChange: number;
215
+ unauthorizedExternalMutation: number;
216
+ essentialEvidenceMissing: number;
217
+ absolutePolicyDeny: number;
218
+ }
219
+ /**
220
+ * Jev's own answer, kept apart from the final decision because a reasoning
221
+ * reviewer may replace it. Numbers, enum choices, fixed contradiction strings,
222
+ * and the provider-reported model ID only; never evidence text.
223
+ */
224
+ interface SystemOneScores {
225
+ /** Versioned model ID the provider reported as having answered. */
226
+ returnedModel: string;
227
+ outcome: SystemOneChoiceScore<ReviewOutcome> & {
228
+ probabilities: Record<ReviewOutcome, number>;
229
+ };
230
+ supporting: {
231
+ riskLevel: SystemOneChoiceScore<RiskLevel>;
232
+ userAuthorization: SystemOneChoiceScore<UserAuthorization>;
233
+ scopeAlignment: SystemOneChoiceScore<ScopeAlignment>;
234
+ evidenceCompleteness: SystemOneChoiceScore<EvidenceSufficiency>;
235
+ primaryBasis: SystemOneChoiceScore<SystemOnePrimaryBasis>;
236
+ };
237
+ signals: SystemOneSignals;
238
+ /** Consistency checks that failed; any one marks an allow or deny difficult. */
239
+ contradictions: string[];
240
+ reasoningRecommended: boolean;
44
241
  }
45
-
242
+ //#endregion
243
+ //#region src/types.d.ts
46
244
  type RiskLevel = "low" | "medium" | "high" | "critical";
47
245
  type UserAuthorization = "high" | "medium" | "low" | "unknown";
48
246
  type ReviewOutcome = "allow" | "deny" | "escalate";
@@ -52,41 +250,43 @@ type EvidenceSufficiency = "sufficient" | "partial" | "insufficient" | "unknown"
52
250
  type EscalationMode = "manual" | "deny";
53
251
  /** Effective disposition applied to an internal escalate result. */
54
252
  type EscalationDisposition = "manual" | "deny";
253
+ /** Where an escalation that starts at Jev goes; `reasoning-first` sends every one to the escalation reviewer. */
254
+ type SystemOneEscalationMode = "standard" | "reasoning-first";
55
255
  interface ReviewDecision {
56
- /** Structured-decision schema version. Always 2 for the current schema. */
57
- version: 2;
58
- outcome: ReviewOutcome;
59
- risk_level: RiskLevel;
60
- user_authorization: UserAuthorization;
61
- /** How well the request aligns with the recovered user/delegated intent. */
62
- scope_alignment: ScopeAlignment;
63
- /** Whether the evidence was sufficient to decide confidently. */
64
- evidence_completeness: EvidenceSufficiency;
65
- rationale: string;
66
- confidence: number;
67
- /** Optional script-only semantic analysis. Never conveys authorization. */
68
- script_analysis?: string;
256
+ /** Structured-decision schema version. Always 2 for the current schema. */
257
+ version: 2;
258
+ outcome: ReviewOutcome;
259
+ risk_level: RiskLevel;
260
+ user_authorization: UserAuthorization;
261
+ /** How well the request aligns with the recovered user/delegated intent. */
262
+ scope_alignment: ScopeAlignment;
263
+ /** Whether the evidence was sufficient to decide confidently. */
264
+ evidence_completeness: EvidenceSufficiency;
265
+ rationale: string;
266
+ confidence: number;
267
+ /** Optional script-only semantic analysis. Never conveys authorization. */
268
+ script_analysis?: string;
69
269
  }
70
270
  interface PermissionToolSource {
71
- messageID: string;
72
- callID: string;
271
+ messageID: string;
272
+ callID: string;
73
273
  }
74
274
  interface PermissionRequest {
75
- id: string;
76
- sessionID: string;
77
- permission: string;
78
- patterns: string[];
79
- metadata: Record<string, unknown>;
80
- always: string[];
81
- tool?: PermissionToolSource;
275
+ id: string;
276
+ sessionID: string;
277
+ permission: string;
278
+ patterns: string[];
279
+ metadata: Record<string, unknown>;
280
+ always: string[];
281
+ tool?: PermissionToolSource;
82
282
  }
83
283
  interface MessageWithParts {
84
- info: Record<string, unknown> & {
85
- id?: string;
86
- role?: string;
87
- structured?: unknown;
88
- };
89
- parts: Array<Record<string, unknown>>;
284
+ info: Record<string, unknown> & {
285
+ id?: string;
286
+ role?: string;
287
+ structured?: unknown;
288
+ };
289
+ parts: Array<Record<string, unknown>>;
90
290
  }
91
291
  /** Deterministic risk×authorization matrix that gates reviewer `allow`
92
292
  * outcomes. For each risk level, lists the authorization levels that permit an
@@ -94,15 +294,15 @@ interface MessageWithParts {
94
294
  * risk (the action is escalated). Only ever RESTRICTS; deny/escalate are always
95
295
  * preserved. */
96
296
  interface RiskPolicy {
97
- allow: {
98
- low: UserAuthorization[];
99
- medium: UserAuthorization[];
100
- high: UserAuthorization[];
101
- critical: UserAuthorization[];
102
- };
103
- minimumConfidence: number;
104
- onInvalidDecision: "manual" | "deny";
105
- onReviewerFailure: "manual" | "deny";
297
+ allow: {
298
+ low: UserAuthorization[];
299
+ medium: UserAuthorization[];
300
+ high: UserAuthorization[];
301
+ critical: UserAuthorization[];
302
+ };
303
+ minimumConfidence: number;
304
+ onInvalidDecision: "manual" | "deny";
305
+ onReviewerFailure: "manual" | "deny";
106
306
  }
107
307
  /** Conservative repository trust model. A repository cannot mark itself trusted
108
308
  * through project configuration alone — trust comes from global config or an
@@ -112,490 +312,320 @@ type RepositoryTrust = "trusted" | "untrusted" | "unknown";
112
312
  * is optional; the rule matches when ALL specified fields match. A missing
113
313
  * `when` (or `{ always: true }`) makes the rule universal. */
114
314
  interface PolicyCondition {
115
- /** Explicit catch-all: valid only as the sole key. */
116
- always?: true;
117
- actionClass?: CapabilityActionClass[];
118
- actorProfile?: ActorProfile[];
119
- writesWorkspace?: boolean;
120
- writesExternal?: boolean;
121
- writesTemporary?: boolean;
122
- deletion?: boolean;
123
- executesCode?: boolean;
124
- createsAdHocCode?: boolean;
125
- packageManagement?: boolean;
126
- gitMutation?: boolean;
127
- networkObserved?: boolean;
128
- credentialRead?: boolean;
129
- privilegeEscalation?: boolean;
130
- remoteEnabled?: boolean;
131
- persistence?: boolean;
132
- repositoryTrust?: RepositoryTrust[];
315
+ /** Explicit catch-all: valid only as the sole key. */
316
+ always?: true;
317
+ actionClass?: CapabilityActionClass[];
318
+ actorProfile?: ActorProfile[];
319
+ writesWorkspace?: boolean;
320
+ writesExternal?: boolean;
321
+ writesTemporary?: boolean;
322
+ deletion?: boolean;
323
+ executesCode?: boolean;
324
+ createsAdHocCode?: boolean;
325
+ packageManagement?: boolean;
326
+ gitMutation?: boolean;
327
+ networkObserved?: boolean;
328
+ credentialRead?: boolean;
329
+ privilegeEscalation?: boolean;
330
+ remoteEnabled?: boolean;
331
+ persistence?: boolean;
332
+ repositoryTrust?: RepositoryTrust[];
133
333
  }
134
334
  /** A declarative rule that routes a request based on capability+actor facts.
135
335
  * `when` is optional: omitting it (or `{ always: true }`) matches every
136
336
  * request. An explicitly empty `when: {}` is rejected at load. */
137
337
  interface PolicyRule {
138
- id: string;
139
- source: "builtin" | "global" | "project" | "inline";
140
- when?: PolicyCondition;
141
- effect: "review" | "manual" | "deny" | "allow";
142
- reason: string;
338
+ id: string;
339
+ source: "builtin" | "global" | "project" | "inline";
340
+ when?: PolicyCondition;
341
+ effect: "review" | "manual" | "deny" | "allow";
342
+ reason: string;
143
343
  }
144
344
  /** The result of evaluating the declarative policy. */
145
345
  interface PolicyTrace {
146
- /** Stable hash of the effective rule set (not the matched rules) for audit
147
- * reproducibility. */
148
- effectivePolicyHash: string;
149
- matchedRules: Array<{
150
- id: string;
151
- source: string;
152
- effect: string;
153
- reason: string;
154
- }>;
155
- /** The route the engine computed (counterfactual in observe mode: what enforce
156
- * mode WOULD have done with the same facts and rules). */
157
- finalRoute: "review" | "manual" | "deny" | "allow";
158
- mode: "observe" | "enforce";
346
+ /** Stable hash of the effective rule set (not the matched rules) for audit
347
+ * reproducibility. */
348
+ effectivePolicyHash: string;
349
+ matchedRules: Array<{
350
+ id: string;
351
+ source: string;
352
+ effect: string;
353
+ reason: string;
354
+ }>;
355
+ /** The route the engine computed (counterfactual in observe mode: what enforce
356
+ * mode WOULD have done with the same facts and rules). */
357
+ finalRoute: "review" | "manual" | "deny" | "allow";
358
+ mode: "observe" | "enforce";
159
359
  }
160
360
  type ReviewerOutputFormat = "json_schema" | "text";
161
361
  interface EscalationReviewerConfig {
162
- model: string;
163
- variant: string;
164
- outputFormat: ReviewerOutputFormat;
165
- timeoutMs: number;
362
+ model: string;
363
+ variant: string;
364
+ outputFormat: ReviewerOutputFormat;
365
+ timeoutMs: number;
166
366
  }
167
367
  interface ReviewerConfig {
168
- model: string;
169
- variant: string;
170
- /** How the reviewer model returns its decision. `json_schema` requests
171
- * OpenCode's structured-output format (requires provider support); `text`
172
- * asks the model to emit JSON in plain text and parses it locally. */
173
- outputFormat: ReviewerOutputFormat;
174
- /** Optional reasoning reviewer for valid System One decisions that remain
175
- * uncertain or conflict with deterministic review gates. */
176
- escalationReviewer?: EscalationReviewerConfig;
177
- /** Calibrated outcome-confidence floor for System One decisions. */
178
- systemOneConfidenceThreshold: number;
179
- /** Minimum combined non-escalate probability for routing an explicit
180
- * System One escalation to the optional reasoning reviewer. */
181
- systemOneReasoningThreshold: number;
182
- timeoutMs: number;
183
- /** Total review budget, including context, queueing, and retries. */
184
- reviewBudgetMs?: number;
185
- maxContextChars: number;
186
- maxPartChars: number;
187
- maxEnrichmentChars: number;
188
- maxIntentChars: number;
189
- transcriptMessages: number;
190
- intentMessages: number;
191
- historyMessages: number;
192
- confidenceThreshold: number;
193
- retainReviewSessions: boolean;
194
- audit: boolean;
195
- auditPath?: string;
196
- policy?: string;
197
- debug: boolean;
198
- /** When "observe", actor evidence is collected and audited but never enforces
199
- * new gates; "enforce" applies declarative policy routes. */
200
- enforcementMode: "observe" | "enforce";
201
- /**
202
- * How internal `escalate` results are disposed before UI/reply.
203
- * - `manual` (default): leave the request for a human (interactive mode).
204
- * - `deny`: convert every final escalation into a reject with rationale
205
- * (non-interactive fail-closed). Never relaxes an explicit deny.
206
- */
207
- escalationMode: EscalationMode;
208
- /** Max hops when walking session parents (default 8). */
209
- maxSessionDepth: number;
210
- /** Max parent sessions fetched during lineage traversal. */
211
- maxParentSessions: number;
212
- /** Trusted name→profile mappings (empty by default; no mappings shipped). */
213
- actorProfiles: Record<string, ActorProfile>;
214
- /** Deterministic risk×authorization gate, configurable but defaults reproduce
215
- * the previous hard-coded matrix exactly. */
216
- riskPolicy: RiskPolicy;
217
- /** Repository trust level derived from global config (never from project). */
218
- repositoryTrust: RepositoryTrust;
219
- /** Declarative policy rules (empty by default; observe mode audits the trace
220
- * without enforcing). Project-sourced allow rules are rejected. */
221
- policyRules: PolicyRule[];
222
- /** Capture user answers to agent ask dialogs (question tool) and surface
223
- * them to the reviewer as scoped authorization evidence. */
224
- askDecisions: boolean;
225
- /** Non-empty when a TRUSTED config source (global file, inline options)
226
- * existed but could not be fully honored (malformed file, unreadable file,
227
- * or rules dropped by validation). Degraded configs block automatic
228
- * approval: restrictions may have been lost, so requests escalate instead. */
229
- configDegraded?: string[];
368
+ model: string;
369
+ variant: string;
370
+ /** How the reviewer model returns its decision. `json_schema` requests
371
+ * OpenCode's structured-output format (requires provider support); `text`
372
+ * asks the model to emit JSON in plain text and parses it locally. */
373
+ outputFormat: ReviewerOutputFormat;
374
+ /** Optional reasoning reviewer for valid System One decisions that remain
375
+ * uncertain or conflict with deterministic review gates. */
376
+ escalationReviewer?: EscalationReviewerConfig;
377
+ /** Calibrated outcome-confidence floor for System One decisions. */
378
+ systemOneConfidenceThreshold: number;
379
+ /** Minimum combined non-escalate probability for routing an explicit
380
+ * System One escalation to the optional reasoning reviewer. */
381
+ systemOneReasoningThreshold: number;
382
+ /** Read through resolveSystemOneRouting, which applies the Jev and escalationReviewer conditions. */
383
+ systemOneEscalation: SystemOneEscalationMode;
384
+ /** Send uncertain Jev denials to the escalation reviewer. Read through resolveSystemOneRouting. */
385
+ systemOneDenialReview: boolean;
386
+ timeoutMs: number;
387
+ /** Total review budget, including context, queueing, and retries. */
388
+ reviewBudgetMs?: number;
389
+ maxContextChars: number;
390
+ maxPartChars: number;
391
+ maxEnrichmentChars: number;
392
+ maxIntentChars: number;
393
+ transcriptMessages: number;
394
+ intentMessages: number;
395
+ historyMessages: number;
396
+ confidenceThreshold: number;
397
+ retainReviewSessions: boolean;
398
+ audit: boolean;
399
+ auditPath?: string;
400
+ policy?: string;
401
+ debug: boolean;
402
+ /** When "observe", actor evidence is collected and audited but never enforces
403
+ * new gates; "enforce" applies declarative policy routes. */
404
+ enforcementMode: "observe" | "enforce";
405
+ /**
406
+ * How internal `escalate` results are disposed before UI/reply.
407
+ * - `manual` (default): leave the request for a human (interactive mode).
408
+ * - `deny`: convert every final escalation into a reject with rationale
409
+ * (non-interactive fail-closed). Never relaxes an explicit deny.
410
+ */
411
+ escalationMode: EscalationMode;
412
+ /** Max hops when walking session parents (default 8). */
413
+ maxSessionDepth: number;
414
+ /** Max parent sessions fetched during lineage traversal. */
415
+ maxParentSessions: number;
416
+ /** Trusted name→profile mappings (empty by default; no mappings shipped). */
417
+ actorProfiles: Record<string, ActorProfile>;
418
+ /** Deterministic risk×authorization gate, configurable but defaults reproduce
419
+ * the previous hard-coded matrix exactly. */
420
+ riskPolicy: RiskPolicy;
421
+ /** Repository trust level derived from global config (never from project). */
422
+ repositoryTrust: RepositoryTrust;
423
+ /** Declarative policy rules (empty by default; observe mode audits the trace
424
+ * without enforcing). Project-sourced allow rules are rejected. */
425
+ policyRules: PolicyRule[];
426
+ /** Capture user answers to agent ask dialogs (question tool) and surface
427
+ * them to the reviewer as scoped authorization evidence. */
428
+ askDecisions: boolean;
429
+ /** Non-empty when a TRUSTED config source (global file, inline options)
430
+ * existed but could not be fully honored (malformed file, unreadable file,
431
+ * or rules dropped by validation). Degraded configs block automatic
432
+ * approval: restrictions may have been lost, so requests escalate instead. */
433
+ configDegraded?: string[];
434
+ /** Non-empty when a setting was invalid and fell back to its default, or is
435
+ * on but inert. Informational only: never affects a decision. */
436
+ configWarnings?: string[];
230
437
  }
231
438
  interface ReviewEnvelope {
232
- request: PermissionRequest;
233
- directory: string;
234
- worktree: string;
235
- transcript: string;
236
- intentHistory: string;
237
- enrichment: string;
238
- verifiedScript?: VerifiedScriptEvidence;
239
- sshAudit: NonNullable<ReviewAuditRecord["ssh"]>;
240
- preflightDenial?: string;
241
- /** Agent-aware context (actor, lineage, intent). Observe-only: flows into the
242
- * reviewer prompt and audit as evidence, never into enforcement decisions.
243
- * Optional so older callers/tests still compile. */
244
- actor?: ActorContext;
245
- lineage?: SessionLineage;
246
- intent?: IntentContext;
247
- evidenceCompleteness?: EvidenceCompleteness;
248
- /** Structured capability facts derived from the bash command. Observe-only:
249
- * feeds the reviewer prompt and audit, never enforcement. */
250
- capability?: CapabilityAssessment;
251
- /** The policy trace produced for this request, surfaced to the reviewer prompt
252
- * as EFFECTIVE_POLICY_SUMMARY and to audit. Observe-only. */
253
- policyTrace?: PolicyTrace;
254
- /** Per-phase timing captured during evidence assembly (context/enrichment).
255
- * The reviewer and reply phases are timed in the coordinator. */
256
- timings?: {
257
- contextMs?: number;
258
- enrichmentMs?: number;
259
- reviewerMs?: number;
260
- replyMs?: number;
261
- };
262
- /** False when a material part of the action under review (e.g. an elided
263
- * command segment) never reached the rendered evidence. Blocking: the
264
- * coordinator must not auto-approve an action the reviewer could not see
265
- * in full, whatever confidence the model reports. */
266
- actionEvidenceComplete?: boolean;
267
- /** The parsed command reused across evidence providers. */
268
- parsedCommand?: ParsedCommand;
269
- /** Operational purpose of the pending action (evidence, never authorization). */
270
- actionPurpose?: ActionPurpose;
271
- /** User answers to agent ask dialogs in this session or its ancestors,
272
- * captured live from question events. Observe-only: flows into the reviewer
273
- * prompt (USER_ASK_DECISIONS) and audit, never into enforcement. */
274
- askDecisions?: AskDecision[];
275
- }
276
- /** Which layer produced the final decision for a request. Threaded into the
277
- * audit record so reports can split outcomes by source. */
278
- type DecisionSource = "emergency-brake" | "deterministic-policy" | "llm-reviewer" | "system-one-reviewer" | "manual-superseded" | "failure-safe";
279
- interface ReviewAuditRecord {
280
- /**
281
- * Audit schema version. Present on every record; readers default a missing
282
- * field to `1` (additive — old records are still valid).
283
- * Bump only on a breaking change to the record shape.
284
- */
285
- schemaVersion?: number;
286
- reviewID?: string;
287
- hostRequestID?: string;
288
- hostGeneration?: "v1" | "v2";
289
- hostVersion?: string;
290
- generation?: string;
291
- nativeAction?: string;
292
- directory?: string;
293
- application?: "evaluation-returned" | "reply-accepted" | "human-pending" | "superseded" | "cancelled" | "unknown";
294
- pluginVersion?: string;
295
- effectiveConfigHash?: string;
296
- actionFingerprint?: string;
297
- /** Version of the structured-decision schema the reviewer was asked to emit. */
298
- decisionSchemaVersion?: number;
299
- /** Version of the reviewer system prompt used for this decision. */
300
- promptVersion?: string;
301
- /** Which layer produced the outcome (brake, policy, reviewer, supersede,
302
- * failure-safe). Absent on legacy v1 records. */
303
- decisionSource?: DecisionSource;
304
- timestamp: string;
305
- durationMs: number;
306
- requestID: string;
307
- sessionID: string;
308
- permission: string;
309
- /** Stable hash of the canonical request (permission, patterns, metadata,
310
- * tool) for cross-record correlation. Absent on legacy v1 records. */
311
- actionHash?: string;
312
- outcome: ReviewExecutionResult["kind"];
313
- reason: string;
314
- riskLevel?: RiskLevel;
315
- userAuthorization?: UserAuthorization;
316
- /** How well the action aligned with the recovered intent (from the reviewer
317
- * decision). Absent when no reviewer decision was reached. */
318
- scopeAlignment?: ScopeAlignment;
319
- confidence?: number;
320
- /**
321
- * Structured outcome emitted by the reviewer LLM before gates/disposition.
322
- * Absent when no valid structured decision was produced (brake, policy,
323
- * failure-safe, supersede).
324
- */
325
- reviewerOutcome?: ReviewOutcome;
326
- /**
327
- * How an internal escalate was disposed. Present only when the logical result
328
- * was escalate (or a gate converted allow→escalate) and enforcement chose
329
- * manual or deny. Absent for explicit deny, allow, and manual-superseded.
330
- */
331
- escalationDisposition?: EscalationDisposition;
332
- /** The model that produced the final reviewer decision. */
333
- reviewerModel?: string;
334
- /** Present when a System One result was handed to a reasoning reviewer. */
335
- reviewerEscalatedFrom?: {
336
- model: string;
337
- reason: string;
338
- };
339
- /** Jev's scores whenever it returned a parsed decision, including when a
340
- * reasoning reviewer made the final call. */
341
- systemOne?: SystemOneScores;
342
- /** Per-phase timings. Absent on legacy v1 records and on deterministic paths
343
- * that never reach that phase. */
344
- timings?: {
345
- contextMs?: number;
346
- enrichmentMs?: number;
347
- reviewerMs?: number;
348
- replyMs?: number;
349
- };
350
- /** Non-fatal warnings accumulated during evidence collection/analysis. */
351
- warnings?: string[];
352
- reviewerSessionID?: string;
353
- /** Content identity and inspection mode only; never script text or local path. */
354
- verifiedScript?: {
355
- sha256: string;
356
- status: "full" | "reused" | "unavailable";
357
- bytes?: number;
358
- };
359
- /** Root session of the request's ancestry (additive; absent when lineage was
360
- * unavailable). */
361
- rootSessionID?: string;
362
- /** Overall evidence completeness for the request (additive). */
363
- evidenceCompleteness?: string;
364
- /** Resolved actor snapshot for audit (additive). Uses identityCompleteness
365
- * (not the decision's numeric confidence) to avoid field ambiguity; v2 also
366
- * carries identitySource + confidence. */
367
- actor?: {
368
- name?: string;
369
- mode?: string;
370
- profile: ActorProfile;
371
- identityCompleteness: "complete" | "partial" | "unknown";
372
- /** How the agent identity was established (tool-message, session-api,
373
- * unavailable, …). Absent on legacy v1 records. */
374
- identitySource?: string;
375
- /** Reliability of the identity claim. Absent on legacy v1 records. */
376
- confidence?: EvidenceConfidence;
377
- delegationDepth?: number;
378
- };
379
- ssh?: Array<{
380
- destination: string;
381
- port?: string;
382
- remoteCommandSha256?: string;
383
- stdinSource?: string;
384
- stdinStatus?: string;
385
- stdinReason?: string;
386
- }>;
387
- /** Additive capability snapshot for audit (observe-only). */
388
- capability?: {
389
- actionClass: string;
390
- summary: string;
391
- parserCompleteness: string;
392
- executesCode?: boolean;
393
- createsAdHocCode?: boolean;
394
- invokesPackageLifecycleScripts?: boolean;
395
- writeEffects?: {
396
- temporaryWrite?: boolean;
397
- workspaceWrite?: boolean;
398
- externalWrite?: boolean;
399
- deletion?: boolean;
400
- };
401
- networkObserved?: boolean;
402
- credentialRead?: boolean;
403
- privilegeEscalation?: boolean;
404
- persistence?: boolean;
405
- remoteEnabled?: boolean;
406
- gitMutation?: boolean;
407
- };
408
- /** Additive policy trace for audit (observe-only). */
409
- policyTrace?: {
410
- effectivePolicyHash: string;
411
- matchedRules: Array<{
412
- id: string;
413
- source: string;
414
- effect: string;
415
- reason: string;
416
- }>;
417
- finalRoute: string;
418
- mode: string;
419
- };
420
- /** Additive snapshot of the ask decisions surfaced to the reviewer prompt
421
- * (observe-only; capped to the most recent few). */
422
- askDecisions?: Array<{
423
- at: number;
424
- question: string;
425
- answer: string;
426
- }>;
427
- }
428
- declare const SYSTEM_ONE_BASES: readonly ["authorized_routine", "authorized_reversible_change", "insufficient_authorization", "scope_mismatch", "insufficient_evidence", "destructive_effect", "credential_or_private_data", "security_or_privilege_change", "external_or_remote_effect", "trusted_policy_restriction", "conflicting_evidence"];
429
- type SystemOnePrimaryBasis = (typeof SYSTEM_ONE_BASES)[number];
430
- interface SystemOneChoiceScore<T extends string> {
431
- choice: T;
432
- confidence: number;
433
- }
434
- /** Probability (0-1) that each safety question is true. */
435
- interface SystemOneSignals {
436
- materialAuthorization: number;
437
- withinIntentScope: number;
438
- unauthorizedDataLoss: number;
439
- untrustedSensitiveDisclosure: number;
440
- excessiveCredentialAccess: number;
441
- unauthorizedSecurityChange: number;
442
- unauthorizedExternalMutation: number;
443
- essentialEvidenceMissing: number;
444
- absolutePolicyDeny: number;
445
- }
446
- /**
447
- * Jev's own answer, kept apart from the final decision because a reasoning
448
- * reviewer may replace it. Numbers, enum choices, fixed contradiction strings,
449
- * and the provider-reported model ID only; never evidence text.
450
- */
451
- interface SystemOneScores {
452
- /** Versioned model ID the provider reported as having answered. */
453
- returnedModel: string;
454
- outcome: SystemOneChoiceScore<ReviewOutcome> & {
455
- probabilities: Record<ReviewOutcome, number>;
456
- };
457
- supporting: {
458
- riskLevel: SystemOneChoiceScore<RiskLevel>;
459
- userAuthorization: SystemOneChoiceScore<UserAuthorization>;
460
- scopeAlignment: SystemOneChoiceScore<ScopeAlignment>;
461
- evidenceCompleteness: SystemOneChoiceScore<EvidenceSufficiency>;
462
- primaryBasis: SystemOneChoiceScore<SystemOnePrimaryBasis>;
463
- };
464
- signals: SystemOneSignals;
465
- /** Consistency checks that failed; any one marks an allow or deny difficult. */
466
- contradictions: string[];
467
- reasoningRecommended: boolean;
439
+ request: PermissionRequest;
440
+ directory: string;
441
+ worktree: string;
442
+ transcript: string;
443
+ intentHistory: string;
444
+ enrichment: string;
445
+ verifiedScript?: VerifiedScriptEvidence;
446
+ sshAudit: NonNullable<ReviewAuditRecord["ssh"]>;
447
+ preflightDenial?: string;
448
+ /** Agent-aware context (actor, lineage, intent). Observe-only: flows into the
449
+ * reviewer prompt and audit as evidence, never into enforcement decisions.
450
+ * Optional so older callers/tests still compile. */
451
+ actor?: ActorContext;
452
+ lineage?: SessionLineage;
453
+ intent?: IntentContext;
454
+ evidenceCompleteness?: EvidenceCompleteness;
455
+ /** Structured capability facts derived from the bash command. Observe-only:
456
+ * feeds the reviewer prompt and audit, never enforcement. */
457
+ capability?: CapabilityAssessment;
458
+ /** The policy trace produced for this request, surfaced to the reviewer prompt
459
+ * as EFFECTIVE_POLICY_SUMMARY and to audit. Observe-only. */
460
+ policyTrace?: PolicyTrace;
461
+ /** Per-phase timing captured during evidence assembly (context/enrichment).
462
+ * The reviewer and reply phases are timed in the coordinator. */
463
+ timings?: {
464
+ contextMs?: number;
465
+ enrichmentMs?: number;
466
+ reviewerMs?: number;
467
+ replyMs?: number;
468
+ };
469
+ /** False when a material part of the action under review (e.g. an elided
470
+ * command segment) never reached the rendered evidence. Blocking: the
471
+ * coordinator must not auto-approve an action the reviewer could not see
472
+ * in full, whatever confidence the model reports. */
473
+ actionEvidenceComplete?: boolean;
474
+ /** The parsed command reused across evidence providers. */
475
+ parsedCommand?: ParsedCommand;
476
+ /** Operational purpose of the pending action (evidence, never authorization). */
477
+ actionPurpose?: ActionPurpose;
478
+ /** User answers to agent ask dialogs in this session or its ancestors,
479
+ * captured live from question events. Observe-only: flows into the reviewer
480
+ * prompt (USER_ASK_DECISIONS) and audit, never into enforcement. */
481
+ askDecisions?: AskDecision[];
468
482
  }
469
483
  interface ApprovedAnnotation {
470
- requestID: string;
471
- sessionID: string;
472
- decision: ReviewDecision;
484
+ requestID: string;
485
+ sessionID: string;
486
+ decision: ReviewDecision;
487
+ }
488
+ /** Why a System One (Jev) result was handed to the reasoning reviewer. */
489
+ type HandoffTrigger = "jev-escalate" | "jev-uncertain-allow" | "jev-gate" | "jev-invalid" | "jev-failure" | "jev-uncertain-deny";
490
+ /** The primary model, routing reason and hand-off trigger of a review a
491
+ * second reviewer decided. */
492
+ interface EscalatedFrom {
493
+ model: string;
494
+ reason: string;
495
+ trigger?: HandoffTrigger;
473
496
  }
497
+ /** How an escalation that left the System One backend was reached. */
498
+ type ManualResolution = "reviewer" | "reasoning-escalated" | "reasoning-unavailable" | "budget-exhausted";
474
499
  interface ReviewExecutionResult {
475
- kind: "allow" | "deny" | "escalate";
476
- decision?: ReviewDecision;
477
- reason: string;
478
- reviewSessionID?: string;
479
- /** Which layer produced this result; threaded into the audit record. */
480
- decisionSource?: DecisionSource;
481
- /** Actual model that produced the final reviewer decision. */
482
- reviewerModel?: string;
483
- /** Primary model and routing reason when a second reviewer was used. */
484
- reviewerEscalatedFrom?: {
485
- model: string;
486
- reason: string;
487
- };
488
- /** Jev's scores whenever it returned a parsed decision. */
489
- systemOne?: SystemOneScores;
490
- /**
491
- * Structured outcome from the reviewer LLM before gates/disposition.
492
- * Absent when no valid structured decision was produced.
493
- */
494
- reviewerOutcome?: ReviewOutcome;
495
- /**
496
- * How an internal escalate was disposed at the enforcement boundary.
497
- * Absent when the result was never an escalate (explicit allow/deny) or when
498
- * the request was already answered manually (`manual-superseded`).
499
- */
500
- escalationDisposition?: EscalationDisposition;
500
+ kind: "allow" | "deny" | "escalate";
501
+ decision?: ReviewDecision;
502
+ reason: string;
503
+ reviewSessionID?: string;
504
+ /** Which layer produced this result; threaded into the audit record. */
505
+ decisionSource?: DecisionSource;
506
+ /** Actual model that produced the final reviewer decision. */
507
+ reviewerModel?: string;
508
+ /** Primary model, routing reason and hand-off trigger when a second
509
+ * reviewer was used. */
510
+ reviewerEscalatedFrom?: EscalatedFrom;
511
+ /** Jev's scores whenever it returned a parsed decision. */
512
+ systemOne?: SystemOneScores;
513
+ /**
514
+ * Structured outcome from the reviewer LLM before gates/disposition.
515
+ * Absent when no valid structured decision was produced.
516
+ */
517
+ reviewerOutcome?: ReviewOutcome;
518
+ /**
519
+ * How an internal escalate was disposed at the enforcement boundary.
520
+ * Absent when the result was never an escalate (explicit allow/deny) or when
521
+ * the request was already answered manually (`manual-superseded`).
522
+ */
523
+ escalationDisposition?: EscalationDisposition;
524
+ /** Set only by the System One backend, on escalations; kept when a
525
+ * disposition turns one into a deny. */
526
+ resolution?: ManualResolution;
501
527
  }
528
+ /** Generic policy templates, NOT automatic trust levels. */
529
+ type ActorProfile = "read-only" | "validation" | "workspace" | "operator" | "reviewer" | "unknown";
530
+ /** High-level classification of what the action does. */
531
+ type CapabilityActionClass = "read-only" | "workspace-write" | "temporary-write" | "external-write" | "destruction" | "code-execution" | "package-management" | "git-mutation" | "network" | "remote-operation" | "service-management" | "persistence" | "privilege-escalation" | "unknown";
532
+ //#endregion
533
+ //#region src/actor-context-types.d.ts
502
534
  /** Reliability of a derived fact. */
503
535
  type EvidenceConfidence = "confirmed" | "high" | "medium" | "low" | "unknown";
504
536
  /** Every non-trivial derived fact carries provenance so the LLM and audit can
505
537
  * weigh claims by how reliably they were established. */
506
538
  interface Provenanced<T> {
507
- value: T;
508
- source: "permission-event" | "tool-message" | "session-api" | "parent-session" | "global-config" | "project-config" | "effective-permissions" | "static-analysis" | "heuristic" | "unavailable";
509
- confidence: EvidenceConfidence;
510
- notes?: string[];
539
+ value: T;
540
+ source: "permission-event" | "tool-message" | "session-api" | "parent-session" | "global-config" | "project-config" | "effective-permissions" | "static-analysis" | "heuristic" | "unavailable";
541
+ confidence: EvidenceConfidence;
542
+ notes?: string[];
511
543
  }
512
- /** Generic policy templates, NOT automatic trust levels. */
513
- type ActorProfile = "read-only" | "validation" | "workspace" | "operator" | "reviewer" | "unknown";
514
544
  /** Normalized effective-permission summary when the SDK exposes it.
515
545
  * The v1 SDK does not expose effective rules, so this stays `undefined`. */
516
546
  interface EffectivePermissionSummary {
517
- edit: "allow" | "ask" | "deny" | "mixed" | "unknown";
518
- bash: "allow" | "ask" | "deny" | "mixed" | "unknown";
519
- task: "allow" | "ask" | "deny" | "mixed" | "unknown";
520
- externalDirectory: "allow" | "ask" | "deny" | "mixed" | "unknown";
521
- source: "session" | "agent-config" | "derived" | "unknown";
547
+ edit: "allow" | "ask" | "deny" | "mixed" | "unknown";
548
+ bash: "allow" | "ask" | "deny" | "mixed" | "unknown";
549
+ task: "allow" | "ask" | "deny" | "mixed" | "unknown";
550
+ externalDirectory: "allow" | "ask" | "deny" | "mixed" | "unknown";
551
+ source: "session" | "agent-config" | "derived" | "unknown";
522
552
  }
523
553
  /** Who is requesting the permission. */
524
554
  interface ActorContext {
525
- agentName: Provenanced<string | undefined>;
526
- mode: Provenanced<string | undefined>;
527
- profile: Provenanced<ActorProfile>;
528
- sessionID: string;
529
- parentSessionID: Provenanced<string | undefined>;
530
- rootSessionID: Provenanced<string>;
531
- delegationDepth: Provenanced<number>;
532
- effectivePermissions?: EffectivePermissionSummary;
533
- identityCompleteness: "complete" | "partial" | "unknown";
555
+ agentName: Provenanced<string | undefined>;
556
+ mode: Provenanced<string | undefined>;
557
+ profile: Provenanced<ActorProfile>;
558
+ sessionID: string;
559
+ parentSessionID: Provenanced<string | undefined>;
560
+ rootSessionID: Provenanced<string>;
561
+ delegationDepth: Provenanced<number>;
562
+ effectivePermissions?: EffectivePermissionSummary;
563
+ identityCompleteness: "complete" | "partial" | "unknown";
534
564
  }
535
565
  /** A node in the session ancestry chain. */
536
566
  interface SessionNode {
537
- sessionID: string;
538
- parentID?: string;
539
- title?: string;
540
- version?: string;
541
- actorName?: string;
542
- mode?: string;
543
- createdAt?: number;
567
+ sessionID: string;
568
+ parentID?: string;
569
+ title?: string;
570
+ version?: string;
571
+ actorName?: string;
572
+ mode?: string;
573
+ createdAt?: number;
544
574
  }
545
575
  /** The resolved session ancestry with failure modes made explicit. */
546
576
  interface SessionLineage {
547
- origin?: "human-root" | "delegated" | "unknown";
548
- nodes: SessionNode[];
549
- rootSessionID: string;
550
- depth: number;
551
- cycleDetected: boolean;
552
- truncated: boolean;
553
- missingParents: string[];
577
+ origin?: "human-root" | "delegated" | "unknown";
578
+ nodes: SessionNode[];
579
+ rootSessionID: string;
580
+ depth: number;
581
+ cycleDetected: boolean;
582
+ truncated: boolean;
583
+ missingParents: string[];
554
584
  }
555
585
  /** A single authorization/intent statement. */
556
586
  interface IntentBlock {
557
- sessionID: string;
558
- messageID: string;
559
- actor: "user" | "assistant" | "system" | "unknown";
560
- text: string;
561
- synthetic: boolean;
562
- createdAt?: number;
563
- provenance: Provenanced<"intent">;
587
+ sessionID: string;
588
+ messageID: string;
589
+ actor: "user" | "assistant" | "system" | "unknown";
590
+ text: string;
591
+ synthetic: boolean;
592
+ createdAt?: number;
593
+ provenance: Provenanced<"intent">;
564
594
  }
565
595
  /** One user decision on an agent-initiated ask dialog (question tool). The
566
596
  * question text is agent-generated and untrusted; only the answer is a user
567
597
  * authorization signal, scoped to the subject and time of the ask. */
568
598
  interface AskDecision {
569
- /** Epoch ms when the reply (or dismissal) was observed. */
570
- at: number;
571
- /** What the agent asked, already redacted and truncated. */
572
- question: string;
573
- /** The option labels the user selected, or a dismissal marker. */
574
- answer: string;
599
+ /** Epoch ms when the reply (or dismissal) was observed. */
600
+ at: number;
601
+ /** What the agent asked, already redacted and truncated. */
602
+ question: string;
603
+ /** The option labels the user selected, or a dismissal marker. */
604
+ answer: string;
575
605
  }
576
606
  /** Direct user intent kept separate from delegated task. */
577
607
  interface IntentContext {
578
- directUserIntent: IntentBlock[];
579
- delegatedTask: IntentBlock[];
580
- localSessionIntent: IntentBlock[];
581
- conflictingInstructions: string[];
582
- latestExplicitAuthorization?: IntentBlock;
583
- completeness: "complete" | "partial" | "insufficient";
608
+ directUserIntent: IntentBlock[];
609
+ delegatedTask: IntentBlock[];
610
+ localSessionIntent: IntentBlock[];
611
+ conflictingInstructions: string[];
612
+ latestExplicitAuthorization?: IntentBlock;
613
+ completeness: "complete" | "partial" | "insufficient";
584
614
  }
585
615
  /** Meta-summary of what evidence was available. */
586
616
  interface EvidenceCompleteness {
587
- permission: boolean;
588
- actor: boolean;
589
- lineage: boolean;
590
- directUserIntent: boolean;
591
- delegatedTask: boolean;
592
- /** Whether a non-unavailable ACTION_PURPOSE was recovered. */
593
- purpose: boolean;
594
- capability: boolean;
595
- repositoryState: boolean;
596
- referencedCode: boolean;
597
- reasons: string[];
598
- overall: "sufficient" | "partial" | "insufficient";
617
+ permission: boolean;
618
+ actor: boolean;
619
+ lineage: boolean;
620
+ directUserIntent: boolean;
621
+ delegatedTask: boolean;
622
+ /** Whether a non-unavailable ACTION_PURPOSE was recovered. */
623
+ purpose: boolean;
624
+ capability: boolean;
625
+ repositoryState: boolean;
626
+ referencedCode: boolean;
627
+ reasons: string[];
628
+ overall: "sufficient" | "partial" | "insufficient";
599
629
  }
600
630
  /**
601
631
  * Operational purpose of the pending action — what the agent appears to be
@@ -603,129 +633,183 @@ interface EvidenceCompleteness {
603
633
  * user authorization by itself.
604
634
  */
605
635
  interface ActionPurpose {
606
- text?: string;
607
- source: "agent-context" | "intent-derived" | "unavailable";
608
- confidence: EvidenceConfidence;
609
- }
610
- /** How completely the command could be statically analyzed. */
611
- type ParserCompleteness =
612
- /** Fully parsed: no variables, globs, substitutions, or heredoc bodies. */
613
- "complete-for-supported-form"
614
- /** Some constructs could not be resolved (variables, partial heredoc). */
615
- | "partial"
616
- /** Heavy dynamic constructs (command substitution, eval, dynamic heredoc). */
617
- | "opaque";
618
- /** A redirection extracted from a parsed command segment. */
619
- interface Redirection {
620
- /** `>` `>>` `<` `2>` `&>` etc. */
621
- operator: string;
622
- /** Target path (file descriptor targets normalized to a path when possible). */
623
- target: string;
624
- /** Whether the target was quoted in the source (affects literal-ness). */
625
- quoted: boolean;
626
- }
627
- /** A heredoc extracted before lexing so its body never reaches the lexer/brake. */
628
- interface HeredocRecord {
629
- /** The literal delimiter token as it appeared (`EOF`, `END`, …). */
630
- delimiter: string;
631
- /** `<<` (expansion on) or `<<-` (tabs stripped) — normalized form. */
632
- operator: string;
633
- /** Whether the delimiter was quoted, disabling expansion (`<<'EOF'`). */
634
- expansionDisabled: boolean;
635
- /** Bounded + redacted body (truncated to a safe length). */
636
- bodyBounded: string;
637
- /** SHA-256 of the full, unredacted body (stable identity without leaking it). */
638
- bodySha256: string;
639
- /** Whether the body was truncated for storage. */
640
- truncated: boolean;
641
- /** Output path associated with the heredoc when a `> path` precedes it. */
642
- outputTarget?: string;
643
- /** Whether the body is dynamically constructed (unresolvable expansion). */
644
- dynamic: boolean;
645
- }
646
- /** A command parsed into a reusable structure. Wraps the existing lexer output
647
- * plus pre-extracted redirections and heredocs. */
648
- interface ParsedCommand {
649
- /** The command after heredoc bodies were replaced with placeholders. */
650
- sanitizedCommand: string;
651
- /** Lexed segments of the sanitized command. */
652
- segments: ShellSegment[];
653
- /** Effective commands (wrappers peeled) per segment. */
654
- effective: ShellToken[][];
655
- /** Redirections grouped by segment index. */
656
- redirections: Redirection[][];
657
- /** Heredocs extracted before lexing. */
658
- heredocs: HeredocRecord[];
659
- /** Whether the original command contained any dynamic constructs. */
660
- hasDynamicConstructs: boolean;
661
- /** True when the lexer's depth or expansion budget stopped command-string
662
- * resolution early; `effective` is then a prefix of the real structure and
663
- * deterministic facts do not cover the whole command. */
664
- analysisTruncated: boolean;
636
+ text?: string;
637
+ source: "agent-context" | "intent-derived" | "unavailable";
638
+ confidence: EvidenceConfidence;
665
639
  }
666
- /** High-level classification of what the action does. */
667
- type CapabilityActionClass = "read-only" | "workspace-write" | "temporary-write" | "external-write" | "destruction" | "code-execution" | "package-management" | "git-mutation" | "network" | "remote-operation" | "service-management" | "persistence" | "privilege-escalation" | "unknown";
668
- /** What the action can do, what it appears to do, and analysis confidence. */
669
- interface CapabilityAssessment {
670
- /** Best single-label summary of the dominant capability. */
671
- actionClass: Provenanced<CapabilityActionClass>;
672
- /** Human-readable summary of the detected surface. */
640
+ //#endregion
641
+ //#region src/audit-record.d.ts
642
+ /** Which layer produced the final decision for a request. Threaded into the
643
+ * audit record so reports can split outcomes by source. */
644
+ type DecisionSource = "emergency-brake" | "deterministic-policy" | "llm-reviewer" | "system-one-reviewer" | "manual-superseded" | "failure-safe";
645
+ interface ReviewAuditRecord {
646
+ /**
647
+ * Audit schema version. Present on every record; readers default a missing
648
+ * field to `1` (additive — old records are still valid).
649
+ * Bump only on a breaking change to the record shape.
650
+ */
651
+ schemaVersion?: number;
652
+ reviewID?: string;
653
+ hostRequestID?: string;
654
+ hostGeneration?: "v1" | "v2";
655
+ hostVersion?: string;
656
+ generation?: string;
657
+ nativeAction?: string;
658
+ directory?: string;
659
+ application?: "evaluation-returned" | "reply-accepted" | "human-pending" | "superseded" | "cancelled" | "unknown";
660
+ pluginVersion?: string;
661
+ effectiveConfigHash?: string;
662
+ actionFingerprint?: string;
663
+ /** Version of the structured-decision schema the reviewer was asked to emit. */
664
+ decisionSchemaVersion?: number;
665
+ /** Version of the reviewer system prompt used for this decision. */
666
+ promptVersion?: string;
667
+ /** Which layer produced the outcome (brake, policy, reviewer, supersede,
668
+ * failure-safe). Absent on legacy v1 records. */
669
+ decisionSource?: DecisionSource;
670
+ timestamp: string;
671
+ durationMs: number;
672
+ requestID: string;
673
+ sessionID: string;
674
+ permission: string;
675
+ /** Stable hash of the canonical request (permission, patterns, metadata,
676
+ * tool) for cross-record correlation. Absent on legacy v1 records. */
677
+ actionHash?: string;
678
+ outcome: ReviewExecutionResult["kind"];
679
+ reason: string;
680
+ riskLevel?: RiskLevel;
681
+ userAuthorization?: UserAuthorization;
682
+ /** How well the action aligned with the recovered intent (from the reviewer
683
+ * decision). Absent when no reviewer decision was reached. */
684
+ scopeAlignment?: ScopeAlignment;
685
+ confidence?: number;
686
+ /**
687
+ * Structured outcome emitted by the reviewer LLM before gates/disposition.
688
+ * Absent when no valid structured decision was produced (brake, policy,
689
+ * failure-safe, supersede).
690
+ */
691
+ reviewerOutcome?: ReviewOutcome;
692
+ /**
693
+ * How an internal escalate was disposed. Present only when the logical result
694
+ * was escalate (or a gate converted allow→escalate) and enforcement chose
695
+ * manual or deny. Absent for explicit deny, allow, and manual-superseded.
696
+ */
697
+ escalationDisposition?: EscalationDisposition;
698
+ /** The model that produced the final reviewer decision. */
699
+ reviewerModel?: string;
700
+ /** Present when a System One result was handed to a reasoning reviewer;
701
+ * `trigger` says why. */
702
+ reviewerEscalatedFrom?: EscalatedFrom;
703
+ /** How an escalation from the System One backend was reached. */
704
+ resolution?: ManualResolution;
705
+ /** Warnings on the resolved config (inert or invalid settings); present
706
+ * only when there are any. Not the evidence `warnings` below. */
707
+ configWarnings?: string[];
708
+ /** Jev's scores whenever it returned a parsed decision, including when a
709
+ * reasoning reviewer made the final call. */
710
+ systemOne?: SystemOneScores;
711
+ /** Per-phase timings. Absent on legacy v1 records and on deterministic paths
712
+ * that never reach that phase. */
713
+ timings?: {
714
+ contextMs?: number;
715
+ enrichmentMs?: number;
716
+ reviewerMs?: number;
717
+ replyMs?: number;
718
+ };
719
+ /** Non-fatal warnings accumulated during evidence collection/analysis. */
720
+ warnings?: string[];
721
+ reviewerSessionID?: string;
722
+ /** Content identity and inspection mode only; never script text or local path. */
723
+ verifiedScript?: {
724
+ sha256: string;
725
+ status: "full" | "reused" | "unavailable";
726
+ bytes?: number;
727
+ };
728
+ /** Root session of the request's ancestry (additive; absent when lineage was
729
+ * unavailable). */
730
+ rootSessionID?: string;
731
+ /** Overall evidence completeness for the request (additive). */
732
+ evidenceCompleteness?: string;
733
+ /** Resolved actor snapshot for audit (additive). Uses identityCompleteness
734
+ * (not the decision's numeric confidence) to avoid field ambiguity; v2 also
735
+ * carries identitySource + confidence. */
736
+ actor?: {
737
+ name?: string;
738
+ mode?: string;
739
+ profile: ActorProfile;
740
+ identityCompleteness: "complete" | "partial" | "unknown";
741
+ /** How the agent identity was established (tool-message, session-api,
742
+ * unavailable, …). Absent on legacy v1 records. */
743
+ identitySource?: string;
744
+ /** Reliability of the identity claim. Absent on legacy v1 records. */
745
+ confidence?: EvidenceConfidence;
746
+ delegationDepth?: number;
747
+ };
748
+ ssh?: Array<{
749
+ destination: string;
750
+ port?: string;
751
+ remoteCommandSha256?: string;
752
+ stdinSource?: string;
753
+ stdinStatus?: string;
754
+ stdinReason?: string;
755
+ }>;
756
+ /** Additive capability snapshot for audit (observe-only). */
757
+ capability?: {
758
+ actionClass: string;
673
759
  summary: string;
674
- /** Executes an interpreter or runtime (sh, python, node, bun, …). */
675
- executesCode: Provenanced<boolean | "unknown">;
676
- /** Executes code that lives in the repository (scripts, test files). */
677
- executesRepositoryCode: Provenanced<boolean | "unknown">;
678
- /** Executes ad-hoc code generated by the agent (heredoc/inline). */
679
- createsAdHocCode: Provenanced<boolean | "unknown">;
680
- /** Invokes a known test runner (pytest, jest, bun test, …). */
681
- invokesExistingTestRunner: Provenanced<boolean | "unknown">;
682
- /** Runs a package manager that may execute lifecycle scripts. */
683
- invokesPackageLifecycleScripts: Provenanced<boolean | "unknown">;
684
- /** Reads literal credential material through a known file reader. */
685
- credentialRead: Provenanced<boolean | "unknown">;
686
- /** Detected file-write surface. */
687
- writeEffects: {
688
- temporaryWrite: Provenanced<boolean | "unknown">;
689
- workspaceWrite: Provenanced<boolean | "unknown">;
690
- externalWrite: Provenanced<boolean | "unknown">;
691
- deletion: Provenanced<boolean | "unknown">;
692
- };
693
- /** Detected network surface. */
694
- network: {
695
- observed: Provenanced<boolean | "unknown">;
696
- possible: Provenanced<boolean | "unknown">;
697
- /** Hosts/destinations observed literally in the command. */
698
- destinations: string[];
699
- observedAccess: Provenanced<boolean | "unknown">;
700
- possibleAccess: Provenanced<boolean | "unknown">;
701
- };
702
- /** Detected process side-effects. */
703
- process: {
704
- childProcesses: Provenanced<boolean | "unknown">;
705
- persistence: Provenanced<boolean | "unknown">;
706
- privilegeEscalation: Provenanced<boolean | "unknown">;
707
- };
708
- /** Detected remote-operation surface (ssh, etc.). */
709
- remote: {
710
- enabled: Provenanced<boolean | "unknown">;
711
- mutationHint: Provenanced<boolean | "unknown">;
712
- };
713
- /** Detected git mutation surface. */
714
- git: {
715
- observed: Provenanced<boolean | "unknown">;
716
- possible: Provenanced<boolean | "unknown">;
717
- observedAccess: Provenanced<boolean | "unknown">;
718
- possibleAccess: Provenanced<boolean | "unknown">;
760
+ parserCompleteness: string;
761
+ executesCode?: boolean;
762
+ createsAdHocCode?: boolean;
763
+ invokesPackageLifecycleScripts?: boolean;
764
+ writeEffects?: {
765
+ temporaryWrite?: boolean;
766
+ workspaceWrite?: boolean;
767
+ externalWrite?: boolean;
768
+ deletion?: boolean;
719
769
  };
720
- /** How completely the command could be analyzed. */
721
- parserCompleteness: ParserCompleteness;
722
- /** Free-form warnings about analysis limitations. */
723
- analysisWarnings: string[];
770
+ networkObserved?: boolean;
771
+ credentialRead?: boolean;
772
+ privilegeEscalation?: boolean;
773
+ persistence?: boolean;
774
+ remoteEnabled?: boolean;
775
+ gitMutation?: boolean;
776
+ };
777
+ /** Additive policy trace for audit (observe-only). */
778
+ policyTrace?: {
779
+ effectivePolicyHash: string;
780
+ matchedRules: Array<{
781
+ id: string;
782
+ source: string;
783
+ effect: string;
784
+ reason: string;
785
+ }>;
786
+ finalRoute: string;
787
+ mode: string;
788
+ };
789
+ /** Additive snapshot of the ask decisions surfaced to the reviewer prompt
790
+ * (observe-only; capped to the most recent few). */
791
+ askDecisions?: Array<{
792
+ at: number;
793
+ question: string;
794
+ answer: string;
795
+ }>;
724
796
  }
725
-
797
+ //#endregion
798
+ //#region src/audit.d.ts
799
+ export declare const DEFAULT_AUDIT_PATH = "~/.local/share/opencode/permission-reviewer-audit.jsonl";
800
+ type AuditLogger = (message: string, details?: unknown) => void;
801
+ export declare function createAuditWriter(config: ReviewerConfig, logger?: AuditLogger): ((record: ReviewAuditRecord) => Promise<void>) | undefined;
802
+ //#endregion
803
+ //#region src/config/sources.d.ts
726
804
  /** The host passing an options object does not attest who authored it. */
727
805
  type InlineOptionsTrust = "trusted" | "project" | "unknown";
728
-
806
+ //#endregion
807
+ //#region src/config/loader.d.ts
808
+ interface LoadOptions {
809
+ /** Off for a caller that shows `configWarnings` another way, such as the TUI
810
+ * from server statuses. */
811
+ printConfigWarnings?: boolean;
812
+ }
729
813
  /** Load and merge config from global, project, and inline sources.
730
814
  *
731
815
  * Precedence (lowest to highest): builtin defaults → global → project → inline,
@@ -736,161 +820,99 @@ type InlineOptionsTrust = "trusted" | "project" | "unknown";
736
820
  *
737
821
  * When no global or project files exist (the common case), the result is
738
822
  * byte-identical to calling `resolveConfig(inlineOptions)` directly. */
739
- declare function loadResolvedConfig(inlineOptions: Record<string, unknown> | undefined, directory?: string, inlineTrust?: InlineOptionsTrust): ReviewerConfig;
740
-
741
- type Context = Parameters<Plugin.Plugin["setup"]>[0];
742
- declare function setup(ctx: Context): Promise<() => Promise<void>>;
743
-
744
- /** What the plugin learned about the host client at startup. */
745
- interface OpenCodeCapabilities {
746
- /** A public SDK method to answer a permission request exists. */
747
- publicPermissionReply: boolean;
748
- /** That public method can carry a free-text feedback `message`. */
749
- permissionReplyMessage: boolean;
750
- /** The authenticated raw `_client.post` transport is reachable. */
751
- rawAuthenticatedTransport: boolean;
752
- /** `client.session.get` is available (lineage walking depends on it). */
753
- sessionGet: boolean;
754
- /** Session records expose a `parentID` (lineage traversal). */
755
- sessionParentID: boolean;
756
- /** Assistant messages carry an `agent` field (actor identity). */
757
- assistantAgentMetadata: boolean;
758
- /** Assistant messages carry a `mode` field (actor identity). */
759
- assistantModeMetadata: boolean;
760
- /** Effective permission rules can be resolved per session. */
761
- effectivePermissions: boolean;
762
- /** `client.tui.publish` is available for status broadcasting. */
763
- tuiPublish: boolean;
764
- }
765
-
766
- type ReviewUiPhase = "reviewing" | "approved" | "denied" | "manual" | "unknown";
767
- interface ReviewUiStatus {
768
- version: 1;
769
- requestID: string;
770
- sessionID: string;
771
- phase: ReviewUiPhase;
772
- permission: string;
773
- action: string;
774
- model: string;
775
- variant: string;
776
- emittedAt: number;
777
- timeoutMs: number;
778
- reason?: string;
779
- decision?: ReviewDecision;
780
- /**
781
- * When phase is `denied` and this is `"deny"`, the block came from fail-closed
782
- * escalation disposition rather than an explicit reviewer/policy deny.
783
- */
784
- escalationDisposition?: EscalationDisposition;
785
- /** Resolved actor (absent on the initial "reviewing" phase, before context
786
- * collection completes). */
787
- actorName?: string;
788
- actorProfile?: ActorProfile;
789
- }
790
- declare function permissionAction(request: PermissionRequest): string;
791
- declare function createUiStatus(request: PermissionRequest, phase: ReviewUiPhase, options: {
792
- model: string;
793
- variant: string;
794
- timeoutMs: number;
795
- reason?: string;
796
- decision?: ReviewDecision;
797
- escalationDisposition?: EscalationDisposition;
798
- emittedAt?: number;
799
- actorName?: string;
800
- actorProfile?: ActorProfile;
801
- }): ReviewUiStatus;
802
- declare function encodeUiStatus(status: ReviewUiStatus): string;
803
- declare function decodeUiStatus(command: string): ReviewUiStatus | undefined;
804
-
805
- interface ClientResponse<T> {
806
- data?: T;
807
- error?: unknown;
808
- }
809
- interface OpenCodeClientLike {
810
- session: {
811
- create(options: unknown): Promise<ClientResponse<Record<string, unknown>>>;
812
- messages(options: unknown): Promise<ClientResponse<unknown>>;
813
- prompt(options: unknown): Promise<ClientResponse<Record<string, unknown>>>;
814
- delete?(options: unknown): Promise<ClientResponse<unknown>>;
815
- abort?(options: unknown): Promise<ClientResponse<unknown>>;
816
- /** Fetch session metadata (parentID, title, …). Optional: the actor resolver
817
- * degrades to "lineage unavailable" when the host client does not expose it. */
818
- get?(options: unknown): Promise<ClientResponse<unknown>>;
819
- };
820
- tool: {
821
- ids(options?: unknown): Promise<ClientResponse<string[]>>;
822
- };
823
- /** Host MCP inventory, keyed by server name. The V1 host exposes
824
- * `mcp.status({ query: { directory } })` and returns `{}` for a location
825
- * whose config excludes MCP. Optional so narrow clients still typecheck;
826
- * the reviewer guard fails closed when it is absent. */
827
- mcp?: {
828
- status(options?: unknown): Promise<ClientResponse<Record<string, unknown>>>;
829
- };
830
- }
831
- interface RuntimeContext {
832
- hostVersion?: string;
833
- client: OpenCodeClientLike;
834
- /** What the plugin learned about the host client at startup (probe result).
835
- * Surfaced to diagnostics and available to any future adapter consumer. */
836
- capabilities: OpenCodeCapabilities;
837
- permissionReply(options: unknown): Promise<ClientResponse<unknown>>;
838
- publishUiStatus?(status: ReviewUiStatus): Promise<ClientResponse<unknown>>;
839
- writeAudit?(record: ReviewAuditRecord): Promise<void>;
840
- directory: string;
841
- worktree: string;
842
- /** Where reviewer sessions run when isolation is available: a directory
843
- * without project instructions or project config. Production resolves the
844
- * shared data directory; tests inject a scratch path so they never touch
845
- * the developer's HOME. */
846
- reviewerDirectoryBase?: string;
847
- }
848
-
849
- interface SshAuditSummary {
850
- destination: string;
851
- port?: string;
852
- remoteCommandSha256?: string;
853
- stdinSource?: string;
854
- stdinStatus?: string;
855
- stdinReason?: string;
856
- }
857
- interface SshEnrichmentResult {
858
- text: string;
859
- audit: SshAuditSummary[];
860
- preflightDenial?: string;
823
+ export declare function loadResolvedConfig(inlineOptions: Record<string, unknown> | undefined, directory?: string, inlineTrust?: InlineOptionsTrust, { printConfigWarnings }?: LoadOptions): ReviewerConfig;
824
+ //#endregion
825
+ //#region src/system-one/backend.d.ts
826
+ /** Jev's hand-off to the reasoning reviewer, on the second "reviewing" status
827
+ * and on the result of a handed-off review. */
828
+ interface HandoffInfo {
829
+ from: string;
830
+ to: string;
831
+ trigger: HandoffTrigger;
832
+ /** Jev's failure ("timeout"), only when `trigger` is `jev-failure`. */
833
+ failureKind?: string;
861
834
  }
862
- declare function enrichSshEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<SshEnrichmentResult>;
863
-
864
- /**
865
- * A single piece of evidence gathered about a permission request. The runtime
866
- * only consumes `text`, `audit`, and `preflightDenial` today; the remaining
867
- * fields give future providers room to surface warnings and cost without
868
- * changing the interface.
869
- */
870
- interface EvidenceFragment {
871
- kind: "ssh" | "local_script" | "git";
872
- text: string;
873
- audit?: SshAuditSummary[];
874
- preflightDenial?: string;
875
- warnings?: string[];
876
- durationMs?: number;
835
+ //#endregion
836
+ //#region src/ui-status-extras.d.ts
837
+ interface StatusExtrasOptions {
838
+ handoff?: HandoffInfo;
839
+ resolution?: ManualResolution;
840
+ decidedBy?: string;
841
+ configWarnings?: readonly string[];
842
+ configDegraded?: readonly string[];
877
843
  }
878
- interface EvidenceProviderInput {
879
- request: PermissionRequest;
880
- directory: string;
881
- worktree: string;
882
- maxChars: number;
844
+ //#endregion
845
+ //#region src/ui-protocol.d.ts
846
+ type ReviewUiPhase = "reviewing" | "approved" | "denied" | "manual" | "unknown";
847
+ /** One command of a shell action as the server split it, for the TUI to fit
848
+ * to its width. Built by `src/ui-action-segments.ts`. */
849
+ interface ActionSegment {
850
+ /** The segment as typed in the command, heredoc bodies left out,
851
+ * whitespace collapsed, at most 200 code points. */
852
+ text: string;
853
+ /** The operator that ends this segment: "|", "||", "&&", ";", "&". */
854
+ separator?: string;
855
+ /** Total body lines of the segment's heredocs, whose bodies are not
856
+ * shown. */
857
+ heredocLines?: number;
883
858
  }
884
- /**
885
- * Enriches a permission request with one category of evidence (SSH analysis,
886
- * local script inspection, Git state, …). Providers run concurrently and their
887
- * fragments are assembled into a single review envelope.
888
- */
889
- interface EvidenceProvider {
890
- readonly id: string;
891
- collect(input: EvidenceProviderInput): Promise<EvidenceFragment>;
859
+ interface ReviewUiStatus {
860
+ version: 1;
861
+ requestID: string;
862
+ sessionID: string;
863
+ phase: ReviewUiPhase;
864
+ permission: string;
865
+ action: string;
866
+ model: string;
867
+ variant: string;
868
+ emittedAt: number;
869
+ timeoutMs: number;
870
+ reason?: string;
871
+ decision?: ReviewDecision;
872
+ /**
873
+ * When phase is `denied` and this is `"deny"`, the block came from fail-closed
874
+ * escalation disposition rather than an explicit reviewer/policy deny.
875
+ */
876
+ escalationDisposition?: EscalationDisposition;
877
+ /** Resolved actor (absent on the initial "reviewing" phase, before context
878
+ * collection completes). */
879
+ actorName?: string;
880
+ actorProfile?: ActorProfile;
881
+ /** Jev's hand-off to the reasoning reviewer, on the second "reviewing"
882
+ * status and on the result of a handed-off review. */
883
+ handoff?: HandoffInfo;
884
+ /** How a manual outcome came about; chooses the manual-review toast. */
885
+ resolution?: ManualResolution;
886
+ /** The model that made the decision, on a final status a reviewer model
887
+ * decided; absent on a brake, policy or failure-safe result. */
888
+ decidedBy?: string;
889
+ /** The server's config warnings and degraded-config reasons. V1 carries them
890
+ * on every status; V2 reads them from the `status` RPC. */
891
+ configWarnings?: string[];
892
+ configDegraded?: string[];
893
+ /** The action split at its top-level shell operators. Absent when the
894
+ * server did not segment it or left the segments off to fit the status
895
+ * cap, and from a server that predates segments. */
896
+ actionSegments?: ActionSegment[];
892
897
  }
893
-
898
+ export declare function permissionAction(request: PermissionRequest): string;
899
+ type UiStatusOptions = {
900
+ model: string;
901
+ variant: string;
902
+ timeoutMs: number;
903
+ reason?: string;
904
+ decision?: ReviewDecision;
905
+ escalationDisposition?: EscalationDisposition;
906
+ emittedAt?: number;
907
+ actorName?: string;
908
+ actorProfile?: ActorProfile;
909
+ actionSegments?: ActionSegment[];
910
+ } & StatusExtrasOptions;
911
+ export declare function createUiStatus(request: PermissionRequest, phase: ReviewUiPhase, options: UiStatusOptions): ReviewUiStatus;
912
+ export declare function encodeUiStatus(status: ReviewUiStatus): string;
913
+ export declare function decodeUiStatus(command: string): ReviewUiStatus | undefined;
914
+ //#endregion
915
+ //#region src/context/ask-decisions.d.ts
894
916
  /**
895
917
  * Captures user answers to agent ask dialogs (the `question` tool) from the
896
918
  * OpenCode event stream and exposes them as compact, session-scoped
@@ -917,43 +939,170 @@ interface EvidenceProvider {
917
939
  * as a custom answer must never land in the registry, prompt, or audit.
918
940
  */
919
941
  /** Marker recorded when the user dismisses an ask without answering. */
920
- declare const DISMISSED_ANSWER = "Dismissed by user";
942
+ export declare const DISMISSED_ANSWER = "Dismissed by user";
921
943
  type Logger$1 = (message: string, details?: unknown) => void;
922
944
  /** What the evidence assembler consumes: a bounded, lineage-scoped query. */
923
945
  interface AskDecisionSource {
924
- recentFor(sessionIDs: string[], limit?: number): AskDecision[];
946
+ recentFor(sessionIDs: string[], limit?: number): AskDecision[];
947
+ }
948
+ export declare class AskDecisionRegistry implements AskDecisionSource {
949
+ private readonly pending;
950
+ private readonly resolved;
951
+ private readonly log;
952
+ private readonly now;
953
+ constructor(logger?: Logger$1, now?: () => number);
954
+ /**
955
+ * Observe one raw event. Total: never throws; anything malformed or
956
+ * unrelated is dropped silently. Must be called synchronously from the event
957
+ * hook so registry mutations are visible to reviews started later.
958
+ */
959
+ observe(event: unknown): void;
960
+ /**
961
+ * Decisions visible to a review running in `sessionIDs` (the requesting
962
+ * session plus its resolved ancestors), oldest first, bounded to the most
963
+ * recent `limit`. Sibling and unrelated sessions are never visible.
964
+ */
965
+ recentFor(sessionIDs: string[], limit?: number): AskDecision[];
966
+ /** Observed-but-unresolved asks (diagnostics only). */
967
+ pendingCount(): number;
968
+ /** Resolved decisions retained (diagnostics only). */
969
+ resolvedCount(): number;
970
+ private onAsked;
971
+ private onReplied;
972
+ private onRejected;
973
+ private store;
974
+ }
975
+ //#endregion
976
+ //#region src/opencode/v2/server-state.d.ts
977
+ type Context = Parameters<Plugin$1.Plugin["setup"]>[0];
978
+ //#endregion
979
+ //#region src/opencode/v2/server.d.ts
980
+ declare function setup(ctx: Context): Promise<() => Promise<void>>;
981
+ //#endregion
982
+ //#region src/config.d.ts
983
+ export declare function resolveConfig(options: Record<string, unknown> | undefined): ReviewerConfig;
984
+ //#endregion
985
+ //#region src/ssh-evidence.d.ts
986
+ interface SshAuditSummary {
987
+ destination: string;
988
+ port?: string;
989
+ remoteCommandSha256?: string;
990
+ stdinSource?: string;
991
+ stdinStatus?: string;
992
+ stdinReason?: string;
993
+ }
994
+ interface SshEnrichmentResult {
995
+ text: string;
996
+ audit: SshAuditSummary[];
997
+ preflightDenial?: string;
998
+ }
999
+ export declare function enrichSshEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<SshEnrichmentResult>;
1000
+ //#endregion
1001
+ //#region src/evidence/provider.d.ts
1002
+ /**
1003
+ * A single piece of evidence gathered about a permission request. The runtime
1004
+ * only consumes `text`, `audit`, and `preflightDenial` today; the remaining
1005
+ * fields give future providers room to surface warnings and cost without
1006
+ * changing the interface.
1007
+ */
1008
+ interface EvidenceFragment {
1009
+ kind: "ssh" | "local_script" | "git";
1010
+ text: string;
1011
+ audit?: SshAuditSummary[];
1012
+ preflightDenial?: string;
1013
+ warnings?: string[];
1014
+ durationMs?: number;
1015
+ }
1016
+ interface EvidenceScope {
1017
+ directory: string;
1018
+ worktree: string;
1019
+ maxChars: number;
1020
+ }
1021
+ interface EvidenceProviderInput extends EvidenceScope {
1022
+ request: PermissionRequest;
1023
+ }
1024
+ /**
1025
+ * Enriches a permission request with one category of evidence (SSH analysis,
1026
+ * local script inspection, Git state, …). Providers run concurrently and their
1027
+ * fragments are assembled into a single review envelope.
1028
+ */
1029
+ interface EvidenceProvider {
1030
+ readonly id: string;
1031
+ collect(input: EvidenceProviderInput): Promise<EvidenceFragment>;
1032
+ }
1033
+ //#endregion
1034
+ //#region src/opencode/adapter.d.ts
1035
+ /** What the plugin learned about the host client at startup. */
1036
+ interface OpenCodeCapabilities {
1037
+ /** A public SDK method to answer a permission request exists. */
1038
+ publicPermissionReply: boolean;
1039
+ /** That public method can carry a free-text feedback `message`. */
1040
+ permissionReplyMessage: boolean;
1041
+ /** The authenticated raw `_client.post` transport is reachable. */
1042
+ rawAuthenticatedTransport: boolean;
1043
+ /** `client.session.get` is available (lineage walking depends on it). */
1044
+ sessionGet: boolean;
1045
+ /** Session records expose a `parentID` (lineage traversal). */
1046
+ sessionParentID: boolean;
1047
+ /** Assistant messages carry an `agent` field (actor identity). */
1048
+ assistantAgentMetadata: boolean;
1049
+ /** Assistant messages carry a `mode` field (actor identity). */
1050
+ assistantModeMetadata: boolean;
1051
+ /** Effective permission rules can be resolved per session. */
1052
+ effectivePermissions: boolean;
1053
+ /** `client.tui.publish` is available for status broadcasting. */
1054
+ tuiPublish: boolean;
1055
+ }
1056
+ //#endregion
1057
+ //#region src/opencode/types.d.ts
1058
+ interface ClientResponse<T> {
1059
+ data?: T;
1060
+ error?: unknown;
925
1061
  }
926
- declare class AskDecisionRegistry implements AskDecisionSource {
927
- private readonly pending;
928
- private readonly resolved;
929
- private readonly log;
930
- private readonly now;
931
- constructor(logger?: Logger$1, now?: () => number);
932
- /**
933
- * Observe one raw event. Total: never throws; anything malformed or
934
- * unrelated is dropped silently. Must be called synchronously from the event
935
- * hook so registry mutations are visible to reviews started later.
936
- */
937
- observe(event: unknown): void;
938
- /**
939
- * Decisions visible to a review running in `sessionIDs` (the requesting
940
- * session plus its resolved ancestors), oldest first, bounded to the most
941
- * recent `limit`. Sibling and unrelated sessions are never visible.
942
- */
943
- recentFor(sessionIDs: string[], limit?: number): AskDecision[];
944
- /** Observed-but-unresolved asks (diagnostics only). */
945
- pendingCount(): number;
946
- /** Resolved decisions retained (diagnostics only). */
947
- resolvedCount(): number;
948
- private takePending;
949
- private store;
950
- /** Enforce the pending cap and TTL. Map iteration order is insertion
951
- * order, so `keys().next()` is the oldest entry. */
952
- private prunePending;
953
- private pruneExpired;
1062
+ interface OpenCodeClientLike {
1063
+ session: {
1064
+ create(options: unknown): Promise<ClientResponse<Record<string, unknown>>>;
1065
+ messages(options: unknown): Promise<ClientResponse<unknown>>;
1066
+ prompt(options: unknown): Promise<ClientResponse<Record<string, unknown>>>;
1067
+ delete?(options: unknown): Promise<ClientResponse<unknown>>;
1068
+ abort?(options: unknown): Promise<ClientResponse<unknown>>;
1069
+ /** Fetch session metadata (parentID, title, …). Optional: the actor resolver
1070
+ * degrades to "lineage unavailable" when the host client does not expose it. */
1071
+ get?(options: unknown): Promise<ClientResponse<unknown>>;
1072
+ };
1073
+ tool: {
1074
+ ids(options?: unknown): Promise<ClientResponse<string[]>>;
1075
+ };
1076
+ /** Host MCP inventory, keyed by server name. The V1 host exposes
1077
+ * `mcp.status({ query: { directory } })` and returns `{}` for a location
1078
+ * whose config excludes MCP. Optional so narrow clients still typecheck;
1079
+ * the reviewer guard fails closed when it is absent. */
1080
+ mcp?: {
1081
+ status(options?: unknown): Promise<ClientResponse<Record<string, unknown>>>;
1082
+ };
954
1083
  }
955
-
1084
+ interface RuntimeContext {
1085
+ hostVersion?: string;
1086
+ client: OpenCodeClientLike;
1087
+ /** What the plugin learned about the host client at startup (probe result).
1088
+ * Surfaced to diagnostics and available to any future adapter consumer. */
1089
+ capabilities: OpenCodeCapabilities;
1090
+ permissionReply(options: unknown): Promise<ClientResponse<unknown>>;
1091
+ publishUiStatus?(status: ReviewUiStatus): Promise<ClientResponse<unknown>>;
1092
+ writeAudit?(record: ReviewAuditRecord): Promise<void>;
1093
+ directory: string;
1094
+ worktree: string;
1095
+ /** Where reviewer sessions run when isolation is available: a directory
1096
+ * without project instructions or project config. Production resolves the
1097
+ * shared data directory; tests inject a scratch path so they never touch
1098
+ * the developer's HOME. */
1099
+ reviewerDirectoryBase?: string;
1100
+ }
1101
+ //#endregion
1102
+ //#region src/core/coordinator-state.d.ts
956
1103
  type Logger = (message: string, details?: unknown) => void;
1104
+ //#endregion
1105
+ //#region src/core/review-coordinator.d.ts
957
1106
  /**
958
1107
  * Owns the review lifecycle for permission requests: orchestration, the
959
1108
  * supersede state machine, and the model call. The adapter (transport) and the
@@ -961,144 +1110,92 @@ type Logger = (message: string, details?: unknown) => void;
961
1110
  * races.
962
1111
  */
963
1112
  declare class ReviewCoordinator {
964
- private readonly ctx;
965
- private readonly config;
966
- private readonly generation;
967
- private readonly attempts;
968
- private stopped;
969
- private readonly limiter;
970
- private readonly pending;
971
- private readonly backend;
972
- /**
973
- * Request IDs that a human (or any other reply source) resolved while the
974
- * automatic review was still in flight. The in-flight review must then give
975
- * up silently: no `emit`, no `reply`. OpenCode resolves a request on a
976
- * first-writer basis, so a late programmatic reply returns 404
977
- * PermissionNotFoundError — we treat that the same way.
978
- */
979
- private readonly resolvedManually;
980
- private readonly log;
981
- private readonly providers;
982
- private readonly scriptRegistry;
983
- /** Live ask-decision capture (enrichment-only; undefined when disabled). */
984
- private readonly askDecisions;
985
- /** Bound for metadata SDK calls (session create, tool listing, replies,
986
- * status publishing): a hung call must never leave a review pending
987
- * forever; the reviewer prompt keeps its own full timeout budget. */
988
- private readonly metadataCallTimeoutMs;
989
- constructor(ctx: RuntimeContext, config: ReviewerConfig, logger?: Logger, providers?: EvidenceProvider[], askDecisions?: AskDecisionSource);
990
- pendingCount(): number;
991
- waitForIdle(): Promise<void>;
992
- dispose(): Promise<void>;
993
- handle(request: PermissionRequest): void;
994
- process(request: PermissionRequest): Promise<ReviewExecutionResult>;
995
- private supersedeResult;
996
- private isSuperseded;
997
- /**
998
- * Reject a request with `reject` while honoring supersede. Returns `undefined`
999
- * when the rejection was applied, or the supersede result when the request had
1000
- * already been answered manually (so the caller returns it unchanged).
1001
- */
1002
- private denyAndReply;
1003
- /**
1004
- * Apply a fully disposed result (allow / deny / escalate) to UI + reply.
1005
- * This is the single side-effect boundary after logical disposition.
1006
- */
1007
- private applyDisposition;
1008
- private processRequest;
1009
- handlePermissionReply(event: unknown): void;
1010
- /**
1011
- * @deprecated No-op. Approvals no longer annotate tool results so they do not
1012
- * contaminate the primary agent context. Kept for public API compatibility;
1013
- * the plugin no longer registers a host hook that calls this. Rationale
1014
- * remains in audit, TUI, and debug.
1015
- */
1016
- annotateToolResult(callID: string, output: {
1017
- output?: unknown;
1018
- metadata?: unknown;
1019
- }): void;
1020
- private collectEnvelope;
1021
- private audit;
1022
- private runReviewer;
1023
- private remember;
1024
- /** Fold the reviewer phase's elapsed time into the request's timing record. */
1025
- private recordReviewerMs;
1026
- /**
1027
- * Send a permission reply. Returns `true` on success, `false` when the
1028
- * request was already resolved by another source (human TUI, a duplicate
1029
- * event, etc.) so the caller can treat itself as superseded. Other errors
1030
- * (transport failure, malformed reply) are still thrown.
1031
- */
1032
- private safeReply;
1033
- private emit;
1113
+ private readonly state;
1114
+ private readonly limiter;
1115
+ private readonly pending;
1116
+ constructor(ctx: RuntimeContext, config: ReviewerConfig, logger?: Logger, providers?: EvidenceProvider[], askDecisions?: AskDecisionSource);
1117
+ pendingCount(): number;
1118
+ waitForIdle(): Promise<void>;
1119
+ dispose(): Promise<void>;
1120
+ handle(request: PermissionRequest): void;
1121
+ process(request: PermissionRequest): Promise<ReviewExecutionResult>;
1122
+ handlePermissionReply(event: unknown): void;
1123
+ /**
1124
+ * @deprecated No-op. Approvals no longer annotate tool results so they do not
1125
+ * contaminate the primary agent context. Kept for public API compatibility;
1126
+ * the plugin no longer registers a host hook that calls this. Rationale
1127
+ * remains in audit, TUI, and debug.
1128
+ */
1129
+ annotateToolResult(callID: string, output: {
1130
+ output?: unknown;
1131
+ metadata?: unknown;
1132
+ }): void;
1034
1133
  }
1035
-
1036
- /**
1037
- * Normalize a raw OpenCode event into a {@link PermissionRequest}.
1038
- *
1039
- * Returns `undefined` for anything that is not a well-formed
1040
- * `permission.asked` event, so callers can ignore irrelevant events without
1041
- * inspecting their shape.
1042
- */
1043
- declare function extractPermissionRequest(event: unknown): PermissionRequest | undefined;
1044
-
1045
- declare function resolveConfig(options: Record<string, unknown> | undefined): ReviewerConfig;
1046
-
1047
- declare function parseDecision(value: unknown): ReviewDecision | undefined;
1048
- declare function enforceDecision(decision: ReviewDecision, config: ReviewerConfig): ReviewExecutionResult;
1049
- declare const DECISION_SCHEMA: {
1050
- readonly type: "object";
1051
- readonly additionalProperties: false;
1052
- readonly required: readonly ["version", "outcome", "risk_level", "user_authorization", "scope_alignment", "evidence_completeness", "rationale", "confidence"];
1053
- readonly properties: {
1054
- readonly version: {
1055
- readonly type: "number";
1056
- readonly enum: readonly [2];
1057
- readonly description: "Structured-decision schema version. Must be exactly 2.";
1058
- };
1059
- readonly outcome: {
1060
- readonly type: "string";
1061
- readonly enum: readonly ["allow", "deny", "escalate"];
1062
- readonly description: "allow executes once, deny rejects, escalate leaves the request for a human";
1063
- };
1064
- readonly risk_level: {
1065
- readonly type: "string";
1066
- readonly enum: readonly ["low", "medium", "high", "critical"];
1067
- };
1068
- readonly user_authorization: {
1069
- readonly type: "string";
1070
- readonly enum: readonly ["high", "medium", "low", "unknown"];
1071
- };
1072
- readonly rationale: {
1073
- readonly type: "string";
1074
- readonly minLength: 3;
1075
- readonly maxLength: 2000;
1076
- readonly description: "One concise sentence explaining the main reason for the decision";
1077
- };
1078
- readonly confidence: {
1079
- readonly type: "number";
1080
- readonly minimum: 0;
1081
- readonly maximum: 1;
1082
- };
1083
- readonly scope_alignment: {
1084
- readonly type: "string";
1085
- readonly enum: readonly ["aligned", "partial", "misaligned", "unknown"];
1086
- readonly description: "How well the request aligns with the recovered user or delegated intent: aligned (within scope), partial (tangential), misaligned (outside scope), unknown (insufficient context).";
1087
- };
1088
- readonly evidence_completeness: {
1089
- readonly type: "string";
1090
- readonly enum: readonly ["sufficient", "partial", "insufficient", "unknown"];
1091
- readonly description: "Whether the evidence was sufficient to decide: sufficient, partial (some gaps), insufficient (major gaps), unknown.";
1092
- };
1093
- readonly script_analysis: {
1094
- readonly type: "string";
1095
- readonly minLength: 20;
1096
- readonly maxLength: 1500;
1097
- readonly description: "Optional factual analysis of a fully supplied verified script. Describe effects and uncertainty, never user authorization or an approval.";
1098
- };
1134
+ //#endregion
1135
+ //#region src/decision.d.ts
1136
+ export declare function parseDecision(value: unknown): ReviewDecision | undefined;
1137
+ //#endregion
1138
+ //#region src/decision-gates.d.ts
1139
+ export declare function enforceDecision(decision: ReviewDecision, config: ReviewerConfig): ReviewExecutionResult;
1140
+ //#endregion
1141
+ //#region src/decision-schema.d.ts
1142
+ export declare const DECISION_SCHEMA: {
1143
+ readonly type: "object";
1144
+ readonly additionalProperties: false;
1145
+ readonly required: readonly ["version", "outcome", "risk_level", "user_authorization", "scope_alignment", "evidence_completeness", "rationale", "confidence"];
1146
+ readonly properties: {
1147
+ readonly version: {
1148
+ readonly type: "number";
1149
+ readonly enum: readonly [2];
1150
+ readonly description: "Structured-decision schema version. Must be exactly 2.";
1151
+ };
1152
+ readonly outcome: {
1153
+ readonly type: "string";
1154
+ readonly enum: readonly ["allow", "deny", "escalate"];
1155
+ readonly description: "allow executes once, deny rejects, escalate leaves the request for a human";
1156
+ };
1157
+ readonly risk_level: {
1158
+ readonly type: "string";
1159
+ readonly enum: readonly ["low", "medium", "high", "critical"];
1160
+ };
1161
+ readonly user_authorization: {
1162
+ readonly type: "string";
1163
+ readonly enum: readonly ["high", "medium", "low", "unknown"];
1164
+ };
1165
+ readonly rationale: {
1166
+ readonly type: "string";
1167
+ readonly minLength: 3;
1168
+ readonly maxLength: 2000;
1169
+ readonly description: "One concise sentence explaining the main reason for the decision";
1170
+ };
1171
+ readonly confidence: {
1172
+ readonly type: "number";
1173
+ readonly minimum: 0;
1174
+ readonly maximum: 1;
1175
+ };
1176
+ readonly scope_alignment: {
1177
+ readonly type: "string";
1178
+ readonly enum: readonly ["aligned", "partial", "misaligned", "unknown"];
1179
+ readonly description: "How well the request aligns with the recovered user or delegated intent: aligned (within scope), partial (tangential), misaligned (outside scope), unknown (insufficient context).";
1180
+ };
1181
+ readonly evidence_completeness: {
1182
+ readonly type: "string";
1183
+ readonly enum: readonly ["sufficient", "partial", "insufficient", "unknown"];
1184
+ readonly description: "Whether the evidence was sufficient to decide: sufficient, partial (some gaps), insufficient (major gaps), unknown.";
1099
1185
  };
1186
+ readonly script_analysis: {
1187
+ readonly type: "string";
1188
+ readonly minLength: 20;
1189
+ readonly maxLength: 1500;
1190
+ readonly description: "Optional factual analysis of a fully supplied verified script. Describe effects and uncertainty, never user authorization or an approval.";
1191
+ };
1192
+ };
1100
1193
  };
1101
-
1194
+ //#endregion
1195
+ //#region src/emergency-brake.d.ts
1196
+ export declare function emergencyBrakeReason(request: PermissionRequest): string | undefined;
1197
+ //#endregion
1198
+ //#region src/escalation.d.ts
1102
1199
  /**
1103
1200
  * Categories that can be hardened independently of the global escalation mode
1104
1201
  * via `riskPolicy.onInvalidDecision` / `riskPolicy.onReviewerFailure`.
@@ -1116,7 +1213,7 @@ type EscalationCategory = "general" | "invalid-decision" | "reviewer-failure";
1116
1213
  *
1117
1214
  * `manual-superseded` is never converted: the request is already closed.
1118
1215
  */
1119
- declare function resolveEscalationDisposition(result: ReviewExecutionResult, config: ReviewerConfig, category?: EscalationCategory): EscalationDisposition;
1216
+ export declare function resolveEscalationDisposition(result: ReviewExecutionResult, config: ReviewerConfig, category?: EscalationCategory): EscalationDisposition;
1120
1217
  /**
1121
1218
  * Single enforcement boundary: convert an internal escalate into the effective
1122
1219
  * disposition used for UI, reply, and audit. Allow/deny and manual-superseded
@@ -1129,51 +1226,63 @@ declare function resolveEscalationDisposition(result: ReviewExecutionResult, con
1129
1226
  * structured decision. `reviewerOutcome` is only set when a structured
1130
1227
  * decision actually existed.
1131
1228
  */
1132
- declare function applyEscalationDisposition(result: ReviewExecutionResult, config: ReviewerConfig, category?: EscalationCategory): ReviewExecutionResult;
1133
-
1134
- declare function emergencyBrakeReason(request: PermissionRequest): string | undefined;
1135
-
1136
- declare function redactSecrets(input: string): string;
1137
-
1138
- interface UiStateOptions {
1139
- model: string;
1140
- variant: string;
1141
- timeoutMs: number;
1142
- }
1143
- declare class ReviewUiState {
1144
- private readonly options;
1145
- private readonly requests;
1146
- private readonly acknowledged;
1147
- constructor(options: UiStateOptions);
1148
- asked(request: PermissionRequest, now?: number): ReviewUiStatus;
1149
- apply(status: ReviewUiStatus): boolean;
1150
- replied(requestID: string): void;
1151
- remove(requestID: string): void;
1152
- get(requestID: string): ReviewUiStatus | undefined;
1153
- all(): ReviewUiStatus[];
1154
- activeFor(sessionID: string, parentOf: (sessionID: string) => string | undefined): ReviewUiStatus | undefined;
1155
- expire(now?: number): ReviewUiStatus[];
1156
- dismissResults(now?: number): string[];
1229
+ export declare function applyEscalationDisposition(result: ReviewExecutionResult, config: ReviewerConfig, category?: EscalationCategory): ReviewExecutionResult;
1230
+ //#endregion
1231
+ //#region src/git-evidence.d.ts
1232
+ interface GitEnrichmentResult {
1233
+ text: string;
1157
1234
  }
1158
-
1159
- declare const DEFAULT_AUDIT_PATH = "~/.local/share/opencode/permission-reviewer-audit.jsonl";
1160
- declare function createAuditWriter(config: ReviewerConfig, logger?: (message: string, details?: unknown) => void): ((record: ReviewAuditRecord) => Promise<void>) | undefined;
1161
-
1235
+ export declare function enrichGitEvidence(request: PermissionRequest, directory: string, maxChars: number, worktree?: string): Promise<GitEnrichmentResult>;
1236
+ //#endregion
1237
+ //#region src/local-script-evidence.d.ts
1162
1238
  interface LocalScriptEnrichmentResult {
1163
- text: string;
1239
+ text: string;
1164
1240
  }
1165
- declare function enrichLocalScriptEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<LocalScriptEnrichmentResult>;
1166
-
1167
- interface GitEnrichmentResult {
1168
- text: string;
1241
+ /** `rootDirectory` is the approved evidence root, which can sit above
1242
+ * `directory` (package-script expansion passes the session directory). */
1243
+ export declare function enrichLocalScriptEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number, rootDirectory?: string): Promise<LocalScriptEnrichmentResult>;
1244
+ //#endregion
1245
+ //#region src/opencode/event-normalizer.d.ts
1246
+ /**
1247
+ * Normalize a raw OpenCode event into a {@link PermissionRequest}.
1248
+ *
1249
+ * Returns `undefined` for anything that is not a well-formed
1250
+ * `permission.asked` event, so callers can ignore irrelevant events without
1251
+ * inspecting their shape.
1252
+ */
1253
+ export declare function extractPermissionRequest(event: unknown): PermissionRequest | undefined;
1254
+ //#endregion
1255
+ //#region src/redact.d.ts
1256
+ export declare function redactSecrets(input: string): string;
1257
+ //#endregion
1258
+ //#region src/ui-state.d.ts
1259
+ interface UiStateOptions {
1260
+ model: string;
1261
+ variant: string;
1262
+ timeoutMs: number;
1169
1263
  }
1170
- declare function enrichGitEvidence(request: PermissionRequest, directory: string, maxChars: number, worktree?: string): Promise<GitEnrichmentResult>;
1171
-
1172
- declare const server: Plugin$1;
1173
- declare const module$1: {
1174
- id: string;
1175
- server: Plugin$1;
1176
- setup: typeof setup;
1264
+ export declare class ReviewUiState {
1265
+ private readonly options;
1266
+ private readonly requests;
1267
+ private readonly acknowledged;
1268
+ constructor(options: UiStateOptions);
1269
+ asked(request: PermissionRequest, now?: number): ReviewUiStatus;
1270
+ apply(status: ReviewUiStatus): boolean;
1271
+ replied(requestID: string): void;
1272
+ remove(requestID: string): void;
1273
+ get(requestID: string): ReviewUiStatus | undefined;
1274
+ all(): ReviewUiStatus[];
1275
+ activeFor(sessionID: string, parentOf: (sessionID: string) => string | undefined): ReviewUiStatus | undefined;
1276
+ expire(now?: number): ReviewUiStatus[];
1277
+ dismissResults(now?: number): string[];
1278
+ }
1279
+ //#endregion
1280
+ //#region src/index.d.ts
1281
+ export declare const server: Plugin;
1282
+ declare const module: {
1283
+ id: string;
1284
+ server: Plugin;
1285
+ setup: typeof setup;
1177
1286
  };
1178
-
1179
- export { type ActionPurpose, type ActorContext, type ActorProfile, ReviewCoordinator as ApprovalReviewerRuntime, type ApprovedAnnotation, type AskDecision, AskDecisionRegistry, type CapabilityActionClass, type CapabilityAssessment, DECISION_SCHEMA, DEFAULT_AUDIT_PATH, DISMISSED_ANSWER, type DecisionSource, type EffectivePermissionSummary, type EscalationDisposition, type EscalationMode, type EscalationReviewerConfig, type EvidenceCompleteness, type EvidenceConfidence, type EvidenceSufficiency, type HeredocRecord, type IntentBlock, type IntentContext, type MessageWithParts, type ParsedCommand, type ParserCompleteness, type PermissionRequest, type PermissionToolSource, type PolicyCondition, type PolicyRule, type PolicyTrace, type Provenanced, type Redirection, type RepositoryTrust, type ReviewAuditRecord, type ReviewDecision, type ReviewEnvelope, type ReviewExecutionResult, type ReviewOutcome, ReviewUiState, type ReviewerConfig, type ReviewerOutputFormat, type RiskLevel, type RiskPolicy, SYSTEM_ONE_BASES, type ScopeAlignment, type SessionLineage, type SessionNode, type SystemOneChoiceScore, type SystemOnePrimaryBasis, type SystemOneScores, type SystemOneSignals, type UserAuthorization, applyEscalationDisposition, createAuditWriter, createUiStatus, decodeUiStatus, module$1 as default, emergencyBrakeReason, encodeUiStatus, enforceDecision, enrichGitEvidence, enrichLocalScriptEvidence, enrichSshEvidence, extractPermissionRequest, loadResolvedConfig, parseDecision, permissionAction, redactSecrets, resolveConfig, resolveEscalationDisposition, server };
1287
+ //#endregion
1288
+ export { type ActionPurpose, type ActorContext, type ActorProfile, ReviewCoordinator as ApprovalReviewerRuntime, type ApprovedAnnotation, type AskDecision, type CapabilityActionClass, type CapabilityAssessment, type DecisionSource, type EffectivePermissionSummary, type EscalatedFrom, type EscalationDisposition, type EscalationMode, type EscalationReviewerConfig, type EvidenceCompleteness, type EvidenceConfidence, type EvidenceSufficiency, type HandoffTrigger, type HeredocRecord, type IntentBlock, type IntentContext, type ManualResolution, type MessageWithParts, type ParsedCommand, type ParserCompleteness, type PermissionRequest, type PermissionToolSource, type PolicyCondition, type PolicyRule, type PolicyTrace, type Provenanced, type Redirection, type RepositoryTrust, type ReviewAuditRecord, type ReviewDecision, type ReviewEnvelope, type ReviewExecutionResult, type ReviewOutcome, type ReviewerConfig, type ReviewerOutputFormat, type RiskLevel, type RiskPolicy, type SYSTEM_ONE_BASES, type ScopeAlignment, type SessionLineage, type SessionNode, type SystemOneChoiceScore, type SystemOneEscalationMode, type SystemOnePrimaryBasis, type SystemOneScores, type SystemOneSignals, type UserAuthorization, module as default };