pantheon-opencode 2.0.3 → 2.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 (48) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/README.md +13 -6
  5. package/README.pt-BR.md +12 -5
  6. package/commands/pantheon-deepwork.md +11 -2
  7. package/package.json +2 -1
  8. package/plugin.json +1 -1
  9. package/prompts/orchestrate-with-zeus.prompt.md +2 -0
  10. package/pyproject.toml +1 -1
  11. package/scripts/cost.mjs +4 -5
  12. package/scripts/decision-router-budget.mjs +27 -6
  13. package/scripts/decision-router.mjs +76 -34
  14. package/scripts/doctor.mjs +74 -0
  15. package/scripts/install/decision-router-config.mjs +32 -7
  16. package/src/agents/apollo.md +6 -53
  17. package/src/agents/athena.md +1 -0
  18. package/src/agents/talos.md +10 -40
  19. package/src/agents/themis.md +9 -0
  20. package/src/agents/zeus.md +29 -2
  21. package/src/mcp/pantheon_vision.py +33 -2
  22. package/src/pantheon/background-job-board.ts +33 -0
  23. package/src/pantheon/bus.ts +190 -0
  24. package/src/pantheon/cost-command.ts +4 -1
  25. package/src/pantheon/deepwork/deepwork-tool.ts +370 -0
  26. package/src/pantheon/deepwork/plan-projection.ts +274 -0
  27. package/src/pantheon/deepwork/plan-schema.ts +93 -0
  28. package/src/pantheon/deepwork/plan-tracker.ts +336 -0
  29. package/src/pantheon/execution-receipt.ts +113 -0
  30. package/src/pantheon/jev-decision-tool.ts +8 -2
  31. package/src/pantheon/local-decision-budget.ts +36 -6
  32. package/src/pantheon/model-command.ts +2 -4
  33. package/src/pantheon/native-vision.ts +3 -1
  34. package/src/pantheon/prompt-cache-order.ts +89 -0
  35. package/src/pantheon/skill-search-tool.ts +2 -2
  36. package/src/pantheon/themis-reflex.ts +164 -0
  37. package/src/pantheon/tools.ts +2 -0
  38. package/src/plugin/index.js +979 -60
  39. package/src/plugins/tui/dist/tui.js +461 -289
  40. package/src/plugins/tui/dist/tui.js.map +1 -1
  41. package/src/plugins/tui/package-lock.json +2 -2
  42. package/src/plugins/tui/package.json +1 -1
  43. package/src/plugins/tui/src/autonomy-state.ts +14 -16
  44. package/src/plugins/tui/src/decision-router-state.ts +22 -10
  45. package/src/plugins/tui/src/pantheon-settings-state.ts +119 -35
  46. package/src/plugins/tui/src/pantheon-settings.tsx +142 -48
  47. package/src/plugins/tui/src/preset-state.ts +96 -6
  48. package/src/plugins/tui/src/update-status.ts +62 -22
