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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +174 -1
  2. package/LICENSE +21 -201
  3. package/LICENSE-APACHE +201 -0
  4. package/MIGRATION.md +2 -1
  5. package/NOTICE +14 -6
  6. package/README.md +109 -787
  7. package/SECURITY.md +41 -22
  8. package/dist/explain.d.ts +3 -4
  9. package/dist/explain.js +9708 -4298
  10. package/dist/index.d.ts +1096 -987
  11. package/dist/index.js +18646 -10575
  12. package/dist/rpc.d.ts +38 -38
  13. package/dist/rpc.js +30 -18
  14. package/dist/tui/config/jsonc.ts +71 -63
  15. package/dist/tui/config/layer-read.ts +120 -0
  16. package/dist/tui/config/loader.ts +73 -512
  17. package/dist/tui/config/risk-policy-clamp.ts +80 -0
  18. package/dist/tui/config/trust-boundary-keys.ts +102 -0
  19. package/dist/tui/config/trust-boundary.ts +148 -0
  20. package/dist/tui/config/trusted-degradation.ts +97 -0
  21. package/dist/tui/config-fields.ts +75 -0
  22. package/dist/tui/config-knobs.ts +119 -0
  23. package/dist/tui/config-policy-rules.ts +86 -0
  24. package/dist/tui/config-risk-policy.ts +59 -0
  25. package/dist/tui/config-rule-condition.ts +150 -0
  26. package/dist/tui/config.ts +72 -431
  27. package/dist/tui/descriptor-io.ts +42 -0
  28. package/dist/tui/failure-kind.ts +28 -0
  29. package/dist/tui/is-record.ts +13 -0
  30. package/dist/tui/opencode/event-normalizer.ts +41 -31
  31. package/dist/tui/reviewer-model.ts +87 -0
  32. package/dist/tui/system-one-routing.ts +110 -0
  33. package/dist/tui/tui.tsx +97 -99
  34. package/dist/tui/types.ts +206 -596
  35. package/dist/tui/ui/action-fit.ts +161 -0
  36. package/dist/tui/ui/action-spans.tsx +60 -0
  37. package/dist/tui/ui/attribution.ts +113 -0
  38. package/dist/tui/ui/components.tsx +69 -137
  39. package/dist/tui/ui/config-notices.ts +137 -0
  40. package/dist/tui/ui/fit-parts.ts +76 -0
  41. package/dist/tui/ui/manual-toast.ts +87 -0
  42. package/dist/tui/ui/review-connection.ts +32 -0
  43. package/dist/tui/ui/review-feed.ts +156 -0
  44. package/dist/tui/ui/review-overlay.tsx +111 -0
  45. package/dist/tui/ui/review-result.tsx +74 -0
  46. package/dist/tui/ui/review-store.ts +88 -0
  47. package/dist/tui/ui/review-theme.ts +70 -0
  48. package/dist/tui/ui/rpc.ts +5 -2
  49. package/dist/tui/ui/v1-host.ts +66 -0
  50. package/dist/tui/ui/v2.tsx +82 -220
  51. package/dist/tui/ui-protocol.ts +112 -124
  52. package/dist/tui/ui-state.ts +86 -64
  53. package/dist/tui/ui-status-extras.ts +165 -0
  54. package/dist/tui/ui-status-parse.ts +132 -0
  55. package/dist/tui/ui-text-elide.ts +89 -0
  56. package/package.json +24 -23
  57. package/rpc.js +2 -1
  58. package/server.js +2 -2
  59. package/tui.tsx +2 -1
@@ -1,30 +1,33 @@
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
+ systemOneRoutingFields,
9
+ trimmedText,
10
+ } from "./config-fields.ts";
11
+ import {
12
+ CONFIDENCE_FLOORS,
13
+ CONTEXT_BUDGETS,
14
+ integerKnobs,
15
+ LINEAGE_LIMITS,
16
+ numberKnobs,
17
+ REVIEW_TIMEOUT,
18
+ reviewBudgetKnob,
19
+ } from "./config-knobs.ts";
20
+ import { resolvePolicyRules } from "./config-policy-rules.ts";
21
+ import {
22
+ DEFAULT_RISK_POLICY,
23
+ resolveRiskPolicy,
24
+ } from "./config-risk-policy.ts";
25
+ import {
26
+ isProviderModelId,
27
+ resolveEscalationReviewer,
28
+ } from "./reviewer-model.ts";
29
+ import { withSystemOneRoutingWarnings } from "./system-one-routing.ts";
30
+ import type { ReviewerConfig } from "./types.ts";
28
31
 
29
32
  export const DEFAULT_CONFIG: ReviewerConfig = {
30
33
  model: "openai/gpt-6-luna",
@@ -41,6 +44,8 @@ export const DEFAULT_CONFIG: ReviewerConfig = {
41
44
  confidenceThreshold: 0.7,
42
45
  systemOneConfidenceThreshold: 0.4,
43
46
  systemOneReasoningThreshold: 0.38,
47
+ systemOneEscalation: "standard",
48
+ systemOneDenialReview: false,
44
49
  retainReviewSessions: false,
45
50
  audit: true,
46
51
  debug: false,
@@ -53,427 +58,63 @@ export const DEFAULT_CONFIG: ReviewerConfig = {
53
58
  repositoryTrust: "unknown",
54
59
  policyRules: [],
55
60
  askDecisions: true,
56
- }
61
+ };
57
62
 
58
63
  /** Total deadline for a review, shared by the server and TUI watchdog. */
59
64
  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
65
+ const escalationMs = config.escalationReviewer?.timeoutMs ?? config.timeoutMs;
66
+ return (
67
+ config.reviewBudgetMs ??
68
+ config.timeoutMs + Math.max(config.timeoutMs, escalationMs) + 60_000
69
+ );
217
70
  }
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
71
 
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
- }
72
+ type FlagKey = "retainReviewSessions" | "audit" | "debug" | "askDecisions";
286
73
 
