@noppu-labs/opencode-permission-reviewer 2.4.1 → 3.0.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 (46) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/NOTICE +14 -6
  5. package/README.md +100 -750
  6. package/SECURITY.md +41 -22
  7. package/dist/explain.js +4932 -3522
  8. package/dist/index.d.ts +520 -513
  9. package/dist/index.js +12595 -9115
  10. package/dist/rpc.js +4 -1
  11. package/dist/tui/config/jsonc.ts +71 -63
  12. package/dist/tui/config/layer-read.ts +120 -0
  13. package/dist/tui/config/loader.ts +61 -513
  14. package/dist/tui/config/risk-policy-clamp.ts +80 -0
  15. package/dist/tui/config/trust-boundary-keys.ts +100 -0
  16. package/dist/tui/config/trust-boundary.ts +135 -0
  17. package/dist/tui/config/trusted-degradation.ts +97 -0
  18. package/dist/tui/config-fields.ts +55 -0
  19. package/dist/tui/config-knobs.ts +119 -0
  20. package/dist/tui/config-policy-rules.ts +86 -0
  21. package/dist/tui/config-risk-policy.ts +59 -0
  22. package/dist/tui/config-rule-condition.ts +150 -0
  23. package/dist/tui/config.ts +61 -430
  24. package/dist/tui/descriptor-io.ts +42 -0
  25. package/dist/tui/is-record.ts +13 -0
  26. package/dist/tui/opencode/event-normalizer.ts +41 -31
  27. package/dist/tui/reviewer-model.ts +87 -0
  28. package/dist/tui/tui.tsx +87 -99
  29. package/dist/tui/types.ts +171 -538
  30. package/dist/tui/ui/components.tsx +32 -136
  31. package/dist/tui/ui/review-connection.ts +32 -0
  32. package/dist/tui/ui/review-feed.ts +131 -0
  33. package/dist/tui/ui/review-overlay.tsx +83 -0
  34. package/dist/tui/ui/review-result.tsx +56 -0
  35. package/dist/tui/ui/review-store.ts +88 -0
  36. package/dist/tui/ui/review-theme.ts +63 -0
  37. package/dist/tui/ui/rpc.ts +5 -2
  38. package/dist/tui/ui/v1-host.ts +39 -0
  39. package/dist/tui/ui/v2.tsx +66 -220
  40. package/dist/tui/ui-protocol.ts +63 -118
  41. package/dist/tui/ui-state.ts +71 -64
  42. package/dist/tui/ui-status-parse.ts +74 -0
  43. package/package.json +18 -17
  44. package/rpc.js +2 -1
  45. package/server.js +2 -2
  46. package/tui.tsx +2 -1
@@ -1,30 +1,31 @@
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
- }
1
+ import {
2
+ isStringArray,
3
+ nonEmptyStringOr,
4
+ optional,
5
+ resolveActorProfiles,
6
+ resolveEscalationMode,
7
+ resolveRepositoryTrust,
8
+ trimmedText,
9
+ } from "./config-fields.ts";
10
+ import {
11
+ CONFIDENCE_FLOORS,
12
+ CONTEXT_BUDGETS,
13
+ integerKnobs,
14
+ LINEAGE_LIMITS,
15
+ numberKnobs,
16
+ REVIEW_TIMEOUT,
17
+ reviewBudgetKnob,
18
+ } from "./config-knobs.ts";
19
+ import { resolvePolicyRules } from "./config-policy-rules.ts";
20
+ import {
21
+ DEFAULT_RISK_POLICY,
22
+ resolveRiskPolicy,
23
+ } from "./config-risk-policy.ts";
24
+ import {
25
+ isProviderModelId,
26
+ resolveEscalationReviewer,
27
+ } from "./reviewer-model.ts";
28
+ import type { ReviewerConfig } from "./types.ts";
28
29
 
29
30
  export const DEFAULT_CONFIG: ReviewerConfig = {
30
31
  model: "openai/gpt-6-luna",
@@ -53,427 +54,57 @@ export const DEFAULT_CONFIG: ReviewerConfig = {
53
54
  repositoryTrust: "unknown",
54
55
  policyRules: [],
55
56
  askDecisions: true,
56
- }
57
+ };
57
58
 
