Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sovereign-intelligence/blob/main/harness/coder/omega-guard.ts # sovereign-intelligence Front door to Drake Stapleton's sovereign stack. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `sovereign-intelligence / harness / coder / omega-guard.ts` 319 lines ยท 15350 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 OM-2 qualification conductor `seed/qualification/om2/gate.om` (built by the pinned omc) 5 // runs and compares task cases. This file only routes paths, starts those two binaries and sandboxes 6 // 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: read-only root, private 17 // /tmp, no network, own pid namespace, 10 s wall limit. 18 // - The session cannot end while any touched `.om` file fails to compile, or, when OMEGA_CASES names a 19 // gate case list, until the gate prints `OM2GATE PASS`. 20 // 21 // Environment: OMEGA_HOME (default ~/.local/share/aien-omega: omc, gate, gate fixtures, context/), 22 // OMEGA_CASES (optional case list for the stop check; keep it outside the session directory). 23 import { spawnSync } from 'node:child_process' 24 import { createHash } from 'node:crypto' 25 import { appendFileSync, chmodSync, existsSync, mkdtempSync, readFileSync, realpathSync } from 'node:fs' 26 import { homedir, tmpdir } from 'node:os' 27 import { basename, isAbsolute, join, resolve, sep } from 'node:path' 28 29 const OMEGA_HOME = process.env.OMEGA_HOME || join(homedir(), '.local/share/aien-omega') 30 const OMC = join(OMEGA_HOME, 'omc') 31 const GATE = join(OMEGA_HOME, 'gate') 32 // Readable Omega reference. The eval control arm points this at an empty directory. 33 const 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). 35 const STOP_LIMIT = Number(process.env.OMEGA_STOP_LIMIT || 0) 36 // omega-mv `f1b9ecb5d13f3b7303c055a187fff06e802eb952`, seed/out/omc (commit `82a399b9f` "batch 2 pin `2c824805`"). 37 const OMC_SHA256 = '`2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f`' 38 const LOG = process.env.OMEGA_LOG 39 40 function note(line: string): void { 41 if (LOG) appendFileSync(LOG, `${new Date().toISOString()} ${line}\n`) 42 } 43 const ALLOWED_TOOLS = new Set(['read', 'grep', 'glob', 'edit', 'write', 'omega_run']) 44 const BUILD = mkdtempSync(join(tmpdir(), 'aien-omega-')) 45 46 const ERRORS: Record = { 47 1: 'compiler I/O', 2: 'compiler I/O', 3: 'unknown name or field', 4: 'line ends too early (missing value)', 48 5: 'extra words on the line', 6: 'malformed number', 7: 'type mismatch (no implicit conversion)', 49 8: 'number out of range', 9: 'word in a disallowed place', 10: 'duplicate name', 11: 'ambiguous bare number (give it a type: uint 5)', 50 12: 'register pool exhausted (fewer live names or split the function)', 13: 'name too long (non-function names at most 8 characters)', 51 14: 'capacity', 15: 'missing end', 16: 'syntax error or unknown word', 17: 'line after ret/break/continue/trap/exit', 52 18: 'missing ret (end of a value-returning function is reachable)', 19: 'global passed as argument, or same array twice in one call', 53 20: 'write to a view or text', 21: 'constant index out of range', 22: 'bad text literal', 23: 'size capacity', 54 } 55 56 type Ctx = { cwd?: string } 57 type Content = { type: string; text?: string } 58 type Pi = { 59 on(name: string, handler: (event: any, ctx: Ctx) => unknown): void 60 registerTool(def: any): void 61 zod: any 62 } 63 64 function omcVerified(): string | undefined { 65 try { 66 const sha = createHash('sha256').update(readFileSync(OMC)).digest('hex') 67 return sha === OMC_SHA256 ? undefined : `pinned omc mismatch: ${OMC} sha256 ${sha}, expected ${OMC_SHA256}` 68 } catch (e) { 69 return `pinned omc unreadable: ${OMC}: ${e}` 70 } 71 } 72 73 function root(ctx: Ctx): string { 74 return realpathSync(ctx.cwd || process.cwd()) 75 } 76 77 // Resolve a model-supplied path the way the file tools do (relative to the session directory). 78 // Symlinks are resolved for the existing prefix so a link cannot carry a write outside the root. 79 function resolvePath(p: string, base: string): string { 80 let abs = resolve(base, p) 81 let probe = abs 82 const tail: string[] = [] 83 while (!existsSync(probe) && probe !== sep) { 84 tail.unshift(basename(probe)) 85 probe = resolve(probe, '..') 86 } 87 try { 88 abs = join(realpathSync(probe), ...tail) 89 } catch {} 90 return abs 91 } 92 93 function inside(abs: string, dir: string): boolean { 94 return abs === dir || abs.startsWith(dir.endsWith(sep) ? dir : dir + sep) 95 } 96 97 function writePaths(tool: string, input: any): string[] { 98 const out: string[] = [] 99 // The edit tool takes `path` as `FILE#TAG` (TAG = snapshot hash from the last read); the tag is not part of the 100 // path. Anything else after a `#` is kept, and checkWrite refuses every path that still contains `#`. 101 for (const k of ['path', 'file_path', 'file', 'target']) { 102 const p = input?.[k] 103 if (typeof p !== 'string') continue 104 const h = p.lastIndexOf('#') 105 out.push(h >= 0 && /^[0-9A-Za-z]+$/.test(p.slice(h + 1)) ? p.slice(0, h) : p) 106 } 107 if (typeof input?.input === 'string') { 108 for (const m of input.input.matchAll(/^\[([^\]#\n]+)#/gm)) out.push(m[1]) 109 for (const m of input.input.matchAll(/^\s*MV\s+("([^"]+)"|(\S+))/gm)) out.push(m[2] ?? m[3]) 110 } 111 if (Array.isArray(input?.edits)) for (const e of input.edits) if (typeof e?.path === 'string') out.push(e.path) 112 if (tool === 'write' && out.length === 0) out.push('') 113 return out 114 } 115 116 function readPaths(input: any): string[] { 117 const out: string[] = [] 118 for (const k of ['path', 'paths', 'file_path']) { 119 const v = input?.[k] 120 if (typeof v === 'string') out.push(...v.split(';').map((s: string) => s.trim()).filter(Boolean)) 121 if (Array.isArray(v)) out.push(...v.filter((s: unknown) => typeof s === 'string')) 122 } 123 return out 124 } 125 126 function stripSelector(p: string): string { 127 // read accepts `file.om:10-20`; the selector is not part of the path. 128 return p.replace(/:(raw|conflicts|img|[-+0-9,]+[-+0-9,:raw]*)$/, '') 129 } 130 131 function checkWrite(p: string, base: string): string | undefined { 132 if (!p) return 'write needs a path ending in .om' 133 if (p.includes('://') || p.includes(':') || p.includes('#')) return `refused: ${p}: only plain paths to .om files may be written` 134 const abs = resolvePath(p, base) 135 if (!inside(abs, base)) return `refused: ${p} is outside the session directory ${base}` 136 if (abs.endsWith('.om') || basename(abs) === 'NOTES.md') return undefined 137 return `refused: ${p}: this session writes Omega only; edit or create .om files (or NOTES.md for notes)` 138 } 139 140 function checkRead(p: string, base: string): string | undefined { 141 if (p.startsWith('artifact://')) return undefined 142 if (p.includes('://')) return `refused: ${p}: read only files in ${base} or the Omega reference` 143 const abs = resolvePath(stripSelector(p).replace(/[*?{[].*$/, '') || '.', base) 144 let pack = CONTEXT 145 try { 146 pack = realpathSync(CONTEXT) 147 } catch {} 148 if (inside(abs, base) || inside(abs, pack)) return undefined 149 return `refused: ${p} is outside ${base} and the Omega reference ${pack}` 150 } 151 152 type Compile = { rc: number; elf: string; report: string } 153 154 function compile(file: string): Compile { 155 const bad = omcVerified() 156 if (bad) return { rc: -1, elf: '', report: `OMC REFUSED: ${bad}` } 157 const src = readFileSync(file) 158 const elf = join(BUILD, createHash('sha256').update(file).digest('hex').slice(0, 16)) 159 const r = spawnSync('sh', ['-c', '"$1" < "$2" > "$3" 2> "$3.err"', 'omc', OMC, file, elf]) 160 const rc = r.status ?? -1 161 let err = '' 162 try { 163 err = readFileSync(`${elf}.err`, 'utf8').trim() 164 } catch {} 165 if (rc === 0) { 166 chmodSync(elf, 0o755) 167 return { rc, elf, report: `omc: compile rc=0 (${basename(file)}, pinned omc ${OMC_SHA256.slice(0, 8)})` } 168 } 169 const m = err.match(/line (\d+): error (\d+)/) 170 let detail = err || '(no diagnostic)' 171 if (m) { 172 const line = src.toString('utf8').split('\n')[Number(m[1]) - 1] ?? '' 173 detail = `${err}\n error ${m[2]} = ${ERRORS[Number(m[2])] ?? 'see the error table'}\n line ${m[1]}: ${line}` 174 } 175 return { rc, elf: '', report: `omc: compile FAILED rc=${rc} (${basename(file)})\n${detail}\nFix the .om source; never run output from a failed compile.` } 176 } 177 178 function sandboxRun(elf: string, base: string, args: string[], stdin: string): { rc: number; out: string; err: string } { 179 const r = spawnSync( 180 'bwrap', 181 ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp', '--ro-bind', base, base, '--ro-bind', elf, '/tmp/prog', 182 '--unshare-net', '--unshare-pid', '--die-with-parent', '--chdir', base, '--', '/tmp/prog', ...args], 183 { input: stdin, timeout: 10_000, maxBuffer: 1 << 22 }, 184 ) 185 const cut = (b: Buffer | null) => { 186 const s = (b ?? Buffer.alloc(0)).toString('utf8') 187 return s.length > 8192 ? `${s.slice(0, 8192)}\n[... ${s.length - 8192} more bytes cut]` : s 188 } 189 return { rc: r.error ? -1 : (r.status ?? (r.signal ? 128 : -1)), out: cut(r.stdout), err: r.error ? String(r.error) : cut(r.stderr) } 190 } 191 192 function trapNote(rc: number): string { 193 const traps: Record = { 194 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', 195 105: 'trap 5 conversion does not fit', 106: 'trap 6 stack exhausted', 107: 'trap 7 shift amount out of range', 196 } 197 if (rc < 0) return ' (did not finish: timeout or sandbox failure)' 198 if (traps[rc]) return ` (${traps[rc]})` 199 if (rc > 100 && rc <= 114) return ` (trap ${rc - 100})` 200 return '' 201 } 202 203 export default function (pi: Pi) { 204 const touched = new Map() 205 const z = pi.zod 206 207 const block = (tool: string, reason: string) => { 208 note(`tool ${tool} refused: ${reason}`) 209 return { block: true, reason } 210 } 211 212 pi.on('tool_call', async (event: any, ctx: Ctx) => { 213 const base = root(ctx) 214 const tool = String(event.toolName) 215 if (!ALLOWED_TOOLS.has(tool)) return block(tool, `refused: ${tool} is not available in Omega mode; use omega_run to run .om programs`) 216 if (tool === 'edit' || tool === 'write') { 217 for (const p of writePaths(tool, event.input)) { 218 const why = checkWrite(p, base) 219 if (why) return block(tool, why) 220 } 221 } 222 if (tool === 'read' || tool === 'grep' || tool === 'glob') { 223 for (const p of readPaths(event.input)) { 224 const why = checkRead(p, base) 225 if (why) return block(tool, why) 226 } 227 } 228 note(`tool ${tool} allowed`) 229 return undefined 230 }) 231 232 pi.on('tool_result', async (event: any, ctx: Ctx) => { 233 const tool = String(event.toolName) 234 if ((tool !== 'edit' && tool !== 'write') || event.isError) return undefined 235 const base = root(ctx) 236 const reports: string[] = [] 237 for (const p of writePaths(tool, event.input)) { 238 const abs = resolvePath(p, base) 239 if (!abs.endsWith('.om') || !existsSync(abs)) continue 240 const c = compile(abs) 241 touched.set(abs, c.rc) 242 reports.push(c.report) 243 note(`${tool} ${basename(abs)}: ${c.report.split('\n').slice(0, 2).join(' | ')}`) 244 } 245 if (reports.length === 0) return undefined 246 const content: Content[] = [...(event.content ?? []), { type: 'text', text: `\n${reports.join('\n')}` }] 247 return { content } 248 }) 249 250 pi.registerTool({ 251 name: 'omega_run', 252 label: 'Omega run', 253 description: 254 '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).', 255 parameters: z.object({ 256 path: z.string().describe('the .om file to compile and run'), 257 stdin: z.string().optional().describe('bytes given to the program on standard input'), 258 args: z.array(z.string()).optional().describe('command-line arguments after the program name'), 259 }), 260 loadMode: 'essential', 261 async execute(_id: string, params: { path: string; stdin?: string; args?: string[] }, _signal: unknown, _onUpdate: unknown, ctx: Ctx) { 262 const base = root(ctx) 263 const abs = resolvePath(params.path, base) 264 const text = (t: string) => ({ content: [{ type: 'text', text: t }] }) 265 if (!abs.endsWith('.om') || !inside(abs, base) || !existsSync(abs)) return text(`omega_run: ${params.path} is not a .om file in ${base}`) 266 const c = compile(abs) 267 touched.set(abs, c.rc) 268 if (c.rc !== 0) { 269 note(`omega_run ${basename(abs)}: compile FAILED rc=${c.rc}`) 270 return text(c.report) 271 } 272 const r = sandboxRun(c.elf, base, params.args ?? [], params.stdin ?? '') 273 note(`omega_run ${basename(abs)}: run exit=${r.rc} stdout_bytes=${Buffer.byteLength(r.out)}`) 274 return text(`${c.report}\nrun exit status=${r.rc}${trapNote(r.rc)}\n--- stdout ---\n${r.out}\n--- stderr ---\n${r.err}`) 275 }, 276 }) 277 278 let refusals = 0 279 const refuse = (reason: string) => { 280 refusals += 1 281 if (STOP_LIMIT > 0 && refusals > STOP_LIMIT) { 282 note(`stop allowed after ${STOP_LIMIT} refusals (OMEGA_STOP_LIMIT); last: ${reason.split('\n')[0]}`) 283 return undefined 284 } 285 note(`stop refused #${refusals}: ${reason.split('\n')[0]}`) 286 return { decision: 'block', reason } 287 } 288 289 pi.on('session_stop', async (_event: unknown, ctx: Ctx) => { 290 const failing = [...touched].filter(([f, rc]) => rc !== 0 && existsSync(f)).map(([f]) => f) 291 for (const f of failing) { 292 const c = compile(f) 293 touched.set(f, c.rc) 294 if (c.rc !== 0) return refuse(`Not done: ${basename(f)} does not compile.\n${c.report}`) 295 } 296 const cases = process.env.OMEGA_CASES 297 if (!cases) { 298 note('stop allowed: every touched .om compiles; no OMEGA_CASES') 299 return undefined 300 } 301 const base = root(ctx) 302 const scratchParent = mkdtempSync(join(tmpdir(), 'aien-omega-gate-')) 303 const r = spawnSync( 304 'bwrap', 305 ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--bind', scratchParent, scratchParent, '--unshare-net', '--unshare-pid', 306 '--die-with-parent', '--chdir', OMEGA_HOME, '--', GATE, OMC, OMC_SHA256, cases, join(scratchParent, 's')], 307 { cwd: base, timeout: 120_000, maxBuffer: 1 << 22 }, 308 ) 309 const out = (r.stdout ?? Buffer.alloc(0)).toString('utf8') 310 if (/^OM2GATE PASS /m.test(out)) { 311 note('stop allowed: OM2GATE PASS') 312 return undefined 313 } 314 const verdicts = out.split('\n').filter(l => l.startsWith('VERDICT') || l.startsWith('OM2GATE')).join('\n') 315 return refuse(`Not done: the task check did not pass.\n${verdicts || `gate exit ${r.status}`}\nRead the task again, fix the program, check it with omega_run, then finish.`) 316 }) 317 } 318 319 export { checkRead, checkWrite, writePaths }