alineo 0.6.0 → 0.8.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.
@@ -0,0 +1,855 @@
1
+ let node_child_process = require("node:child_process");
2
+ let node_fs = require("node:fs");
3
+ let node_http = require("node:http");
4
+ let node_readline = require("node:readline");
5
+ //#region src/permissions.ts
6
+ /**
7
+ * First tokens that make a shell command a pure reader — used by the `"classify"` action
8
+ * and by the `bash` rule `"readonly"` installs. Deliberately conservative: an unrecognised
9
+ * command falls through to `ask`, never to `allow`.
10
+ */
11
+ const SAFE_BASH_COMMANDS = [
12
+ "ls",
13
+ "cat",
14
+ "head",
15
+ "tail",
16
+ "grep",
17
+ "rg",
18
+ "egrep",
19
+ "fgrep",
20
+ "zgrep",
21
+ "find",
22
+ "pwd",
23
+ "whoami",
24
+ "id",
25
+ "env",
26
+ "printenv",
27
+ "echo",
28
+ "printf",
29
+ "which",
30
+ "type",
31
+ "file",
32
+ "stat",
33
+ "wc",
34
+ "date",
35
+ "uname",
36
+ "hostname",
37
+ "df",
38
+ "du",
39
+ "tree",
40
+ "basename",
41
+ "dirname",
42
+ "realpath",
43
+ "readlink",
44
+ "true",
45
+ "false",
46
+ "cmp",
47
+ "diff",
48
+ "column",
49
+ "nl",
50
+ "less",
51
+ "more",
52
+ "tac",
53
+ "hexdump",
54
+ "xxd",
55
+ "od",
56
+ "strings",
57
+ "sha1sum",
58
+ "sha256sum",
59
+ "md5sum",
60
+ "cksum"
61
+ ];
62
+ /** `git <sub>` combinations that only read. */
63
+ const SAFE_GIT_SUBCOMMANDS = [
64
+ "status",
65
+ "log",
66
+ "diff",
67
+ "show",
68
+ "branch",
69
+ "remote",
70
+ "rev-parse",
71
+ "describe",
72
+ "blame",
73
+ "tag",
74
+ "config",
75
+ "ls-files",
76
+ "ls-tree",
77
+ "shortlog",
78
+ "reflog",
79
+ "cat-file",
80
+ "for-each-ref",
81
+ "whatchanged",
82
+ "rev-list",
83
+ "name-rev",
84
+ "symbolic-ref",
85
+ "count-objects"
86
+ ];
87
+ const WRAPPER_COMMANDS = /* @__PURE__ */ new Set([
88
+ "env",
89
+ "command",
90
+ "nice",
91
+ "stdbuf",
92
+ "time"
93
+ ]);
94
+ /**
95
+ * True if `seg` contains a file output redirection (`> file`, `>> file`). A `>` immediately
96
+ * followed by `&` (`2>&1`, `>&2`), preceded by a digit (`2>`, stderr), or preceded by `&`
97
+ * is a file-descriptor op, not a file write. Linear scan — no regex (ReDoS-safe).
98
+ */
99
+ function hasOutputRedirect(seg) {
100
+ for (let i = 0; i < seg.length; i++) {
101
+ if (seg[i] !== ">") continue;
102
+ const next = seg[i + 1];
103
+ const prev = seg[i - 1];
104
+ if (next === "&" || prev === "&" || prev >= "0" && prev <= "9") continue;
105
+ return true;
106
+ }
107
+ return false;
108
+ }
109
+ /**
110
+ * Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
111
+ * recognised pure reader with no output redirection; `false` = something needs a human.
112
+ * Mirrored verbatim in `bridge/pi-permission-gate.ts`.
113
+ */
114
+ function isReadOnlyBashCommand(command) {
115
+ const segments = command.split(/&&|\|\||[;\n|]/).map((s) => s.trim()).filter(Boolean);
116
+ if (segments.length === 0) return false;
117
+ return segments.every((seg) => {
118
+ if (hasOutputRedirect(seg)) return false;
119
+ let tokens = seg.split(/\s+/).filter(Boolean);
120
+ while (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) tokens = tokens.slice(1);
121
+ while (tokens.length > 1 && WRAPPER_COMMANDS.has(tokens[0])) tokens = tokens.slice(1);
122
+ if (tokens[0] === "timeout" && tokens.length > 2) tokens = tokens.slice(2);
123
+ const first = tokens[0] ?? "";
124
+ const slash = first.lastIndexOf("/");
125
+ const cmd = slash === -1 ? first : first.slice(slash + 1);
126
+ if (!cmd) return false;
127
+ if (SAFE_BASH_COMMANDS.includes(cmd)) return true;
128
+ if (cmd === "git" && SAFE_GIT_SUBCOMMANDS.includes(tokens[1] ?? "")) return true;
129
+ return false;
130
+ });
131
+ }
132
+ /** Compile a rule glob to an anchored RegExp. `*` → `.*`, `?` → `.`, everything else literal. */
133
+ function globToRegExp(glob) {
134
+ const body = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
135
+ return new RegExp(`^${body}$`, "s");
136
+ }
137
+ function ruleMatches(rule, tool, target) {
138
+ if (!globToRegExp(rule.tool).test(tool)) return false;
139
+ if (rule.pattern !== void 0 && !globToRegExp(rule.pattern).test(target)) return false;
140
+ return true;
141
+ }
142
+ /**
143
+ * Resolve a tool call to an action: the last matching rule's, or the policy default.
144
+ * `disabledTools` short-circuits to `"deny"`. `"classify"` is resolved here to `"allow"`
145
+ * or `"ask"` (bash reader-triage; any other tool → `"ask"`).
146
+ */
147
+ function evaluatePolicy(policy, tool, target) {
148
+ if (policy.disabledTools.includes(tool)) return { action: "deny" };
149
+ let match;
150
+ for (const rule of policy.rules) if (ruleMatches(rule, tool, target)) match = rule;
151
+ if ((match ? match.action : policy.default) === "classify") return {
152
+ action: tool === "bash" && isReadOnlyBashCommand(target) ? "allow" : "ask",
153
+ rule: match
154
+ };
155
+ return match ? {
156
+ action: match.action,
157
+ rule: match
158
+ } : { action: policy.default };
159
+ }
160
+ //#endregion
161
+ //#region src/bridge/codex-bridge.ts
162
+ /**
163
+ * The in-sandbox bridge for Codex: runs `codex app-server --listen stdio://` as a long-lived
164
+ * child, speaks its JSON-RPC (thread / turn / item), and serves the same HTTP+SSE contract as
165
+ * the other bridges (`harness/bridge.ts`), each frame already a `HarnessEvent`.
166
+ *
167
+ * Bundled to one CommonJS file (`dist/codex-bridge.cjs`) and written into the sandbox at
168
+ * `/alineo-bridge.js`. The `codex` binary is installed globally in the sandbox image.
169
+ *
170
+ * Protocol facts used here come from codex-rs `app-server-protocol` (2026-09-13):
171
+ * `turn/start`, `turn/steer` (needs the active turn id), `turn/interrupt`,
172
+ * `thread/compact/start`, `thread/fork` (by `lastTurnId`, the turn cannot be in progress),
173
+ * and the server requests `item/commandExecution/requestApproval` and
174
+ * `item/fileChange/requestApproval`.
175
+ */
176
+ const PORT = Number(process.env.ALINEO_BRIDGE_PORT) || 3001;
177
+ const ENV_FILE = process.env.ALINEO_ENV_FILE || "/etc/alineo-env";
178
+ const CONFIG_FILE = process.env.ALINEO_CODEX_CONFIG || "/etc/alineo-codex.json";
179
+ const THREAD_FILE = process.env.ALINEO_CODEX_THREAD_FILE || "/tmp/alineo-codex-thread";
180
+ const CODEX_BIN = process.env.ALINEO_CODEX_BIN || "codex";
181
+ const PERMISSION_TIMEOUT_MS = 3e5;
182
+ const RPC_TIMEOUT_MS = 3e4;
183
+ const logBuf = [];
184
+ function log(msg) {
185
+ const entry = "[" + (/* @__PURE__ */ new Date()).toISOString() + "] " + msg;
186
+ if (logBuf.length >= 200) logBuf.shift();
187
+ logBuf.push(entry);
188
+ process.stderr.write(entry + "\n");
189
+ }
190
+ function loadEnv() {
191
+ if (!(0, node_fs.existsSync)(ENV_FILE)) return;
192
+ for (const line of (0, node_fs.readFileSync)(ENV_FILE, "utf8").split("\n")) {
193
+ const m = line.match(/^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/);
194
+ if (m) process.env[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
195
+ }
196
+ }
197
+ function loadConfig() {
198
+ try {
199
+ return JSON.parse((0, node_fs.readFileSync)(CONFIG_FILE, "utf8"));
200
+ } catch {
201
+ return {};
202
+ }
203
+ }
204
+ function send(res, frame) {
205
+ try {
206
+ res.write("data: " + JSON.stringify(frame) + "\n\n");
207
+ } catch {}
208
+ }
209
+ function respond(res, status, body) {
210
+ try {
211
+ res.writeHead(status, { "Content-Type": "application/json" });
212
+ res.end(JSON.stringify(body));
213
+ } catch {}
214
+ }
215
+ let proc = null;
216
+ let nextId = 1;
217
+ const pending = /* @__PURE__ */ new Map();
218
+ function write(msg) {
219
+ proc?.stdin?.write(JSON.stringify(msg) + "\n");
220
+ }
221
+ function request(method, params) {
222
+ return new Promise((resolve, reject) => {
223
+ const id = nextId++;
224
+ const timer = setTimeout(() => {
225
+ pending.delete(id);
226
+ reject(/* @__PURE__ */ new Error(`codex app-server ${method} timed out`));
227
+ }, RPC_TIMEOUT_MS);
228
+ pending.set(id, {
229
+ resolve,
230
+ reject,
231
+ timer
232
+ });
233
+ write(params === void 0 ? {
234
+ method,
235
+ id
236
+ } : {
237
+ method,
238
+ id,
239
+ params
240
+ });
241
+ });
242
+ }
243
+ function failAll(why) {
244
+ for (const p of pending.values()) {
245
+ clearTimeout(p.timer);
246
+ p.reject(new Error(why));
247
+ }
248
+ pending.clear();
249
+ }
250
+ const state = {
251
+ ready: false,
252
+ threadId: null,
253
+ active: null,
254
+ pending: /* @__PURE__ */ new Map(),
255
+ alwaysAllow: /* @__PURE__ */ new Set(),
256
+ config: {}
257
+ };
258
+ /** Interrupt the running turn, once its id is known. */
259
+ function interruptIfRequested() {
260
+ const a = state.active;
261
+ if (a?.abortPending && a.turnId && state.threadId) {
262
+ a.abortPending = false;
263
+ request("turn/interrupt", {
264
+ threadId: state.threadId,
265
+ turnId: a.turnId
266
+ }).catch(() => {});
267
+ }
268
+ }
269
+ function emit(frame) {
270
+ if (state.active) send(state.active.res, frame);
271
+ }
272
+ /** Park a request for the host. Resolves with the decision. */
273
+ function park(requestId, tool, target, title) {
274
+ return new Promise((resolve) => {
275
+ const settle = (d) => {
276
+ clearTimeout(timer);
277
+ state.pending.delete(requestId);
278
+ resolve(d);
279
+ };
280
+ const timer = setTimeout(() => {
281
+ settle({
282
+ kind: "reject",
283
+ feedback: "Approval timed out."
284
+ });
285
+ }, PERMISSION_TIMEOUT_MS);
286
+ state.pending.set(requestId, {
287
+ requestId,
288
+ tool,
289
+ target,
290
+ title,
291
+ since: Date.now(),
292
+ settle,
293
+ timer
294
+ });
295
+ emit({
296
+ type: "permission_request",
297
+ requestId,
298
+ tool,
299
+ target,
300
+ title
301
+ });
302
+ });
303
+ }
304
+ /**
305
+ * Decide an approval request from the app-server. `accept`, `acceptForSession` or `decline`.
306
+ * With no policy, everything is accepted (the thread is also started with `approvalPolicy:
307
+ * never`, so none arrive).
308
+ */
309
+ async function decide(requestId, tool, target) {
310
+ const policy = state.config.permissions;
311
+ if (!policy) return "accept";
312
+ if (policy.restrictToTools.length > 0 && !policy.restrictToTools.includes(tool)) return "decline";
313
+ const key = `${tool} ${target}`;
314
+ if (state.alwaysAllow.has(key)) return "accept";
315
+ const { action } = evaluatePolicy(policy, tool, target);
316
+ if (action === "allow") return "accept";
317
+ if (action === "deny") return "decline";
318
+ const decision = await park(requestId, tool, target, `Run ${tool}: ${target}`);
319
+ emit({
320
+ type: "permission_resolved",
321
+ requestId,
322
+ decision
323
+ });
324
+ if (decision.kind === "once") return "accept";
325
+ if (decision.kind === "always") {
326
+ state.alwaysAllow.add(key);
327
+ for (const other of [...state.pending.values()]) if (other.tool === tool) other.settle({ kind: "once" });
328
+ return "acceptForSession";
329
+ }
330
+ return "decline";
331
+ }
332
+ async function onServerRequest(id, method, params) {
333
+ try {
334
+ if (method === "item/commandExecution/requestApproval") {
335
+ write({
336
+ id,
337
+ result: { decision: await decide(String(params.approvalId ?? params.itemId ?? id), "bash", typeof params.command === "string" ? params.command : "") }
338
+ });
339
+ return;
340
+ }
341
+ if (method === "item/fileChange/requestApproval") {
342
+ write({
343
+ id,
344
+ result: { decision: await decide(String(params.itemId ?? id), "edit", typeof params.reason === "string" ? params.reason : "") }
345
+ });
346
+ return;
347
+ }
348
+ write({
349
+ id,
350
+ error: {
351
+ code: -32601,
352
+ message: `Client does not support ${method}`
353
+ }
354
+ });
355
+ } catch (e) {
356
+ write({
357
+ id,
358
+ error: {
359
+ code: -32603,
360
+ message: e instanceof Error ? e.message : String(e)
361
+ }
362
+ });
363
+ }
364
+ }
365
+ /** The turn id that groups an item, for fork points. Codex forks at turn granularity. */
366
+ let currentTurnId = null;
367
+ /**
368
+ * The last error message sent in this turn. Codex reports a failure twice: an `error`
369
+ * notification, then `turn/completed` with the same error. One `error` event is enough.
370
+ */
371
+ let lastError = null;
372
+ function toolOf(item) {
373
+ switch (item.type) {
374
+ case "commandExecution": return {
375
+ name: "bash",
376
+ args: {
377
+ command: item.command,
378
+ cwd: item.cwd
379
+ }
380
+ };
381
+ case "fileChange": return {
382
+ name: "edit",
383
+ args: { changes: item.changes }
384
+ };
385
+ case "mcpToolCall": return {
386
+ name: `${String(item.server)}/${String(item.tool)}`,
387
+ args: item.arguments ?? {}
388
+ };
389
+ case "dynamicToolCall": return {
390
+ name: String(item.tool),
391
+ args: item.arguments ?? {}
392
+ };
393
+ default: return null;
394
+ }
395
+ }
396
+ function onNotification(method, params) {
397
+ if (!state.active) return;
398
+ switch (method) {
399
+ case "turn/started": {
400
+ const turn = params.turn;
401
+ if (typeof turn?.id === "string") {
402
+ currentTurnId = turn.id;
403
+ state.active.turnId = turn.id;
404
+ interruptIfRequested();
405
+ }
406
+ emit({
407
+ type: "run_start",
408
+ sessionRef: state.threadId ?? void 0
409
+ });
410
+ return;
411
+ }
412
+ case "item/started": {
413
+ const item = params.item ?? {};
414
+ if (item.type === "agentMessage") {
415
+ emit({
416
+ type: "message_start",
417
+ messageId: currentTurnId
418
+ });
419
+ return;
420
+ }
421
+ const t = toolOf(item);
422
+ if (t && typeof item.id === "string") emit({
423
+ type: "tool_start",
424
+ toolCallId: item.id,
425
+ toolName: t.name,
426
+ args: t.args
427
+ });
428
+ return;
429
+ }
430
+ case "item/agentMessage/delta":
431
+ if (typeof params.delta === "string") emit({
432
+ type: "text",
433
+ text: params.delta
434
+ });
435
+ return;
436
+ case "item/reasoning/textDelta":
437
+ case "item/reasoning/summaryTextDelta":
438
+ if (typeof params.delta === "string") emit({
439
+ type: "reasoning",
440
+ text: params.delta
441
+ });
442
+ return;
443
+ case "item/commandExecution/outputDelta":
444
+ if (typeof params.itemId === "string") emit({
445
+ type: "tool_update",
446
+ toolCallId: params.itemId,
447
+ toolName: "bash",
448
+ partial: params.delta ?? null
449
+ });
450
+ return;
451
+ case "item/completed": {
452
+ const item = params.item ?? {};
453
+ if (item.type === "agentMessage") {
454
+ emit({
455
+ type: "message_end",
456
+ messageId: currentTurnId
457
+ });
458
+ return;
459
+ }
460
+ const t = toolOf(item);
461
+ if (t && typeof item.id === "string") {
462
+ const status = String(item.status ?? "");
463
+ const exit = typeof item.exitCode === "number" ? item.exitCode : 0;
464
+ const failed = status === "failed" || status === "declined" || exit !== 0;
465
+ emit({
466
+ type: "tool_end",
467
+ toolCallId: item.id,
468
+ toolName: t.name,
469
+ result: item.aggregatedOutput ?? item.result ?? item.changes ?? null,
470
+ isError: failed
471
+ });
472
+ }
473
+ return;
474
+ }
475
+ case "error": {
476
+ const error = params.error ?? {};
477
+ const message = typeof error.message === "string" ? error.message : "codex reported an error";
478
+ if (params.willRetry === true) {
479
+ const n = message.match(/(\d+)\s*\/\s*(\d+)/);
480
+ emit({
481
+ type: "retry",
482
+ phase: "start",
483
+ attempt: n ? Number(n[1]) : 1,
484
+ maxAttempts: n ? Number(n[2]) : void 0,
485
+ error: message
486
+ });
487
+ } else if (message !== lastError) {
488
+ lastError = message;
489
+ emit({
490
+ type: "error",
491
+ message
492
+ });
493
+ }
494
+ return;
495
+ }
496
+ case "turn/completed": {
497
+ const turn = params.turn ?? {};
498
+ if (typeof turn.id === "string" && state.active.turnId && turn.id !== state.active.turnId) return;
499
+ const status = String(turn.status ?? "completed");
500
+ if (status === "failed") {
501
+ const e = turn.error ?? {};
502
+ const message = typeof e.message === "string" ? e.message : "the turn failed";
503
+ if (message !== lastError) emit({
504
+ type: "error",
505
+ message
506
+ });
507
+ emit({
508
+ type: "done",
509
+ reason: "error"
510
+ });
511
+ } else if (status === "interrupted") emit({
512
+ type: "done",
513
+ reason: "aborted"
514
+ });
515
+ else emit({
516
+ type: "done",
517
+ reason: "completed"
518
+ });
519
+ state.active.finish();
520
+ return;
521
+ }
522
+ default: return;
523
+ }
524
+ }
525
+ async function startServer() {
526
+ loadEnv();
527
+ const key = process.env.OPENAI_API_KEY ?? process.env.CODEX_API_KEY;
528
+ if (key) await new Promise((resolve) => {
529
+ const login = (0, node_child_process.spawn)(CODEX_BIN, ["login", "--with-api-key"], {
530
+ stdio: [
531
+ "pipe",
532
+ "ignore",
533
+ "ignore"
534
+ ],
535
+ env: process.env
536
+ });
537
+ login.on("error", () => {
538
+ resolve();
539
+ });
540
+ login.on("exit", () => {
541
+ resolve();
542
+ });
543
+ login.stdin.end(key + "\n");
544
+ });
545
+ proc = (0, node_child_process.spawn)(CODEX_BIN, [
546
+ "app-server",
547
+ "--listen",
548
+ "stdio://"
549
+ ], {
550
+ stdio: [
551
+ "pipe",
552
+ "pipe",
553
+ "pipe"
554
+ ],
555
+ env: process.env
556
+ });
557
+ proc.on("error", (e) => {
558
+ log("codex app-server failed to start: " + e.message);
559
+ });
560
+ proc.stderr?.on("data", (c) => {
561
+ log("codex stderr: " + c.toString().trim().slice(0, 300));
562
+ });
563
+ proc.on("exit", (code) => {
564
+ log("codex app-server exited code=" + code);
565
+ state.ready = false;
566
+ failAll("codex app-server exited");
567
+ if (state.active) {
568
+ emit({ error: "codex app-server exited" });
569
+ state.active.finish();
570
+ }
571
+ });
572
+ if (!proc.stdout) throw new Error("codex app-server has no stdout");
573
+ (0, node_readline.createInterface)({ input: proc.stdout }).on("line", (line) => {
574
+ let msg;
575
+ try {
576
+ msg = JSON.parse(line);
577
+ } catch {
578
+ return;
579
+ }
580
+ const id = msg.id;
581
+ if (id !== void 0 && typeof msg.method === "string") {
582
+ onServerRequest(id, msg.method, msg.params ?? {});
583
+ return;
584
+ }
585
+ if (id !== void 0 && typeof id === "number") {
586
+ const p = pending.get(id);
587
+ if (!p) return;
588
+ pending.delete(id);
589
+ clearTimeout(p.timer);
590
+ if (msg.error) {
591
+ const e = msg.error;
592
+ p.reject(new Error(typeof e.message === "string" ? e.message : "rpc error"));
593
+ } else p.resolve(msg.result ?? {});
594
+ return;
595
+ }
596
+ if (typeof msg.method === "string") onNotification(msg.method, msg.params ?? {});
597
+ });
598
+ await request("initialize", {
599
+ clientInfo: {
600
+ name: "alineo",
601
+ title: "alineo",
602
+ version: "0"
603
+ },
604
+ capabilities: { experimentalApi: false }
605
+ });
606
+ write({ method: "initialized" });
607
+ state.ready = true;
608
+ }
609
+ /** Start the thread on the first turn, or resume the one a previous bridge process started. */
610
+ async function ensureThread() {
611
+ if (state.threadId) return state.threadId;
612
+ const policy = state.config.permissions;
613
+ if (state.config.resume && (0, node_fs.existsSync)(THREAD_FILE)) {
614
+ const saved = (0, node_fs.readFileSync)(THREAD_FILE, "utf8").trim();
615
+ if (saved) try {
616
+ await request("thread/resume", { threadId: saved });
617
+ state.threadId = saved;
618
+ return saved;
619
+ } catch (e) {
620
+ log("could not resume thread " + saved + ": " + (e instanceof Error ? e.message : String(e)));
621
+ }
622
+ }
623
+ const params = {
624
+ approvalPolicy: policy ? "untrusted" : "never",
625
+ sandbox: policy ? "workspace-write" : "danger-full-access",
626
+ ephemeral: false
627
+ };
628
+ if (state.config.model) params.model = state.config.model;
629
+ const id = (await request("thread/start", params)).thread?.id;
630
+ if (typeof id !== "string") throw new Error("thread/start returned no thread id");
631
+ state.threadId = id;
632
+ try {
633
+ (0, node_fs.writeFileSync)(THREAD_FILE, id);
634
+ } catch {}
635
+ return id;
636
+ }
637
+ async function runTurn(res, message) {
638
+ const heartbeat = setInterval(() => {
639
+ try {
640
+ res.write(": ping\n\n");
641
+ } catch {}
642
+ }, 3e3);
643
+ let finish;
644
+ const done = new Promise((r) => {
645
+ finish = r;
646
+ });
647
+ lastError = null;
648
+ state.active = {
649
+ res,
650
+ turnId: null,
651
+ abortPending: false,
652
+ heartbeat,
653
+ finish
654
+ };
655
+ res.writeHead(200, {
656
+ "Content-Type": "text/event-stream",
657
+ "Cache-Control": "no-cache",
658
+ Connection: "keep-alive"
659
+ });
660
+ try {
661
+ const turnId = (await request("turn/start", {
662
+ threadId: await ensureThread(),
663
+ input: [{
664
+ type: "text",
665
+ text: message,
666
+ text_elements: []
667
+ }]
668
+ })).turn?.id;
669
+ if (typeof turnId === "string" && state.active && !state.active.turnId) {
670
+ state.active.turnId = turnId;
671
+ currentTurnId = turnId;
672
+ interruptIfRequested();
673
+ }
674
+ await done;
675
+ } catch (e) {
676
+ const text = e instanceof Error ? e.message : String(e);
677
+ log("turn failed: " + text);
678
+ send(res, { error: text });
679
+ } finally {
680
+ clearInterval(heartbeat);
681
+ for (const p of [...state.pending.values()]) p.settle({
682
+ kind: "reject",
683
+ feedback: "The turn ended."
684
+ });
685
+ state.active = null;
686
+ try {
687
+ res.write("data: [DONE]\n\n");
688
+ res.end();
689
+ } catch {}
690
+ }
691
+ }
692
+ function main() {
693
+ state.config = loadConfig();
694
+ startServer().catch((e) => {
695
+ log("startup failed: " + (e instanceof Error ? e.message : String(e)));
696
+ });
697
+ (0, node_http.createServer)((req, res) => {
698
+ if (req.method === "GET") {
699
+ if (req.url === "/health") return respond(res, 200, { ok: state.ready });
700
+ if (req.url === "/logs") {
701
+ res.writeHead(200, { "Content-Type": "text/plain" });
702
+ res.end(logBuf.join("\n"));
703
+ return;
704
+ }
705
+ if (req.url === "/state") return respond(res, 200, {
706
+ ok: true,
707
+ data: { threadId: state.threadId }
708
+ });
709
+ if (req.url === "/pending-permissions") return respond(res, 200, {
710
+ ok: true,
711
+ data: { pending: [...state.pending.values()].map((p) => ({
712
+ requestId: p.requestId,
713
+ tool: p.tool,
714
+ target: p.target,
715
+ title: p.title,
716
+ since: p.since
717
+ })) }
718
+ });
719
+ res.writeHead(404);
720
+ res.end();
721
+ return;
722
+ }
723
+ if (req.method !== "POST") {
724
+ res.writeHead(405);
725
+ res.end();
726
+ return;
727
+ }
728
+ let body = "";
729
+ req.on("data", (d) => {
730
+ body += d;
731
+ });
732
+ req.on("end", () => {
733
+ let data = {};
734
+ try {
735
+ if (body) data = JSON.parse(body);
736
+ } catch {
737
+ res.writeHead(400);
738
+ res.end("bad json");
739
+ return;
740
+ }
741
+ switch (req.url) {
742
+ case "/prompt":
743
+ if (!state.ready) return respond(res, 503, {
744
+ ok: false,
745
+ error: "codex not ready"
746
+ });
747
+ if (state.active) return respond(res, 409, {
748
+ ok: false,
749
+ error: "a turn is already running"
750
+ });
751
+ runTurn(res, data.message ?? "");
752
+ return;
753
+ case "/abort":
754
+ if (state.active) {
755
+ state.active.abortPending = true;
756
+ interruptIfRequested();
757
+ }
758
+ return respond(res, 200, {
759
+ ok: true,
760
+ data: null
761
+ });
762
+ case "/steer": {
763
+ const a = state.active;
764
+ if (!a?.turnId || !state.threadId) return respond(res, 409, {
765
+ ok: false,
766
+ error: "no turn in progress"
767
+ });
768
+ request("turn/steer", {
769
+ threadId: state.threadId,
770
+ expectedTurnId: a.turnId,
771
+ input: [{
772
+ type: "text",
773
+ text: data.message ?? "",
774
+ text_elements: []
775
+ }]
776
+ }).then(() => respond(res, 200, {
777
+ ok: true,
778
+ data: null
779
+ })).catch((e) => {
780
+ respond(res, 400, {
781
+ ok: false,
782
+ error: e instanceof Error ? e.message : String(e)
783
+ });
784
+ });
785
+ return;
786
+ }
787
+ case "/compact":
788
+ if (!state.threadId) return respond(res, 409, {
789
+ ok: false,
790
+ error: "no thread yet"
791
+ });
792
+ request("thread/compact/start", { threadId: state.threadId }).then(() => respond(res, 200, {
793
+ ok: true,
794
+ data: null
795
+ })).catch((e) => {
796
+ respond(res, 400, {
797
+ ok: false,
798
+ error: e instanceof Error ? e.message : String(e)
799
+ });
800
+ });
801
+ return;
802
+ case "/fork":
803
+ if (!state.threadId) return respond(res, 409, {
804
+ ok: false,
805
+ error: "no thread to fork yet"
806
+ });
807
+ if (state.active) return respond(res, 409, {
808
+ ok: false,
809
+ error: "a turn is running"
810
+ });
811
+ request("thread/fork", {
812
+ threadId: state.threadId,
813
+ lastTurnId: data.entryId
814
+ }).then((r) => {
815
+ const id = r.thread?.id;
816
+ if (typeof id !== "string") throw new Error("thread/fork returned no thread id");
817
+ state.threadId = id;
818
+ try {
819
+ (0, node_fs.writeFileSync)(THREAD_FILE, id);
820
+ } catch {}
821
+ respond(res, 200, {
822
+ ok: true,
823
+ data: { sessionRef: id }
824
+ });
825
+ }).catch((e) => {
826
+ respond(res, 500, {
827
+ ok: false,
828
+ error: e instanceof Error ? e.message : String(e)
829
+ });
830
+ });
831
+ return;
832
+ case "/permission-response": {
833
+ const p = state.pending.get(data.requestId ?? "");
834
+ if (!p) return respond(res, 404, {
835
+ ok: false,
836
+ error: "no such pending permission"
837
+ });
838
+ const d = data.decision ?? {};
839
+ p.settle(d.kind === "once" ? { kind: "once" } : d.kind === "always" ? { kind: "always" } : {
840
+ kind: "reject",
841
+ feedback: d.feedback
842
+ });
843
+ return respond(res, 200, { ok: true });
844
+ }
845
+ default:
846
+ res.writeHead(404);
847
+ res.end("not found");
848
+ }
849
+ });
850
+ }).listen(PORT, "0.0.0.0", () => {
851
+ process.stderr.write("alineo-bridge :" + PORT + "\n");
852
+ });
853
+ }
854
+ main();
855
+ //#endregion