287
- function isStringArray(value: unknown): value is string[] {
288
- return Array.isArray(value) && value.every((v) => typeof v === "string")
74
+ function flag(source: Record<string, unknown>, key: FlagKey): boolean {
75
+ const value = source[key];
76
+ return typeof value === "boolean" ? value : DEFAULT_CONFIG[key];
289
77
  }
290
78
 
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("/")
79
+ export function resolveConfig(
80
+ options: Record<string, unknown> | undefined,
81
+ ): ReviewerConfig {
82
+ const source = options ?? {};
83
+ // Key order is part of the output: the server hashes the serialized config.
84
+ const resolved: ReviewerConfig = {
85
+ model: isProviderModelId(source.model)
304
86
  ? 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,
87
+ : DEFAULT_CONFIG.model,
88
+ variant: nonEmptyStringOr(source.variant, DEFAULT_CONFIG.variant),
89
+ outputFormat: source.outputFormat === "text" ? "text" : "json_schema",
90
+ ...optional(
91
+ "escalationReviewer",
92
+ resolveEscalationReviewer(source.escalationReviewer, DEFAULT_CONFIG),
379
93
  ),
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,
94
+ ...integerKnobs(source, REVIEW_TIMEOUT, DEFAULT_CONFIG),
95
+ ...reviewBudgetKnob(source),
96
+ ...integerKnobs(source, CONTEXT_BUDGETS, DEFAULT_CONFIG),
97
+ ...numberKnobs(source, CONFIDENCE_FLOORS, DEFAULT_CONFIG),
98
+ ...systemOneRoutingFields(source),
99
+ retainReviewSessions: flag(source, "retainReviewSessions"),
100
+ audit: flag(source, "audit"),
101
+ ...optional("auditPath", trimmedText(source.auditPath)),
102
+ ...optional("policy", trimmedText(source.policy)),
103
+ debug: flag(source, "debug"),
388
104
  enforcementMode:
389
- source.enforcementMode === "enforce" ? "enforce" : DEFAULT_CONFIG.enforcementMode,
105
+ source.enforcementMode === "enforce"
106
+ ? "enforce"
107
+ : DEFAULT_CONFIG.enforcementMode,
390
108
  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
- ),
109
+ ...integerKnobs(source, LINEAGE_LIMITS, DEFAULT_CONFIG),
398
110
  actorProfiles: resolveActorProfiles(source.actorProfiles),
399
111
  riskPolicy: resolveRiskPolicy(source.riskPolicy),
400
112
  repositoryTrust: resolveRepositoryTrust(source.repositoryTrust),
401
113
  policyRules: resolvePolicyRules(source.policyRules),
402
- askDecisions:
403
- typeof source.askDecisions === "boolean" ? source.askDecisions : DEFAULT_CONFIG.askDecisions,
114
+ askDecisions: flag(source, "askDecisions"),
404
115
  ...(isStringArray(source.configDegraded) && source.configDegraded.length > 0
405
116
  ? { configDegraded: source.configDegraded }
406
117
  : {}),
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
- )
118
+ };
119
+ return withSystemOneRoutingWarnings(resolved, source);
479
120
  }
@@ -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,28 @@
1
+ // Reads back the error name that formatFailureReason ("<phase> failed
2
+ // (<Name>…): …") puts in a failure-safe reason, as a short word to show.
3
+
4
+ const FAILED_NAME = /\bfailed \(([A-Za-z]+)/;
5
+ const TIMED_OUT = /\btimed out\b/i;
6
+ /** The TypeSafe SDK errors Jev's invoker throws, as the short words the TUI shows. */
7
+ const SDK_KINDS = new Map([
8
+ ["APIConnectionError", "transport"],
9
+ ["APIUserAbortError", "abort"],
10
+ ["AuthenticationError", "auth"],
11
+ ["PermissionDeniedError", "auth"],
12
+ ["RateLimitError", "rate-limit"],
13
+ ["InternalServerError", "server"],
14
+ ["BadRequestError", "bad-request"],
15
+ ["UnprocessableEntityError", "bad-request"],
16
+ ["NotFoundError", "not-found"],
17
+ ]);
18
+
19
+ /** "timeout" for a timeout, a short word for a known SDK error, else the
20
+ * error name without its "Error" suffix in lower case ("error" for a bare
21
+ * Error); undefined when `reason` names no failure. */
22
+ export function failureKind(reason: string): string | undefined {
23
+ const name = FAILED_NAME.exec(reason)?.[1];
24
+ if (name === undefined) return;
25
+ if (name === "TimeoutError" || TIMED_OUT.test(reason)) return "timeout";
26
+ if (name === "Error") return "error";
27
+ return SDK_KINDS.get(name) ?? name.replace(/Error$/, "").toLowerCase();
28
+ }
@@ -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
+ }