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 / cli / src / harness.ts

311 lines · 8916 bytes Raw Blame History
1import crypto from 'node:crypto';
2import fs from 'node:fs';
3import os from 'node:os';
4import path from 'node:path';
5import { spawnSync } from 'node:child_process';
6
7export interface SkillMeta {
8 name: string;
9 description: string;
10 filePath: string;
11}
12
13export interface PinInfo {
14 omegaMvCommit?: string;
15 omcSha256?: string;
16 localOmcPath?: string;
17 localOmcSha256?: string;
18 pinMatches?: boolean;
19}
20
21export interface OmcErrorDoc {
22 code: number;
23 meaning: string;
24 cause?: string;
25 fix?: string;
26}
27
28export interface OmcCompileResult {
29 ok: boolean;
30 exitCode: number;
31 stderr: string;
32 outputPath?: string;
33 binarySize?: number;
34 errorCode?: number;
35 errorDoc?: OmcErrorDoc;
36 omcPath?: string;
37}
38
39export interface OmcRunResult {
40 compile: OmcCompileResult;
41 ran: boolean;
42 exitCode?: number;
43 signal?: string | null;
44 stdout: string;
45 stderr: string;
46 timedOut?: boolean;
47}
48
49export function readPinInfo(harnessRoot: string, omcPath?: string): PinInfo {
50 const info: PinInfo = { localOmcPath: omcPath };
51 const pinFile = path.join(harnessRoot, 'PIN');
52 try {
53 const raw = fs.readFileSync(pinFile, 'utf8');
54 for (const line of raw.split(/\r?\n/)) {
55 const m1 = line.match(/^omega-mv\s+(\S+)/);
56 if (m1) info.omegaMvCommit = m1[1];
57 const m2 = line.match(/^omc-sha256\s+(\S+)/);
58 if (m2) info.omcSha256 = m2[1];
59 }
60 } catch {
61 // PIN missing
62 }
63
64 if (omcPath) {
65 try {
66 const real = fs.realpathSync(omcPath);
67 const buf = fs.readFileSync(real);
68 info.localOmcSha256 = crypto.createHash('sha256').update(buf).digest('hex');
69 if (info.omcSha256) {
70 info.pinMatches = info.localOmcSha256 === info.omcSha256;
71 }
72 } catch {
73 // unreadable
74 }
75 }
76 return info;
77}
78
79function parseFrontmatter(content: string): { name?: string; description?: string } {
80 const m = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
81 if (!m) return {};
82 const fm = m[1];
83 const nameMatch = fm.match(/^name:\s*(.+)$/m);
84 let desc = '';
85 const descIdx = fm.search(/^description:/m);
86 if (descIdx >= 0) {
87 const after = fm.slice(descIdx).replace(/^description:\s*/, '');
88 const firstLine = after.split(/\r?\n/)[0].trim();
89 if (firstLine === '>' || firstLine === '>-' || firstLine === '|' || firstLine === '|-') {
90 const lines = after.split(/\r?\n/).slice(1);
91 const collected: string[] = [];
92 for (const l of lines) {
93 if (/^\s+/.test(l)) {
94 collected.push(l.trim());
95 } else {
96 break;
97 }
98 }
99 desc = collected.join(' ');
100 } else {
101 desc = firstLine.replace(/^["']|["']$/g, '');
102 }
103 }
104 return {
105 name: nameMatch ? nameMatch[1].trim().replace(/^["']|["']$/g, '') : undefined,
106 description: desc || undefined,
107 };
108}
109
110export function discoverSkills(harnessRoot: string): SkillMeta[] {
111 const skillsDir = path.join(harnessRoot, 'skills');
112 const results: SkillMeta[] = [];
113 let entries: fs.Dirent[] = [];
114 try {
115 entries = fs.readdirSync(skillsDir, { withFileTypes: true });
116 } catch {
117 return results;
118 }
119
120 for (const entry of entries) {
121 if (!entry.isDirectory()) continue;
122 const skillPath = path.join(skillsDir, entry.name, 'SKILL.md');
123 if (!fs.existsSync(skillPath)) continue;
124 try {
125 const content = fs.readFileSync(skillPath, 'utf8');
126 const fm = parseFrontmatter(content);
127 results.push({
128 name: fm.name || entry.name,
129 description: fm.description || 'Omega Harness skill',
130 filePath: skillPath,
131 });
132 } catch {
133 // skip unreadable
134 }
135 }
136
137 return results.sort((a, b) => a.name.localeCompare(b.name));
138}
139
140export function readSkillContent(harnessRoot: string, skillName: string): { meta: SkillMeta; content: string } | null {
141 const skills = discoverSkills(harnessRoot);
142 const match = skills.find(
143 (s) => s.name === skillName || s.name.toLowerCase() === skillName.toLowerCase()
144 );
145 if (!match) return null;
146 const content = fs.readFileSync(match.filePath, 'utf8');
147 return { meta: match, content };
148}
149
150export function loadErrorTable(harnessRoot: string): Map<number, OmcErrorDoc> {
151 const table = new Map<number, OmcErrorDoc>();
152 const refPath = path.join(harnessRoot, 'data', 'reference.tsv');
153 let raw = '';
154 try {
155 raw = fs.readFileSync(refPath, 'utf8');
156 } catch {
157 return table;
158 }
159
160 for (const line of raw.split(/\r?\n/)) {
161 const tab = line.indexOf('\t');
162 if (tab < 0) continue;
163 const key = line.slice(0, tab);
164 const val = line.slice(tab + 1);
165 const m = key.match(/^\/errors\/(\d+)\/(meaning|cause|fix)$/);
166 if (!m) continue;
167 const code = Number(m[1]);
168 const field = m[2] as 'meaning' | 'cause' | 'fix';
169 const doc = table.get(code) || { code, meaning: '' };
170 doc[field] = val;
171 table.set(code, doc);
172 }
173 return table;
174}
175
176export function compileOmFile(
177 sourcePath: string,
178 opts: { omcPath?: string; harnessRoot: string; outputPath?: string }
179): OmcCompileResult {
180 if (!opts.omcPath) {
181 return {
182 ok: false,
183 exitCode: 127,
184 stderr: 'omc compiler binary not found. Set OMEGA_OMC or install omc into ~/.local/bin/omc.',
185 };
186 }
187 if (!fs.existsSync(sourcePath)) {
188 return {
189 ok: false,
190 exitCode: 1,
191 stderr: `Source file not found: ${sourcePath}`,
192 omcPath: opts.omcPath,
193 };
194 }
195
196 const src = fs.readFileSync(sourcePath);
197 const tmpOut =
198 opts.outputPath ||
199 path.join(os.tmpdir(), `omega-cli-${process.pid}-${Date.now()}.bin`);
200
201 const res = spawnSync(opts.omcPath, [], {
202 input: src,
203 maxBuffer: 64 * 1024 * 1024,
204 timeout: 30_000,
205 });
206
207 const stderr = res.stderr ? res.stderr.toString('utf8').trim() : '';
208 const exitCode = res.status ?? 1;
209
210 if (exitCode !== 0) {
211 const errMatch = stderr.match(/error\s+(\d+)/);
212 const errorCode = errMatch ? Number(errMatch[1]) : undefined;
213 let errorDoc: OmcErrorDoc | undefined;
214 if (errorCode !== undefined) {
215 errorDoc = loadErrorTable(opts.harnessRoot).get(errorCode);
216 }
217 return {
218 ok: false,
219 exitCode,
220 stderr,
221 errorCode,
222 errorDoc,
223 omcPath: opts.omcPath,
224 };
225 }
226
227 const bin = res.stdout || Buffer.alloc(0);
228 fs.writeFileSync(tmpOut, bin, { mode: 0o755 });
229 return {
230 ok: true,
231 exitCode: 0,
232 stderr,
233 outputPath: tmpOut,
234 binarySize: bin.length,
235 omcPath: opts.omcPath,
236 };
237}
238
239export function compileAndRunOmFile(
240 sourcePath: string,
241 opts: { omcPath?: string; harnessRoot: string; stdin?: string; timeoutMs?: number }
242): OmcRunResult {
243 const compile = compileOmFile(sourcePath, {
244 omcPath: opts.omcPath,
245 harnessRoot: opts.harnessRoot,
246 });
247 if (!compile.ok || !compile.outputPath) {
248 return { compile, ran: false, stdout: '', stderr: compile.stderr };
249 }
250
251 try {
252 const run = spawnSync(compile.outputPath, [], {
253 input: opts.stdin ?? '',
254 encoding: 'utf8',
255 timeout: opts.timeoutMs ?? 10_000,
256 maxBuffer: 16 * 1024 * 1024,
257 });
258 const timedOut = Boolean(run.error && (run.error as NodeJS.ErrnoException).code === 'ETIMEDOUT');
259 return {
260 compile,
261 ran: true,
262 exitCode: run.status ?? undefined,
263 signal: run.signal,
264 stdout: run.stdout || '',
265 stderr: run.stderr || (run.error ? String(run.error.message) : ''),
266 timedOut,
267 };
268 } finally {
269 try {
270 fs.unlinkSync(compile.outputPath);
271 } catch {
272 // ignore cleanup error
273 }
274 }
275}
276
277export function buildSystemPrompt(opts: {
278 harnessRoot: string;
279 cwd: string;
280 activeSkills: string[];
281 approvalMode: string;
282 pinInfo: PinInfo;
283}): string {
284 const skills = discoverSkills(opts.harnessRoot);
285 const skillNames = skills.map((s) => s.name).join(', ');
286
287 const loadedSkillBlocks: string[] = [];
288 for (const name of opts.activeSkills) {
289 const loaded = readSkillContent(opts.harnessRoot, name);
290 if (loaded) {
291 const body =
292 loaded.content.length > 16000
293 ? loaded.content.slice(0, 16000) + '\n...[truncated; use read_file for full skill]...'
294 : loaded.content;
295 loadedSkillBlocks.push(`### Active Skill: ${loaded.meta.name}\n\n${body}`);
296 }
297 }
298
299 const omegaOnlyNote =
300 opts.approvalMode === 'omega-only'
301 ? ' OMEGA-ONLY MODE: write/edit only .om files and NOTES.md.'
302 : '';
303
304 return [
305 `You are Ω Omega Harness CLI, Drake Stapleton's systems-engineering coding agent (Inkling-2-Mini on GB10).`,
306 `cwd: ${opts.cwd} | harness: ${opts.harnessRoot} | mode: ${opts.approvalMode}.${omegaOnlyNote}`,
307 `Use your tools (files, shell, git, web, todo, memory, omc, spawn_subagent, spawn_parallel_subagents) to verify facts and execute work. Never fabricate outputs. Interplane is the canonical forge.`,
308 `Available skills (use load_skill): ${skillNames || 'none'}.`,
309 ...(loadedSkillBlocks.length > 0 ? ['', ...loadedSkillBlocks] : []),
310 ].join('\n');
311}