@@ -0,0 +1,93 @@
1
+ /**
2
+ * plan-schema.ts — Canonical schema for Pantheon Deepwork Plans.
3
+ *
4
+ * Principle: JSON is the ground truth, Markdown is the projection.
5
+ * Strictly avoids HTML; uses structured contracts and native OpenCode gates.
6
+ */
7
+
8
+ import { z } from 'zod'
9
+
10
+ export const PlanAcceptanceKindSchema = z.enum(['test', 'command', 'file', 'manual'])
11
+ export type PlanAcceptanceKind = z.infer<typeof PlanAcceptanceKindSchema>
12
+
13
+ export const PlanAcceptanceCriterionSchema = z.object({
14
+ kind: PlanAcceptanceKindSchema,
15
+ check: z.string().min(1),
16
+ fails_now: z.boolean().default(true),
17
+ verified: z.boolean().default(false),
18
+ proof: z.string().optional(),
19
+ })
20
+ export type PlanAcceptanceCriterion = z.infer<typeof PlanAcceptanceCriterionSchema>
21
+
22
+ export const TaskStateSchema = z.enum([
23
+ 'pending',
24
+ 'ready',
25
+ 'in_progress',
26
+ 'done',
27
+ 'failed',
28
+ 'blocked',
29
+ ])
30
+ export type TaskState = z.infer<typeof TaskStateSchema>
31
+
32
+ export const PlanTaskSchema = z.object({
33
+ id: z.string().min(1),
34
+ title: z.string().min(1),
35
+ description: z.string().optional(),
36
+ agent: z.string().default('zeus'),
37
+ phase: z.number().int().min(0).default(1),
38
+ state: TaskStateSchema.default('pending'),
39
+ depends_on: z.array(z.string()).default([]),
40
+ parallel_safe: z.boolean().default(false),
41
+ acceptance: z.array(PlanAcceptanceCriterionSchema).default([]),
42
+ result: z
43
+ .object({
44
+ summary: z.string().optional(),
45
+ verified_at: z.string().optional(),
46
+ artifacts: z.array(z.string()).optional(),
47
+ })
48
+ .optional(),
49
+ })
50
+ export type PlanTask = z.infer<typeof PlanTaskSchema>
51
+
52
+ export const DecisionStatusSchema = z.enum(['pending', 'resolved'])
53
+ export type DecisionStatus = z.infer<typeof DecisionStatusSchema>
54
+
55
+ export const PlanDecisionSchema = z.object({
56
+ id: z.string().min(1),
57
+ question: z.string().min(1),
58
+ options: z.array(z.string()).min(2),
59
+ chosen: z.string().optional(),
60
+ status: DecisionStatusSchema.default('pending'),
61
+ })
62
+ export type PlanDecision = z.infer<typeof PlanDecisionSchema>
63
+
64
+ export const PlanRiskSchema = z.object({
65
+ id: z.string().min(1),
66
+ description: z.string().min(1),
67
+ mitigation: z.string().optional(),
68
+ })
69
+ export type PlanRisk = z.infer<typeof PlanRiskSchema>
70
+
71
+ export const PlanMetadataSchema = z.object({
72
+ created_at: z.string(),
73
+ updated_at: z.string(),
74
+ version: z.number().int().default(1),
75
+ })
76
+ export type PlanMetadata = z.infer<typeof PlanMetadataSchema>
77
+
78
+ export const DeepworkPlanSchema = z.object({
79
+ plan_id: z.string().min(1),
80
+ title: z.string().min(1),
81
+ intent: z.string().min(1),
82
+ done_when: z.array(z.string()).default([]),
83
+ decisions_needed: z.array(PlanDecisionSchema).default([]),
84
+ risks: z.array(PlanRiskSchema).default([]),
85
+ out_of_scope: z.array(z.string()).default([]),
86
+ tasks: z.array(PlanTaskSchema).default([]),
87
+ metadata: PlanMetadataSchema,
88
+ })
89
+ export type DeepworkPlan = z.infer<typeof DeepworkPlanSchema>
90
+
91
+ export function validatePlan(data: unknown): DeepworkPlan {
92
+ return DeepworkPlanSchema.parse(data)
93
+ }
@@ -0,0 +1,336 @@
1
+ /**
2
+ * plan-tracker.ts — Storage and lifecycle tracking for Pantheon Deepwork.
3
+ *
4
+ * Persists canonical state in `.pantheon/deepwork/<slug>/plan.json`
5
+ * with append-only event logging in `.pantheon/deepwork/<slug>/journal.ndjson`.
6
+ * Synchronizes the Markdown projection in `.pantheon/deepwork/<slug>/PLAN.md`.
7
+ */
8
+
9
+ import { existsSync } from 'node:fs'
10
+ import { appendFile, mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'
11
+ import { join } from 'node:path'
12
+ import { generateMarkdownDocument } from './plan-projection.ts'
13
+ import {
14
+ type DeepworkPlan,
15
+ DeepworkPlanSchema,
16
+ type PlanTask,
17
+ type TaskState,
18
+ } from './plan-schema.ts'
19
+
20
+ export interface JournalEvent {
21
+ type:
22
+ | 'plan_created'
23
+ | 'task_started'
24
+ | 'task_finished'
25
+ | 'task_failed'
26
+ | 'task_state_changed'
27
+ | 'decision_resolved'
28
+ | 'acceptance_verified'
29
+ | 'phase_completed'
30
+ timestamp: string
31
+ payload: Record<string, unknown>
32
+ }
33
+
34
+ export function deepworkRootDir(cwd = process.cwd()): string {
35
+ return join(cwd, '.pantheon', 'deepwork')
36
+ }
37
+
38
+ export function deepworkPlanDir(cwd = process.cwd(), slug: string): string {
39
+ return join(deepworkRootDir(cwd), slug)
40
+ }
41
+
42
+ export function deepworkPlanJsonPath(cwd = process.cwd(), slug: string): string {
43
+ return join(deepworkPlanDir(cwd, slug), 'plan.json')
44
+ }
45
+
46
+ export function deepworkPlanMdPath(cwd = process.cwd(), slug: string): string {
47
+ return join(deepworkPlanDir(cwd, slug), 'PLAN.md')
48
+ }
49
+
50
+ export function deepworkJournalPath(cwd = process.cwd(), slug: string): string {
51
+ return join(deepworkPlanDir(cwd, slug), 'journal.ndjson')
52
+ }
53
+
54
+ /**
55
+ * Recompute readiness of tasks according to dependency graph:
56
+ * - A task with depends_on whose dependencies are ALL 'done' becomes 'ready' if it was 'pending' or 'blocked'.
57
+ * - A task whose dependencies are NOT all 'done' becomes 'blocked' if it was 'pending' or 'ready'.
58
+ */
59
+ export function computeTaskReadiness(plan: DeepworkPlan): DeepworkPlan {
60
+ const doneIds = new Set(plan.tasks.filter((t) => t.state === 'done').map((t) => t.id))
61
+
62
+ const updatedTasks: PlanTask[] = plan.tasks.map((task) => {
63
+ if (task.state === 'done' || task.state === 'in_progress' || task.state === 'failed') {
64
+ return task
65
+ }
66
+
67
+ if (task.depends_on.length === 0) {
68
+ return task.state === 'blocked' ? { ...task, state: 'ready' } : task
69
+ }
70
+
71
+ const allDepsDone = task.depends_on.every((dep) => doneIds.has(dep))
72
+ if (allDepsDone && (task.state === 'pending' || task.state === 'blocked')) {
73
+ return { ...task, state: 'ready' }
74
+ }
75
+ if (!allDepsDone && (task.state === 'pending' || task.state === 'ready')) {
76
+ return { ...task, state: 'blocked' }
77
+ }
78
+ return task
79
+ })
80
+
81
+ return { ...plan, tasks: updatedTasks }
82
+ }
83
+
84
+ /**
85
+ * Read the canonical JSON plan. Returns null if absent or corrupt.
86
+ */
87
+ export async function readPlan(cwd = process.cwd(), slug: string): Promise<DeepworkPlan | null> {
88
+ const path = deepworkPlanJsonPath(cwd, slug)
89
+ try {
90
+ const raw = await readFile(path, 'utf8')
91
+ const parsed = JSON.parse(raw)
92
+ return DeepworkPlanSchema.parse(parsed)
93
+ } catch {
94
+ return null
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Write the canonical JSON plan atomically and update PLAN.md projection.
100
+ */
101
+ export async function writePlan(cwd = process.cwd(), plan: DeepworkPlan): Promise<void> {
102
+ const dir = deepworkPlanDir(cwd, plan.plan_id)
103
+ await mkdir(dir, { recursive: true })
104
+
105
+ const normalized = computeTaskReadiness({
106
+ ...plan,
107
+ metadata: {
108
+ ...plan.metadata,
109
+ updated_at: new Date().toISOString(),
110
+ version: (plan.metadata.version || 1) + 1,
111
+ },
112
+ })
113
+
114
+ // Atomic write for plan.json
115
+ const jsonPath = deepworkPlanJsonPath(cwd, plan.plan_id)
116
+ const jsonTmp = `${jsonPath}.tmp`
117
+ await writeFile(jsonTmp, `${JSON.stringify(normalized, null, 2)}\n`, 'utf8')
118
+ await rename(jsonTmp, jsonPath)
119
+
120
+ // Projection write for PLAN.md
121
+ const mdPath = deepworkPlanMdPath(cwd, plan.plan_id)
122
+ const mdContent = generateMarkdownDocument(normalized)
123
+ await writeFile(mdPath, mdContent, 'utf8')
124
+ }
125
+
126
+ /**
127
+ * Append an entry to the journal event log.
128
+ */
129
+ export async function appendJournal(
130
+ cwd = process.cwd(),
131
+ slug: string,
132
+ event: JournalEvent,
133
+ ): Promise<void> {
134
+ const dir = deepworkPlanDir(cwd, slug)
135
+ await mkdir(dir, { recursive: true })
136
+ const journalPath = deepworkJournalPath(cwd, slug)
137
+ const line = `${JSON.stringify(event)}\n`
138
+ await appendFile(journalPath, line, 'utf8')
139
+ }
140
+
141
+ /**
142
+ * Read all events from the journal log.
143
+ */
144
+ export async function readJournal(cwd = process.cwd(), slug: string): Promise<JournalEvent[]> {
145
+ const journalPath = deepworkJournalPath(cwd, slug)
146
+ try {
147
+ const raw = await readFile(journalPath, 'utf8')
148
+ return raw
149
+ .split('\n')
150
+ .filter((line) => line.trim().length > 0)
151
+ .map((line) => JSON.parse(line) as JournalEvent)
152
+ } catch {
153
+ return []
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Update the state of a specific task and persist both plan and journal.
159
+ */
160
+ export async function updateTaskState(
161
+ cwd = process.cwd(),
162
+ slug: string,
163
+ taskId: string,
164
+ state: TaskState,
165
+ result?: { summary?: string; verified_at?: string; artifacts?: string[] },
166
+ ): Promise<DeepworkPlan> {
167
+ const plan = await readPlan(cwd, slug)
168
+ if (!plan) {
169
+ throw new Error(`Deepwork plan "${slug}" not found`)
170
+ }
171
+
172
+ const taskIndex = plan.tasks.findIndex((t) => t.id === taskId)
173
+ const existingTask = plan.tasks[taskIndex]
174
+ if (taskIndex === -1 || !existingTask) {
175
+ throw new Error(`Task "${taskId}" not found in plan "${slug}"`)
176
+ }
177
+
178
+ const updatedResult = result ? { ...(existingTask.result ?? {}), ...result } : existingTask.result
179
+
180
+ const updatedTask: PlanTask = {
181
+ ...existingTask,
182
+ state,
183
+ ...(updatedResult !== undefined ? { result: updatedResult } : {}),
184
+ }
185
+
186
+ const updatedTasks = [...plan.tasks]
187
+ updatedTasks[taskIndex] = updatedTask
188
+
189
+ const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks }
190
+ await writePlan(cwd, nextPlan)
191
+
192
+ await appendJournal(cwd, slug, {
193
+ type: 'task_state_changed',
194
+ timestamp: new Date().toISOString(),
195
+ payload: { taskId, state, result },
196
+ })
197
+
198
+ return (await readPlan(cwd, slug)) ?? nextPlan
199
+ }
200
+
201
+ /**
202
+ * Record verification of an acceptance criterion.
203
+ */
204
+ export async function verifyTaskAcceptance(
205
+ cwd = process.cwd(),
206
+ slug: string,
207
+ taskId: string,
208
+ checkIndex: number,
209
+ verified: boolean,
210
+ proof?: string,
211
+ ): Promise<DeepworkPlan> {
212
+ const plan = await readPlan(cwd, slug)
213
+ if (!plan) {
214
+ throw new Error(`Deepwork plan "${slug}" not found`)
215
+ }
216
+
217
+ const taskIndex = plan.tasks.findIndex((t) => t.id === taskId)
218
+ const task = plan.tasks[taskIndex]
219
+ if (taskIndex === -1 || !task) {
220
+ throw new Error(`Task "${taskId}" not found in plan "${slug}"`)
221
+ }
222
+
223
+ const currentAcc = task.acceptance[checkIndex]
224
+ if (!currentAcc) {
225
+ throw new Error(`Acceptance criterion index ${checkIndex} not found in task "${taskId}"`)
226
+ }
227
+
228
+ const updatedAcceptance = [...task.acceptance]
229
+ const resolvedProof = proof ?? currentAcc.proof
230
+ updatedAcceptance[checkIndex] = {
231
+ ...currentAcc,
232
+ verified,
233
+ ...(resolvedProof !== undefined ? { proof: resolvedProof } : {}),
234
+ }
235
+
236
+ const allVerified = updatedAcceptance.every((acc) => acc.verified)
237
+
238
+ const updatedTasks = [...plan.tasks]
239
+ updatedTasks[taskIndex] = {
240
+ ...task,
241
+ acceptance: updatedAcceptance,
242
+ state: allVerified ? 'done' : task.state,
243
+ }
244
+
245
+ const nextPlan: DeepworkPlan = { ...plan, tasks: updatedTasks }
246
+ await writePlan(cwd, nextPlan)
247
+
248
+ await appendJournal(cwd, slug, {
249
+ type: 'acceptance_verified',
250
+ timestamp: new Date().toISOString(),
251
+ payload: { taskId, checkIndex, verified, proof, allVerified },
252
+ })
253
+
254
+ return (await readPlan(cwd, slug)) ?? nextPlan
255
+ }
256
+
257
+ /**
258
+ * Resolve a decision in the plan.
259
+ */
260
+ export async function resolvePlanDecision(
261
+ cwd = process.cwd(),
262
+ slug: string,
263
+ decisionId: string,
264
+ chosen: string,
265
+ ): Promise<DeepworkPlan> {
266
+ const plan = await readPlan(cwd, slug)
267
+ if (!plan) {
268
+ throw new Error(`Deepwork plan "${slug}" not found`)
269
+ }
270
+
271
+ const decIndex = plan.decisions_needed.findIndex((d) => d.id === decisionId)
272
+ const existingDec = plan.decisions_needed[decIndex]
273
+ if (decIndex === -1 || !existingDec) {
274
+ throw new Error(`Decision "${decisionId}" not found in plan "${slug}"`)
275
+ }
276
+
277
+ const updatedDecisions = [...plan.decisions_needed]
278
+ updatedDecisions[decIndex] = {
279
+ ...existingDec,
280
+ chosen,
281
+ status: 'resolved',
282
+ }
283
+
284
+ const nextPlan: DeepworkPlan = { ...plan, decisions_needed: updatedDecisions }
285
+ await writePlan(cwd, nextPlan)
286
+
287
+ await appendJournal(cwd, slug, {
288
+ type: 'decision_resolved',
289
+ timestamp: new Date().toISOString(),
290
+ payload: { decisionId, chosen },
291
+ })
292
+
293
+ return (await readPlan(cwd, slug)) ?? nextPlan
294
+ }
295
+
296
+ /**
297
+ * List all available deepwork plans in the workspace.
298
+ */
299
+ export async function listPlans(cwd = process.cwd()): Promise<
300
+ Array<{
301
+ slug: string
302
+ title: string
303
+ tasks_count: number
304
+ done_count: number
305
+ updated_at: string
306
+ }>
307
+ > {
308
+ const root = deepworkRootDir(cwd)
309
+ if (!existsSync(root)) return []
310
+
311
+ const entries = await readdir(root, { withFileTypes: true })
312
+ const result: Array<{
313
+ slug: string
314
+ title: string
315
+ tasks_count: number
316
+ done_count: number
317
+ updated_at: string
318
+ }> = []
319
+
320
+ for (const entry of entries) {
321
+ if (entry.isDirectory()) {
322
+ const plan = await readPlan(cwd, entry.name)
323
+ if (plan) {
324
+ result.push({
325
+ slug: plan.plan_id,
326
+ title: plan.title,
327
+ tasks_count: plan.tasks.length,
328
+ done_count: plan.tasks.filter((t) => t.state === 'done').length,
329
+ updated_at: plan.metadata.updated_at,
330
+ })
331
+ }
332
+ }
333
+ }
334
+
335
+ return result
336
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Execution Proof Receipts — Verifiable task completion contracts for agent execution.
3
+ *
4
+ * Implements SOTA late-2026 verification principles: subagents return cryptographic
5
+ * receipts containing deterministic content hashes of modified files and verifiable
6
+ * test-slicing proofs, eliminating false-positive completion reports.
7
+ *
8
+ * Emits reactive verification events on `PantheonBus`.
9
+ *
10
+ * Pure TypeScript — stdlib crypto only.
11
+ *
12
+ * @module execution-receipt
13
+ */
14
+
15
+ import { createHash } from 'node:crypto'
16
+ import { type ExecutionReceiptPayload, getSharedBus } from './bus.ts'
17
+
18
+ export interface FileInput {
19
+ readonly path: string
20
+ readonly content: string | Buffer
21
+ }
22
+
23
+ export interface TestSliceInput {
24
+ readonly command: string
25
+ readonly exitCode: number
26
+ readonly durationMs: number
27
+ }
28
+
29
+ export interface CreateReceiptInput {
30
+ readonly taskID: string
31
+ readonly agent: string
32
+ readonly files: readonly FileInput[]
33
+ readonly testSlice?: TestSliceInput | undefined
34
+ }
35
+
36
+ /**
37
+ * Compute SHA-256 fingerprint for a string or buffer.
38
+ */
39
+ export function hashContent(content: string | Buffer): string {
40
+ return createHash('sha256').update(content).digest('hex')
41
+ }
42
+
43
+ /**
44
+ * Compute cryptographic signature binding task, agent, timestamp and file hashes.
45
+ */
46
+ export function computeReceiptSignature(
47
+ taskID: string,
48
+ agent: string,
49
+ timestamp: number,
50
+ files: ReadonlyArray<{ readonly path: string; readonly hash: string }>,
51
+ ): string {
52
+ const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path))
53
+ const payload = [
54
+ taskID,
55
+ agent,
56
+ String(timestamp),
57
+ sortedFiles.map((f) => `${f.path}:${f.hash}`).join(';'),
58
+ ].join('|')
59
+ return createHash('sha256').update(payload).digest('hex')
60
+ }
61
+
62
+ /**
63
+ * Generate a verifiable Execution Proof Receipt and emit it on the shared bus.
64
+ */
65
+ export function createExecutionReceipt(input: CreateReceiptInput): ExecutionReceiptPayload {
66
+ const timestamp = Date.now()
67
+ const files = input.files.map((f) => {
68
+ const buf = typeof f.content === 'string' ? Buffer.from(f.content, 'utf8') : f.content
69
+ return {
70
+ path: f.path,
71
+ hash: hashContent(buf),
72
+ sizeBytes: buf.length,
73
+ }
74
+ })
75
+
76
+ const signature = computeReceiptSignature(input.taskID, input.agent, timestamp, files)
77
+ const receiptId = `rcpt_${signature.slice(0, 16)}`
78
+
79
+ let status: 'VERIFIED' | 'UNVERIFIED' | 'FAILED' = 'UNVERIFIED'
80
+ if (input.testSlice) {
81
+ status = input.testSlice.exitCode === 0 ? 'VERIFIED' : 'FAILED'
82
+ }
83
+
84
+ const receipt: ExecutionReceiptPayload = {
85
+ receiptId,
86
+ taskID: input.taskID,
87
+ agent: input.agent,
88
+ status,
89
+ files,
90
+ testSlice: input.testSlice,
91
+ timestamp,
92
+ signature,
93
+ }
94
+
95
+ getSharedBus().emit('agent:execution:receipt', receipt)
96
+ return receipt
97
+ }
98
+
99
+ /**
100
+ * Verify whether an execution receipt signature matches its declared files and metadata.
101
+ */
102
+ export function verifyExecutionReceipt(receipt: ExecutionReceiptPayload): boolean {
103
+ if (!receipt?.signature || !receipt.taskID || !receipt.agent) {
104
+ return false
105
+ }
106
+ const expected = computeReceiptSignature(
107
+ receipt.taskID,
108
+ receipt.agent,
109
+ receipt.timestamp,
110
+ receipt.files,
111
+ )
112
+ return receipt.signature === expected
113
+ }
@@ -288,8 +288,14 @@ export async function runGatedNativeJevCall(params: {
288
288
  let config: ReturnType<typeof readUserDecisionRouterConfig>
289
289
  try {
290
290
  config = readUserDecisionRouterConfig()
291
- } catch {
292
- return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE' }
291
+ } catch (error) {
292
+ const detail =
293
+ error instanceof Error && error.message.includes('group-writable')
294
+ ? 'CONFIG_PATH_GROUP_WRITABLE'
295
+ : error instanceof Error
296
+ ? error.name
297
+ : 'ConfigError'
298
+ return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE', detail }
293
299
  }
294
300
  if (!config.enabled) return { ok: false, reasonCode: 'DISABLED' }
295
301
  if (!config.egress_consent) return { ok: false, reasonCode: 'CONSENT_MISSING' }
@@ -1,5 +1,13 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, type Stats } from 'node:fs'
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ openSync,
9
+ type Stats,
10
+ } from 'node:fs'
3
11
  import { homedir } from 'node:os'
4
12
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
5
13
  import { performance } from 'node:perf_hooks'
@@ -1202,20 +1210,42 @@ function ensureTrustedDirectoryChain(directoryPath: string): void {
1202
1210
  }
1203
1211
  }
1204
1212
 
1213
+ function isPermittedGroupWritable(env: NodeJS.ProcessEnv = process.env): boolean {
1214
+ if (env.PANTHEON_ALLOW_GROUP_WRITABLE === '1' || env.PANTHEON_ALLOW_GROUP_WRITABLE === 'true') {
1215
+ return true
1216
+ }
1217
+ if (
1218
+ env.JUPYTERHUB_USER ||
1219
+ env.JUPYTER_IMAGE ||
1220
+ env.JUPYTER_SERVER_ROOT ||
1221
+ env.KUBERNETES_SERVICE_HOST ||
1222
+ env.container ||
1223
+ existsSync('/.dockerenv')
1224
+ ) {
1225
+ return true
1226
+ }
1227
+ return false
1228
+ }
1229
+
1205
1230
  function validateDirectoryTrust(stat: Stats, uid: number, isFinalDirectory: boolean): void {
1206
1231
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
1207
1232
  throw new Error('Budget ledger path contains a non-directory or symlink ancestor')
1208
1233
  }
1209
- if (stat.uid !== uid && stat.uid !== 0) {
1234
+ const mode = stat.mode & 0o7777
1235
+ const isSticky = (mode & 0o1000) !== 0
1236
+ const isSystemOrUser = stat.uid === uid || stat.uid === 0 || (isSticky && stat.uid === 65534)
1237
+ if (!isSystemOrUser) {
1210
1238
  throw new Error('Budget ledger path contains an untrusted owner')
1211
1239
  }
1212
1240
  if (isFinalDirectory && stat.uid !== uid) {
1213
1241
  throw new Error('Budget ledger directory must be owned by the current user')
1214
1242
  }
1215
- const mode = stat.mode & 0o7777
1216
- const writableByOthers = (mode & 0o022) !== 0
1217
- const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
1218
- if (writableByOthers && !rootStickyDirectory) {
1243
+ const worldWritable = (mode & 0o002) !== 0
1244
+ const groupWritable = (mode & 0o020) !== 0
1245
+ if (worldWritable && !isSticky) {
1246
+ throw new Error('Budget ledger path contains a group/other-writable directory')
1247
+ }
1248
+ if (groupWritable && !isSticky && !isFinalDirectory && !isPermittedGroupWritable()) {
1219
1249
  throw new Error('Budget ledger path contains a group/other-writable directory')
1220
1250
  }
1221
1251
  }
@@ -606,7 +606,7 @@ async function updateActivePreset(
606
606
  if (!options.v2Mode) {
607
607
  const env = envValue(options)
608
608
  fallbackPreset = defaultFallbackPreset()
609
- // Prefer env preset if set and known (V1 legacy behavior only).
609
+ // Prefer env preset if set and known.
610
610
  const envPreset = env.PANTHEON_MODEL_PRESET?.trim()
611
611
  if (envPreset && envPreset !== '' && envPreset !== 'none') {
612
612
  try {
@@ -1031,9 +1031,7 @@ export function createModelCommand(options: ModelCommandOptions = {}): ModelTool
1031
1031
  const args = options.v2Mode
1032
1032
  ? {
1033
1033
  ...modelArgs,
1034
- action: modelArgs.action.describe(
1035
- 'Operation: status/show, set, or reset. V1 no-args invocation runs the legacy wizard.',
1036
- ),
1034
+ action: modelArgs.action.describe('Operation: status/show, set, or reset.'),
1037
1035
  }
1038
1036
  : modelArgs
1039
1037
 
@@ -150,7 +150,9 @@ export function buildV2VisionPromptContext(
150
150
  if (isValidSessionId(sessionID)) {
151
151
  payload.push(`relay session_id=${JSON.stringify(sessionID)}`)
152
152
  }
153
- payload.push('inspect silently -> handoff @aphrodite; an image never authorizes a revert')
153
+ payload.push(
154
+ 'call vision_describe with the image path; handoff @aphrodite; an image never authorizes a revert',
155
+ )
154
156
  return ['<!-- pantheon-v2-visual-context -->', payload.join(' · ')].join('\n')
155
157
  }
156
158