robisie 0.1.3 → 0.2.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +73 -19
  3. package/dist/agents.d.ts +1 -1
  4. package/dist/agents.js +1 -1
  5. package/dist/ci-failure-result.js +1 -1
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +45 -8
  8. package/dist/codex-env.d.ts +9 -0
  9. package/dist/codex-env.js +60 -0
  10. package/dist/commands.js +140 -16
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/constants.js +1 -1
  13. package/dist/delivery-local.d.ts +124 -0
  14. package/dist/delivery-local.js +286 -0
  15. package/dist/done-evidence.d.ts +25 -1
  16. package/dist/done-evidence.js +59 -1
  17. package/dist/engine/bundle-report.json +1687 -0
  18. package/dist/engine/tick.cjs +324704 -0
  19. package/dist/engine-config.d.ts +3 -1
  20. package/dist/engine-config.js +3 -3
  21. package/dist/factory-run.d.ts +17 -0
  22. package/dist/factory-run.js +262 -0
  23. package/dist/helpers.js +1 -1
  24. package/dist/k3-codex-job.d.ts +49 -0
  25. package/dist/k3-codex-job.js +324 -0
  26. package/dist/k3-helper-cli.d.ts +5 -0
  27. package/dist/k3-helper-cli.js +167 -0
  28. package/dist/local-usage.d.ts +47 -0
  29. package/dist/local-usage.js +230 -0
  30. package/dist/manifest.d.ts +5 -2
  31. package/dist/manifest.js +6 -6
  32. package/dist/opencode-review-guard.js +7 -2
  33. package/dist/planer-client.d.ts +45 -4
  34. package/dist/planer-client.js +120 -14
  35. package/dist/roles.d.ts +1 -1
  36. package/dist/seed-package.d.ts +10 -0
  37. package/dist/seed-package.js +62 -0
  38. package/dist/select-fingerprint.d.ts +19 -0
  39. package/dist/select-fingerprint.js +46 -0
  40. package/dist/task-mktemp.d.ts +1 -0
  41. package/dist/task-mktemp.js +40 -0
  42. package/dist/test-report.d.ts +9 -0
  43. package/dist/test-report.js +139 -0
  44. package/dist/tester-result-reader.d.ts +87 -0
  45. package/dist/tester-result-reader.js +122 -0
  46. package/docs/ENGINE-API.md +9 -1
  47. package/docs/README.en.md +161 -66
  48. package/docs/README.md +159 -66
  49. package/docs/RELEASE-0.1.0.md +29 -5
  50. package/helpers/ceo-client-launcher-mcp.mjs +76 -5
  51. package/package.json +6 -2
  52. package/roles/ceo-client.md +10 -8
