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,905 @@
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/bridge/pi-bridge.ts
6
+ /**
7
+ * The in-sandbox bridge: wraps `pi --mode rpc` in an HTTP server so the host can talk to it
8
+ * without interactive stdin from the sandbox exec API.
9
+ *
10
+ * Bundled to one CommonJS file (`dist/pi-bridge.cjs`) and written into the sandbox at
11
+ * `/alineo-bridge.js`, where it runs with plain `node`. Import only Node built-ins and
12
+ * `type`s from `./wire.ts`: nothing else exists in the sandbox.
13
+ */
14
+ const PORT = Number(process.env.ALINEO_BRIDGE_PORT) || 3001;
15
+ const ENV_FILE = process.env.ALINEO_ENV_FILE || "/etc/alineo-env";
16
+ const PI_CONFIG_FILE = process.env.ALINEO_PI_CONFIG || "/etc/alineo-pi.json";
17
+ const PI_BIN = process.env.ALINEO_PI_BIN || "pi";
18
+ function loadEnv() {
19
+ if (!(0, node_fs.existsSync)(ENV_FILE)) return;
20
+ const lines = (0, node_fs.readFileSync)(ENV_FILE, "utf8").split("\n");
21
+ for (const line of lines) {
22
+ const m = line.match(/^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/);
23
+ if (m) process.env[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
24
+ }
25
+ }
26
+ let POLICY_ACTIVE = false;
27
+ const PERMISSION_GATE_PATH = process.env.ALINEO_PERMISSION_GATE_PATH || "/alineo-permission-gate.js";
28
+ function buildPiArgs() {
29
+ const args = [
30
+ "--mode",
31
+ "rpc",
32
+ "--approve"
33
+ ];
34
+ try {
35
+ if ((0, node_fs.existsSync)(PI_CONFIG_FILE)) {
36
+ const cfg = JSON.parse((0, node_fs.readFileSync)(PI_CONFIG_FILE, "utf8"));
37
+ if (cfg.provider) args.push("--provider", cfg.provider);
38
+ if (cfg.model) args.push("--model", cfg.model);
39
+ if (cfg.resume) args.push("--continue");
40
+ if (cfg.permissions && (0, node_fs.existsSync)(PERMISSION_GATE_PATH)) {
41
+ POLICY_ACTIVE = true;
42
+ args.push("-e", PERMISSION_GATE_PATH);
43
+ }
44
+ }
45
+ } catch {}
46
+ return args;
47
+ }
48
+ const logBuf = [];
49
+ function log(msg) {
50
+ const entry = "[" + (/* @__PURE__ */ new Date()).toISOString() + "] " + msg;
51
+ if (logBuf.length >= 200) logBuf.shift();
52
+ logBuf.push(entry);
53
+ process.stderr.write(entry + "\n");
54
+ }
55
+ function startHeartbeat(res) {
56
+ return setInterval(() => {
57
+ try {
58
+ res.write(": ping\n\n");
59
+ } catch {}
60
+ }, 3e3);
61
+ }
62
+ function stopHeartbeat(iv) {
63
+ if (iv) clearInterval(iv);
64
+ }
65
+ /** Write one SSE `data:` frame. */
66
+ function sse(res, obj) {
67
+ res.write("data: " + JSON.stringify(obj) + "\n\n");
68
+ }
69
+ const state = {
70
+ proc: null,
71
+ rl: null,
72
+ ready: false,
73
+ active: null,
74
+ queue: [],
75
+ gen: 0,
76
+ pendingCmds: {},
77
+ pendingPermissions: {},
78
+ permissionChannel: null
79
+ };
80
+ const PERM_MARKER = "ALINEO_PERM ";
81
+ const PERMISSION_TIMEOUT_MS = 3e5;
82
+ function emitPermission(obj) {
83
+ const line = "data: " + JSON.stringify(obj) + "\n\n";
84
+ const sinks = [state.active, state.permissionChannel];
85
+ for (const sink of sinks) if (sink && sink.res) try {
86
+ sink.res.write(line);
87
+ } catch {}
88
+ }
89
+ function answerPermission(id, value) {
90
+ if (value === null) rpc({
91
+ type: "extension_ui_response",
92
+ id,
93
+ cancelled: true
94
+ });
95
+ else rpc({
96
+ type: "extension_ui_response",
97
+ id,
98
+ value
99
+ });
100
+ }
101
+ function resolveMatchingPending(exceptId, tool, verdict) {
102
+ for (const pid of Object.keys(state.pendingPermissions)) {
103
+ if (pid === exceptId) continue;
104
+ const p = state.pendingPermissions[pid];
105
+ if (p.tool !== tool) continue;
106
+ if (p.timer) clearTimeout(p.timer);
107
+ delete state.pendingPermissions[pid];
108
+ answerPermission(pid, verdict === "allow" ? JSON.stringify({
109
+ verdict: "allow",
110
+ scope: "once"
111
+ }) : JSON.stringify({ verdict: "reject" }));
112
+ emitPermission({
113
+ type: "permission_resolved",
114
+ requestId: pid,
115
+ decision: verdict === "allow" ? { kind: "once" } : { kind: "reject" }
116
+ });
117
+ }
118
+ }
119
+ function expirePermission(pid) {
120
+ if (!state.pendingPermissions[pid]) return;
121
+ delete state.pendingPermissions[pid];
122
+ answerPermission(pid, null);
123
+ emitPermission({
124
+ type: "permission_resolved",
125
+ requestId: pid,
126
+ decision: { kind: "reject" }
127
+ });
128
+ }
129
+ function suspendPermissionTimers() {
130
+ for (const pid of Object.keys(state.pendingPermissions)) {
131
+ const p = state.pendingPermissions[pid];
132
+ if (p.timer) {
133
+ clearTimeout(p.timer);
134
+ p.timer = null;
135
+ }
136
+ }
137
+ }
138
+ function resumePermissionTimers() {
139
+ for (const pid of Object.keys(state.pendingPermissions)) {
140
+ const p = state.pendingPermissions[pid];
141
+ if (!p.timer) p.timer = setTimeout(() => {
142
+ expirePermission(pid);
143
+ }, PERMISSION_TIMEOUT_MS);
144
+ }
145
+ }
146
+ function cancelPendingPermissions() {
147
+ for (const pid of Object.keys(state.pendingPermissions)) {
148
+ const p = state.pendingPermissions[pid];
149
+ if (p.timer) clearTimeout(p.timer);
150
+ answerPermission(pid, null);
151
+ }
152
+ state.pendingPermissions = {};
153
+ }
154
+ function cleanupPendingCmds(reason) {
155
+ for (const id of Object.keys(state.pendingCmds)) {
156
+ const p = state.pendingCmds[id];
157
+ if (p.timer) clearTimeout(p.timer);
158
+ stopHeartbeat(p.heartbeat);
159
+ if (p.bash) try {
160
+ sse(p.res, { error: reason });
161
+ p.res.end();
162
+ } catch {}
163
+ else respond(p.res, 500, {
164
+ ok: false,
165
+ error: reason
166
+ });
167
+ }
168
+ state.pendingCmds = {};
169
+ }
170
+ function startPi() {
171
+ if (state.active) {
172
+ stopHeartbeat(state.active.heartbeat);
173
+ sse(state.active.res, { error: "pi restarted" });
174
+ state.active.res.end();
175
+ state.active = null;
176
+ }
177
+ cleanupPendingCmds("pi restarted");
178
+ cancelPendingPermissions();
179
+ if (state.rl) try {
180
+ state.rl.close();
181
+ } catch {}
182
+ if (state.proc) try {
183
+ state.proc.kill("SIGTERM");
184
+ } catch {}
185
+ state.proc = null;
186
+ state.rl = null;
187
+ state.ready = false;
188
+ loadEnv();
189
+ const args = buildPiArgs();
190
+ const gen = ++state.gen;
191
+ log("pi start gen=" + gen + ": " + args.join(" "));
192
+ const proc = (0, node_child_process.spawn)(PI_BIN, args, {
193
+ stdio: [
194
+ "pipe",
195
+ "pipe",
196
+ "pipe"
197
+ ],
198
+ env: Object.assign({}, process.env)
199
+ });
200
+ state.proc = proc;
201
+ proc.stderr.on("data", (chunk) => {
202
+ if (state.gen === gen) log("pi stderr: " + chunk.toString().trim());
203
+ });
204
+ state.rl = (0, node_readline.createInterface)({ input: proc.stdout });
205
+ state.rl.on("line", (line) => {
206
+ if (state.gen === gen) handleLine(line);
207
+ });
208
+ proc.on("exit", (code) => {
209
+ if (state.gen !== gen) return;
210
+ log("pi exit gen=" + gen + " code=" + code);
211
+ state.proc = null;
212
+ state.ready = false;
213
+ cleanupPendingCmds("pi exited");
214
+ cancelPendingPermissions();
215
+ if (state.active) {
216
+ stopHeartbeat(state.active.heartbeat);
217
+ sse(state.active.res, { error: "pi exited" });
218
+ state.active.res.end();
219
+ state.active = null;
220
+ }
221
+ });
222
+ setTimeout(() => {
223
+ if (state.gen !== gen || !state.proc) return;
224
+ log("pi probe gen=" + gen);
225
+ rpc({
226
+ id: "__probe__",
227
+ type: "get_state"
228
+ });
229
+ }, 500);
230
+ }
231
+ function rpc(msg) {
232
+ if (state.proc && state.proc.stdin) state.proc.stdin.write(JSON.stringify(msg) + "\n");
233
+ }
234
+ function rpcWithAck(msg, res) {
235
+ const pending = { res };
236
+ state.pendingCmds[msg.id] = pending;
237
+ rpc(msg);
238
+ pending.timer = setTimeout(() => {
239
+ const p = state.pendingCmds[msg.id];
240
+ if (p) {
241
+ respond(p.res, 504, { error: "timeout" });
242
+ delete state.pendingCmds[msg.id];
243
+ }
244
+ }, 5e3);
245
+ }
246
+ function handleLine(line) {
247
+ if (!line.trim()) return;
248
+ let ev;
249
+ try {
250
+ ev = JSON.parse(line);
251
+ } catch {
252
+ return;
253
+ }
254
+ if (!state.ready && ev.id === "__probe__" && ev.type === "response") {
255
+ state.ready = true;
256
+ const m = ev.data && ev.data.model || {};
257
+ log("pi ready model=" + m.id + " api=" + m.api);
258
+ flush();
259
+ return;
260
+ }
261
+ if (ev.type === "response" && ev.command === "prompt" && !ev.success) {
262
+ if (!state.active) return;
263
+ stopHeartbeat(state.active.heartbeat);
264
+ log("prompt rejected: " + (ev.error || "unknown"));
265
+ sse(state.active.res, { error: ev.error || "prompt rejected" });
266
+ state.active.res.end();
267
+ state.active = null;
268
+ flush();
269
+ return;
270
+ }
271
+ if (ev.type === "response" && ev.id && state.pendingCmds[ev.id]) {
272
+ const pending = state.pendingCmds[ev.id];
273
+ if (pending.timer) clearTimeout(pending.timer);
274
+ stopHeartbeat(pending.heartbeat);
275
+ delete state.pendingCmds[ev.id];
276
+ if (pending.bash) {
277
+ const output = ev.data && ev.data.output || "";
278
+ if (output) try {
279
+ sse(pending.res, {
280
+ type: "text",
281
+ text: output
282
+ });
283
+ } catch {}
284
+ try {
285
+ pending.res.write("data: [DONE]\n\n");
286
+ pending.res.end();
287
+ } catch {}
288
+ } else if (ev.success) respond(pending.res, 200, {
289
+ ok: true,
290
+ data: ev.data || null
291
+ });
292
+ else respond(pending.res, 400, {
293
+ ok: false,
294
+ error: ev.error || "unknown"
295
+ });
296
+ return;
297
+ }
298
+ if (ev.type === "tool_execution_start") {
299
+ if (!state.active) return;
300
+ sse(state.active.res, {
301
+ type: "tool_start",
302
+ toolCallId: ev.toolCallId,
303
+ toolName: ev.toolName,
304
+ args: ev.args
305
+ });
306
+ return;
307
+ }
308
+ if (ev.type === "tool_execution_update") {
309
+ if (!state.active) return;
310
+ sse(state.active.res, {
311
+ type: "tool_update",
312
+ toolCallId: ev.toolCallId,
313
+ toolName: ev.toolName,
314
+ partialResult: ev.partialResult
315
+ });
316
+ return;
317
+ }
318
+ if (ev.type === "tool_execution_end") {
319
+ if (!state.active) return;
320
+ sse(state.active.res, {
321
+ type: "tool_end",
322
+ toolCallId: ev.toolCallId,
323
+ toolName: ev.toolName,
324
+ result: ev.result,
325
+ isError: !!ev.isError
326
+ });
327
+ return;
328
+ }
329
+ if (ev.type === "extension_ui_request") {
330
+ if (POLICY_ACTIVE && ev.method === "select" && ev.id && typeof ev.title === "string" && ev.title.indexOf(PERM_MARKER) === 0) {
331
+ let meta = {};
332
+ try {
333
+ meta = JSON.parse(ev.title.slice(12));
334
+ } catch {}
335
+ const requestId = ev.id;
336
+ const entry = {
337
+ tool: meta.tool || "unknown",
338
+ target: meta.target || "",
339
+ title: meta.title || "Approve tool call",
340
+ since: Date.now(),
341
+ timer: null
342
+ };
343
+ if (!state.permissionChannel) entry.timer = setTimeout(() => {
344
+ expirePermission(requestId);
345
+ }, PERMISSION_TIMEOUT_MS);
346
+ state.pendingPermissions[requestId] = entry;
347
+ emitPermission({
348
+ type: "permission_request",
349
+ requestId,
350
+ tool: entry.tool,
351
+ target: entry.target,
352
+ title: entry.title
353
+ });
354
+ return;
355
+ }
356
+ const isDialog = [
357
+ "select",
358
+ "confirm",
359
+ "input",
360
+ "editor"
361
+ ].indexOf(ev.method ?? "") !== -1;
362
+ const uiParams = {};
363
+ for (const k of Object.keys(ev)) if (k !== "type" && k !== "id") uiParams[k] = ev[k];
364
+ if (state.active) sse(state.active.res, {
365
+ type: "extension_ui",
366
+ method: ev.method,
367
+ params: uiParams,
368
+ isDialog,
369
+ requestId: isDialog ? ev.id : void 0
370
+ });
371
+ if (isDialog && ev.id) rpc({
372
+ type: "extension_ui_response",
373
+ id: ev.id,
374
+ cancelled: true
375
+ });
376
+ return;
377
+ }
378
+ if (ev.type === "auto_retry_start") {
379
+ if (state.active) sse(state.active.res, {
380
+ type: "auto_retry_start",
381
+ attempt: ev.attempt,
382
+ maxAttempts: ev.maxAttempts,
383
+ delayMs: ev.delayMs,
384
+ errorMessage: ev.errorMessage || ""
385
+ });
386
+ return;
387
+ }
388
+ if (ev.type === "auto_retry_end") {
389
+ if (state.active) sse(state.active.res, {
390
+ type: "auto_retry_end",
391
+ success: !!ev.success,
392
+ attempt: ev.attempt,
393
+ finalError: ev.finalError
394
+ });
395
+ return;
396
+ }
397
+ if (ev.type === "agent_start") {
398
+ if (state.active) sse(state.active.res, { type: "agent_start" });
399
+ return;
400
+ }
401
+ if (ev.type === "turn_start") {
402
+ if (state.active) sse(state.active.res, {
403
+ type: "turn_start",
404
+ turnIndex: ev.turnIndex,
405
+ timestamp: ev.timestamp
406
+ });
407
+ return;
408
+ }
409
+ if (ev.type === "turn_end") {
410
+ if (state.active) sse(state.active.res, {
411
+ type: "turn_end",
412
+ turnIndex: ev.turnIndex,
413
+ message: ev.message,
414
+ toolResults: ev.toolResults || []
415
+ });
416
+ return;
417
+ }
418
+ if (ev.type === "message_start") {
419
+ if (state.active) sse(state.active.res, {
420
+ type: "message_start",
421
+ message: ev.message
422
+ });
423
+ return;
424
+ }
425
+ if (ev.type === "message_end") {
426
+ if (state.active) sse(state.active.res, {
427
+ type: "message_end",
428
+ message: ev.message
429
+ });
430
+ return;
431
+ }
432
+ if (ev.type === "queue_update") {
433
+ if (state.active) sse(state.active.res, {
434
+ type: "queue_update",
435
+ steering: ev.steering || [],
436
+ followUp: ev.followUp || []
437
+ });
438
+ return;
439
+ }
440
+ if (ev.type === "compaction_start") {
441
+ if (state.active) sse(state.active.res, {
442
+ type: "compaction_start",
443
+ reason: ev.reason
444
+ });
445
+ return;
446
+ }
447
+ if (ev.type === "compaction_end") {
448
+ if (state.active) sse(state.active.res, {
449
+ type: "compaction_end",
450
+ reason: ev.reason,
451
+ result: ev.result || null,
452
+ aborted: !!ev.aborted,
453
+ willRetry: !!ev.willRetry
454
+ });
455
+ return;
456
+ }
457
+ if (ev.type === "extension_error") {
458
+ if (state.active) sse(state.active.res, {
459
+ type: "extension_error",
460
+ extensionPath: ev.extensionPath,
461
+ event: ev.event,
462
+ error: ev.error
463
+ });
464
+ return;
465
+ }
466
+ if (ev.type === "message_update") {
467
+ if (!state.active) return;
468
+ sse(state.active.res, {
469
+ type: "message_update",
470
+ message: ev.message,
471
+ delta: ev.assistantMessageEvent
472
+ });
473
+ const aev = ev.assistantMessageEvent || {};
474
+ if (aev.type === "text_delta" && aev.delta) {
475
+ state.active.text += aev.delta;
476
+ sse(state.active.res, {
477
+ type: "text",
478
+ text: aev.delta
479
+ });
480
+ }
481
+ return;
482
+ }
483
+ if (ev.type === "agent_end") {
484
+ if (!state.active) return;
485
+ stopHeartbeat(state.active.heartbeat);
486
+ sse(state.active.res, {
487
+ type: "agent_end",
488
+ messages: ev.messages || []
489
+ });
490
+ log("agent_end: " + state.active.text.length + " chars in " + (Date.now() - state.active.t0) + "ms");
491
+ state.active.res.write("data: [DONE]\n\n");
492
+ state.active.res.end();
493
+ state.active = null;
494
+ flush();
495
+ }
496
+ }
497
+ function flush() {
498
+ if (!state.ready || !state.queue.length || !state.proc) return;
499
+ const item = state.queue[0];
500
+ if (state.active && !item.streamingBehavior) return;
501
+ state.queue.shift();
502
+ if (!item.streamingBehavior) state.active = item;
503
+ item.t0 = Date.now();
504
+ const rpcMsg = {
505
+ id: "p" + item.t0,
506
+ type: "prompt",
507
+ message: item.message
508
+ };
509
+ if (item.streamingBehavior) rpcMsg.streamingBehavior = item.streamingBehavior;
510
+ rpc(rpcMsg);
511
+ item.res.writeHead(200, {
512
+ "Content-Type": "text/event-stream",
513
+ "Cache-Control": "no-cache",
514
+ Connection: "keep-alive"
515
+ });
516
+ if (!item.streamingBehavior) item.heartbeat = startHeartbeat(item.res);
517
+ if (item.streamingBehavior) {
518
+ item.res.write("data: [DONE]\n\n");
519
+ item.res.end();
520
+ flush();
521
+ }
522
+ }
523
+ function respond(res, status, body) {
524
+ try {
525
+ res.writeHead(status, { "Content-Type": "application/json" });
526
+ res.end(JSON.stringify(body));
527
+ } catch {}
528
+ }
529
+ startPi();
530
+ (0, node_http.createServer)((req, res) => {
531
+ if (req.method === "GET") {
532
+ if (req.url === "/health") {
533
+ respond(res, 200, { ok: state.ready });
534
+ return;
535
+ }
536
+ if (req.url === "/logs") {
537
+ res.writeHead(200, { "Content-Type": "text/plain" });
538
+ res.end(logBuf.join("\n"));
539
+ return;
540
+ }
541
+ if (req.url === "/permission-stream") {
542
+ if (state.permissionChannel) try {
543
+ state.permissionChannel.res.end();
544
+ } catch {}
545
+ res.writeHead(200, {
546
+ "Content-Type": "text/event-stream",
547
+ "Cache-Control": "no-cache",
548
+ Connection: "keep-alive"
549
+ });
550
+ const pHeartbeat = startHeartbeat(res);
551
+ state.permissionChannel = { res };
552
+ suspendPermissionTimers();
553
+ for (const pid of Object.keys(state.pendingPermissions)) {
554
+ const p = state.pendingPermissions[pid];
555
+ try {
556
+ sse(res, {
557
+ type: "permission_request",
558
+ requestId: pid,
559
+ tool: p.tool,
560
+ target: p.target,
561
+ title: p.title
562
+ });
563
+ } catch {}
564
+ }
565
+ req.on("close", () => {
566
+ stopHeartbeat(pHeartbeat);
567
+ if (state.permissionChannel && state.permissionChannel.res === res) {
568
+ state.permissionChannel = null;
569
+ resumePermissionTimers();
570
+ }
571
+ });
572
+ return;
573
+ }
574
+ if (req.url === "/pending-permissions") {
575
+ respond(res, 200, {
576
+ ok: true,
577
+ data: { pending: Object.keys(state.pendingPermissions).map((pid) => {
578
+ const p = state.pendingPermissions[pid];
579
+ return {
580
+ requestId: pid,
581
+ tool: p.tool,
582
+ target: p.target,
583
+ title: p.title,
584
+ since: p.since || 0
585
+ };
586
+ }) }
587
+ });
588
+ return;
589
+ }
590
+ if (req.url === "/messages") {
591
+ rpcWithAck({
592
+ id: "gm" + Date.now(),
593
+ type: "get_messages"
594
+ }, res);
595
+ return;
596
+ }
597
+ if (req.url === "/available-models") {
598
+ rpcWithAck({
599
+ id: "gam" + Date.now(),
600
+ type: "get_available_models"
601
+ }, res);
602
+ return;
603
+ }
604
+ if (req.url === "/state") {
605
+ rpcWithAck({
606
+ id: "gs" + Date.now(),
607
+ type: "get_state"
608
+ }, res);
609
+ return;
610
+ }
611
+ res.writeHead(404);
612
+ res.end();
613
+ return;
614
+ }
615
+ if (req.method !== "POST") {
616
+ res.writeHead(405);
617
+ res.end();
618
+ return;
619
+ }
620
+ let body = "";
621
+ req.on("data", (d) => {
622
+ body += d;
623
+ });
624
+ req.on("end", () => {
625
+ let data = {};
626
+ try {
627
+ if (body) data = JSON.parse(body);
628
+ } catch {
629
+ res.writeHead(400);
630
+ res.end("bad json");
631
+ return;
632
+ }
633
+ switch (req.url) {
634
+ case "/prompt":
635
+ state.queue.push({
636
+ message: data.message || "",
637
+ streamingBehavior: data.streamingBehavior,
638
+ res,
639
+ text: "",
640
+ t0: 0
641
+ });
642
+ flush();
643
+ return;
644
+ case "/bash": {
645
+ if (!state.ready || !state.proc) {
646
+ respond(res, 503, { error: "pi not ready" });
647
+ return;
648
+ }
649
+ const bashId = "b" + Date.now();
650
+ const bashTimer = setTimeout(() => {
651
+ const p = state.pendingCmds[bashId];
652
+ if (p) {
653
+ stopHeartbeat(p.heartbeat);
654
+ delete state.pendingCmds[bashId];
655
+ try {
656
+ sse(res, { error: "bash timeout" });
657
+ res.end();
658
+ } catch {}
659
+ }
660
+ }, 3e4);
661
+ res.writeHead(200, {
662
+ "Content-Type": "text/event-stream",
663
+ "Cache-Control": "no-cache",
664
+ Connection: "keep-alive"
665
+ });
666
+ state.pendingCmds[bashId] = {
667
+ res,
668
+ timer: bashTimer,
669
+ bash: true,
670
+ heartbeat: startHeartbeat(res)
671
+ };
672
+ rpc({
673
+ id: bashId,
674
+ type: "bash",
675
+ command: data.command || ""
676
+ });
677
+ return;
678
+ }
679
+ case "/abort":
680
+ cancelPendingPermissions();
681
+ state.queue.length = 0;
682
+ if (state.active) {
683
+ stopHeartbeat(state.active.heartbeat);
684
+ state.active.res.write("data: [DONE]\n\n");
685
+ state.active.res.end();
686
+ state.active = null;
687
+ }
688
+ rpcWithAck({
689
+ id: "a" + Date.now(),
690
+ type: "abort"
691
+ }, res);
692
+ return;
693
+ case "/steer":
694
+ if (!state.active) {
695
+ respond(res, 409, {
696
+ ok: false,
697
+ error: "no turn in progress"
698
+ });
699
+ return;
700
+ }
701
+ rpcWithAck({
702
+ id: "s" + Date.now(),
703
+ type: "steer",
704
+ message: data.message || ""
705
+ }, res);
706
+ return;
707
+ case "/permission-response": {
708
+ const requestId = data.requestId ?? "";
709
+ const pp = state.pendingPermissions[requestId];
710
+ if (!pp) {
711
+ respond(res, 404, {
712
+ ok: false,
713
+ error: "no such pending permission"
714
+ });
715
+ return;
716
+ }
717
+ if (pp.timer) clearTimeout(pp.timer);
718
+ delete state.pendingPermissions[requestId];
719
+ const decision = data.decision || {};
720
+ if (decision.kind === "once") answerPermission(requestId, JSON.stringify({
721
+ verdict: "allow",
722
+ scope: "once"
723
+ }));
724
+ else if (decision.kind === "always") {
725
+ answerPermission(requestId, JSON.stringify({
726
+ verdict: "allow",
727
+ scope: "always"
728
+ }));
729
+ resolveMatchingPending(requestId, pp.tool, "allow");
730
+ } else {
731
+ answerPermission(requestId, JSON.stringify({
732
+ verdict: "reject",
733
+ feedback: decision.feedback || ""
734
+ }));
735
+ resolveMatchingPending(requestId, pp.tool, "reject");
736
+ }
737
+ emitPermission({
738
+ type: "permission_resolved",
739
+ requestId,
740
+ decision
741
+ });
742
+ respond(res, 200, { ok: true });
743
+ return;
744
+ }
745
+ case "/follow-up":
746
+ rpcWithAck({
747
+ id: "fu" + Date.now(),
748
+ type: "follow_up",
749
+ message: data.message || ""
750
+ }, res);
751
+ return;
752
+ case "/new-session":
753
+ rpcWithAck({
754
+ id: "n" + Date.now(),
755
+ type: "new_session"
756
+ }, res);
757
+ return;
758
+ case "/fork":
759
+ rpcWithAck({
760
+ id: "fk" + Date.now(),
761
+ type: "fork",
762
+ entryId: data.entryId || ""
763
+ }, res);
764
+ return;
765
+ case "/clone":
766
+ rpcWithAck({
767
+ id: "cl" + Date.now(),
768
+ type: "clone"
769
+ }, res);
770
+ return;
771
+ case "/switch-session":
772
+ rpcWithAck({
773
+ id: "ss" + Date.now(),
774
+ type: "switch_session",
775
+ sessionPath: data.sessionPath || ""
776
+ }, res);
777
+ return;
778
+ case "/set-model":
779
+ rpcWithAck({
780
+ id: "sm" + Date.now(),
781
+ type: "set_model",
782
+ provider: data.provider || "",
783
+ modelId: data.modelId || ""
784
+ }, res);
785
+ return;
786
+ case "/cycle-model":
787
+ rpcWithAck({
788
+ id: "cm" + Date.now(),
789
+ type: "cycle_model"
790
+ }, res);
791
+ return;
792
+ case "/set-thinking-level":
793
+ rpcWithAck({
794
+ id: "stl" + Date.now(),
795
+ type: "set_thinking_level",
796
+ level: data.level || "medium"
797
+ }, res);
798
+ return;
799
+ case "/cycle-thinking-level":
800
+ rpcWithAck({
801
+ id: "ctl" + Date.now(),
802
+ type: "cycle_thinking_level"
803
+ }, res);
804
+ return;
805
+ case "/compact": {
806
+ const compactMsg = {
807
+ id: "co" + Date.now(),
808
+ type: "compact"
809
+ };
810
+ if (data.customInstructions) compactMsg.customInstructions = data.customInstructions;
811
+ rpcWithAck(compactMsg, res);
812
+ return;
813
+ }
814
+ case "/set-auto-compaction":
815
+ rpcWithAck({
816
+ id: "sac" + Date.now(),
817
+ type: "set_auto_compaction",
818
+ enabled: !!data.enabled
819
+ }, res);
820
+ return;
821
+ case "/set-auto-retry":
822
+ rpcWithAck({
823
+ id: "sar" + Date.now(),
824
+ type: "set_auto_retry",
825
+ enabled: !!data.enabled
826
+ }, res);
827
+ return;
828
+ case "/abort-retry":
829
+ rpcWithAck({
830
+ id: "ar" + Date.now(),
831
+ type: "abort_retry"
832
+ }, res);
833
+ return;
834
+ case "/abort-bash":
835
+ rpcWithAck({
836
+ id: "ab" + Date.now(),
837
+ type: "abort_bash"
838
+ }, res);
839
+ return;
840
+ case "/get-session-stats":
841
+ rpcWithAck({
842
+ id: "gss" + Date.now(),
843
+ type: "get_session_stats"
844
+ }, res);
845
+ return;
846
+ case "/get-last-assistant-text":
847
+ rpcWithAck({
848
+ id: "glat" + Date.now(),
849
+ type: "get_last_assistant_text"
850
+ }, res);
851
+ return;
852
+ case "/get-fork-messages":
853
+ rpcWithAck({
854
+ id: "gfm" + Date.now(),
855
+ type: "get_fork_messages"
856
+ }, res);
857
+ return;
858
+ case "/get-commands":
859
+ rpcWithAck({
860
+ id: "gc" + Date.now(),
861
+ type: "get_commands"
862
+ }, res);
863
+ return;
864
+ case "/set-session-name":
865
+ rpcWithAck({
866
+ id: "ssn" + Date.now(),
867
+ type: "set_session_name",
868
+ name: data.name
869
+ }, res);
870
+ return;
871
+ case "/set-steering-mode":
872
+ rpcWithAck({
873
+ id: "ssm" + Date.now(),
874
+ type: "set_steering_mode",
875
+ mode: data.mode
876
+ }, res);
877
+ return;
878
+ case "/set-follow-up-mode":
879
+ rpcWithAck({
880
+ id: "sfum" + Date.now(),
881
+ type: "set_follow_up_mode",
882
+ mode: data.mode
883
+ }, res);
884
+ return;
885
+ case "/export-html":
886
+ rpcWithAck({
887
+ id: "eh" + Date.now(),
888
+ type: "export_html",
889
+ outputPath: data.outputPath
890
+ }, res);
891
+ return;
892
+ case "/reload-env":
893
+ if (data.env && typeof data.env === "object") Object.assign(process.env, data.env);
894
+ startPi();
895
+ respond(res, 200, { ok: true });
896
+ return;
897
+ default:
898
+ res.writeHead(404);
899
+ res.end("not found");
900
+ }
901
+ });
902
+ }).listen(PORT, "0.0.0.0", () => {
903
+ process.stderr.write("alineo-bridge :" + PORT + "\n");
904
+ });
905
+ //#endregion