@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.
- package/CHANGELOG.md +652 -0
- package/LICENSE +201 -0
- package/MIGRATION.md +111 -0
- package/NOTICE +13 -0
- package/README.md +842 -2
- package/SECURITY.md +31 -0
- package/dist/explain.d.ts +4 -0
- package/dist/explain.js +4422 -0
- package/dist/index.d.ts +1179 -0
- package/dist/index.js +10770 -0
- package/dist/rpc.d.ts +42 -0
- package/dist/rpc.js +19 -0
- package/dist/tui/config/jsonc.ts +100 -0
- package/dist/tui/config/loader.ts +573 -0
- package/dist/tui/config.ts +479 -0
- package/dist/tui/opencode/event-normalizer.ts +52 -0
- package/dist/tui/tui.tsx +162 -0
- package/dist/tui/types.ts +747 -0
- package/dist/tui/ui/components.tsx +181 -0
- package/dist/tui/ui/rpc.ts +16 -0
- package/dist/tui/ui/v2.tsx +261 -0
- package/dist/tui/ui-protocol.ts +183 -0
- package/dist/tui/ui-state.ts +139 -0
- package/package.json +128 -4
- package/rpc.js +1 -0
- package/server.js +2 -0
- package/tui.tsx +1 -0
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ActorProfile,
|
|
3
|
+
CapabilityActionClass,
|
|
4
|
+
EscalationMode,
|
|
5
|
+
PolicyCondition,
|
|
6
|
+
PolicyRule,
|
|
7
|
+
RiskPolicy,
|
|
8
|
+
RepositoryTrust,
|
|
9
|
+
ReviewerConfig,
|
|
10
|
+
EscalationReviewerConfig,
|
|
11
|
+
UserAuthorization,
|
|
12
|
+
} from "./types.ts"
|
|
13
|
+
|
|
14
|
+
/** Default risk×authorization matrix. Reproduces exactly the previous
|
|
15
|
+
* hard-coded gate: critical never auto-allows; high needs at least medium auth;
|
|
16
|
+
* medium needs at least low auth; low allows any auth including unknown. */
|
|
17
|
+
export const DEFAULT_RISK_POLICY: RiskPolicy = {
|
|
18
|
+
allow: {
|
|
19
|
+
low: ["high", "medium", "low", "unknown"],
|
|
20
|
+
medium: ["high", "medium", "low"],
|
|
21
|
+
high: ["high", "medium"],
|
|
22
|
+
critical: [],
|
|
23
|
+
},
|
|
24
|
+
minimumConfidence: 0.7,
|
|
25
|
+
onInvalidDecision: "manual",
|
|
26
|
+
onReviewerFailure: "manual",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const DEFAULT_CONFIG: ReviewerConfig = {
|
|
30
|
+
model: "openai/gpt-6-luna",
|
|
31
|
+
variant: "medium",
|
|
32
|
+
outputFormat: "json_schema",
|
|
33
|
+
timeoutMs: 120_000,
|
|
34
|
+
maxContextChars: 32_000,
|
|
35
|
+
maxPartChars: 8_000,
|
|
36
|
+
maxEnrichmentChars: 24_000,
|
|
37
|
+
maxIntentChars: 8_000,
|
|
38
|
+
transcriptMessages: 12,
|
|
39
|
+
intentMessages: 8,
|
|
40
|
+
historyMessages: 200,
|
|
41
|
+
confidenceThreshold: 0.7,
|
|
42
|
+
systemOneConfidenceThreshold: 0.4,
|
|
43
|
+
systemOneReasoningThreshold: 0.38,
|
|
44
|
+
retainReviewSessions: false,
|
|
45
|
+
audit: true,
|
|
46
|
+
debug: false,
|
|
47
|
+
enforcementMode: "observe",
|
|
48
|
+
escalationMode: "manual",
|
|
49
|
+
maxSessionDepth: 8,
|
|
50
|
+
maxParentSessions: 8,
|
|
51
|
+
actorProfiles: {},
|
|
52
|
+
riskPolicy: DEFAULT_RISK_POLICY,
|
|
53
|
+
repositoryTrust: "unknown",
|
|
54
|
+
policyRules: [],
|
|
55
|
+
askDecisions: true,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Total deadline for a review, shared by the server and TUI watchdog. */
|
|
59
|
+
export function reviewBudgetMs(config: ReviewerConfig): number {
|
|
60
|
+
return config.reviewBudgetMs ?? config.timeoutMs * 2 + 60_000
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function boundedInteger(value: unknown, fallback: number, min: number, max: number): number {
|
|
64
|
+
if (typeof value !== "number" || !Number.isInteger(value)) return fallback
|
|
65
|
+
return Math.min(max, Math.max(min, value))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function boundedNumber(value: unknown, fallback: number, min: number, max: number): number {
|
|
69
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return fallback
|
|
70
|
+
return Math.min(max, Math.max(min, value))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const ACTOR_PROFILES: ReadonlySet<ActorProfile> = new Set([
|
|
74
|
+
"read-only",
|
|
75
|
+
"validation",
|
|
76
|
+
"workspace",
|
|
77
|
+
"operator",
|
|
78
|
+
"reviewer",
|
|
79
|
+
"unknown",
|
|
80
|
+
])
|
|
81
|
+
|
|
82
|
+
/** Every action class the capability analyzer can produce. The `satisfies`
|
|
83
|
+
* clause keeps this list in sync with the union type: adding a member to
|
|
84
|
+
* `CapabilityActionClass` without listing it here is a compile error. */
|
|
85
|
+
const ACTION_CLASS_MEMBERS = {
|
|
86
|
+
"read-only": true,
|
|
87
|
+
"workspace-write": true,
|
|
88
|
+
"temporary-write": true,
|
|
89
|
+
"external-write": true,
|
|
90
|
+
destruction: true,
|
|
91
|
+
"code-execution": true,
|
|
92
|
+
"package-management": true,
|
|
93
|
+
"git-mutation": true,
|
|
94
|
+
network: true,
|
|
95
|
+
"remote-operation": true,
|
|
96
|
+
"service-management": true,
|
|
97
|
+
persistence: true,
|
|
98
|
+
"privilege-escalation": true,
|
|
99
|
+
unknown: true,
|
|
100
|
+
} satisfies Record<CapabilityActionClass, true>
|
|
101
|
+
|
|
102
|
+
const VALID_ACTION_CLASS: ReadonlySet<string> = new Set(Object.keys(ACTION_CLASS_MEMBERS))
|
|
103
|
+
|
|
104
|
+
const VALID_REPOSITORY_TRUST: ReadonlySet<string> = new Set(["trusted", "untrusted", "unknown"])
|
|
105
|
+
|
|
106
|
+
/** Parse a trusted name→profile mapping. Invalid entries are dropped. */
|
|
107
|
+
function resolveActorProfiles(value: unknown): Record<string, ActorProfile> {
|
|
108
|
+
if (typeof value !== "object" || value === null) return {}
|
|
109
|
+
const out: Record<string, ActorProfile> = {}
|
|
110
|
+
for (const [name, profile] of Object.entries(value as Record<string, unknown>)) {
|
|
111
|
+
if (typeof profile === "string" && ACTOR_PROFILES.has(profile as ActorProfile)) {
|
|
112
|
+
out[name] = profile as ActorProfile
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return out
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const VALID_AUTH = new Set(["high", "medium", "low", "unknown"])
|
|
119
|
+
|
|
120
|
+
/** Parse a risk×authorization matrix. Invalid or partial entries fall back to
|
|
121
|
+
* the conservative default. Failure-mode knobs only accept the stricter
|
|
122
|
+
* `"deny"` override; anything else keeps the default `"manual"`. */
|
|
123
|
+
function resolveRiskPolicy(value: unknown): RiskPolicy {
|
|
124
|
+
if (typeof value !== "object" || value === null)
|
|
125
|
+
return { ...DEFAULT_RISK_POLICY, allow: { ...DEFAULT_RISK_POLICY.allow } }
|
|
126
|
+
const src = value as Record<string, unknown>
|
|
127
|
+
const allowSrc = typeof src.allow === "object" && src.allow !== null ? src.allow : {}
|
|
128
|
+
const merged: RiskPolicy = {
|
|
129
|
+
allow: { ...DEFAULT_RISK_POLICY.allow },
|
|
130
|
+
minimumConfidence: DEFAULT_RISK_POLICY.minimumConfidence,
|
|
131
|
+
// Prefer an explicit deny from either the field or a pre-clamped trusted
|
|
132
|
+
// baseline (loader may have already hardened the knob).
|
|
133
|
+
onInvalidDecision:
|
|
134
|
+
src.onInvalidDecision === "deny" ? "deny" : DEFAULT_RISK_POLICY.onInvalidDecision,
|
|
135
|
+
onReviewerFailure:
|
|
136
|
+
src.onReviewerFailure === "deny" ? "deny" : DEFAULT_RISK_POLICY.onReviewerFailure,
|
|
137
|
+
}
|
|
138
|
+
for (const risk of ["low", "medium", "high", "critical"] as const) {
|
|
139
|
+
const cell = (allowSrc as Record<string, unknown>)[risk]
|
|
140
|
+
if (!Array.isArray(cell)) continue
|
|
141
|
+
const auths = cell.filter(
|
|
142
|
+
(a) => typeof a === "string" && VALID_AUTH.has(a),
|
|
143
|
+
) as UserAuthorization[]
|
|
144
|
+
merged.allow[risk] = auths
|
|
145
|
+
}
|
|
146
|
+
if (typeof src.minimumConfidence === "number" && Number.isFinite(src.minimumConfidence)) {
|
|
147
|
+
merged.minimumConfidence = Math.min(1, Math.max(0.5, src.minimumConfidence))
|
|
148
|
+
}
|
|
149
|
+
return merged
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function resolveEscalationMode(value: unknown): EscalationMode {
|
|
153
|
+
return value === "deny" ? "deny" : "manual"
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function resolveRepositoryTrust(value: unknown): RepositoryTrust {
|
|
157
|
+
if (value === "trusted") return "trusted"
|
|
158
|
+
if (value === "untrusted") return "untrusted"
|
|
159
|
+
return "unknown"
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const VALID_EFFECTS = new Set(["review", "manual", "deny", "allow"])
|
|
163
|
+
const VALID_SOURCES = new Set(["builtin", "global", "project", "inline"])
|
|
164
|
+
|
|
165
|
+
/** Parse one declarative policy rule. Malformed entries return null so the
|
|
166
|
+
* caller decides whether dropping them is safe (untrusted layer) or must
|
|
167
|
+
* degrade the config (trusted layer — a dropped restriction may be the whole
|
|
168
|
+
* point of the rule). A missing `when` is a valid universal rule. */
|
|
169
|
+
function parsePolicyRule(raw: unknown): PolicyRule | null {
|
|
170
|
+
if (typeof raw !== "object" || raw === null) return null
|
|
171
|
+
const r = raw as Record<string, unknown>
|
|
172
|
+
if (typeof r.id !== "string" || r.id.length === 0) return null
|
|
173
|
+
if (typeof r.source !== "string" || !VALID_SOURCES.has(r.source)) return null
|
|
174
|
+
if (typeof r.effect !== "string" || !VALID_EFFECTS.has(r.effect)) return null
|
|
175
|
+
if (typeof r.reason !== "string" || r.reason.length === 0) return null
|
|
176
|
+
if (r.when !== undefined) {
|
|
177
|
+
if (typeof r.when !== "object" || r.when === null) return null
|
|
178
|
+
const when = validateCondition(r.when as Record<string, unknown>)
|
|
179
|
+
if (when === null) return null
|
|
180
|
+
return {
|
|
181
|
+
id: r.id,
|
|
182
|
+
source: r.source as PolicyRule["source"],
|
|
183
|
+
when,
|
|
184
|
+
effect: r.effect as PolicyRule["effect"],
|
|
185
|
+
reason: r.reason,
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// No `when` at all: a universal rule. `{ always: true }` is the explicit
|
|
189
|
+
// spelling of the same thing for admins who prefer it.
|
|
190
|
+
return {
|
|
191
|
+
id: r.id,
|
|
192
|
+
source: r.source as PolicyRule["source"],
|
|
193
|
+
effect: r.effect as PolicyRule["effect"],
|
|
194
|
+
reason: r.reason,
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Parse declarative policy rules. Malformed entries are dropped. */
|
|
199
|
+
function resolvePolicyRules(value: unknown): PolicyRule[] {
|
|
200
|
+
if (!Array.isArray(value)) return []
|
|
201
|
+
const out: PolicyRule[] = []
|
|
202
|
+
for (const raw of value) {
|
|
203
|
+
const rule = parsePolicyRule(raw)
|
|
204
|
+
if (rule !== null) out.push(rule)
|
|
205
|
+
}
|
|
206
|
+
return out
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** How many entries a policyRules array would silently drop under
|
|
210
|
+
* `resolvePolicyRules`. Trusted layers use this to refuse silent degradation:
|
|
211
|
+
* an admin rule that vanishes on a typo must block auto-approval, not just
|
|
212
|
+
* disappear. */
|
|
213
|
+
export function countInvalidPolicyRules(value: unknown): number {
|
|
214
|
+
if (value === undefined) return 0
|
|
215
|
+
if (!Array.isArray(value)) return 1
|
|
216
|
+
return value.filter((raw) => parsePolicyRule(raw) === null).length
|
|
217
|
+
}
|
|
218
|
+
/** Validate a policy condition's sub-fields; return null if malformed (so a bad
|
|
219
|
+
* rule is dropped rather than crashing the engine at match time). */
|
|
220
|
+
const CONDITION_LIST_KEYS = ["actionClass", "actorProfile", "repositoryTrust"] as const
|
|
221
|
+
const CONDITION_FLAG_KEYS = [
|
|
222
|
+
"writesWorkspace",
|
|
223
|
+
"writesExternal",
|
|
224
|
+
"writesTemporary",
|
|
225
|
+
"deletion",
|
|
226
|
+
"executesCode",
|
|
227
|
+
"createsAdHocCode",
|
|
228
|
+
"packageManagement",
|
|
229
|
+
"gitMutation",
|
|
230
|
+
"networkObserved",
|
|
231
|
+
"credentialRead",
|
|
232
|
+
"privilegeEscalation",
|
|
233
|
+
"remoteEnabled",
|
|
234
|
+
"persistence",
|
|
235
|
+
] as const
|
|
236
|
+
|
|
237
|
+
function validateCondition(value: Record<string, unknown>): PolicyCondition | null {
|
|
238
|
+
// An unknown key (usually a typo) must drop the rule: silently discarding it
|
|
239
|
+
// could strip the rule's only condition and turn a narrow rule into a
|
|
240
|
+
// universal match.
|
|
241
|
+
const knownKeys = new Set<string>(["always", ...CONDITION_LIST_KEYS, ...CONDITION_FLAG_KEYS])
|
|
242
|
+
for (const key of Object.keys(value)) {
|
|
243
|
+
if (!knownKeys.has(key)) return null
|
|
244
|
+
}
|
|
245
|
+
// `always` is the explicit catch-all spelling; it makes sense only alone.
|
|
246
|
+
if (value.always !== undefined) {
|
|
247
|
+
if (value.always !== true || Object.keys(value).length !== 1) return null
|
|
248
|
+
return { always: true }
|
|
249
|
+
}
|
|
250
|
+
const out: Record<string, unknown> = {}
|
|
251
|
+
// List conditions are matched with `includes()` at match time, so a member
|
|
252
|
+
// outside the closed set (usually a typo) would never match and would
|
|
253
|
+
// silently disable the rule. Rejecting it drops the rule through the normal
|
|
254
|
+
// path, which degrades trusted configs fail-closed instead of losing a
|
|
255
|
+
// restriction quietly. Empty lists never match either, so they are rejected
|
|
256
|
+
// for the same reason.
|
|
257
|
+
if (value.actionClass !== undefined) {
|
|
258
|
+
if (!isClosedSetMemberArray(value.actionClass, VALID_ACTION_CLASS)) return null
|
|
259
|
+
out.actionClass = value.actionClass
|
|
260
|
+
}
|
|
261
|
+
if (value.actorProfile !== undefined) {
|
|
262
|
+
if (!isClosedSetMemberArray(value.actorProfile, ACTOR_PROFILES as ReadonlySet<string>))
|
|
263
|
+
return null
|
|
264
|
+
out.actorProfile = value.actorProfile
|
|
265
|
+
}
|
|
266
|
+
if (value.repositoryTrust !== undefined) {
|
|
267
|
+
if (!isClosedSetMemberArray(value.repositoryTrust, VALID_REPOSITORY_TRUST)) return null
|
|
268
|
+
out.repositoryTrust = value.repositoryTrust
|
|
269
|
+
}
|
|
270
|
+
for (const flag of CONDITION_FLAG_KEYS) {
|
|
271
|
+
if (value[flag] !== undefined) {
|
|
272
|
+
if (typeof value[flag] !== "boolean") return null
|
|
273
|
+
// Capability facts are `true | "unknown"` — never false — so a `false`
|
|
274
|
+
// condition could never match. Reject it instead of ignoring the filter:
|
|
275
|
+
// an ignored condition widens the rule.
|
|
276
|
+
if (value[flag] === false) return null
|
|
277
|
+
out[flag] = value[flag]
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
// A condition that validated to nothing would match every request while
|
|
281
|
+
// LOOKING conditioned; catch-alls must be spelled unambiguously (omit `when`
|
|
282
|
+
// entirely, or `{ always: true }`).
|
|
283
|
+
if (Object.keys(out).length === 0) return null
|
|
284
|
+
return out as PolicyCondition
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function isStringArray(value: unknown): value is string[] {
|
|
288
|
+
return Array.isArray(value) && value.every((v) => typeof v === "string")
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** A non-empty string array whose members all belong to the closed set. */
|
|
292
|
+
function isClosedSetMemberArray(value: unknown, valid: ReadonlySet<string>): value is string[] {
|
|
293
|
+
return (
|
|
294
|
+
Array.isArray(value) &&
|
|
295
|
+
value.length > 0 &&
|
|
296
|
+
value.every((v) => typeof v === "string" && valid.has(v))
|
|
297
|
+
)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function resolveConfig(options: Record<string, unknown> | undefined): ReviewerConfig {
|
|
301
|
+
const source = options ?? {}
|
|
302
|
+
const model =
|
|
303
|
+
typeof source.model === "string" && source.model.includes("/")
|
|
304
|
+
? source.model
|
|
305
|
+
: DEFAULT_CONFIG.model
|
|
306
|
+
const variant =
|
|
307
|
+
typeof source.variant === "string" && source.variant.length > 0
|
|
308
|
+
? source.variant
|
|
309
|
+
: DEFAULT_CONFIG.variant
|
|
310
|
+
const outputFormat = source.outputFormat === "text" ? "text" : "json_schema"
|
|
311
|
+
const escalationReviewer = resolveEscalationReviewer(source.escalationReviewer)
|
|
312
|
+
const policy =
|
|
313
|
+
typeof source.policy === "string" && source.policy.trim().length > 0
|
|
314
|
+
? source.policy.trim()
|
|
315
|
+
: undefined
|
|
316
|
+
const auditPath =
|
|
317
|
+
typeof source.auditPath === "string" && source.auditPath.trim().length > 0
|
|
318
|
+
? source.auditPath.trim()
|
|
319
|
+
: undefined
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
model,
|
|
323
|
+
variant,
|
|
324
|
+
outputFormat,
|
|
325
|
+
...(escalationReviewer === undefined ? {} : { escalationReviewer }),
|
|
326
|
+
timeoutMs: boundedInteger(source.timeoutMs, DEFAULT_CONFIG.timeoutMs, 5_000, 600_000),
|
|
327
|
+
...(source.reviewBudgetMs === undefined
|
|
328
|
+
? {}
|
|
329
|
+
: { reviewBudgetMs: boundedInteger(source.reviewBudgetMs, 180_000, 5_000, 900_000) }),
|
|
330
|
+
maxContextChars: boundedInteger(
|
|
331
|
+
source.maxContextChars,
|
|
332
|
+
DEFAULT_CONFIG.maxContextChars,
|
|
333
|
+
4_000,
|
|
334
|
+
200_000,
|
|
335
|
+
),
|
|
336
|
+
maxPartChars: boundedInteger(source.maxPartChars, DEFAULT_CONFIG.maxPartChars, 500, 50_000),
|
|
337
|
+
maxEnrichmentChars: boundedInteger(
|
|
338
|
+
source.maxEnrichmentChars,
|
|
339
|
+
DEFAULT_CONFIG.maxEnrichmentChars,
|
|
340
|
+
1_000,
|
|
341
|
+
100_000,
|
|
342
|
+
),
|
|
343
|
+
maxIntentChars: boundedInteger(
|
|
344
|
+
source.maxIntentChars,
|
|
345
|
+
DEFAULT_CONFIG.maxIntentChars,
|
|
346
|
+
1_000,
|
|
347
|
+
50_000,
|
|
348
|
+
),
|
|
349
|
+
transcriptMessages: boundedInteger(
|
|
350
|
+
source.transcriptMessages,
|
|
351
|
+
DEFAULT_CONFIG.transcriptMessages,
|
|
352
|
+
1,
|
|
353
|
+
100,
|
|
354
|
+
),
|
|
355
|
+
intentMessages: boundedInteger(source.intentMessages, DEFAULT_CONFIG.intentMessages, 1, 50),
|
|
356
|
+
historyMessages: boundedInteger(
|
|
357
|
+
source.historyMessages,
|
|
358
|
+
DEFAULT_CONFIG.historyMessages,
|
|
359
|
+
20,
|
|
360
|
+
500,
|
|
361
|
+
),
|
|
362
|
+
confidenceThreshold: boundedNumber(
|
|
363
|
+
source.confidenceThreshold,
|
|
364
|
+
DEFAULT_CONFIG.confidenceThreshold,
|
|
365
|
+
0.5,
|
|
366
|
+
1,
|
|
367
|
+
),
|
|
368
|
+
systemOneConfidenceThreshold: boundedNumber(
|
|
369
|
+
source.systemOneConfidenceThreshold,
|
|
370
|
+
DEFAULT_CONFIG.systemOneConfidenceThreshold,
|
|
371
|
+
0.3,
|
|
372
|
+
1,
|
|
373
|
+
),
|
|
374
|
+
systemOneReasoningThreshold: boundedNumber(
|
|
375
|
+
source.systemOneReasoningThreshold,
|
|
376
|
+
DEFAULT_CONFIG.systemOneReasoningThreshold,
|
|
377
|
+
0,
|
|
378
|
+
1,
|
|
379
|
+
),
|
|
380
|
+
retainReviewSessions:
|
|
381
|
+
typeof source.retainReviewSessions === "boolean"
|
|
382
|
+
? source.retainReviewSessions
|
|
383
|
+
: DEFAULT_CONFIG.retainReviewSessions,
|
|
384
|
+
audit: typeof source.audit === "boolean" ? source.audit : DEFAULT_CONFIG.audit,
|
|
385
|
+
...(auditPath === undefined ? {} : { auditPath }),
|
|
386
|
+
...(policy === undefined ? {} : { policy }),
|
|
387
|
+
debug: typeof source.debug === "boolean" ? source.debug : DEFAULT_CONFIG.debug,
|
|
388
|
+
enforcementMode:
|
|
389
|
+
source.enforcementMode === "enforce" ? "enforce" : DEFAULT_CONFIG.enforcementMode,
|
|
390
|
+
escalationMode: resolveEscalationMode(source.escalationMode),
|
|
391
|
+
maxSessionDepth: boundedInteger(source.maxSessionDepth, DEFAULT_CONFIG.maxSessionDepth, 1, 32),
|
|
392
|
+
maxParentSessions: boundedInteger(
|
|
393
|
+
source.maxParentSessions,
|
|
394
|
+
DEFAULT_CONFIG.maxParentSessions,
|
|
395
|
+
0,
|
|
396
|
+
32,
|
|
397
|
+
),
|
|
398
|
+
actorProfiles: resolveActorProfiles(source.actorProfiles),
|
|
399
|
+
riskPolicy: resolveRiskPolicy(source.riskPolicy),
|
|
400
|
+
repositoryTrust: resolveRepositoryTrust(source.repositoryTrust),
|
|
401
|
+
policyRules: resolvePolicyRules(source.policyRules),
|
|
402
|
+
askDecisions:
|
|
403
|
+
typeof source.askDecisions === "boolean" ? source.askDecisions : DEFAULT_CONFIG.askDecisions,
|
|
404
|
+
...(isStringArray(source.configDegraded) && source.configDegraded.length > 0
|
|
405
|
+
? { configDegraded: source.configDegraded }
|
|
406
|
+
: {}),
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function resolveEscalationReviewer(value: unknown): EscalationReviewerConfig | undefined {
|
|
411
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return
|
|
412
|
+
const source = value as Record<string, unknown>
|
|
413
|
+
if (
|
|
414
|
+
typeof source.model !== "string" ||
|
|
415
|
+
!source.model.includes("/") ||
|
|
416
|
+
isSystemOneReviewerModel(source.model)
|
|
417
|
+
)
|
|
418
|
+
return
|
|
419
|
+
return {
|
|
420
|
+
model: source.model,
|
|
421
|
+
variant:
|
|
422
|
+
typeof source.variant === "string" && source.variant.length > 0
|
|
423
|
+
? source.variant
|
|
424
|
+
: DEFAULT_CONFIG.variant,
|
|
425
|
+
outputFormat: source.outputFormat === "text" ? "text" : "json_schema",
|
|
426
|
+
timeoutMs: boundedInteger(source.timeoutMs, DEFAULT_CONFIG.timeoutMs, 5_000, 600_000),
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function isValidEscalationReviewer(value: unknown): boolean {
|
|
431
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false
|
|
432
|
+
const source = value as Record<string, unknown>
|
|
433
|
+
if (
|
|
434
|
+
typeof source.model !== "string" ||
|
|
435
|
+
!source.model.includes("/") ||
|
|
436
|
+
isSystemOneReviewerModel(source.model)
|
|
437
|
+
)
|
|
438
|
+
return false
|
|
439
|
+
if (source.variant !== undefined && (typeof source.variant !== "string" || !source.variant))
|
|
440
|
+
return false
|
|
441
|
+
if (
|
|
442
|
+
source.outputFormat !== undefined &&
|
|
443
|
+
source.outputFormat !== "text" &&
|
|
444
|
+
source.outputFormat !== "json_schema"
|
|
445
|
+
)
|
|
446
|
+
return false
|
|
447
|
+
if (
|
|
448
|
+
source.timeoutMs !== undefined &&
|
|
449
|
+
(typeof source.timeoutMs !== "number" || !Number.isInteger(source.timeoutMs))
|
|
450
|
+
)
|
|
451
|
+
return false
|
|
452
|
+
return true
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export function splitModel(model: string): { providerID: string; modelID: string } {
|
|
456
|
+
const slash = model.indexOf("/")
|
|
457
|
+
if (slash <= 0 || slash === model.length - 1) {
|
|
458
|
+
throw new Error(`Invalid reviewer model "${model}"; expected provider/model`)
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
providerID: model.slice(0, slash),
|
|
462
|
+
modelID: model.slice(slash + 1),
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
export function isSystemOneReviewerModel(model: string): boolean {
|
|
467
|
+
let parsed: { providerID: string; modelID: string }
|
|
468
|
+
try {
|
|
469
|
+
parsed = splitModel(model)
|
|
470
|
+
} catch {
|
|
471
|
+
return false
|
|
472
|
+
}
|
|
473
|
+
// Jev uses the typed System One API rather than a chat-session transport.
|
|
474
|
+
return (
|
|
475
|
+
((parsed.providerID === "opencode" || parsed.providerID === "typesafe-ai") &&
|
|
476
|
+
/^jev(?:-|$)/.test(parsed.modelID)) ||
|
|
477
|
+
(parsed.providerID === "commandcode" && parsed.modelID === "typesafe/jev")
|
|
478
|
+
)
|
|
479
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { PermissionRequest } from "../types.ts"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Normalize a raw OpenCode event into a {@link PermissionRequest}.
|
|
5
|
+
*
|
|
6
|
+
* Returns `undefined` for anything that is not a well-formed
|
|
7
|
+
* `permission.asked` event, so callers can ignore irrelevant events without
|
|
8
|
+
* inspecting their shape.
|
|
9
|
+
*/
|
|
10
|
+
export function extractPermissionRequest(event: unknown): PermissionRequest | undefined {
|
|
11
|
+
if (typeof event !== "object" || event === null) return
|
|
12
|
+
const record = event as Record<string, unknown>
|
|
13
|
+
if (record.type !== "permission.asked") return
|
|
14
|
+
const properties = record.properties
|
|
15
|
+
if (typeof properties !== "object" || properties === null) return
|
|
16
|
+
const request = properties as Record<string, unknown>
|
|
17
|
+
if (typeof request.id !== "string" || typeof request.sessionID !== "string") return
|
|
18
|
+
if (typeof request.permission !== "string" || !Array.isArray(request.patterns)) return
|
|
19
|
+
|
|
20
|
+
const patterns = request.patterns.filter((item): item is string => typeof item === "string")
|
|
21
|
+
if (patterns.length !== request.patterns.length) return
|
|
22
|
+
const metadata =
|
|
23
|
+
typeof request.metadata === "object" && request.metadata !== null
|
|
24
|
+
? (request.metadata as Record<string, unknown>)
|
|
25
|
+
: {}
|
|
26
|
+
const always = Array.isArray(request.always)
|
|
27
|
+
? request.always.filter((item): item is string => typeof item === "string")
|
|
28
|
+
: []
|
|
29
|
+
// `always` is parsed for forward compatibility (a future "persist this
|
|
30
|
+
// approval" surface) but is not consumed by the reviewer yet.
|
|
31
|
+
void always
|
|
32
|
+
const tool =
|
|
33
|
+
typeof request.tool === "object" &&
|
|
34
|
+
request.tool !== null &&
|
|
35
|
+
typeof (request.tool as Record<string, unknown>).messageID === "string" &&
|
|
36
|
+
typeof (request.tool as Record<string, unknown>).callID === "string"
|
|
37
|
+
? {
|
|
38
|
+
messageID: (request.tool as Record<string, unknown>).messageID as string,
|
|
39
|
+
callID: (request.tool as Record<string, unknown>).callID as string,
|
|
40
|
+
}
|
|
41
|
+
: undefined
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
id: request.id,
|
|
45
|
+
sessionID: request.sessionID,
|
|
46
|
+
permission: request.permission,
|
|
47
|
+
patterns,
|
|
48
|
+
metadata,
|
|
49
|
+
always,
|
|
50
|
+
...(tool === undefined ? {} : { tool }),
|
|
51
|
+
}
|
|
52
|
+
}
|
package/dist/tui/tui.tsx
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/solid */
|
|
2
|
+
import type { TuiPlugin, TuiPluginApi } from "@opencode-ai/plugin/tui"
|
|
3
|
+
import { createSignal, Show } from "solid-js"
|
|
4
|
+
import { DEFAULT_CONFIG, reviewBudgetMs } from "./config.ts"
|
|
5
|
+
import { loadResolvedConfig } from "./config/loader.ts"
|
|
6
|
+
// Import the normalizer directly. Going through ./runtime.ts would evaluate the
|
|
7
|
+
// whole server engine (coordinator, git/ssh evidence, node:child_process) inside
|
|
8
|
+
// the TUI process for a single unused re-export.
|
|
9
|
+
import { extractPermissionRequest } from "./opencode/event-normalizer.ts"
|
|
10
|
+
import { decodeUiStatus, type ReviewUiStatus } from "./ui-protocol.ts"
|
|
11
|
+
import { ReviewUiState } from "./ui-state.ts"
|
|
12
|
+
import { ReviewOverlay, ReviewResult, SPINNER } from "./ui/components.tsx"
|
|
13
|
+
import { setupTuiV2 } from "./ui/v2.tsx"
|
|
14
|
+
|
|
15
|
+
const REVIEW_MODE = "permission-reviewer"
|
|
16
|
+
|
|
17
|
+
function routeSessionID(api: TuiPluginApi): string | undefined {
|
|
18
|
+
const route = api.route.current
|
|
19
|
+
if (route.name !== "session") return
|
|
20
|
+
const params = "params" in route ? route.params : undefined
|
|
21
|
+
const sessionID = params?.sessionID
|
|
22
|
+
return typeof sessionID === "string" ? sessionID : undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parentSessionID(api: TuiPluginApi, sessionID: string): string | undefined {
|
|
26
|
+
return api.state.session.get(sessionID)?.parentID
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function notifyManual(api: TuiPluginApi, status: ReviewUiStatus): void {
|
|
30
|
+
api.ui.toast({
|
|
31
|
+
variant: "warning",
|
|
32
|
+
title: "Manual review required",
|
|
33
|
+
message:
|
|
34
|
+
status.reason ?? "The reviewer could not decide. This permission now needs your approval.",
|
|
35
|
+
duration: 8_000,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const tui: TuiPlugin = async (api, options) => {
|
|
40
|
+
const config = loadResolvedConfig(options)
|
|
41
|
+
const state = new ReviewUiState({
|
|
42
|
+
model: config.model,
|
|
43
|
+
variant: config.variant,
|
|
44
|
+
timeoutMs: reviewBudgetMs(config),
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
// Signal bumps whenever the UI state changes. Both slot factories read it
|
|
48
|
+
// directly in their bodies, which makes the host re-render each panel:
|
|
49
|
+
// a factory that only returns a component without reading any signal in its
|
|
50
|
+
// own scope renders exactly once at boot and never updates again.
|
|
51
|
+
const [revision, setRevision] = createSignal(0)
|
|
52
|
+
const [frame, setFrame] = createSignal(0)
|
|
53
|
+
const touch = () => {
|
|
54
|
+
syncMode()
|
|
55
|
+
setRevision((value) => value + 1)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const active = () => {
|
|
59
|
+
const sessionID = routeSessionID(api)
|
|
60
|
+
if (!sessionID) return
|
|
61
|
+
return state.activeFor(sessionID, (id) => parentSessionID(api, id))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let popMode: (() => void) | undefined
|
|
65
|
+
const syncMode = () => {
|
|
66
|
+
const status = active()
|
|
67
|
+
const wanted = status?.phase === "reviewing"
|
|
68
|
+
if (wanted && popMode === undefined) {
|
|
69
|
+
try {
|
|
70
|
+
popMode = api.mode.push(REVIEW_MODE)
|
|
71
|
+
} catch {
|
|
72
|
+
// mode.push can throw if the host rejects unknown modes; keep the panel.
|
|
73
|
+
}
|
|
74
|
+
} else if (!wanted && popMode !== undefined) {
|
|
75
|
+
popMode()
|
|
76
|
+
popMode = undefined
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
api.event.on("permission.asked", (event) => {
|
|
81
|
+
const request = extractPermissionRequest(event)
|
|
82
|
+
if (!request) return
|
|
83
|
+
state.asked(request)
|
|
84
|
+
touch()
|
|
85
|
+
})
|
|
86
|
+
api.event.on("permission.replied", (event) => {
|
|
87
|
+
state.replied(event.properties.requestID)
|
|
88
|
+
touch()
|
|
89
|
+
})
|
|
90
|
+
api.event.on("tui.command.execute", (event) => {
|
|
91
|
+
const status = decodeUiStatus(event.properties.command)
|
|
92
|
+
if (!status) return
|
|
93
|
+
if (!state.apply(status)) return
|
|
94
|
+
if (status.phase === "manual") notifyManual(api, status)
|
|
95
|
+
touch()
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
// Keep watchdog and result expiry running even when the UI is hidden.
|
|
99
|
+
const ticker = setInterval(() => {
|
|
100
|
+
if (active()?.phase === "reviewing") setFrame((value) => (value + 1) % SPINNER.length)
|
|
101
|
+
const expired = state.expire()
|
|
102
|
+
const dismissed = state.dismissResults()
|
|
103
|
+
if (expired.length > 0 || dismissed.length > 0) touch()
|
|
104
|
+
}, 250)
|
|
105
|
+
|
|
106
|
+
api.lifecycle.onDispose(() => {
|
|
107
|
+
clearInterval(ticker)
|
|
108
|
+
popMode?.()
|
|
109
|
+
popMode = undefined
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
api.slots.register({
|
|
113
|
+
order: 1_000,
|
|
114
|
+
slots: {
|
|
115
|
+
app() {
|
|
116
|
+
// Load-bearing direct read: it subscribes the slot's render pass to
|
|
117
|
+
// every state transition (touch), so the factory re-runs and renders
|
|
118
|
+
// the current status. The spinner frame is deliberately NOT read here
|
|
119
|
+
// (only inside the panel's text children) so 250ms ticks update those
|
|
120
|
+
// texts without re-running this factory.
|
|
121
|
+
revision()
|
|
122
|
+
const status = active()
|
|
123
|
+
syncMode()
|
|
124
|
+
return (
|
|
125
|
+
<Show when={status?.phase === "reviewing" ? status : undefined} keyed>
|
|
126
|
+
{(current) => (
|
|
127
|
+
<ReviewOverlay theme={() => api.theme.current} status={current} frame={frame} />
|
|
128
|
+
)}
|
|
129
|
+
</Show>
|
|
130
|
+
)
|
|
131
|
+
},
|
|
132
|
+
app_bottom() {
|
|
133
|
+
revision()
|
|
134
|
+
const status = active()
|
|
135
|
+
syncMode()
|
|
136
|
+
return (
|
|
137
|
+
<Show
|
|
138
|
+
when={
|
|
139
|
+
status?.phase === "approved" ||
|
|
140
|
+
status?.phase === "denied" ||
|
|
141
|
+
status?.phase === "unknown"
|
|
142
|
+
? status
|
|
143
|
+
: undefined
|
|
144
|
+
}
|
|
145
|
+
keyed
|
|
146
|
+
>
|
|
147
|
+
{(current) => <ReviewResult theme={() => api.theme.current} status={current} />}
|
|
148
|
+
</Show>
|
|
149
|
+
)
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const module = {
|
|
156
|
+
id: "opencode-permission-reviewer",
|
|
157
|
+
tui,
|
|
158
|
+
setup: setupTuiV2,
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export default module
|
|
162
|
+
export { ReviewUiState, decodeUiStatus, DEFAULT_CONFIG }
|