58
59
  /** Total deadline for a review, shared by the server and TUI watchdog. */
59
60
  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
61
+ return config.reviewBudgetMs ?? config.timeoutMs * 2 + 60_000;
116
62
  }
117
63
 
118
- const VALID_AUTH = new Set(["high", "medium", "low", "unknown"])
64
+ type FlagKey = "retainReviewSessions" | "audit" | "debug" | "askDecisions";
119
65
 
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
66
+ function flag(source: Record<string, unknown>, key: FlagKey): boolean {
67
+ const value = source[key];
68
+ return typeof value === "boolean" ? value : DEFAULT_CONFIG[key];
150
69
  }
151
70
 
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.
71
+ export function resolveConfig(
72
+ options: Record<string, unknown> | undefined,
73
+ ): ReviewerConfig {
74
+ const source = options ?? {};
75
+ // Key order is part of the output: the server hashes the serialized config.
190
76
  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("/")
77
+ model: isProviderModelId(source.model)
304
78
  ? 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,
79
+ : DEFAULT_CONFIG.model,
80
+ variant: nonEmptyStringOr(source.variant, DEFAULT_CONFIG.variant),
81
+ outputFormat: source.outputFormat === "text" ? "text" : "json_schema",
82
+ ...optional(
83
+ "escalationReviewer",
84
+ resolveEscalationReviewer(source.escalationReviewer, DEFAULT_CONFIG),
379
85
  ),
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,
86
+ ...integerKnobs(source, REVIEW_TIMEOUT, DEFAULT_CONFIG),
87
+ ...reviewBudgetKnob(source),
88
+ ...integerKnobs(source, CONTEXT_BUDGETS, DEFAULT_CONFIG),
89
+ ...numberKnobs(source, CONFIDENCE_FLOORS, DEFAULT_CONFIG),
90
+ retainReviewSessions: flag(source, "retainReviewSessions"),
91
+ audit: flag(source, "audit"),
92
+ ...optional("auditPath", trimmedText(source.auditPath)),
93
+ ...optional("policy", trimmedText(source.policy)),
94
+ debug: flag(source, "debug"),
388
95
  enforcementMode:
389
- source.enforcementMode === "enforce" ? "enforce" : DEFAULT_CONFIG.enforcementMode,
96
+ source.enforcementMode === "enforce"
97
+ ? "enforce"
98
+ : DEFAULT_CONFIG.enforcementMode,
390
99
  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
- ),
100
+ ...integerKnobs(source, LINEAGE_LIMITS, DEFAULT_CONFIG),
398
101
  actorProfiles: resolveActorProfiles(source.actorProfiles),
399
102
  riskPolicy: resolveRiskPolicy(source.riskPolicy),
400
103
  repositoryTrust: resolveRepositoryTrust(source.repositoryTrust),
401
104
  policyRules: resolvePolicyRules(source.policyRules),
402
- askDecisions:
403
- typeof source.askDecisions === "boolean" ? source.askDecisions : DEFAULT_CONFIG.askDecisions,
105
+ askDecisions: flag(source, "askDecisions"),
404
106
  ...(isStringArray(source.configDegraded) && source.configDegraded.length > 0
405
107
  ? { configDegraded: source.configDegraded }
406
108
  : {}),
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
- )
109
+ };
479
110
  }
