interplane.Get Omega
Read in your language

omega-harness

Agent skills for operating, encoding and communicating in Omega (.om) and the AIEN repositories

Brought by drakestapleton

branch main Branches Tags History

omega-harness / coder / omega-guard.ts

322 lines · 15271 bytes Raw Blame History
1// omega-guard: omp extension for `aien --omega`. Harness configuration, not product code: omp
2// extensions are TypeScript, so this file is the smallest shim between the omp tool loop and the
3// pinned seeded Omega compiler. All checking of programs is done by Omega itself: `omc` compiles,
4// and the finish check (OMEGA_CHECK; the eval's coder/eval/score.sh runs the OM-2 qualification conductor
5// `seed/qualification/om2/gate.om`, built by the pinned omc) runs and compares task cases. This file only
6// routes paths, starts those programs and sandboxes model-written programs with bubblewrap.
7//
8// Policy
9// - write/edit may touch only `*.om` files (plus NOTES.md) inside the session directory; every other
10// path, an `MV` to a non-.om name, and archive/URL targets are refused before the tool runs.
11// - read/grep/glob are confined to the session directory and the Omega context pack.
12// - Every tool other than read, grep, glob, edit, write and omega_run is refused (no shell).
13// - After a successful write/edit of a `.om` file the pinned omc compiles it; the result (rc, the
14// `omc: line N: error K` line, the offending source line and the error's meaning) is appended to
15// the tool result the model sees.
16// - omega_run compiles a `.om` file and runs it in a bubblewrap sandbox that holds only the program and the
17// session directory (read-only), a private /tmp and /dev: no other file of this machine, no /proc, no
18// network, own pid namespace, 10 s wall limit.
19// - The session cannot end while any touched `.om` file fails to compile, or, when OMEGA_CHECK is set, until
20// that command (run with `sh -c` in the session directory) exits 0 and prints a `SCORE <id> pass` line.
21//
22// Environment: OMEGA_HOME (default ~/.local/share/aien-omega: omc, context/ with PIN and errors.tsv),
23// OMEGA_CHECK (optional finish check; it must keep the task's expected output outside the session directory).
24import { spawnSync } from 'node:child_process'
25import { createHash } from 'node:crypto'
26import { appendFileSync, chmodSync, existsSync, mkdtempSync, readFileSync, realpathSync } from 'node:fs'
27import { homedir, tmpdir } from 'node:os'
28import { basename, isAbsolute, join, resolve, sep } from 'node:path'
29
30const OMEGA_HOME = process.env.OMEGA_HOME || join(homedir(), '.local/share/aien-omega')
31const OMC = join(OMEGA_HOME, 'omc')
32// Readable Omega reference. The eval control arm points this at an empty directory.
33const CONTEXT = process.env.OMEGA_CONTEXT || join(OMEGA_HOME, 'context')
34// Stop refusals before the session may end anyway (eval runs set it; unset means no limit).
35const STOP_LIMIT = Number(process.env.OMEGA_STOP_LIMIT || 0)
36// The pin and the error meanings are not typed here: build-context.sh writes both into the pack from the
37// repository's PIN and from data/reference.tsv (meaning and fix of each error code). They are read from OMEGA_HOME/context, not
38// OMEGA_CONTEXT, so the eval control arm (an empty readable context) runs with the same guard.
39const PACK = join(OMEGA_HOME, 'context')
40function readPack(name: string): string {
41 try {
42 return readFileSync(join(PACK, name), 'utf8')
43 } catch {
44 return ''
45 }
46}
47const OMC_SHA256 = (readPack('PIN').match(/^omc-sha256 ([0-9a-f]{64})$/m) || [])[1] || ''
48const LOG = process.env.OMEGA_LOG
49
50function note(line: string): void {
51 if (LOG) appendFileSync(LOG, `${new Date().toISOString()} ${line}\n`)
52}
53const ALLOWED_TOOLS = new Set(['read', 'grep', 'glob', 'edit', 'write', 'omega_run'])
54const BUILD = mkdtempSync(join(tmpdir(), 'aien-omega-'))
55
56const ERRORS: Record<number, string> = {}
57for (const row of readPack('errors.tsv').split('\n')) {
58 const tab = row.indexOf('\t')
59 if (tab > 0) ERRORS[Number(row.slice(0, tab))] = row.slice(tab + 1)
60}
61
62type Ctx = { cwd?: string }
63type Content = { type: string; text?: string }
64type Pi = {
65 on(name: string, handler: (event: any, ctx: Ctx) => unknown): void
66 registerTool(def: any): void
67 zod: any
68}
69
70function omcVerified(): string | undefined {
71 try {
72 if (!OMC_SHA256) return `no pin: ${join(PACK, 'PIN')} has no omc-sha256 line (run build-context.sh)`
73 const sha = createHash('sha256').update(readFileSync(OMC)).digest('hex')
74 return sha === OMC_SHA256 ? undefined : `pinned omc mismatch: ${OMC} sha256 ${sha}, expected ${OMC_SHA256}`
75 } catch (e) {
76 return `pinned omc unreadable: ${OMC}: ${e}`
77 }
78}
79
80function root(ctx: Ctx): string {
81 return realpathSync(ctx.cwd || process.cwd())
82}
83
84// Resolve a model-supplied path the way the file tools do (relative to the session directory).
85// Symlinks are resolved for the existing prefix so a link cannot carry a write outside the root.
86function resolvePath(p: string, base: string): string {
87 let abs = resolve(base, p)
88 let probe = abs
89 const tail: string[] = []
90 while (!existsSync(probe) && probe !== sep) {
91 tail.unshift(basename(probe))
92 probe = resolve(probe, '..')
93 }
94 try {
95 abs = join(realpathSync(probe), ...tail)
96 } catch {}
97 return abs
98}
99
100function inside(abs: string, dir: string): boolean {
101 return abs === dir || abs.startsWith(dir.endsWith(sep) ? dir : dir + sep)
102}
103
104function writePaths(tool: string, input: any): string[] {
105 const out: string[] = []
106 // The edit tool takes `path` as `FILE#TAG` (TAG = snapshot hash from the last read); the tag is not part of the
107 // path. Anything else after a `#` is kept, and checkWrite refuses every path that still contains `#`.
108 for (const k of ['path', 'file_path', 'file', 'target']) {
109 const p = input?.[k]
110 if (typeof p !== 'string') continue
111 const h = p.lastIndexOf('#')
112 out.push(h >= 0 && /^[0-9A-Za-z]+$/.test(p.slice(h + 1)) ? p.slice(0, h) : p)
113 }
114 if (typeof input?.input === 'string') {
115 for (const m of input.input.matchAll(/^\[([^\]#\n]+)#/gm)) out.push(m[1])
116 for (const m of input.input.matchAll(/^\s*MV\s+("([^"]+)"|(\S+))/gm)) out.push(m[2] ?? m[3])
117 }
118 if (Array.isArray(input?.edits)) for (const e of input.edits) if (typeof e?.path === 'string') out.push(e.path)
119 if (tool === 'write' && out.length === 0) out.push('')
120 return out
121}
122
123function readPaths(input: any): string[] {
124 const out: string[] = []
125 for (const k of ['path', 'paths', 'file_path']) {
126 const v = input?.[k]
127 if (typeof v === 'string') out.push(...v.split(';').map((s: string) => s.trim()).filter(Boolean))
128 if (Array.isArray(v)) out.push(...v.filter((s: unknown) => typeof s === 'string'))
129 }
130 return out
131}
132
133function stripSelector(p: string): string {
134 // read accepts `file.om:10-20`; the selector is not part of the path.
135 return p.replace(/:(raw|conflicts|img|[-+0-9,]+[-+0-9,:raw]*)$/, '')
136}
137
138function checkWrite(p: string, base: string): string | undefined {
139 if (!p) return 'write needs a path ending in .om'
140 if (p.includes('://') || p.includes(':') || p.includes('#')) return `refused: ${p}: only plain paths to .om files may be written`
141 const abs = resolvePath(p, base)
142 if (!inside(abs, base)) return `refused: ${p} is outside the session directory ${base}`
143 if (abs.endsWith('.om') || basename(abs) === 'NOTES.md') return undefined
144 return `refused: ${p}: this session writes Omega only; edit or create .om files (or NOTES.md for notes)`
145}
146
147function checkRead(p: string, base: string): string | undefined {
148 if (p.startsWith('artifact://')) return undefined
149 if (p.includes('://')) return `refused: ${p}: read only files in ${base} or the Omega reference`
150 const abs = resolvePath(stripSelector(p).replace(/[*?{[].*$/, '') || '.', base)
151 let pack = CONTEXT
152 try {
153 pack = realpathSync(CONTEXT)
154 } catch {}
155 if (inside(abs, base) || inside(abs, pack)) return undefined
156 return `refused: ${p} is outside ${base} and the Omega reference ${pack}`
157}
158
159type Compile = { rc: number; elf: string; report: string }
160
161function compile(file: string): Compile {
162 const bad = omcVerified()
163 if (bad) return { rc: -1, elf: '', report: `OMC REFUSED: ${bad}` }
164 const src = readFileSync(file)
165 const elf = join(BUILD, createHash('sha256').update(file).digest('hex').slice(0, 16))
166 const r = spawnSync('sh', ['-c', '"$1" < "$2" > "$3" 2> "$3.err"', 'omc', OMC, file, elf])
167 const rc = r.status ?? -1
168 let err = ''
169 try {
170 err = readFileSync(`${elf}.err`, 'utf8').trim()
171 } catch {}
172 if (rc === 0) {
173 chmodSync(elf, 0o755)
174 return { rc, elf, report: `omc: compile rc=0 (${basename(file)}, pinned omc ${OMC_SHA256.slice(0, 8)})` }
175 }
176 const m = err.match(/line (\d+): error (\d+)/)
177 let detail = err || '(no diagnostic)'
178 if (m) {
179 const line = src.toString('utf8').split('\n')[Number(m[1]) - 1] ?? ''
180 detail = `${err}\n error ${m[2]} = ${ERRORS[Number(m[2])] ?? 'see the error table'}\n line ${m[1]}: ${line}`
181 }
182 return { rc, elf: '', report: `omc: compile FAILED rc=${rc} (${basename(file)})\n${detail}\nFix the .om source; never run output from a failed compile.` }
183}
184
185function sandboxRun(elf: string, base: string, args: string[], stdin: string): { rc: number; out: string; err: string } {
186 // The program is model-written: whatever it can open it can print. Omega programs are static ELFs, so the view
187 // is the session directory (read-only) and the program itself; the context pack, the task files and the rest
188 // of the machine are not in it.
189 const r = spawnSync(
190 'bwrap',
191 ['--dev', '/dev', '--tmpfs', '/tmp', '--ro-bind', base, base, '--ro-bind', elf, '/tmp/prog',
192 '--unshare-net', '--unshare-pid', '--unshare-ipc', '--die-with-parent', '--chdir', base, '--', '/tmp/prog', ...args],
193 { input: stdin, timeout: 10_000, maxBuffer: 1 << 22 },
194 )
195 const cut = (b: Buffer | null) => {
196 const s = (b ?? Buffer.alloc(0)).toString('utf8')
197 return s.length > 8192 ? `${s.slice(0, 8192)}\n[... ${s.length - 8192} more bytes cut]` : s
198 }
199 return { rc: r.error ? -1 : (r.status ?? (r.signal ? 128 : -1)), out: cut(r.stdout), err: r.error ? String(r.error) : cut(r.stderr) }
200}
201
202function trapNote(rc: number): string {
203 const traps: Record<number, string> = {
204 101: 'trap 1 signed overflow', 102: 'trap 2 divide by zero', 103: 'trap 3 index or slice out of bounds', 104: 'trap 4 loop bound exceeded',
205 105: 'trap 5 conversion does not fit', 106: 'trap 6 stack exhausted', 107: 'trap 7 shift amount out of range',
206 }
207 if (rc < 0) return ' (did not finish: timeout or sandbox failure)'
208 if (traps[rc]) return ` (${traps[rc]})`
209 if (rc > 100 && rc <= 114) return ` (trap ${rc - 100})`
210 return ''
211}
212
213export default function (pi: Pi) {
214 const touched = new Map<string, number>()
215 const z = pi.zod
216
217 const block = (tool: string, reason: string) => {
218 note(`tool ${tool} refused: ${reason}`)
219 return { block: true, reason }
220 }
221
222 pi.on('tool_call', async (event: any, ctx: Ctx) => {
223 const base = root(ctx)
224 const tool = String(event.toolName)
225 if (!ALLOWED_TOOLS.has(tool)) return block(tool, `refused: ${tool} is not available in Omega mode; use omega_run to run .om programs`)
226 if (tool === 'edit' || tool === 'write') {
227 for (const p of writePaths(tool, event.input)) {
228 const why = checkWrite(p, base)
229 if (why) return block(tool, why)
230 }
231 }
232 if (tool === 'read' || tool === 'grep' || tool === 'glob') {
233 for (const p of readPaths(event.input)) {
234 const why = checkRead(p, base)
235 if (why) return block(tool, why)
236 }
237 }
238 note(`tool ${tool} allowed`)
239 return undefined
240 })
241
242 pi.on('tool_result', async (event: any, ctx: Ctx) => {
243 const tool = String(event.toolName)
244 if ((tool !== 'edit' && tool !== 'write') || event.isError) return undefined
245 const base = root(ctx)
246 const reports: string[] = []
247 for (const p of writePaths(tool, event.input)) {
248 const abs = resolvePath(p, base)
249 if (!abs.endsWith('.om') || !existsSync(abs)) continue
250 const c = compile(abs)
251 touched.set(abs, c.rc)
252 reports.push(c.report)
253 note(`${tool} ${basename(abs)}: ${c.report.split('\n').slice(0, 2).join(' | ')}`)
254 }
255 if (reports.length === 0) return undefined
256 const content: Content[] = [...(event.content ?? []), { type: 'text', text: `\n${reports.join('\n')}` }]
257 return { content }
258 })
259
260 pi.registerTool({
261 name: 'omega_run',
262 label: 'Omega run',
263 description:
264 'Compile a .om file with the pinned seeded Omega compiler and, if it compiles, run it in a sandbox (read-only files, no network, 10 s). Returns the compiler diagnostic or the exit status, stdout and stderr. Exit status 101..114 is a runtime trap (100 + trap code).',
265 parameters: z.object({
266 path: z.string().describe('the .om file to compile and run'),
267 stdin: z.string().optional().describe('bytes given to the program on standard input'),
268 args: z.array(z.string()).optional().describe('command-line arguments after the program name'),
269 }),
270 loadMode: 'essential',
271 async execute(_id: string, params: { path: string; stdin?: string; args?: string[] }, _signal: unknown, _onUpdate: unknown, ctx: Ctx) {
272 const base = root(ctx)
273 const abs = resolvePath(params.path, base)
274 const text = (t: string) => ({ content: [{ type: 'text', text: t }] })
275 if (!abs.endsWith('.om') || !inside(abs, base) || !existsSync(abs)) return text(`omega_run: ${params.path} is not a .om file in ${base}`)
276 const c = compile(abs)
277 touched.set(abs, c.rc)
278 if (c.rc !== 0) {
279 note(`omega_run ${basename(abs)}: compile FAILED rc=${c.rc}`)
280 return text(c.report)
281 }
282 const r = sandboxRun(c.elf, base, params.args ?? [], params.stdin ?? '')
283 note(`omega_run ${basename(abs)}: run exit=${r.rc} stdout_bytes=${Buffer.byteLength(r.out)}`)
284 return text(`${c.report}\nrun exit status=${r.rc}${trapNote(r.rc)}\n--- stdout ---\n${r.out}\n--- stderr ---\n${r.err}`)
285 },
286 })
287
288 let refusals = 0
289 const refuse = (reason: string) => {
290 refusals += 1
291 if (STOP_LIMIT > 0 && refusals > STOP_LIMIT) {
292 note(`stop allowed after ${STOP_LIMIT} refusals (OMEGA_STOP_LIMIT); last: ${reason.split('\n')[0]}`)
293 return undefined
294 }
295 note(`stop refused #${refusals}: ${reason.split('\n')[0]}`)
296 return { decision: 'block', reason }
297 }
298
299 pi.on('session_stop', async (_event: unknown, ctx: Ctx) => {
300 const failing = [...touched].filter(([f, rc]) => rc !== 0 && existsSync(f)).map(([f]) => f)
301 for (const f of failing) {
302 const c = compile(f)
303 touched.set(f, c.rc)
304 if (c.rc !== 0) return refuse(`Not done: ${basename(f)} does not compile.\n${c.report}`)
305 }
306 const check = process.env.OMEGA_CHECK
307 if (!check) {
308 note('stop allowed: every touched .om compiles; no OMEGA_CHECK')
309 return undefined
310 }
311 const r = spawnSync('sh', ['-c', check], { cwd: root(ctx), timeout: 120_000, maxBuffer: 1 << 22 })
312 const out = (r.stdout ?? Buffer.alloc(0)).toString('utf8')
313 if (r.status === 0 && /^SCORE \S+ pass /m.test(out)) {
314 note('stop allowed: SCORE pass')
315 return undefined
316 }
317 const verdicts = out.split('\n').filter(l => l.startsWith('VERDICT') || l.startsWith('SCORE')).join('\n')
318 return refuse(`Not done: the task check did not pass.\n${verdicts || `check exit ${r.status}`}\nRead the task again, fix the program, check it with omega_run, then finish.`)
319 })
320}
321
322export { checkRead, checkWrite, sandboxRun, writePaths }