@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/src/rpc.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { Rpc } from '@opencode/plugin/rpc'
2
+ import type { RecordInfo, Op, RunInfo, Evidence } from './model.ts'
3
+ import type { ConfigReport } from './config.ts'
4
+
5
+ const string = { type: 'string', minLength: 1 } as const
6
+ const integer = { type: 'integer', minimum: 1 } as const
7
+ const object = (properties: Record<string, object>, required = Object.keys(properties)) => ({ type: 'object' as const, properties, required, additionalProperties: false })
8
+ const owner = object({ role: { enum: ['planner', 'builder', 'reviewer'] }, sessionID: { ...string, maxLength: 200 } }, ['role'])
9
+ const check = object({ id: { ...string, maxLength: 200 }, name: { ...string, maxLength: 120 }, adapter: { enum: ['command', 'playwright'] }, command: { ...string, maxLength: 160 }, policy: { enum: ['automated-required', 'manual-allowed', 'not-applicable'] }, scope: { enum: ['task', 'final'] }, reason: { ...string, maxLength: 500 }, screenshotDir: string, timeoutMs: { ...integer, maximum: 1800000 } }, ['id', 'name', 'adapter', 'command', 'policy'])
10
+ const storedCheck = { ...check, properties: { ...check.properties, command: { ...string, maxLength: 1000 } } }
11
+ const model = object({ providerID: string, id: string, variant: string }, ['providerID', 'id'])
12
+ const tokens = object({ input: { type: 'number' }, output: { type: 'number' }, reasoning: { type: 'number' }, cache: object({ read: { type: 'number' }, write: { type: 'number' } }) })
13
+ const evidence = object({ id: string, recordID: string, taskID: string, checkID: string, buildRunID: string, result: { enum: ['passed', 'failed', 'unverified', 'manually verified'] }, source: { enum: ['adapter', 'permission-assert'] }, reason: string, note: { ...string, maxLength: 1000 }, exitCode: { type: 'integer' }, output: { type: 'string', maxLength: 4000 }, screenshots: { type: 'array', items: object({ path: string, sha256: string, bytes: { type: 'number', minimum: 0 } }) }, startedAt: { type: 'number' }, endedAt: { type: 'number' }, durationMs: { type: 'number', minimum: 0 } }, ['id', 'recordID', 'taskID', 'checkID', 'buildRunID', 'result', 'source', 'screenshots', 'startedAt', 'endedAt', 'durationMs'])
14
+ const record = object({ schemaVersion: { const: 3 }, id: string, revision: integer, planRevision: integer, phase: { enum: ['draft', 'approved', 'running', 'interrupted', 'completed', 'cancelled'] }, interruptReason: { ...string, maxLength: 500 }, title: string,
15
+ location: object({ directory: string, projectID: string }), sessionID: string, createdAt: string, updatedAt: string,
16
+ pendingApproval: object({ key: string, revision: integer }),
17
+ cancelReason: { ...string, maxLength: 500 },
18
+ plannerSession: object({ previousModel: model, model, tokensAtStart: tokens, tokensAtEnd: tokens, restoredAt: string }, ['tokensAtStart']),
19
+ approvalResult: object({ revision: integer, outcome: { enum: ['approved', 'rejected', 'stale', 'withdrawn'] }, at: string }),
20
+ tasks: { type: 'array', items: object({ id: string, title: string, status: { enum: ['pending', 'running', 'blocked', 'awaiting_approval', 'completed'] }, owner, fixCycles: { type: 'integer', minimum: 0 }, allowedPaths: { type: 'array', items: { ...string, maxLength: 200 }, maxItems: 20 }, updatedAt: string }, ['id', 'title', 'status', 'fixCycles', 'updatedAt']) },
21
+ approvals: { type: 'array', items: object({ kind: { const: 'plan' }, revision: integer, planRevision: integer, approvedAt: string, source: { const: 'permission-assert' } }) },
22
+ checks: { type: 'array', items: storedCheck },
23
+ }, ['schemaVersion', 'id', 'revision', 'planRevision', 'phase', 'title', 'location', 'createdAt', 'updatedAt', 'tasks', 'approvals', 'checks'])
24
+ const errors = { stale_revision: object({ currentRevision: integer }), not_found: object({}), approval_denied: object({}), approval_withdrawn: object({}), approval_required: object({}), invalid_op: object({}), approval_pending: object({}), storage_inconsistent: object({}), limit_exceeded: object({}), verification_incomplete: object({}) }
25
+ const probe = object({ status: { enum: ['verified', 'failed', 'error'] }, sessionID: { type: 'string' }, answer: { type: 'string' }, tokens, at: string })
26
+ const buildReport = object({ outcome: { enum: ['done', 'blocked'] }, summary: { type: 'string' }, checks: { type: 'array', items: object({ command: { type: 'string' }, result: { enum: ['passed', 'failed'] } }) } })
27
+ const reviewReport = object({ verdict: { enum: ['approve', 'changes'] }, summary: { type: 'string' }, findings: { type: 'array', items: object({ severity: { enum: ['major', 'minor'] }, text: { type: 'string' } }) }, inspected: { type: 'array', items: { type: 'string' } } }, ['verdict', 'summary', 'findings'])
28
+ const run = object({ id: string, recordID: string, taskID: string, stage: { enum: ['build', 'review'] }, role: { enum: ['builder', 'reviewer'] }, model, sessionID: string, attempt: integer, status: { enum: ['active', 'reported', 'failed', 'interrupted', 'cancelled'] }, report: { oneOf: [buildReport, reviewReport] }, startedAt: string, endedAt: string, durationMs: { type: 'number', minimum: 0 }, tokens, evidenceIDs: { type: 'array', items: string } }, ['id', 'recordID', 'taskID', 'stage', 'role', 'model', 'sessionID', 'attempt', 'status', 'startedAt'])
29
+ const report = object({ roles: { type: 'array', items: object({ role: { enum: ['planner', 'builder', 'reviewer', 'explorer'] }, model, exists: { type: 'boolean' }, enabled: { type: 'boolean' }, variant: { type: 'boolean' }, tools: { type: 'boolean' }, image: { enum: ['not configured', 'not required', 'unavailable', 'declared', 'verified', 'failed', 'error'] }, errors: { type: 'array', items: string }, probe }, ['role', 'exists', 'enabled', 'variant', 'tools', 'image', 'errors']) }, errors: { type: 'array', items: string }, limits: object({ maxRunningTasks: integer, maxFixCycles: { type: 'integer', minimum: 0 } }), enableProbe: { type: 'boolean' } })
30
+ export const RelayRpc = Rpc.define({
31
+ id: 'opencode-relay-orchestration',
32
+ methods: {
33
+ exportReport: { input: object({ recordID: string, write: { type: 'boolean' } }, ['recordID']), output: object({ name: string, markdown: { type: 'string' }, path: string }, ['name', 'markdown']), errors },
34
+ validateConfig: { input: object({}), output: { ...report, properties: { ...report.properties, widths: { type: 'array', items: integer }, autoStart: { type: 'boolean' }, explorer: { type: 'boolean' }, brainstormFirst: { type: 'boolean' }, source: string, summary: string } }, errors },
35
+ probeImage: { input: object({ parentSessionID: string }), output: report, errors },
36
+ getSnapshot: { input: object({ recordID: string }), output: record, errors },
37
+ createRecord: { input: object({ title: string, sessionID: string }, ['title']), output: record, errors },
38
+ mutate: { input: object({ recordID: string, expectedRevision: integer, op: { oneOf: [object({ type: { const: 'addCheck' }, check }), object({ type: { const: 'removeCheck' }, checkID: string }), object({ type: { const: 'addTask' }, title: string, allowedPaths: { type: 'array', items: { ...string, maxLength: 200 }, maxItems: 20 } }, ['type', 'title']), object({ type: { const: 'setTaskStatus' }, taskID: string, status: { enum: ['pending', 'running', 'blocked', 'awaiting_approval', 'completed'] } }), object({ type: { const: 'assignTask' }, taskID: string, owner }), ...['start', 'resume', 'complete', 'cancel'].map(type => object({ type: { const: type } })), object({ type: { const: 'interrupt' }, reason: { ...string, maxLength: 500 } })] } }), output: record, errors },
39
+ requestApproval: { input: object({ recordID: string, expectedRevision: integer, kind: { const: 'plan' }, sessionID: string }, ['recordID', 'expectedRevision', 'kind']), output: record, errors },
40
+ withdrawApproval: { input: object({ recordID: string, key: string }), output: record, errors },
41
+ listRecords: { input: object({}), output: { type: 'array', items: record }, errors },
42
+ listRuns: { input: object({ recordID: string }), output: { type: 'array', items: run }, errors },
43
+ listEvidence: { input: object({ id: string }), output: { type: 'array', items: evidence }, errors },
44
+ recordManual: { input: object({ id: string, revision: integer, taskID: string, checkID: string, note: { ...string, maxLength: 1000 }, sessionID: string }, ['id', 'revision', 'taskID', 'checkID', 'note']), output: record, errors },
45
+ signOff: { input: object({ recordID: string, expectedRevision: integer, sessionID: string }, ['recordID', 'expectedRevision']), output: record, errors },
46
+ probeWorkerSession: { input: object({ parentSessionID: string, model: object({ providerID: string, id: string, variant: string }, ['providerID', 'id']) }), output: { type: 'object' }, errors },
47
+ },
48
+ events: { changed: { schema: object({ recordID: string, revision: integer }) } },
49
+ })
50
+ // JSON-schema inference is unknown in SDK 2.3.2. This explicit contract mirrors the schemas.
51
+ export interface RelayApi {
52
+ exportReport(input: { recordID: string; write?: boolean }, options?: object): Promise<{ name: string; markdown: string; path?: string }>
53
+ validateConfig(input: object, options?: object): Promise<ConfigReport>
54
+ probeImage(input: { parentSessionID: string }, options?: object): Promise<ConfigReport>
55
+ getSnapshot(input: { recordID: string }, options?: object): Promise<RecordInfo>
56
+ createRecord(input: { title: string; sessionID?: string }, options?: object): Promise<RecordInfo>
57
+ mutate(input: { recordID: string; expectedRevision: number; op: Op }, options?: object): Promise<RecordInfo>
58
+ requestApproval(input: { recordID: string; expectedRevision: number; kind: 'plan'; sessionID?: string }, options?: object): Promise<RecordInfo>
59
+ withdrawApproval(input: { recordID: string; key: string }, options?: object): Promise<RecordInfo>
60
+ listRecords(input: object, options?: object): Promise<RecordInfo[]>
61
+ listRuns(input: { recordID: string }, options?: object): Promise<RunInfo[]>
62
+ listEvidence(input: { id: string }, options?: object): Promise<Evidence[]>
63
+ recordManual(input: { id: string; revision: number; taskID: string; checkID: string; note: string; sessionID?: string }, options?: object): Promise<RecordInfo>
64
+ signOff(input: { recordID: string; expectedRevision: number; sessionID?: string }, options?: object): Promise<RecordInfo>
65
+ }
package/src/scope.ts ADDED
@@ -0,0 +1,116 @@
1
+ export const MAX_ALLOWED_PATHS = 20
2
+ export const MAX_ALLOWED_PATH_LENGTH = 200
3
+ export const EDIT_ACTIONS = new Set(['edit', 'write', 'patch', 'apply_patch', 'multiedit'])
4
+
5
+ const invalidControl = /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\u{e0000}-\u{e007f}]/u
6
+
7
+ function collapseSegments(parts: string[]): string[] | undefined {
8
+ const stack: string[] = []
9
+ for (const part of parts) {
10
+ if (!part || part === '.') continue
11
+ if (part === '..') {
12
+ if (!stack.length) return undefined
13
+ stack.pop()
14
+ continue
15
+ }
16
+ stack.push(part)
17
+ }
18
+ return stack
19
+ }
20
+
21
+ function normalizeAbsolute(raw: string): { root: string; segments: string[] } | undefined {
22
+ let path = raw.replace(/\\/g, '/')
23
+ if (/^file:\/\//i.test(path)) {
24
+ path = path.slice(7)
25
+ if (/^\/[A-Za-z]:\//.test(path)) path = path.slice(1)
26
+ }
27
+ let root = ''
28
+ let rest = path
29
+ const drive = path.match(/^([A-Za-z]:)(\/.*|$)/)
30
+ const unc = !drive ? path.match(/^(\/\/[^/]+\/[^/]+)(\/.*|$)/) : null
31
+ if (drive) { root = drive[1]; rest = drive[2] }
32
+ else if (unc) { root = unc[1]; rest = unc[2] }
33
+ else if (path.startsWith('/')) { root = '/'; rest = path.slice(1) }
34
+ else return undefined
35
+ const segments = collapseSegments(rest.split('/'))
36
+ return segments ? { root, segments } : undefined
37
+ }
38
+
39
+ export function validateAllowedPaths(input: unknown): { ok: true; paths: string[] | undefined } | { ok: false; code: 'invalid_op' | 'limit_exceeded'; message: string } {
40
+ if (input === undefined) return { ok: true, paths: undefined }
41
+ if (!Array.isArray(input)) return { ok: false, code: 'invalid_op', message: 'allowedPaths must be an array of repo-relative paths or globs.' }
42
+ if (input.length === 0) return { ok: true, paths: undefined }
43
+ if (input.length > MAX_ALLOWED_PATHS) return { ok: false, code: 'limit_exceeded', message: `At most ${MAX_ALLOWED_PATHS} allowedPaths entries are allowed per task.` }
44
+ const normalized: string[] = []
45
+ const seen = new Set<string>()
46
+ for (const entry of input) {
47
+ if (typeof entry !== 'string') return { ok: false, code: 'invalid_op', message: 'Each allowedPaths entry must be a non-empty string.' }
48
+ const raw = entry.trim()
49
+ if (!raw || Array.from(raw).length > MAX_ALLOWED_PATH_LENGTH || invalidControl.test(raw)) return { ok: false, code: 'invalid_op', message: 'allowedPaths entries must be valid repo-relative paths without control characters.' }
50
+ if (raw.startsWith('/') || raw.startsWith('\\') || raw.startsWith('~') || /^[A-Za-z]:/.test(raw) || /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(raw)) {
51
+ return { ok: false, code: 'invalid_op', message: `allowedPaths entry must be repo-relative: ${raw}` }
52
+ }
53
+ let clean = raw.replace(/\\/g, '/').replace(/\/+/g, '/')
54
+ while (clean.startsWith('./')) clean = clean.slice(2)
55
+ const trailingSlash = clean.endsWith('/')
56
+ const body = trailingSlash ? clean.slice(0, -1) : clean
57
+ if (!body || body === '.') return { ok: false, code: 'invalid_op', message: `allowedPaths entry cannot be empty or root: ${raw}` }
58
+ const parts = body.split('/')
59
+ if (parts.some(part => !part || part === '.' || part === '..')) return { ok: false, code: 'invalid_op', message: `allowedPaths entry cannot traverse parent directories: ${raw}` }
60
+ const value = trailingSlash ? `${body}/` : body
61
+ if (!seen.has(value)) { seen.add(value); normalized.push(value) }
62
+ }
63
+ return { ok: true, paths: normalized }
64
+ }
65
+
66
+ export function normalizeTarget(directory: string, resource: string): string | undefined {
67
+ const raw = resource.trim()
68
+ if (!raw || invalidControl.test(raw)) return undefined
69
+ if (raw.startsWith('~')) return undefined
70
+ const posix = raw.replace(/\\/g, '/')
71
+ const isAbs = posix.startsWith('/') || /^[A-Za-z]:(\/|$)/.test(posix) || /^file:\/\//i.test(posix)
72
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(posix) && !/^file:\/\//i.test(posix)) return undefined
73
+ if (!isAbs) {
74
+ const segments = collapseSegments(posix.split('/'))
75
+ return segments?.length ? segments.join('/') : undefined
76
+ }
77
+ const base = normalizeAbsolute(directory)
78
+ const target = normalizeAbsolute(posix)
79
+ if (!base || !target) return undefined
80
+ const ci = /^[A-Za-z]:$/.test(base.root) || base.root.startsWith('//')
81
+ const same = (a: string, b: string) => ci ? a.toLowerCase() === b.toLowerCase() : a === b
82
+ if (!same(base.root, target.root) || target.segments.length <= base.segments.length) return undefined
83
+ for (let i = 0; i < base.segments.length; i++) if (!same(base.segments[i], target.segments[i])) return undefined
84
+ return target.segments.slice(base.segments.length).join('/')
85
+ }
86
+
87
+ function patternToRegex(pattern: string, caseInsensitive: boolean): RegExp {
88
+ const glob = pattern.endsWith('/') ? `${pattern}**` : pattern
89
+ let out = ''
90
+ for (let i = 0; i < glob.length;) {
91
+ if (glob.startsWith('**/', i)) { out += '(?:.*/)?'; i += 3 }
92
+ else if (glob.startsWith('**', i)) { out += '.*'; i += 2 }
93
+ else if (glob[i] === '*') { out += '[^/]*'; i += 1 }
94
+ else if (glob[i] === '?') { out += '[^/]'; i += 1 }
95
+ else { out += glob[i].replace(/[.+^${}()|[\]\\]/g, '\\$&'); i += 1 }
96
+ }
97
+ return new RegExp(`^${out}$`, caseInsensitive ? 'i' : '')
98
+ }
99
+
100
+ export function isPathAllowed(directory: string, resource: string, allowedPaths: ReadonlyArray<string>): boolean {
101
+ const target = normalizeTarget(directory, resource)
102
+ if (!target) return false
103
+ const ci = /^[A-Za-z]:/.test(directory) || directory.startsWith('\\\\') || directory.startsWith('//')
104
+ return allowedPaths.some(pattern => patternToRegex(pattern, ci).test(target))
105
+ }
106
+
107
+ export function checkScopeViolation(directory: string, action: string, resources: ReadonlyArray<string>, allowedPaths: ReadonlyArray<string>): string | undefined {
108
+ if (!EDIT_ACTIONS.has(action)) return undefined
109
+ if (!resources.length) return `Out-of-scope file edit blocked: target path unavailable. Allowed paths: ${allowedPaths.join(', ')}`
110
+ for (const resource of resources) {
111
+ if (!isPathAllowed(directory, resource, allowedPaths)) {
112
+ return `Out-of-scope file edit blocked (${resource}). Allowed paths: ${allowedPaths.join(', ')}`
113
+ }
114
+ }
115
+ return undefined
116
+ }