@@ -0,0 +1,42 @@
1
+ // Each open flag is 0 where the platform lacks it, so OR-ing it in is a no-op
2
+ // there rather than an error.
3
+ import { closeSync, constants as fsConstants, readSync } from "node:fs";
4
+
5
+ export const O_RDONLY: number =
6
+ typeof fsConstants.O_RDONLY === "number" ? fsConstants.O_RDONLY : 0;
7
+ export const O_WRONLY: number =
8
+ typeof fsConstants.O_WRONLY === "number" ? fsConstants.O_WRONLY : 0;
9
+ export const O_CREAT: number =
10
+ typeof fsConstants.O_CREAT === "number" ? fsConstants.O_CREAT : 0;
11
+ export const O_APPEND: number =
12
+ typeof fsConstants.O_APPEND === "number" ? fsConstants.O_APPEND : 0;
13
+ export const O_NOFOLLOW: number =
14
+ typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0;
15
+ export const O_NONBLOCK: number =
16
+ typeof fsConstants.O_NONBLOCK === "number" ? fsConstants.O_NONBLOCK : 0;
17
+
18
+ /** Read up to `length` bytes starting at file position `offset` into the
19
+ * start of `buffer`, stopping early at end of file. Returns the bytes read. */
20
+ export function readFully(
21
+ fd: number,
22
+ buffer: Buffer,
23
+ length: number,
24
+ offset: number,
25
+ ): number {
26
+ let read = 0;
27
+ while (read < length) {
28
+ const count = readSync(fd, buffer, read, length - read, offset + read);
29
+ if (count === 0) break;
30
+ read += count;
31
+ }
32
+ return read;
33
+ }
34
+
35
+ export function closeQuietly(fd: number | undefined): void {
36
+ if (fd === undefined) return;
37
+ try {
38
+ closeSync(fd);
39
+ } catch {
40
+ // Best effort; the IO already succeeded or failed on its own.
41
+ }
42
+ }
@@ -0,0 +1,13 @@
1
+ /** A non-null object that is not an array. */
2
+ export function isRecord(value: unknown): value is Record<string, unknown> {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+
6
+ /** A non-null object, arrays included. */
7
+ export function asObjectLike(
8
+ value: unknown,
9
+ ): Record<string, unknown> | undefined {
10
+ return typeof value === "object" && value !== null
11
+ ? (value as Record<string, unknown>)
12
+ : undefined;
13
+ }
@@ -1,4 +1,25 @@
1
- import type { PermissionRequest } from "../types.ts"
1
+ import { asObjectLike } from "../is-record.ts";
2
+ import type { PermissionRequest } from "../types.ts";
3
+
4
+ type UnknownRecord = Record<string, unknown>;
5
+
6
+ function strings(items: unknown[]): string[] {
7
+ return items.filter((item): item is string => typeof item === "string");
8
+ }
9
+
10
+ /** The `properties` record of a `permission.asked` event, if it has one. */
11
+ function askedProperties(event: unknown): UnknownRecord | undefined {
12
+ const record = asObjectLike(event);
13
+ if (record?.type !== "permission.asked") return;
14
+ return asObjectLike(record.properties);
15
+ }
16
+
17
+ function toolReference(value: unknown): PermissionRequest["tool"] {
18
+ const tool = asObjectLike(value);
19
+ if (typeof tool?.messageID !== "string" || typeof tool.callID !== "string")
20
+ return undefined;
21
+ return { messageID: tool.messageID, callID: tool.callID };
22
+ }
2
23
 
3
24
  /**
4
25
  * Normalize a raw OpenCode event into a {@link PermissionRequest}.
@@ -7,38 +28,27 @@ import type { PermissionRequest } from "../types.ts"
7
28
  * `permission.asked` event, so callers can ignore irrelevant events without
8
29
  * inspecting their shape.
9
30
  */
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
31
+ export function extractPermissionRequest(
32
+ event: unknown,
33
+ ): PermissionRequest | undefined {
34
+ const request = askedProperties(event);
35
+ if (!request) return;
36
+ if (typeof request.id !== "string" || typeof request.sessionID !== "string")
37
+ return;
38
+ if (
39
+ typeof request.permission !== "string" ||
40
+ !Array.isArray(request.patterns)
41
+ )
42
+ return;
19
43
 
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
- : []
44
+ const patterns = strings(request.patterns);
45
+ if (patterns.length !== request.patterns.length) return;
46
+ const metadata = asObjectLike(request.metadata) ?? {};
47
+ const always = Array.isArray(request.always) ? strings(request.always) : [];
29
48
  // `always` is parsed for forward compatibility (a future "persist this
30
49
  // 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
50
+ void always;
51
+ const tool = toolReference(request.tool);
42
52
 
43
53
  return {
44
54
  id: request.id,
@@ -48,5 +58,5 @@ export function extractPermissionRequest(event: unknown): PermissionRequest | un
48
58
  metadata,
49
59
  always,
50
60
  ...(tool === undefined ? {} : { tool }),
51
- }
61
+ };
52
62
  }