@nandoblanco/opencode-relay-orchestration 0.0.0-stage → 0.3.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.
- package/CHANGELOG.md +136 -0
- package/LICENSE +21 -0
- package/README.md +312 -2
- package/assets/screenshot-tui.png +0 -0
- package/assets/screenshot.png +0 -0
- package/dist/gui-experimental.cjs +1 -0
- package/package.json +83 -4
- package/src/config.ts +77 -0
- package/src/gui.css +826 -0
- package/src/gui.tsx +394 -0
- package/src/index.ts +1 -0
- package/src/model.ts +58 -0
- package/src/orchestrator.ts +329 -0
- package/src/planner.ts +201 -0
- package/src/report.ts +35 -0
- package/src/rpc.ts +65 -0
- package/src/scope.ts +116 -0
- package/src/server.ts +449 -0
- package/src/store.ts +300 -0
- package/src/tui.ts +413 -0
- package/src/verify.ts +82 -0
- package/src/view.ts +124 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
import { Plugin } from '@opencode/plugin'
|
|
2
|
+
type Context = Plugin.Context
|
|
3
|
+
import { RelayRpc } from './rpc.ts'
|
|
4
|
+
import { createStore, StoreError, validateCheck, type Op, type RecordInfo } from './store.ts'
|
|
5
|
+
import { randomUUID } from 'node:crypto'
|
|
6
|
+
import { mkdir, writeFile } from 'node:fs/promises'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { auditMarkdown } from './report.ts'
|
|
9
|
+
import { effectiveConfig, configSummary, roles, probeKey, type ConfigInput, type SavedConfig, type ConfigReport, type ProbeResult } from './config.ts'
|
|
10
|
+
import { createOrchestrator, cleanTitle as promptTitle, reportSchema, workerApiDenials } from './orchestrator.ts'
|
|
11
|
+
import { Tool } from '@opencode/schema/tool'
|
|
12
|
+
import { preflight, runCheck } from './verify.ts'
|
|
13
|
+
import { registerPlanner, plannerTools } from './planner.ts'
|
|
14
|
+
import { checkScopeViolation } from './scope.ts'
|
|
15
|
+
|
|
16
|
+
export const approveAction = 'relay.approve'
|
|
17
|
+
export const signOffAction = 'relay.signoff'
|
|
18
|
+
export const verifyAction = 'relay.verify'
|
|
19
|
+
export { workerApiDenials, promptTitle }
|
|
20
|
+
export function evaluateApproval(input: { action: string; effect: 'allow' | 'deny' | 'ask'; message?: string; metadata?: Record<string, unknown> }) {
|
|
21
|
+
if (![approveAction, signOffAction, verifyAction].includes(input.action) || input.effect === 'deny') return
|
|
22
|
+
input.effect = 'ask'
|
|
23
|
+
if (input.action === verifyAction) {
|
|
24
|
+
input.message = `Record manual verification for ${promptTitle(String(input.metadata?.checkName ?? 'check'))}, task ${promptTitle(String(input.metadata?.taskTitle ?? 'task'), 40)}? Note: ${promptTitle(String(input.metadata?.note ?? ''), 1000)}. This is not a plugin-run pass.`
|
|
25
|
+
return
|
|
26
|
+
}
|
|
27
|
+
if (input.action === signOffAction) {
|
|
28
|
+
input.message = `Sign off ${promptTitle(String(input.metadata?.title ?? 'record'))}? ${Number(input.metadata?.taskCount) || 0} tasks completed, revision ${Number(input.metadata?.revision) || 0}.`
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
const details = []
|
|
32
|
+
if (input.metadata?.taskCount !== undefined && Number.isFinite(Number(input.metadata.taskCount))) details.push(`${Number(input.metadata.taskCount)} tasks`)
|
|
33
|
+
if (input.metadata?.revision !== undefined && Number.isFinite(Number(input.metadata.revision))) details.push(`revision ${Number(input.metadata.revision)}`)
|
|
34
|
+
input.message = `Approve plan${input.metadata?.title ? ` for ${promptTitle(String(input.metadata.title))}` : ''}?${details.length ? ` ${details.join(', ')}.` : ''}`
|
|
35
|
+
const titles = input.metadata?.taskTitles
|
|
36
|
+
if (Array.isArray(titles) && titles.every(title => typeof title === 'string') && titles.length) {
|
|
37
|
+
const shown = titles.slice(0, 3).map(title => promptTitle(title, 32))
|
|
38
|
+
const more = Math.max(0, Number(input.metadata?.taskCount) - shown.length)
|
|
39
|
+
input.message = input.message.replace(/[?.]$/, '') + `: ${shown.join('; ')}${more ? ` (+${more} more)` : ''}.`
|
|
40
|
+
}
|
|
41
|
+
if (Array.from(input.message).length > 240) input.message = Array.from(input.message).slice(0, 237).join('') + '...'
|
|
42
|
+
const checks = input.metadata?.checks as { name: string; command: string; scope?: string }[] | undefined
|
|
43
|
+
if (checks) input.message += `\nChecks: ${Number(input.metadata?.checkCount) || 0}\n${checks.slice(0, 10).map(check => `${promptTitle(check.name, 120)}${check.scope === 'final' ? ' [final]' : ''}: ${check.command}`).join('\n')}${Number(input.metadata?.checkCount) > checks.length ? `\n+${Number(input.metadata?.checkCount) - checks.length} more` : ''}`
|
|
44
|
+
}
|
|
45
|
+
export async function setup(ctx: Context, adapter = { preflight, runCheck }) {
|
|
46
|
+
const getConfig = async () => effectiveConfig(ctx.options, await ctx.storage.get('relay/config') as SavedConfig | undefined)
|
|
47
|
+
const config = await getConfig()
|
|
48
|
+
const store = createStore(ctx.storage, { directory: ctx.location.directory, projectID: ctx.location.project.id }, config.limits)
|
|
49
|
+
let scopeForSession: ((sessionID: string) => { directory: string; allowedPaths: string[] } | undefined) | undefined
|
|
50
|
+
const hook = await ctx.permission.hook('evaluate', input => {
|
|
51
|
+
const scope = scopeForSession?.(input.sessionID)
|
|
52
|
+
if (scope && input.effect !== 'deny') {
|
|
53
|
+
const violation = checkScopeViolation(scope.directory, input.action, input.resources, scope.allowedPaths)
|
|
54
|
+
if (violation) { input.effect = 'deny'; input.message = violation; return }
|
|
55
|
+
}
|
|
56
|
+
if (input.action === 'relay.configure' && input.effect !== 'deny') { input.effect = 'ask'; input.message = `Save Relay configuration? ${String(input.metadata?.summary ?? '')}`; return }
|
|
57
|
+
evaluateApproval(input)
|
|
58
|
+
})
|
|
59
|
+
const locks = new Set<string>()
|
|
60
|
+
const lockQueues = new Map<string, Promise<void>>()
|
|
61
|
+
const configuring = new Set<string>()
|
|
62
|
+
function lockdown(sessionID: string, active: boolean) {
|
|
63
|
+
const work = (lockQueues.get(sessionID) ?? Promise.resolve()).then(async () => {
|
|
64
|
+
const key = `relay/lockdown/${sessionID}`
|
|
65
|
+
const previous = await ctx.storage.get(key)
|
|
66
|
+
if (previous) locks.add(sessionID)
|
|
67
|
+
const needed = active || configuring.has(sessionID) || (await store.list()).some(record => record.sessionID === sessionID && !['completed', 'cancelled'].includes(record.phase))
|
|
68
|
+
if (needed === locks.has(sessionID)) return
|
|
69
|
+
let session
|
|
70
|
+
try { session = await ctx.session.get({ sessionID }) }
|
|
71
|
+
catch (failure) {
|
|
72
|
+
if (failure && typeof failure === 'object' && '_tag' in failure && failure._tag === 'SessionNotFoundError') {
|
|
73
|
+
locks.delete(sessionID)
|
|
74
|
+
await ctx.storage.remove(key)
|
|
75
|
+
}
|
|
76
|
+
throw failure
|
|
77
|
+
}
|
|
78
|
+
const permissions = [...(session.permissions ?? [])]
|
|
79
|
+
if (needed) {
|
|
80
|
+
// Existing matching denies belong to the user, not this plugin.
|
|
81
|
+
if (permissions.some(rule => rule.action === 'shell' && rule.resource === '*opencode*' && rule.effect === 'deny')) return
|
|
82
|
+
try { await ctx.session.update({ sessionID, permissions: [...permissions, { action: 'shell', resource: '*opencode*', effect: 'deny' }] }) }
|
|
83
|
+
catch (failure) {
|
|
84
|
+
locks.delete(sessionID)
|
|
85
|
+
await ctx.storage.remove(key)
|
|
86
|
+
throw failure
|
|
87
|
+
}
|
|
88
|
+
await ctx.storage.set(key, { owned: true })
|
|
89
|
+
locks.add(sessionID)
|
|
90
|
+
} else {
|
|
91
|
+
const index = permissions.findLastIndex(rule => rule.action === 'shell' && rule.resource === '*opencode*' && rule.effect === 'deny')
|
|
92
|
+
if (index >= 0) permissions.splice(index, 1)
|
|
93
|
+
await ctx.session.update({ sessionID, permissions })
|
|
94
|
+
locks.delete(sessionID)
|
|
95
|
+
await ctx.storage.remove(key)
|
|
96
|
+
}
|
|
97
|
+
}).catch(failure => { console.error('Relay lockdown failed', sessionID, failure) })
|
|
98
|
+
lockQueues.set(sessionID, work)
|
|
99
|
+
return work
|
|
100
|
+
}
|
|
101
|
+
async function configure(input: ConfigInput, sessionID: string) {
|
|
102
|
+
if (configuring.has(sessionID)) throw new Tool.Error({ message: 'A Relay configuration request is already pending in this session.' })
|
|
103
|
+
configuring.add(sessionID)
|
|
104
|
+
try {
|
|
105
|
+
await lockdown(sessionID, true)
|
|
106
|
+
const before = await ctx.storage.get('relay/config') as SavedConfig | undefined
|
|
107
|
+
const saved: SavedConfig = { ...before, ...input, roles: { ...before?.roles, ...input.roles }, limits: { ...before?.limits, ...input.limits }, version: 1, updatedAt: before?.updatedAt ?? 'pending' }
|
|
108
|
+
const summary = `${configSummary(effectiveConfig(ctx.options, saved))}; models ${JSON.stringify(effectiveConfig(ctx.options, saved).models)}`
|
|
109
|
+
try { await ctx.permission.assert({ sessionID, action: 'relay.configure', resources: ['relay-config'], metadata: { summary } }) }
|
|
110
|
+
catch (failure) {
|
|
111
|
+
if (failure && typeof failure === 'object' && '_tag' in failure && (failure._tag === 'Permission.DeclinedError' || failure._tag === 'Tool.Error')) throw new Tool.Error({ message: 'Settings not saved: permission was denied.' })
|
|
112
|
+
throw failure
|
|
113
|
+
}
|
|
114
|
+
if (JSON.stringify(await ctx.storage.get('relay/config')) !== JSON.stringify(before)) throw new Tool.Error({ message: 'Relay configuration changed while approval was pending. Run /relay-configure again to review the current settings.' })
|
|
115
|
+
saved.updatedAt = new Date().toISOString()
|
|
116
|
+
await ctx.storage.set('relay/config', saved)
|
|
117
|
+
const read = await ctx.storage.get('relay/config')
|
|
118
|
+
if (JSON.stringify(read) !== JSON.stringify(saved)) throw new Tool.Error({ message: 'Relay configuration could not be verified after saving.' })
|
|
119
|
+
return `${configSummary(effectiveConfig(ctx.options, saved))}; models ${JSON.stringify(effectiveConfig(ctx.options, saved).models)}`
|
|
120
|
+
} finally {
|
|
121
|
+
configuring.delete(sessionID)
|
|
122
|
+
await lockdown(sessionID, false)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const pending = new Map<string, { token: string; sessionID: string; resource: string; action: string }>()
|
|
126
|
+
const results = new Map<string, NonNullable<RecordInfo['approvalResult']>>()
|
|
127
|
+
const plannerUpdates = new Map<string, Promise<RecordInfo>>()
|
|
128
|
+
async function restorePlanner(record: RecordInfo): Promise<RecordInfo> {
|
|
129
|
+
if (!record.plannerSession || !record.sessionID) return record
|
|
130
|
+
const active = plannerUpdates.get(record.id)
|
|
131
|
+
if (active) {
|
|
132
|
+
const settled = await active
|
|
133
|
+
return ['completed', 'cancelled'].includes(record.phase) && !settled.plannerSession?.tokensAtEnd ? restorePlanner(await store.get(record.id)) : settled
|
|
134
|
+
}
|
|
135
|
+
const work = async () => {
|
|
136
|
+
let current = await store.get(record.id)
|
|
137
|
+
const tracking = current.plannerSession!
|
|
138
|
+
if (!tracking.restoredAt) {
|
|
139
|
+
current = await store.updatePlanner(record.id, planner => { planner.restoredAt = new Date().toISOString() })
|
|
140
|
+
if (tracking.previousModel) try { await ctx.session.switchModel({ sessionID: record.sessionID!, model: tracking.previousModel }) } catch (failure) { console.error('Relay planner model restore failed', record.id, failure) }
|
|
141
|
+
}
|
|
142
|
+
if (['completed', 'cancelled'].includes(current.phase) && !current.plannerSession!.tokensAtEnd) {
|
|
143
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
144
|
+
try {
|
|
145
|
+
const session = await Promise.race([ctx.session.get({ sessionID: record.sessionID! }), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(Error('Planner token capture timed out')), 10000) })])
|
|
146
|
+
const tokens = session.tokens
|
|
147
|
+
current = await store.updatePlanner(record.id, planner => { planner.tokensAtEnd = { input: tokens.input, output: tokens.output, reasoning: tokens.reasoning, cache: { read: tokens.cache.read, write: tokens.cache.write } } })
|
|
148
|
+
} catch (failure) { console.error('Relay planner token capture failed', record.id, failure) }
|
|
149
|
+
finally { clearTimeout(timer) }
|
|
150
|
+
}
|
|
151
|
+
return current
|
|
152
|
+
}
|
|
153
|
+
const pending = work().catch(failure => { console.error('Relay planner lifecycle failed', record.id, failure); return record }).finally(() => plannerUpdates.delete(record.id))
|
|
154
|
+
plannerUpdates.set(record.id, pending)
|
|
155
|
+
return pending
|
|
156
|
+
}
|
|
157
|
+
function snapshot(record: RecordInfo) {
|
|
158
|
+
const key = [...pending.keys()].find(key => key === `${record.id}@${record.revision}` || key === `signoff:${record.id}@${record.revision}` || key.startsWith(`${record.id}@${record.revision}:`))
|
|
159
|
+
return { ...record, ...(key ? { pendingApproval: { key, revision: record.revision } } : {}), ...(results.has(record.id) ? { approvalResult: results.get(record.id) } : {}) }
|
|
160
|
+
}
|
|
161
|
+
const probes = new Set<string>()
|
|
162
|
+
const probeSessions = new Set<string>()
|
|
163
|
+
const imageProbes = new Set<string>()
|
|
164
|
+
const imageErrors = new Map<string, ProbeResult>()
|
|
165
|
+
async function validateConfig(): Promise<ConfigReport> {
|
|
166
|
+
const config = await getConfig()
|
|
167
|
+
const models = await ctx.model.list({})
|
|
168
|
+
const checks: ConfigReport['roles'] = []
|
|
169
|
+
for (const role of roles) {
|
|
170
|
+
const model = config.models[role]
|
|
171
|
+
const found = model ? models.data.find(item => item.id === model.id && item.providerID === model.providerID) : undefined
|
|
172
|
+
const errors = config.errors.filter(message => message.startsWith(`roles.${role}`))
|
|
173
|
+
const variant = Boolean(found && (!model?.variant || found.variants.some(item => item.id === model.variant)))
|
|
174
|
+
if (model) {
|
|
175
|
+
if (!found) errors.push('Model not found')
|
|
176
|
+
else { if (!found.enabled) errors.push('Model is disabled'); if (!variant) errors.push('Variant not found'); if (!found.capabilities.tools) errors.push('Tools are required'); if (role === 'reviewer' && !found.capabilities.input.includes('image')) errors.push('Image input is not declared') }
|
|
177
|
+
}
|
|
178
|
+
const probe = model && role === 'reviewer' ? imageErrors.get(probeKey(model)) ?? await ctx.storage.get(probeKey(model)) as ProbeResult | undefined : undefined
|
|
179
|
+
checks.push({ role, ...(model ? { model } : {}), exists: Boolean(found), enabled: Boolean(found?.enabled), variant, tools: Boolean(found?.capabilities.tools), image: !model ? 'not configured' : role !== 'reviewer' ? 'not required' : probe?.status ?? (found?.capabilities.input.includes('image') ? 'declared' : 'unavailable'), errors, ...(probe ? { probe } : {}) })
|
|
180
|
+
}
|
|
181
|
+
return { roles: checks, errors: config.errors, limits: config.limits, enableProbe: config.enableProbe, widths: config.widths, autoStart: config.autoStart, explorer: config.explorer, brainstormFirst: config.brainstormFirst, source: config.source, summary: configSummary(config) }
|
|
182
|
+
}
|
|
183
|
+
async function validateSession(sessionID: string) {
|
|
184
|
+
let session
|
|
185
|
+
try { session = await ctx.session.get({ sessionID }) } catch { throw new StoreError('invalid_op') }
|
|
186
|
+
if (session.projectID !== ctx.location.project.id || session.location.directory !== ctx.location.directory) throw new StoreError('invalid_op')
|
|
187
|
+
return session
|
|
188
|
+
}
|
|
189
|
+
let registration: { dispose(): Promise<void>; events: { emit(name: 'changed', data: { recordID: string; revision: number }): Promise<void> } }
|
|
190
|
+
const guarded = async (work: () => Promise<unknown>, error: (type: keyof typeof RelayRpc.methods.mutate.errors, message: string, data: object) => unknown) => {
|
|
191
|
+
try { return await work() } catch (failure) {
|
|
192
|
+
if (!(failure instanceof StoreError)) throw failure
|
|
193
|
+
return error(failure.code, failure.message, failure.code === 'stale_revision' ? { currentRevision: failure.currentRevision } : {})
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async function changed(work: Promise<Awaited<ReturnType<typeof store.get>>>) {
|
|
197
|
+
let record = await work
|
|
198
|
+
if (['completed', 'cancelled'].includes(record.phase)) record = await restorePlanner(record)
|
|
199
|
+
if (record.sessionID) await lockdown(record.sessionID, !['completed', 'cancelled'].includes(record.phase))
|
|
200
|
+
try { await registration.events.emit('changed', { recordID: record.id, revision: record.revision }) }
|
|
201
|
+
catch (failure) { console.error('Relay change event failed after persistence', failure) }
|
|
202
|
+
return snapshot(record)
|
|
203
|
+
}
|
|
204
|
+
async function withdraw(record: RecordInfo, key: string) {
|
|
205
|
+
const request = pending.get(key)
|
|
206
|
+
if (!request || !(key.startsWith(`${record.id}@`) || key.startsWith(`signoff:${record.id}@`))) throw new StoreError('invalid_op')
|
|
207
|
+
pending.delete(key)
|
|
208
|
+
results.set(record.id, { revision: Number(key.slice(key.indexOf('@') + 1).split(':')[0]), outcome: 'withdrawn', at: new Date().toISOString() })
|
|
209
|
+
try {
|
|
210
|
+
const requests = await ctx.permission.list({ sessionID: request.sessionID })
|
|
211
|
+
for (const item of requests) if (item.action === request.action && item.resources.length === 1 && item.resources[0] === request.resource) {
|
|
212
|
+
try { await ctx.permission.reply({ sessionID: request.sessionID, requestID: item.id, decision: 'reject' }) }
|
|
213
|
+
catch (failure) { console.error('Relay host approval withdrawal failed', failure) }
|
|
214
|
+
}
|
|
215
|
+
} catch (failure) { console.error('Relay host approval withdrawal failed', failure) }
|
|
216
|
+
return changed(store.get(record.id))
|
|
217
|
+
}
|
|
218
|
+
const orchestrator = createOrchestrator(ctx, store, config, record => changed(Promise.resolve(record)), adapter, getConfig)
|
|
219
|
+
scopeForSession = orchestrator.scopeForSession
|
|
220
|
+
async function mutate(input: { recordID: string; expectedRevision: number; op: Op }) {
|
|
221
|
+
store.limits((await getConfig()).limits)
|
|
222
|
+
const key = [...pending].find(([key, request]) => request.action === approveAction && key.startsWith(`${input.recordID}@`))?.[0]
|
|
223
|
+
if (key && input.op.type !== 'cancel') throw new StoreError('approval_pending')
|
|
224
|
+
if (key && input.op.type === 'cancel') {
|
|
225
|
+
const record = await store.get(input.recordID)
|
|
226
|
+
if (record.revision !== input.expectedRevision) throw new StoreError('stale_revision', record.revision)
|
|
227
|
+
await withdraw(record, key)
|
|
228
|
+
}
|
|
229
|
+
return snapshot(await orchestrator.mutate(input.recordID, input.expectedRevision, input.op))
|
|
230
|
+
}
|
|
231
|
+
async function requestPlan(input: { recordID: string; expectedRevision: number; kind: 'plan'; sessionID?: string }, autoStart = false) {
|
|
232
|
+
const record = await store.get(input.recordID)
|
|
233
|
+
if (record.phase !== 'draft') throw new StoreError('invalid_op')
|
|
234
|
+
if (record.revision !== input.expectedRevision) throw new StoreError('stale_revision', record.revision)
|
|
235
|
+
if (record.sessionID && input.sessionID && record.sessionID !== input.sessionID) throw new StoreError('invalid_op')
|
|
236
|
+
const sessionID = record.sessionID ?? input.sessionID
|
|
237
|
+
if (!sessionID) throw new StoreError('invalid_op')
|
|
238
|
+
await validateSession(sessionID)
|
|
239
|
+
for (const check of record.checks) {
|
|
240
|
+
try { validateCheck(check) }
|
|
241
|
+
catch (failure) {
|
|
242
|
+
if (!(failure instanceof StoreError)) throw failure
|
|
243
|
+
failure.message = `Check "${promptTitle(check.name)}" contains unsupported characters or settings; remove and re-add it.`
|
|
244
|
+
throw failure
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const key = `${record.id}@${input.expectedRevision}`
|
|
248
|
+
if (pending.has(key)) throw new StoreError('approval_pending')
|
|
249
|
+
const token = randomUUID()
|
|
250
|
+
pending.set(key, { token, sessionID, resource: key, action: approveAction })
|
|
251
|
+
// Never race assert against abort: retain the key while the host prompt is open.
|
|
252
|
+
// Once opened, the human answer survives client disconnects unless explicitly withdrawn.
|
|
253
|
+
const waiting = await changed(Promise.resolve(record))
|
|
254
|
+
async function settle() {
|
|
255
|
+
try {
|
|
256
|
+
const approved = await store.approve(input.recordID, input.expectedRevision, async () => {
|
|
257
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
258
|
+
try { await ctx.permission.assert({ sessionID: sessionID!,
|
|
259
|
+
action: approveAction, resources: [`${input.recordID}@${input.expectedRevision}`],
|
|
260
|
+
metadata: { recordID: input.recordID, title: promptTitle(record.title), taskTitles: record.tasks.slice(0, 3).map(task => promptTitle(task.title, 32)), taskCount: record.tasks.length, checks: record.checks.slice(0, 10).map(check => ({ name: promptTitle(check.name, 120), command: check.command, ...(check.scope === 'final' ? { scope: 'final' } : {}) })), checkCount: record.checks.length, revision: input.expectedRevision, kind: input.kind } }) }
|
|
261
|
+
catch (failure) {
|
|
262
|
+
// Exact host tags mean declined or cancelled, not a transport/internal failure.
|
|
263
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
264
|
+
if (failure && typeof failure === 'object' && '_tag' in failure && (failure._tag === 'Tool.Error' || failure._tag === 'Permission.DeclinedError')) throw new StoreError('approval_denied')
|
|
265
|
+
throw failure
|
|
266
|
+
}
|
|
267
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
268
|
+
}, () => { if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn') })
|
|
269
|
+
if (pending.get(key)?.token === token) {
|
|
270
|
+
results.set(record.id, { revision: input.expectedRevision, outcome: 'approved', at: new Date().toISOString() })
|
|
271
|
+
if (autoStart && (await getConfig()).autoStart) {
|
|
272
|
+
try { await orchestrator.mutate(record.id, approved.revision, { type: 'start' }) }
|
|
273
|
+
catch (failure) { console.error('Relay approved plan could not auto-start; start manually after reviewing the current record', record.id, failure) }
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
} catch (failure) {
|
|
277
|
+
if (pending.get(key)?.token === token && failure instanceof StoreError && (failure.code === 'stale_revision' || failure.code === 'approval_denied' || failure.code === 'approval_withdrawn')) {
|
|
278
|
+
results.set(record.id, { revision: failure.code === 'stale_revision' ? failure.currentRevision ?? input.expectedRevision : input.expectedRevision, outcome: failure.code === 'stale_revision' ? 'stale' : failure.code === 'approval_withdrawn' ? 'withdrawn' : 'rejected', at: new Date().toISOString() })
|
|
279
|
+
if (failure.code === 'stale_revision') console.error('Relay plan changed; approval not recorded', key)
|
|
280
|
+
}
|
|
281
|
+
console.error('Relay approval settlement failed', key, failure)
|
|
282
|
+
} finally {
|
|
283
|
+
if (pending.get(key)?.token === token) pending.delete(key)
|
|
284
|
+
try { await changed(store.get(record.id)) }
|
|
285
|
+
catch (failure) { console.error('Relay settlement notification failed', record.id, failure) }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
void settle().catch(failure => console.error('Relay approval settlement failed', key, failure))
|
|
289
|
+
return waiting
|
|
290
|
+
}
|
|
291
|
+
const tool = await ctx.tool.transform(editor => editor.add({ name: 'relay_report', description: 'Report the active Relay worker result exactly once. Does not approve or sign off.', input: reportSchema,
|
|
292
|
+
execute: async (input, context) => {
|
|
293
|
+
try { await orchestrator.report(context.sessionID, input); return { content: 'Relay report recorded. Checks are self-reported and unverified.' } }
|
|
294
|
+
catch (failure) { if (failure instanceof StoreError) throw new Tool.Error({ message: failure.code }); throw failure }
|
|
295
|
+
},
|
|
296
|
+
}))
|
|
297
|
+
registration = await ctx.rpc.register(RelayRpc, {
|
|
298
|
+
exportReport: async (raw, { error }) => guarded(async () => {
|
|
299
|
+
const input = raw as { recordID: string; write?: boolean }
|
|
300
|
+
const record = await store.get(input.recordID)
|
|
301
|
+
if (record.location.projectID !== ctx.location.project.id || record.location.directory !== ctx.location.directory) throw new StoreError('invalid_op')
|
|
302
|
+
const id = record.id.slice(0, 8)
|
|
303
|
+
if (!/^[0-9a-f-]{8}$/.test(id)) throw new StoreError('invalid_op')
|
|
304
|
+
const name = `relay-${id}.md`
|
|
305
|
+
const markdown = auditMarkdown(record, await store.listRuns(record.id), await store.listEvidence(record.id))
|
|
306
|
+
if (input.write) {
|
|
307
|
+
try {
|
|
308
|
+
await mkdir(join(record.location.directory, '.relay', 'reports'), { recursive: true })
|
|
309
|
+
await writeFile(join(record.location.directory, '.relay', 'reports', name), markdown, 'utf8')
|
|
310
|
+
} catch (error) {
|
|
311
|
+
console.error('Relay report write failed', error)
|
|
312
|
+
const failure = new StoreError('invalid_op')
|
|
313
|
+
failure.message = 'Could not write report file.'
|
|
314
|
+
throw failure
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return { name, markdown, ...(input.write ? { path: `.relay/reports/${name}` } : {}) }
|
|
318
|
+
}, error),
|
|
319
|
+
validateConfig: async () => validateConfig(),
|
|
320
|
+
probeImage: async (raw, { error }) => guarded(async () => {
|
|
321
|
+
if (!config.enableProbe) throw new StoreError('invalid_op')
|
|
322
|
+
const input = raw as { parentSessionID: string }
|
|
323
|
+
await validateSession(input.parentSessionID)
|
|
324
|
+
const report = await validateConfig()
|
|
325
|
+
const reviewer = report.roles.find(role => role.role === 'reviewer')!
|
|
326
|
+
if (!reviewer.model || reviewer.errors.length) throw new StoreError('invalid_op')
|
|
327
|
+
const key = probeKey(reviewer.model)
|
|
328
|
+
const cached = await ctx.storage.get(key) as ProbeResult | undefined
|
|
329
|
+
if (cached) return report
|
|
330
|
+
if (imageProbes.has(key)) throw new StoreError('invalid_op')
|
|
331
|
+
imageProbes.add(key)
|
|
332
|
+
let sessionID = ''
|
|
333
|
+
let result: ProbeResult = { status: 'error', sessionID, answer: '', tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, at: new Date().toISOString() }
|
|
334
|
+
try {
|
|
335
|
+
const session = await ctx.session.create({ parentID: input.parentSessionID, title: 'Relay explicit image compatibility probe', model: reviewer.model,
|
|
336
|
+
location: { directory: ctx.location.directory }, permissions: [...['edit', 'write', 'shell', 'subagent', 'question', approveAction, signOffAction, verifyAction, 'relay.configure', ...plannerTools].map(action => ({ action, resource: '*', effect: 'deny' as const })), ...workerApiDenials] })
|
|
337
|
+
sessionID = session.id; result.sessionID = sessionID
|
|
338
|
+
probeSessions.add(sessionID)
|
|
339
|
+
// Fixed red PNG. No user files or environment details leave this probe.
|
|
340
|
+
await ctx.session.prompt({ sessionID, text: 'Identify the solid color in the attached image. Reply with only the color name. Do not use tools.', files: [{ uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', source: { type: 'inline' }, name: 'color.png' }] })
|
|
341
|
+
await ctx.session.wait({ sessionID })
|
|
342
|
+
const messages = await ctx.session.context({ sessionID })
|
|
343
|
+
const answer = messages.filter(message => message.type === 'assistant').flatMap(message => message.content.filter(part => part.type === 'text').map(part => part.text)).join(' ').trim()
|
|
344
|
+
if (!answer) throw new Error('No model answer was produced')
|
|
345
|
+
const info = await ctx.session.get({ sessionID })
|
|
346
|
+
result = { status: answer.replace(/\p{P}/gu, '').trim().toLowerCase() === 'red' ? 'verified' : 'failed', sessionID, answer: Array.from(answer).slice(0, 500).join(''), tokens: { input: info.tokens.input, output: info.tokens.output, reasoning: info.tokens.reasoning, cache: { read: info.tokens.cache.read, write: info.tokens.cache.write } }, at: new Date().toISOString() }
|
|
347
|
+
} catch (failure) {
|
|
348
|
+
console.error('Relay image probe failed', key, failure)
|
|
349
|
+
// Deliberately do not echo exception text: it can contain paths, headers or stacks.
|
|
350
|
+
result = { ...result, status: 'error', answer: sessionID ? 'The host could not complete the image probe. No vision verdict was recorded.' : 'The host could not create the image probe session.' }
|
|
351
|
+
}
|
|
352
|
+
finally { imageProbes.delete(key) }
|
|
353
|
+
if (result.status === 'error') imageErrors.set(key, result)
|
|
354
|
+
else { imageErrors.delete(key); await ctx.storage.set(key, result) }
|
|
355
|
+
return validateConfig()
|
|
356
|
+
}, error),
|
|
357
|
+
getSnapshot: async (raw, { error }) => guarded(async () => snapshot(await store.get((raw as { recordID: string }).recordID)), error),
|
|
358
|
+
listRecords: async (_, { error }) => guarded(async () => (await store.list()).map(snapshot), error),
|
|
359
|
+
createRecord: async (raw, { error }) => guarded(async () => { const input = raw as { title: string; sessionID?: string }; if (input.sessionID) await validateSession(input.sessionID); return changed(store.create(input.title, input.sessionID)) }, error),
|
|
360
|
+
mutate: async (raw, { error }) => guarded(() => mutate(raw as { recordID: string; expectedRevision: number; op: Op }), error),
|
|
361
|
+
listRuns: async (raw, { error }) => guarded(() => store.listRuns((raw as { recordID: string }).recordID), error),
|
|
362
|
+
listEvidence: async (raw, { error }) => guarded(() => store.listEvidence((raw as { id: string }).id), error),
|
|
363
|
+
recordManual: async (raw, { error, signal }) => guarded(async () => {
|
|
364
|
+
const input = raw as { id: string; revision: number; taskID: string; checkID: string; note: string; sessionID?: string }
|
|
365
|
+
const record = await store.get(input.id)
|
|
366
|
+
if (record.sessionID && input.sessionID && record.sessionID !== input.sessionID) throw new StoreError('invalid_op')
|
|
367
|
+
const sessionID = record.sessionID ?? input.sessionID
|
|
368
|
+
if (!sessionID) throw new StoreError('invalid_op')
|
|
369
|
+
await validateSession(sessionID)
|
|
370
|
+
const key = `${input.id}@${input.revision}:${input.taskID}:${input.checkID}`
|
|
371
|
+
if (pending.has(key)) throw new StoreError('approval_pending')
|
|
372
|
+
const token = randomUUID()
|
|
373
|
+
pending.set(key, { token, sessionID, resource: key, action: verifyAction })
|
|
374
|
+
await changed(Promise.resolve(record))
|
|
375
|
+
try {
|
|
376
|
+
return await changed(store.recordManual(input.id, input.revision, input.taskID, input.checkID, input.note, async () => {
|
|
377
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
378
|
+
signal?.throwIfAborted()
|
|
379
|
+
try { await ctx.permission.assert({ sessionID, action: verifyAction, resources: [key], metadata: { checkName: record.checks.find(check => check.id === input.checkID)?.name, taskTitle: record.tasks.find(task => task.id === input.taskID)?.title, note: input.note, revision: input.revision } }) }
|
|
380
|
+
catch (failure) {
|
|
381
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
382
|
+
if (failure && typeof failure === 'object' && '_tag' in failure && (failure._tag === 'Tool.Error' || failure._tag === 'Permission.DeclinedError')) throw new StoreError('approval_denied')
|
|
383
|
+
throw failure
|
|
384
|
+
}
|
|
385
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
386
|
+
}, () => { if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn') }))
|
|
387
|
+
} finally { if (pending.get(key)?.token === token) pending.delete(key); await changed(store.get(record.id)) }
|
|
388
|
+
}, error),
|
|
389
|
+
signOff: async (raw, { error, signal }) => guarded(async () => {
|
|
390
|
+
const input = raw as { recordID: string; expectedRevision: number; sessionID?: string }
|
|
391
|
+
const record = await store.get(input.recordID)
|
|
392
|
+
if (record.sessionID && input.sessionID && record.sessionID !== input.sessionID) throw new StoreError('invalid_op')
|
|
393
|
+
const sessionID = record.sessionID ?? input.sessionID
|
|
394
|
+
if (!sessionID) throw new StoreError('invalid_op')
|
|
395
|
+
await validateSession(sessionID)
|
|
396
|
+
const key = `signoff:${record.id}@${input.expectedRevision}`
|
|
397
|
+
if (pending.has(key)) throw new StoreError('approval_pending')
|
|
398
|
+
const token = randomUUID()
|
|
399
|
+
pending.set(key, { token, sessionID, resource: `${record.id}@${input.expectedRevision}`, action: signOffAction })
|
|
400
|
+
await changed(Promise.resolve(record))
|
|
401
|
+
try {
|
|
402
|
+
return await changed(store.signOff(record.id, input.expectedRevision, async () => {
|
|
403
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
404
|
+
signal?.throwIfAborted()
|
|
405
|
+
try { await ctx.permission.assert({ sessionID, action: signOffAction, resources: [`${record.id}@${input.expectedRevision}`], metadata: { recordID: record.id, title: promptTitle(record.title), taskCount: record.tasks.length, revision: input.expectedRevision } }) }
|
|
406
|
+
catch (failure) {
|
|
407
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
408
|
+
if (failure && typeof failure === 'object' && '_tag' in failure && (failure._tag === 'Tool.Error' || failure._tag === 'Permission.DeclinedError')) throw new StoreError('approval_denied')
|
|
409
|
+
throw failure
|
|
410
|
+
}
|
|
411
|
+
if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn')
|
|
412
|
+
}, () => { if (pending.get(key)?.token !== token) throw new StoreError('approval_withdrawn') }))
|
|
413
|
+
} finally { if (pending.get(key)?.token === token) pending.delete(key); await changed(store.get(record.id)) }
|
|
414
|
+
}, error),
|
|
415
|
+
requestApproval: async (raw, { error }) => guarded(() => requestPlan(raw as { recordID: string; expectedRevision: number; kind: 'plan'; sessionID?: string }), error),
|
|
416
|
+
withdrawApproval: async (raw, { error }) => guarded(async () => {
|
|
417
|
+
const input = raw as { recordID: string; key: string }
|
|
418
|
+
const record = await store.get(input.recordID)
|
|
419
|
+
return withdraw(record, input.key)
|
|
420
|
+
}, error),
|
|
421
|
+
probeWorkerSession: async (raw, { error }) => guarded(async () => {
|
|
422
|
+
const input = raw as { parentSessionID: string; model: { id: string; providerID: string; variant?: string } }
|
|
423
|
+
if (!config.enableProbe) throw new StoreError('invalid_op')
|
|
424
|
+
await validateSession(input.parentSessionID)
|
|
425
|
+
const models = await ctx.model.list({})
|
|
426
|
+
const model = models.data.find(model => model.id === input.model.id && model.providerID === input.model.providerID)
|
|
427
|
+
if (!model || (input.model.variant !== undefined && !model.variants.some(variant => variant.id === input.model.variant))) throw new StoreError('invalid_op')
|
|
428
|
+
if (probes.has(input.parentSessionID)) throw new StoreError('invalid_op')
|
|
429
|
+
probes.add(input.parentSessionID)
|
|
430
|
+
let session
|
|
431
|
+
try {
|
|
432
|
+
session = await ctx.session.create({ parentID: input.parentSessionID, title: 'Relay reviewer compatibility probe', model: input.model,
|
|
433
|
+
location: { directory: ctx.location.directory }, permissions: [
|
|
434
|
+
...['edit', 'write', 'shell', 'subagent', 'question', approveAction, signOffAction, verifyAction, 'relay.configure', ...plannerTools].map(action => ({ action, resource: '*', effect: 'deny' as const })), ...workerApiDenials,
|
|
435
|
+
] })
|
|
436
|
+
} catch (failure) { probes.delete(input.parentSessionID); throw failure }
|
|
437
|
+
probeSessions.add(session.id)
|
|
438
|
+
try { return await ctx.session.get({ sessionID: session.id }) }
|
|
439
|
+
catch { throw new Error(`Probe session ${session.id} was created but could not be read. Inspect that session before retrying.`) }
|
|
440
|
+
}, error),
|
|
441
|
+
})
|
|
442
|
+
const command = await registerPlanner(ctx, { store, snapshot, changed, cancel: (record, cancelReason) => mutate({ recordID: record.id, expectedRevision: record.revision, op: { type: 'cancel', cancelReason } }), config: getConfig, configure, restore: restorePlanner, validateSession, cleanTitle: promptTitle, requestPlan, model: config.models.planner, explorer: config.models.explorer, isWorker: sessionID => orchestrator.isWorker(sessionID) || probeSessions.has(sessionID), pending: id => [...pending].some(([key, value]) => value.action === approveAction && key.startsWith(`${id}@`)) })
|
|
443
|
+
try { await orchestrator.reconcile() } catch (failure) { console.error('Relay startup reconciliation failed', failure) }
|
|
444
|
+
try {
|
|
445
|
+
for (const record of await store.list()) if (record.sessionID && ['completed', 'cancelled'].includes(record.phase) && await ctx.storage.get(`relay/lockdown/${record.sessionID}`)) await lockdown(record.sessionID, false)
|
|
446
|
+
} catch (failure) { console.error('Relay lockdown reconciliation failed', failure) }
|
|
447
|
+
return async () => { await registration.dispose(); await hook.dispose(); await tool.dispose(); await command.dispose() }
|
|
448
|
+
}
|
|
449
|
+
export default Plugin.define({ id: 'opencode-relay-orchestration', setup })
|