@noppu-labs/opencode-permission-reviewer 0.0.0-stage → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1179 @@
1
+ import { Plugin as Plugin$1 } from '@opencode-ai/plugin';
2
+ import { Plugin } from '@opencode/plugin';
3
+
4
+ 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
+ }>;
18
+ }
19
+ 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;
33
+ }
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;
44
+ }
45
+
46
+ type RiskLevel = "low" | "medium" | "high" | "critical";
47
+ type UserAuthorization = "high" | "medium" | "low" | "unknown";
48
+ type ReviewOutcome = "allow" | "deny" | "escalate";
49
+ type ScopeAlignment = "aligned" | "partial" | "misaligned" | "unknown";
50
+ type EvidenceSufficiency = "sufficient" | "partial" | "insufficient" | "unknown";
51
+ /** How final escalations are disposed after reviewer/policy/fail-safe produce them. */
52
+ type EscalationMode = "manual" | "deny";
53
+ /** Effective disposition applied to an internal escalate result. */
54
+ type EscalationDisposition = "manual" | "deny";
55
+ 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;
69
+ }
70
+ interface PermissionToolSource {
71
+ messageID: string;
72
+ callID: string;
73
+ }
74
+ 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;
82
+ }
83
+ interface MessageWithParts {
84
+ info: Record<string, unknown> & {
85
+ id?: string;
86
+ role?: string;
87
+ structured?: unknown;
88
+ };
89
+ parts: Array<Record<string, unknown>>;
90
+ }
91
+ /** Deterministic risk×authorization matrix that gates reviewer `allow`
92
+ * outcomes. For each risk level, lists the authorization levels that permit an
93
+ * auto-allow. An empty array means no authorization permits auto-allow at that
94
+ * risk (the action is escalated). Only ever RESTRICTS; deny/escalate are always
95
+ * preserved. */
96
+ 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";
106
+ }
107
+ /** Conservative repository trust model. A repository cannot mark itself trusted
108
+ * through project configuration alone — trust comes from global config or an
109
+ * interactive decision stored outside the repo. */
110
+ type RepositoryTrust = "trusted" | "untrusted" | "unknown";
111
+ /** A declarative policy condition: matches capability/actor facts. Every field
112
+ * is optional; the rule matches when ALL specified fields match. A missing
113
+ * `when` (or `{ always: true }`) makes the rule universal. */
114
+ 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[];
133
+ }
134
+ /** A declarative rule that routes a request based on capability+actor facts.
135
+ * `when` is optional: omitting it (or `{ always: true }`) matches every
136
+ * request. An explicitly empty `when: {}` is rejected at load. */
137
+ interface PolicyRule {
138
+ id: string;
139
+ source: "builtin" | "global" | "project" | "inline";
140
+ when?: PolicyCondition;
141
+ effect: "review" | "manual" | "deny" | "allow";
142
+ reason: string;
143
+ }
144
+ /** The result of evaluating the declarative policy. */
145
+ 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";
159
+ }
160
+ type ReviewerOutputFormat = "json_schema" | "text";
161
+ interface EscalationReviewerConfig {
162
+ model: string;
163
+ variant: string;
164
+ outputFormat: ReviewerOutputFormat;
165
+ timeoutMs: number;
166
+ }
167
+ 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[];
230
+ }
231
+ 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;
468
+ }
469
+ interface ApprovedAnnotation {
470
+ requestID: string;
471
+ sessionID: string;
472
+ decision: ReviewDecision;
473
+ }
474
+ 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;
501
+ }
502
+ /** Reliability of a derived fact. */
503
+ type EvidenceConfidence = "confirmed" | "high" | "medium" | "low" | "unknown";
504
+ /** Every non-trivial derived fact carries provenance so the LLM and audit can
505
+ * weigh claims by how reliably they were established. */
506
+ 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[];
511
+ }
512
+ /** Generic policy templates, NOT automatic trust levels. */
513
+ type ActorProfile = "read-only" | "validation" | "workspace" | "operator" | "reviewer" | "unknown";
514
+ /** Normalized effective-permission summary when the SDK exposes it.
515
+ * The v1 SDK does not expose effective rules, so this stays `undefined`. */
516
+ 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";
522
+ }
523
+ /** Who is requesting the permission. */
524
+ 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";
534
+ }
535
+ /** A node in the session ancestry chain. */
536
+ interface SessionNode {
537
+ sessionID: string;
538
+ parentID?: string;
539
+ title?: string;
540
+ version?: string;
541
+ actorName?: string;
542
+ mode?: string;
543
+ createdAt?: number;
544
+ }
545
+ /** The resolved session ancestry with failure modes made explicit. */
546
+ 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[];
554
+ }
555
+ /** A single authorization/intent statement. */
556
+ 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">;
564
+ }
565
+ /** One user decision on an agent-initiated ask dialog (question tool). The
566
+ * question text is agent-generated and untrusted; only the answer is a user
567
+ * authorization signal, scoped to the subject and time of the ask. */
568
+ 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;
575
+ }
576
+ /** Direct user intent kept separate from delegated task. */
577
+ interface IntentContext {
578
+ directUserIntent: IntentBlock[];
579
+ delegatedTask: IntentBlock[];
580
+ localSessionIntent: IntentBlock[];
581
+ conflictingInstructions: string[];
582
+ latestExplicitAuthorization?: IntentBlock;
583
+ completeness: "complete" | "partial" | "insufficient";
584
+ }
585
+ /** Meta-summary of what evidence was available. */
586
+ 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";
599
+ }
600
+ /**
601
+ * Operational purpose of the pending action — what the agent appears to be
602
+ * trying to accomplish. This is untrusted evidence: it never demonstrates
603
+ * user authorization by itself.
604
+ */
605
+ 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;
665
+ }
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. */
673
+ 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">;
719
+ };
720
+ /** How completely the command could be analyzed. */
721
+ parserCompleteness: ParserCompleteness;
722
+ /** Free-form warnings about analysis limitations. */
723
+ analysisWarnings: string[];
724
+ }
725
+
726
+ /** The host passing an options object does not attest who authored it. */
727
+ type InlineOptionsTrust = "trusted" | "project" | "unknown";
728
+
729
+ /** Load and merge config from global, project, and inline sources.
730
+ *
731
+ * Precedence (lowest to highest): builtin defaults → global → project → inline,
732
+ * with one deliberate exception: security-sensitive fields cross a trust
733
+ * boundary where the untrusted project layer can only TIGHTEN the trusted
734
+ * baseline (see mergeWithTrustBoundary), and that hardening survives even
735
+ * when inline set the same field.
736
+ *
737
+ * When no global or project files exist (the common case), the result is
738
+ * 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;
861
+ }
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;
877
+ }
878
+ interface EvidenceProviderInput {
879
+ request: PermissionRequest;
880
+ directory: string;
881
+ worktree: string;
882
+ maxChars: number;
883
+ }
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>;
892
+ }
893
+
894
+ /**
895
+ * Captures user answers to agent ask dialogs (the `question` tool) from the
896
+ * OpenCode event stream and exposes them as compact, session-scoped
897
+ * authorization evidence for the reviewer prompt.
898
+ *
899
+ * The host runs questions through a dedicated service (`question.asked` /
900
+ * `question.replied` / `question.rejected` events) that never touches the
901
+ * permission pipeline, so these decisions are invisible to a permission-only
902
+ * observer. This registry is the counterpart capture layer: it is
903
+ * enrichment-only — question events never trigger, supersede, or enforce
904
+ * anything — and it is total (malformed events are dropped, never thrown).
905
+ *
906
+ * Robustness rules:
907
+ * - One logical ask = one record, keyed by the per-ask request ID. The v1 and
908
+ * v2 event spellings of the same ask upsert into the same entry, and a
909
+ * replayed reply or rejection is ignored.
910
+ * - A reply or rejection without a matching pending ask is dropped (the
911
+ * question text is unknowable after the fact).
912
+ * - Pending asks expire (TTL) so a very late reply cannot pair with a stale
913
+ * question from another context.
914
+ * - Resolved decisions are FIFO-bounded globally; the per-review limit is
915
+ * applied at query time, not storage time.
916
+ * - Question and answer text is redacted before storage; a credential pasted
917
+ * as a custom answer must never land in the registry, prompt, or audit.
918
+ */
919
+ /** Marker recorded when the user dismisses an ask without answering. */
920
+ declare const DISMISSED_ANSWER = "Dismissed by user";
921
+ type Logger$1 = (message: string, details?: unknown) => void;
922
+ /** What the evidence assembler consumes: a bounded, lineage-scoped query. */
923
+ interface AskDecisionSource {
924
+ recentFor(sessionIDs: string[], limit?: number): AskDecision[];
925
+ }
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;
954
+ }
955
+
956
+ type Logger = (message: string, details?: unknown) => void;
957
+ /**
958
+ * Owns the review lifecycle for permission requests: orchestration, the
959
+ * supersede state machine, and the model call. The adapter (transport) and the
960
+ * evidence providers are injected so this class stays focused on ordering and
961
+ * races.
962
+ */
963
+ 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;
1034
+ }
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
+ };
1099
+ };
1100
+ };
1101
+
1102
+ /**
1103
+ * Categories that can be hardened independently of the global escalation mode
1104
+ * via `riskPolicy.onInvalidDecision` / `riskPolicy.onReviewerFailure`.
1105
+ * `general` covers every other escalate path (LLM escalate, gates, policy
1106
+ * manual, context failures, …).
1107
+ */
1108
+ type EscalationCategory = "general" | "invalid-decision" | "reviewer-failure";
1109
+ /**
1110
+ * Resolve the effective disposition for an internal escalate.
1111
+ *
1112
+ * Precedence is monotonic (restrictive wins):
1113
+ * 1. `escalationMode: "deny"` hardens every escalate globally.
1114
+ * 2. Category knobs can harden only their own case when mode is `manual`.
1115
+ * 3. Nothing can relax a more restrictive setting.
1116
+ *
1117
+ * `manual-superseded` is never converted: the request is already closed.
1118
+ */
1119
+ declare function resolveEscalationDisposition(result: ReviewExecutionResult, config: ReviewerConfig, category?: EscalationCategory): EscalationDisposition;
1120
+ /**
1121
+ * Single enforcement boundary: convert an internal escalate into the effective
1122
+ * disposition used for UI, reply, and audit. Allow/deny and manual-superseded
1123
+ * pass through unchanged.
1124
+ *
1125
+ * When converting escalate → deny, the original reason is preserved so the
1126
+ * primary agent still receives actionable feedback. The original structured
1127
+ * decision (if any) is kept as-is — never rewritten into a synthetic deny —
1128
+ * so audit can distinguish a real LLM escalate from a fail-safe without a
1129
+ * structured decision. `reviewerOutcome` is only set when a structured
1130
+ * decision actually existed.
1131
+ */
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[];
1157
+ }
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
+
1162
+ interface LocalScriptEnrichmentResult {
1163
+ text: string;
1164
+ }
1165
+ declare function enrichLocalScriptEvidence(request: PermissionRequest, directory: string, worktree: string, maxChars: number): Promise<LocalScriptEnrichmentResult>;
1166
+
1167
+ interface GitEnrichmentResult {
1168
+ text: string;
1169
+ }
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;
1177
+ };
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 };