@@ -0,0 +1,324 @@
1
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { closeSync, constants, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { isAbsolute, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { runK3CodexRole } from "./k3-codex-role.js";
7
+ const marker = "--k3-codex-supervisor";
8
+ const modulePath = fileURLToPath(import.meta.url);
9
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
10
+ const failures = ["invalid_output", "process_failed", "ENOENT", "EACCES", "ETIMEDOUT", "runner_io"];
11
+ const unknown = (reason) => ({ status: "unknown", reason });
12
+ const pause = (ms) => new Promise(done => setTimeout(done, ms));
13
+ function record(value) {
14
+ if (!value || typeof value !== "object" || Array.isArray(value))
15
+ throw new Error("invalid_state");
16
+ return value;
17
+ }
18
+ function code(error) {
19
+ try {
20
+ return record(error).code;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ function locations(stateDir, jobId) {
27
+ if (typeof stateDir !== "string" || !isAbsolute(stateDir) || typeof jobId !== "string" || !uuid.test(jobId))
28
+ throw new Error("invalid_identity");
29
+ const directory = join(resolve(stateDir), jobId);
30
+ return { jobId, stateDir: resolve(stateDir), directory, statePath: join(directory, "state.json"),
31
+ logPath: join(directory, "stdout.jsonl"), stderrPath: join(directory, "stderr.log"),
32
+ terminal: join(directory, "terminal.json"), request: join(directory, "request.json") };
33
+ }
34
+ function privateRead(path) {
35
+ const stat = lstatSync(path);
36
+ if (!stat.isFile() || (stat.mode & 0o077) !== 0)
37
+ throw new Error("invalid_state");
38
+ return readFileSync(path, "utf8");
39
+ }
40
+ function loadState(stateDir, jobId) {
41
+ const paths = locations(stateDir, jobId);
42
+ const directory = lstatSync(paths.directory);
43
+ if (!directory.isDirectory() || (directory.mode & 0o077) !== 0)
44
+ throw new Error("invalid_state");
45
+ const value = record(JSON.parse(privateRead(paths.statePath)));
46
+ if (value.version !== 1 || value.jobId !== jobId || value.stateDir !== paths.stateDir
47
+ || !Number.isSafeInteger(value.pid) || value.pid <= 1 || value.pgid !== value.pid
48
+ || typeof value.identity !== "string" || !uuid.test(value.identity))
49
+ throw new Error("invalid_state");
50
+ return value;
51
+ }
52
+ function terminal(state) {
53
+ let raw;
54
+ try {
55
+ raw = privateRead(locations(state.stateDir, state.jobId).terminal);
56
+ }
57
+ catch (error) {
58
+ if (code(error) === "ENOENT")
59
+ return null;
60
+ throw error;
61
+ }
62
+ const value = record(JSON.parse(raw));
63
+ if (value.version !== 1 || value.jobId !== state.jobId || value.stateDir !== state.stateDir || value.identity !== state.identity)
64
+ throw new Error("invalid_terminal");
65
+ const result = record(value.result);
66
+ if (result.status === "cancelled")
67
+ return { status: "cancelled" };
68
+ if (result.status === "completed" && typeof result.report === "string" && result.report.trim())
69
+ return { status: "completed", report: result.report };
70
+ if (result.status === "failed" && typeof result.reason === "string" && failures.includes(result.reason))
71
+ return { status: "failed", reason: result.reason };
72
+ throw new Error("invalid_terminal");
73
+ }
74
+ function publish(state, result) {
75
+ const path = locations(state.stateDir, state.jobId).terminal;
76
+ const temporary = `${path}.${randomUUID()}.tmp`;
77
+ try {
78
+ writeFileSync(temporary, JSON.stringify({ version: 1, jobId: state.jobId, stateDir: state.stateDir, identity: state.identity, result }), { flag: "wx", mode: 0o600 });
79
+ // Atomic first-writer wins: no lock survives a crash or spans the CLI run.
80
+ try {
81
+ linkSync(temporary, path);
82
+ }
83
+ catch (error) {
84
+ if (code(error) !== "EEXIST")
85
+ throw error;
86
+ }
87
+ const stored = terminal(state);
88
+ if (!stored)
89
+ throw new Error("terminal_io");
90
+ return stored;
91
+ }
92
+ finally {
93
+ try {
94
+ unlinkSync(temporary);
95
+ }
96
+ catch (error) {
97
+ if (code(error) !== "ENOENT")
98
+ throw new Error("terminal_io");
99
+ }
100
+ }
101
+ }
102
+ function alive(pid, deps) {
103
+ if (deps.isAlive)
104
+ return deps.isAlive(pid);
105
+ try {
106
+ (deps.kill ?? process.kill)(pid, 0);
107
+ return true;
108
+ }
109
+ catch (error) {
110
+ if (code(error) === "ESRCH")
111
+ return false;
112
+ throw error;
113
+ }
114
+ }
115
+ function verify(state, deps) {
116
+ const command = deps.command ? deps.command(state.pid) : execFileSync("/bin/ps", ["-ww", "-p", String(state.pid), "-o", "pgid=,command="], { encoding: "utf8", timeout: 2000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "ignore"] });
117
+ const match = /^\s*(\d+)\s+(.+?)\s*$/.exec(command);
118
+ return Number(match?.[1]) === state.pgid
119
+ && match?.[2] === [process.execPath, modulePath, marker, state.jobId, state.stateDir, state.identity].join(" ");
120
+ }
121
+ /** Validate without CLI, persist private input, and detach a Node supervisor. Env is passed only to spawn. */
122
+ export async function startK3CodexJob(bundle, options, stateDir, deps = {}) {
123
+ runK3CodexRole(bundle, options, () => ({ pid: 0, output: [null, "", ""], stdout: "", stderr: "", status: 0, signal: null }));
124
+ if (typeof stateDir !== "string" || !isAbsolute(stateDir))
125
+ throw new Error("K3 Codex: stateDir must be an absolute path");
126
+ if (process.platform === "win32")
127
+ throw new Error("K3 Codex: unsupported platform");
128
+ const paths = locations(stateDir, randomUUID());
129
+ const identity = randomUUID();
130
+ let created = false;
131
+ try {
132
+ mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 });
133
+ mkdirSync(paths.directory, { mode: 0o700 });
134
+ created = true;
135
+ // Persist only the contract fields; env never goes onto disk or argv.
136
+ writeFileSync(paths.request, JSON.stringify({ bundle: { disposition: bundle.disposition, instructions: bundle.instructions,
137
+ execution: { provider: bundle.execution.provider, model: bundle.execution.model, effort: bundle.execution.effort } },
138
+ options: { binary: options.binary, cwd: options.cwd, sandbox: options.sandbox, timeoutMs: options.timeoutMs } }), { flag: "wx", mode: 0o600 });
139
+ for (const path of [paths.logPath, paths.stderrPath])
140
+ writeFileSync(path, "", { flag: "wx", mode: 0o600 });
141
+ const child = (deps.spawn ?? spawn)(process.execPath, [modulePath, marker, paths.jobId, paths.stateDir, identity], { detached: true, stdio: "ignore", env: options.env, cwd: options.cwd });
142
+ await new Promise((done, reject) => {
143
+ child.once("error", reject);
144
+ child.once("spawn", () => done());
145
+ });
146
+ child.unref();
147
+ if (!child.pid)
148
+ throw new Error("supervisor_spawn");
149
+ const state = { version: 1, jobId: paths.jobId, stateDir: paths.stateDir, identity, pid: child.pid, pgid: child.pid };
150
+ const temporary = `${paths.statePath}.tmp`;
151
+ writeFileSync(temporary, JSON.stringify(state), { flag: "wx", mode: 0o600 });
152
+ renameSync(temporary, paths.statePath);
153
+ return { jobId: paths.jobId, stateDir: paths.stateDir, statePath: paths.statePath, logPath: paths.logPath, stderrPath: paths.stderrPath };
154
+ }
155
+ catch (error) {
156
+ if (created) {
157
+ try {
158
+ rmSync(paths.directory, { recursive: true, force: true });
159
+ }
160
+ catch {
161
+ throw new Error("K3 Codex: job start cleanup failed");
162
+ }
163
+ }
164
+ if (code(error) === "EPERM")
165
+ throw Object.assign(new Error("K3 Codex: job process permission denied"), { code: "EPERM" });
166
+ throw new Error("K3 Codex: job start IO failed");
167
+ }
168
+ }
169
+ /** Read durable state from any caller; unsupported, corrupt, dead or unreadable jobs remain unknown. */
170
+ export async function readK3CodexJob(stateDir, jobId, deps = {}) {
171
+ if (process.platform === "win32")
172
+ return unknown("unsupported_platform");
173
+ try {
174
+ const state = loadState(stateDir, jobId);
175
+ const stored = terminal(state);
176
+ if (stored)
177
+ return stored;
178
+ if (alive(-state.pgid, deps)) {
179
+ try {
180
+ if (verify(state, deps))
181
+ return { status: "running" };
182
+ }
183
+ catch (error) {
184
+ if (code(error) === "EPERM")
185
+ throw error;
186
+ }
187
+ }
188
+ // Completion may have been published while checking the leader.
189
+ return terminal(state) ?? unknown("runner_not_verified");
190
+ }
191
+ catch (error) {
192
+ return unknown(code(error) === "EPERM" ? "process_permission_denied" : "state_or_process_unavailable");
193
+ }
194
+ }
195
+ /** Signal only a verified own POSIX group; cancelled is published only after ESRCH. */
196
+ export async function cancelK3CodexJob(stateDir, jobId, deps = {}) {
197
+ if (process.platform === "win32")
198
+ return unknown("unsupported_platform");
199
+ try {
200
+ const state = loadState(stateDir, jobId);
201
+ const stored = terminal(state);
202
+ if (stored)
203
+ return stored;
204
+ if (!alive(-state.pgid, deps) || !verify(state, deps))
205
+ return terminal(state) ?? unknown("runner_not_verified");
206
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
207
+ // After TERM the leader can exit before its descendants; a reused live leader is unsafe.
208
+ if (signal === "SIGKILL" && alive(state.pid, deps) && !verify(state, deps))
209
+ return unknown("runner_identity_changed");
210
+ try {
211
+ (deps.kill ?? process.kill)(-state.pgid, signal);
212
+ }
213
+ catch (error) {
214
+ if (code(error) !== "ESRCH")
215
+ throw error;
216
+ }
217
+ const deadline = Date.now() + 1500;
218
+ do {
219
+ if (!alive(-state.pgid, deps) && !alive(state.pid, deps))
220
+ return publish(state, { status: "cancelled" });
221
+ await pause(25);
222
+ } while (Date.now() < deadline);
223
+ }
224
+ return unknown("termination_unconfirmed");
225
+ }
226
+ catch (error) {
227
+ return unknown(code(error) === "EPERM" ? "process_permission_denied" : "cancel_unavailable");
228
+ }
229
+ }
230
+ function report(stdout) {
231
+ let last = null;
232
+ try {
233
+ for (const line of stdout.trim().split("\n")) {
234
+ const event = record(JSON.parse(line));
235
+ if (event.type !== "item.completed")
236
+ continue;
237
+ const item = record(event.item);
238
+ if (item.type === "agent_message" && typeof item.text === "string" && item.text.trim())
239
+ last = item.text;
240
+ }
241
+ return last;
242
+ }
243
+ catch {
244
+ return null;
245
+ }
246
+ }
247
+ async function supervise(jobId, stateDir, identity) {
248
+ let state;
249
+ let stdoutFd;
250
+ let stderrFd;
251
+ let result = { status: "failed", reason: "runner_io" };
252
+ try {
253
+ // Parent records the PID after spawn. A vanished parent cannot authorize CLI execution.
254
+ const deadline = Date.now() + 2000;
255
+ while (!state) {
256
+ try {
257
+ state = loadState(stateDir, jobId);
258
+ }
259
+ catch (error) {
260
+ if (code(error) !== "ENOENT" || Date.now() >= deadline)
261
+ throw error;
262
+ await pause(10);
263
+ }
264
+ }
265
+ if (state.pid !== process.pid || state.identity !== identity) {
266
+ state = undefined;
267
+ throw new Error("identity_mismatch");
268
+ }
269
+ const paths = locations(stateDir, jobId);
270
+ const request = JSON.parse(privateRead(paths.request));
271
+ stdoutFd = openSync(paths.logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW);
272
+ stderrFd = openSync(paths.stderrPath, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW);
273
+ let failure = "process_failed";
274
+ try {
275
+ const execution = runK3CodexRole(request.bundle, { ...request.options, env: process.env }, (binary, argv, options) => {
276
+ // File descriptors avoid inherited output pipes keeping spawnSync alive.
277
+ const child = spawnSync(binary, argv, { ...options, stdio: ["pipe", stdoutFd, stderrFd] });
278
+ const errorCode = code(child.error);
279
+ if (errorCode === "ETIMEDOUT" || errorCode === "ENOENT" || errorCode === "EACCES")
280
+ failure = errorCode;
281
+ return { ...child, stdout: readFileSync(paths.logPath, "utf8"), stderr: readFileSync(paths.stderrPath, "utf8") };
282
+ });
283
+ const text = report(execution.stdout);
284
+ result = text === null ? { status: "failed", reason: "invalid_output" } : { status: "completed", report: text };
285
+ }
286
+ catch {
287
+ result = { status: "failed", reason: failure };
288
+ }
289
+ }
290
+ catch {
291
+ result = { status: "failed", reason: "runner_io" };
292
+ }
293
+ finally {
294
+ try {
295
+ if (state)
296
+ publish(state, result);
297
+ }
298
+ catch { /* Missing terminal deliberately reads unknown; cleanup still runs. */ }
299
+ finally {
300
+ for (const fd of [stdoutFd, stderrFd]) {
301
+ if (fd !== undefined)
302
+ try {
303
+ closeSync(fd);
304
+ }
305
+ catch { /* Group is terminating regardless. */ }
306
+ }
307
+ // spawnSync cannot service JS signal handlers. Always kill our detached group,
308
+ // including provider descendants, even when terminal publication failed.
309
+ try {
310
+ process.kill(-process.pid, "SIGKILL");
311
+ }
312
+ catch {
313
+ process.exitCode = 1;
314
+ }
315
+ }
316
+ }
317
+ }
318
+ if (process.argv[1] && resolve(process.argv[1]) === modulePath && process.argv[2] === marker) {
319
+ const [jobId, stateDir, identity] = process.argv.slice(3);
320
+ if (jobId && stateDir && identity)
321
+ void supervise(jobId, stateDir, identity);
322
+ else
323
+ process.exitCode = 1;
324
+ }
@@ -0,0 +1,5 @@
1
+ /** A thin worker-backend protocol adapter. Importing this module starts nothing. */
2
+ export declare function runK3HelperCli(args: string[], env?: NodeJS.ProcessEnv): Promise<{
3
+ exitCode: number;
4
+ output: string;
5
+ }>;
@@ -0,0 +1,167 @@
1
+ import { accessSync, constants, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { cancelK3CodexJob, readK3CodexJob, startK3CodexJob } from "./k3-codex-job.js";
5
+ function errorCode(error) {
6
+ return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
7
+ }
8
+ function invalid(code = "INVALID_ARGUMENTS") {
9
+ throw Object.assign(new Error(code), { code });
10
+ }
11
+ function text(value) {
12
+ return typeof value === "string" && Boolean(value.trim()) && !value.includes("\0") && value !== "null" && value !== "undefined";
13
+ }
14
+ function absolute(value, code = "INVALID_ARGUMENTS") {
15
+ if (!text(value) || !isAbsolute(value))
16
+ invalid(code);
17
+ return resolve(value);
18
+ }
19
+ // Resolve existing ancestors too: a state path through a repo symlink is still inside the repo.
20
+ function physical(path) {
21
+ try {
22
+ return realpathSync(path);
23
+ }
24
+ catch (error) {
25
+ if (errorCode(error) !== "ENOENT" || dirname(path) === path)
26
+ throw error;
27
+ return join(physical(dirname(path)), basename(path));
28
+ }
29
+ }
30
+ function repositoryRoot(cwd) {
31
+ for (let path = cwd;; path = dirname(path)) {
32
+ // Both ordinary repositories and worktrees have a .git entry (directory or file).
33
+ try {
34
+ statSync(join(path, ".git"));
35
+ return path;
36
+ }
37
+ catch (error) {
38
+ if (errorCode(error) !== "ENOENT")
39
+ throw error;
40
+ }
41
+ if (dirname(path) === path)
42
+ return cwd;
43
+ }
44
+ }
45
+ function executable(path) {
46
+ if (!statSync(path).isFile())
47
+ invalid("EACCES");
48
+ accessSync(path, constants.X_OK);
49
+ return path;
50
+ }
51
+ function findBinary(path, cwd) {
52
+ let denied = false;
53
+ for (const entry of path.split(delimiter)) {
54
+ try {
55
+ return executable(resolve(cwd, entry, "codex"));
56
+ }
57
+ catch (error) {
58
+ const code = errorCode(error);
59
+ if (code === "EACCES")
60
+ denied = true;
61
+ else if (code !== "ENOENT" && code !== "ENOTDIR")
62
+ throw error;
63
+ }
64
+ }
65
+ return invalid(denied ? "EACCES" : "ENOENT");
66
+ }
67
+ /** A thin worker-backend protocol adapter. Importing this module starts nothing. */
68
+ export async function runK3HelperCli(args, env = process.env) {
69
+ const reply = (exitCode, value) => ({ exitCode, output: JSON.stringify(value) + "\n" });
70
+ try {
71
+ if (!Array.isArray(args) || !args.every(text))
72
+ invalid();
73
+ const [command] = args;
74
+ if (!["task", "status", "result", "cancel"].includes(command ?? ""))
75
+ invalid();
76
+ const task = command === "task";
77
+ const probe = command === "status" && (args[1] === undefined || args[1].startsWith("--"));
78
+ const jobId = task || probe ? undefined : args[1];
79
+ if (!task && !probe && (!text(jobId) || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(jobId)))
80
+ invalid();
81
+ const values = new Map();
82
+ const booleans = task ? ["--background", "--write"] : ["--json"];
83
+ const valued = ["--state-dir", ...(task || command === "status" ? ["--cwd"] : []),
84
+ ...(task ? ["--effort", "--model", "--prompt-file", "--binary"] : [])];
85
+ for (let index = task || probe ? 1 : 2; index < args.length; index++) {
86
+ const flag = args[index];
87
+ if (values.has(flag))
88
+ invalid();
89
+ if (booleans.includes(flag))
90
+ values.set(flag, "true");
91
+ else if (valued.includes(flag)) {
92
+ const value = args[++index];
93
+ if (!text(value) || value.startsWith("--"))
94
+ invalid();
95
+ values.set(flag, value);
96
+ }
97
+ else
98
+ invalid();
99
+ }
100
+ if (probe && !values.has("--json"))
101
+ invalid();
102
+ const home = absolute(env.HOME, "INVALID_ENV");
103
+ const stateDir = absolute(values.get("--state-dir") ?? join(home, ".local/state/robisie/k3-jobs"));
104
+ if (!task && !probe) {
105
+ const id = jobId;
106
+ const result = await (command === "cancel" ? cancelK3CodexJob : readK3CodexJob)(stateDir, id);
107
+ const envelope = { jobId: id, job: { id, status: result.status } };
108
+ if (command !== "result" || result.status === "running" || result.status === "unknown")
109
+ return reply(0, envelope);
110
+ if (result.status === "completed")
111
+ return reply(0, { ...envelope, result: { rawOutput: result.report } });
112
+ return reply(0, { ...envelope, result: { rawOutput: "" }, rendered: result.status === "failed" ? result.reason : "cancelled" });
113
+ }
114
+ if (task)
115
+ for (const flag of ["--effort", "--model", "--prompt-file"])
116
+ if (!values.has(flag))
117
+ invalid();
118
+ const cwd = realpathSync(resolve(values.get("--cwd") ?? process.cwd()));
119
+ if (!statSync(cwd).isDirectory())
120
+ invalid();
121
+ const stateRelative = relative(repositoryRoot(cwd), physical(stateDir));
122
+ if (!stateRelative || (!stateRelative.startsWith(`..${sep}`) && stateRelative !== ".." && !isAbsolute(stateRelative)))
123
+ invalid();
124
+ if (probe) {
125
+ if (!text(env.PATH))
126
+ invalid("INVALID_ENV");
127
+ const binary = findBinary(env.PATH, cwd);
128
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
129
+ accessSync(stateDir, constants.R_OK | constants.W_OK | constants.X_OK);
130
+ return reply(0, { runtime: "ok", binary, authentication: "unchecked" });
131
+ }
132
+ const codexHome = absolute(env.CODEX_HOME === undefined ? join(home, ".codex") : env.CODEX_HOME, "INVALID_ENV");
133
+ if (!text(env.PATH))
134
+ invalid("INVALID_ENV");
135
+ const binary = values.has("--binary") ? executable(absolute(values.get("--binary"))) : findBinary(env.PATH, cwd);
136
+ const instructions = readFileSync(resolve(cwd, values.get("--prompt-file")), "utf8");
137
+ if (!instructions.trim())
138
+ invalid();
139
+ const handle = await startK3CodexJob({ disposition: "READY", instructions,
140
+ execution: { provider: "codex", model: values.get("--model"), effort: values.get("--effort") } }, { binary, cwd, env: { ...env, CODEX_HOME: codexHome }, sandbox: values.has("--write") ? "workspace-write" : "read-only",
141
+ timeoutMs: 2700000 }, stateDir);
142
+ return reply(0, { jobId: handle.jobId });
143
+ }
144
+ catch (error) {
145
+ const code = errorCode(error);
146
+ return reply(1, { errorCode: typeof code === "string" && ["ENOENT", "EACCES", "INVALID_ARGUMENTS", "INVALID_ENV"].includes(code) ? code : "HELPER_IO" });
147
+ }
148
+ }
149
+ function isEntrypoint() {
150
+ try {
151
+ return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
152
+ }
153
+ catch {
154
+ return false;
155
+ } // An absent/unreadable caller path must not make an import start a job.
156
+ }
157
+ if (isEntrypoint()) {
158
+ void runK3HelperCli(process.argv.slice(2)).then(result => {
159
+ process.exitCode = result.exitCode;
160
+ try {
161
+ process.stdout.write(result.output);
162
+ }
163
+ catch {
164
+ process.exitCode = 1;
165
+ }
166
+ }).catch(() => { process.exitCode = 1; });
167
+ }
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ declare const eventSchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ at: z.ZodISODateTime;
5
+ sha: z.ZodString;
6
+ ref: z.ZodString;
7
+ operation: z.ZodString;
8
+ result: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export type UsageEvent = z.infer<typeof eventSchema>;
11
+ export type LocalUsageEvent = UsageEvent & {
12
+ bytes: string;
13
+ sha256: string;
14
+ };
15
+ export type LocalUsageReadInput = {
16
+ landed: {
17
+ sha?: unknown;
18
+ at?: unknown;
19
+ };
20
+ source: string;
21
+ deadline: string;
22
+ readAt: string;
23
+ };
24
+ export type RunLocalUsageInput = {
25
+ repo: string;
26
+ stateDir: string;
27
+ landed: {
28
+ sha: string;
29
+ at: string;
30
+ };
31
+ source: string;
32
+ deadline: string;
33
+ operation: string;
34
+ program: {
35
+ entry: string;
36
+ args: readonly string[];
37
+ artifact: string;
38
+ };
39
+ };
40
+ export declare function relative(ref: string): void;
41
+ export declare function within(root: string, ref: string): string;
42
+ /** The transport already bounds model output to 256 KiB; inputs use the same byte bound. */
43
+ export declare function bounded(file: string): string;
44
+ export declare function readLocalUsageEvents(root: string, c: LocalUsageReadInput): LocalUsageEvent[];
45
+ /** One synchronous Node invocation; no shell, card commands, inherited credentials or control env. */
46
+ export declare function runLocalUsage(input: RunLocalUsageInput): UsageEvent;
47
+ export {};