alineo 0.1.0 → 0.3.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,766 @@
1
+ "use strict";
2
+ var spawn = require("child_process").spawn;
3
+ var createInterface = require("readline").createInterface;
4
+ var http = require("http");
5
+ var fs = require("fs");
6
+
7
+ var PORT = 3001;
8
+ var ENV_FILE = "/etc/alineo-env";
9
+ var PI_CONFIG_FILE = "/etc/alineo-pi.json";
10
+
11
+ // Re-read /etc/alineo-env into process.env on each Pi (re)start so setEnv() changes take effect.
12
+ function loadEnv() {
13
+ if (!fs.existsSync(ENV_FILE)) return;
14
+ var lines = fs.readFileSync(ENV_FILE, "utf8").split("\n");
15
+ for (var i = 0; i < lines.length; i++) {
16
+ var m = lines[i].match(/^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/);
17
+ if (m) process.env[m[1]] = m[2].replace(/\\"/g, '"').replace(/\\\\/g, "\\");
18
+ }
19
+ }
20
+
21
+ // Build the pi CLI args from /etc/alineo-pi.json (model/provider config, written by the host).
22
+ // Supports: provider, model, resume (--continue to resume the most recent session).
23
+ function buildPiArgs() {
24
+ var args = ["--mode", "rpc", "--approve"];
25
+ try {
26
+ if (fs.existsSync(PI_CONFIG_FILE)) {
27
+ var cfg = JSON.parse(fs.readFileSync(PI_CONFIG_FILE, "utf8"));
28
+ if (cfg.provider) args.push("--provider", cfg.provider);
29
+ if (cfg.model) args.push("--model", cfg.model);
30
+ if (cfg.resume) args.push("--continue");
31
+ }
32
+ } catch {}
33
+ return args;
34
+ }
35
+
36
+ // --- Ring-buffer logger ---
37
+ var logBuf = [];
38
+ function log(msg) {
39
+ var entry = "[" + new Date().toISOString() + "] " + msg;
40
+ if (logBuf.length >= 200) logBuf.shift();
41
+ logBuf.push(entry);
42
+ process.stderr.write(entry + "\n");
43
+ }
44
+
45
+ // OpenSandbox's generic port-proxy (what sb.proxy() routes through) proxies via an
46
+ // httpx client with no read timeout configured, which falls back to httpx's 5s
47
+ // default — so any gap that long between bytes written to an SSE response (model
48
+ // "thinking" time, a slow tool call) gets the proxy's connection to us killed,
49
+ // surfacing to the caller as either a 500 or a stream that just ends early with
50
+ // nothing. A ": ping" comment line is valid SSE (clients ignore lines starting
51
+ // with ":") and resets that idle timer without affecting real event data.
52
+ function startHeartbeat(res) {
53
+ return setInterval(function () {
54
+ try {
55
+ res.write(": ping\n\n");
56
+ } catch {}
57
+ }, 3000);
58
+ }
59
+ function stopHeartbeat(iv) {
60
+ if (iv) clearInterval(iv);
61
+ }
62
+
63
+ // --- Pi process state ---
64
+ // All mutable state lives in one object so it's easy to see what changes on restart.
65
+ var state = {
66
+ proc: null, // current ChildProcess
67
+ rl: null, // readline interface on proc.stdout
68
+ ready: false, // true once Pi responds to the get_state probe
69
+ active: null, // { message, res, text, t0 } — the in-flight prompt, if any
70
+ queue: [], // pending items: { message, streamingBehavior?, res, text, t0 }
71
+ gen: 0, // incremented on every (re)start; guards against stale async callbacks
72
+ pendingCmds: {}, // id → { res, timer, bash? } — commands waiting for Pi's response ack
73
+ };
74
+
75
+ // Fail all in-flight pendingCmds cleanly, handling bash (SSE) vs regular (JSON) responses.
76
+ function cleanupPendingCmds(reason) {
77
+ Object.keys(state.pendingCmds).forEach(function (id) {
78
+ var p = state.pendingCmds[id];
79
+ clearTimeout(p.timer);
80
+ stopHeartbeat(p.heartbeat);
81
+ if (p.bash) {
82
+ try {
83
+ p.res.write("data: " + JSON.stringify({ error: reason }) + "\n\n");
84
+ p.res.end();
85
+ } catch {}
86
+ } else {
87
+ respond(p.res, 500, { ok: false, error: reason });
88
+ }
89
+ });
90
+ state.pendingCmds = {};
91
+ }
92
+
93
+ function startPi() {
94
+ // End any in-flight SSE stream so the client isn't left hanging.
95
+ if (state.active) {
96
+ stopHeartbeat(state.active.heartbeat);
97
+ state.active.res.write("data: " + JSON.stringify({ error: "pi restarted" }) + "\n\n");
98
+ state.active.res.end();
99
+ state.active = null;
100
+ }
101
+ cleanupPendingCmds("pi restarted");
102
+
103
+ if (state.rl) {
104
+ try {
105
+ state.rl.close();
106
+ } catch {}
107
+ }
108
+ if (state.proc) {
109
+ try {
110
+ state.proc.kill("SIGTERM");
111
+ } catch {}
112
+ }
113
+ state.proc = null;
114
+ state.rl = null;
115
+ state.ready = false;
116
+ // NB: state.queue is intentionally preserved — queued prompts are re-sent to the new Pi.
117
+
118
+ loadEnv();
119
+ var args = buildPiArgs();
120
+ var gen = ++state.gen;
121
+ log("pi start gen=" + gen + ": " + args.join(" "));
122
+
123
+ var proc = spawn("pi", args, {
124
+ stdio: ["pipe", "pipe", "pipe"],
125
+ env: Object.assign({}, process.env),
126
+ });
127
+ state.proc = proc;
128
+
129
+ proc.stderr.on("data", function (chunk) {
130
+ if (state.gen === gen) log("pi stderr: " + chunk.toString().trim());
131
+ });
132
+
133
+ state.rl = createInterface({ input: proc.stdout });
134
+ state.rl.on("line", function (line) {
135
+ if (state.gen === gen) handleLine(line);
136
+ });
137
+
138
+ proc.on("exit", function (code) {
139
+ if (state.gen !== gen) return;
140
+ log("pi exit gen=" + gen + " code=" + code);
141
+ state.proc = null;
142
+ state.ready = false;
143
+ cleanupPendingCmds("pi exited");
144
+ if (state.active) {
145
+ stopHeartbeat(state.active.heartbeat);
146
+ state.active.res.write("data: " + JSON.stringify({ error: "pi exited" }) + "\n\n");
147
+ state.active.res.end();
148
+ state.active = null;
149
+ }
150
+ });
151
+
152
+ // Pi needs ~500ms to initialise its RPC layer before it can handle commands.
153
+ setTimeout(function () {
154
+ if (state.gen !== gen || !state.proc) return;
155
+ log("pi probe gen=" + gen);
156
+ rpc({ id: "__probe__", type: "get_state" });
157
+ }, 500);
158
+ }
159
+
160
+ // Write a JSON-RPC message to Pi's stdin.
161
+ function rpc(msg) {
162
+ if (state.proc) state.proc.stdin.write(JSON.stringify(msg) + "\n");
163
+ }
164
+
165
+ // Send an RPC command and hold the HTTP response open until Pi acks it.
166
+ function rpcWithAck(msg, res) {
167
+ state.pendingCmds[msg.id] = { res: res };
168
+ rpc(msg);
169
+ state.pendingCmds[msg.id].timer = setTimeout(function () {
170
+ if (state.pendingCmds[msg.id]) {
171
+ respond(state.pendingCmds[msg.id].res, 504, { error: "timeout" });
172
+ delete state.pendingCmds[msg.id];
173
+ }
174
+ }, 5000);
175
+ }
176
+
177
+ // Dispatch a single line of output from Pi's stdout.
178
+ function handleLine(line) {
179
+ if (!line.trim()) return;
180
+ var ev;
181
+ try {
182
+ ev = JSON.parse(line);
183
+ } catch {
184
+ return;
185
+ }
186
+
187
+ if (!state.ready && ev.id === "__probe__" && ev.type === "response") {
188
+ state.ready = true;
189
+ var m = (ev.data && ev.data.model) || {};
190
+ log("pi ready model=" + m.id + " api=" + m.api);
191
+ flush();
192
+ return;
193
+ }
194
+
195
+ // A "prompt" command's own ack is not tracked in pendingCmds (only via
196
+ // state.active) — if Pi rejects it outright (e.g. no API key configured for
197
+ // the provider), no agent_end will ever follow, and without this the client
198
+ // would hang forever behind the heartbeat instead of seeing a clean error.
199
+ if (ev.type === "response" && ev.command === "prompt" && !ev.success) {
200
+ if (!state.active) return;
201
+ stopHeartbeat(state.active.heartbeat);
202
+ log("prompt rejected: " + (ev.error || "unknown"));
203
+ state.active.res.write(
204
+ "data: " + JSON.stringify({ error: ev.error || "prompt rejected" }) + "\n\n",
205
+ );
206
+ state.active.res.end();
207
+ state.active = null;
208
+ flush();
209
+ return;
210
+ }
211
+
212
+ // Resolve a pending command ack.
213
+ // Bash returns output synchronously in ev.data — stream it as SSE then send [DONE].
214
+ // All other commands use JSON response.
215
+ if (ev.type === "response" && ev.id && state.pendingCmds[ev.id]) {
216
+ var pending = state.pendingCmds[ev.id];
217
+ clearTimeout(pending.timer);
218
+ stopHeartbeat(pending.heartbeat);
219
+ delete state.pendingCmds[ev.id];
220
+ if (pending.bash) {
221
+ var output = (ev.data && ev.data.output) || "";
222
+ if (output)
223
+ try {
224
+ pending.res.write("data: " + JSON.stringify({ type: "text", text: output }) + "\n\n");
225
+ } catch {}
226
+ try {
227
+ pending.res.write("data: [DONE]\n\n");
228
+ pending.res.end();
229
+ } catch {}
230
+ } else if (ev.success) {
231
+ respond(pending.res, 200, { ok: true, data: ev.data || null });
232
+ } else {
233
+ respond(pending.res, 400, { ok: false, error: ev.error || "unknown" });
234
+ }
235
+ return;
236
+ }
237
+
238
+ // Tool execution events: forward into the active prompt stream.
239
+ if (ev.type === "tool_execution_start") {
240
+ if (!state.active) return;
241
+ state.active.res.write(
242
+ "data: " +
243
+ JSON.stringify({
244
+ type: "tool_start",
245
+ toolCallId: ev.toolCallId,
246
+ toolName: ev.toolName,
247
+ args: ev.args,
248
+ }) +
249
+ "\n\n",
250
+ );
251
+ return;
252
+ }
253
+ if (ev.type === "tool_execution_update") {
254
+ if (!state.active) return;
255
+ state.active.res.write(
256
+ "data: " +
257
+ JSON.stringify({
258
+ type: "tool_update",
259
+ toolCallId: ev.toolCallId,
260
+ toolName: ev.toolName,
261
+ partialResult: ev.partialResult,
262
+ }) +
263
+ "\n\n",
264
+ );
265
+ return;
266
+ }
267
+ if (ev.type === "tool_execution_end") {
268
+ if (!state.active) return;
269
+ state.active.res.write(
270
+ "data: " +
271
+ JSON.stringify({
272
+ type: "tool_end",
273
+ toolCallId: ev.toolCallId,
274
+ toolName: ev.toolName,
275
+ result: ev.result,
276
+ isError: !!ev.isError,
277
+ }) +
278
+ "\n\n",
279
+ );
280
+ return;
281
+ }
282
+
283
+ // Extension UI requests from Pi extensions.
284
+ // Dialog methods (select/confirm/input/editor) block Pi waiting for extension_ui_response.
285
+ // We auto-cancel them immediately so Pi never stalls — even when there is no active prompt.
286
+ // Fire-and-forget methods need no response; we just forward them.
287
+ if (ev.type === "extension_ui_request") {
288
+ var DIALOG_METHODS = ["select", "confirm", "input", "editor"];
289
+ var isDialog = DIALOG_METHODS.indexOf(ev.method) !== -1;
290
+ var uiParams = {};
291
+ Object.keys(ev).forEach(function (k) {
292
+ if (k !== "type" && k !== "id") uiParams[k] = ev[k];
293
+ });
294
+ if (state.active) {
295
+ state.active.res.write(
296
+ "data: " +
297
+ JSON.stringify({
298
+ type: "extension_ui",
299
+ method: ev.method,
300
+ params: uiParams,
301
+ isDialog: isDialog,
302
+ requestId: isDialog ? ev.id : undefined,
303
+ }) +
304
+ "\n\n",
305
+ );
306
+ }
307
+ if (isDialog && ev.id) {
308
+ rpc({ type: "extension_ui_response", id: ev.id, cancelled: true });
309
+ }
310
+ return;
311
+ }
312
+
313
+ if (ev.type === "auto_retry_start") {
314
+ if (state.active) {
315
+ state.active.res.write(
316
+ "data: " +
317
+ JSON.stringify({
318
+ type: "auto_retry_start",
319
+ attempt: ev.attempt,
320
+ maxAttempts: ev.maxAttempts,
321
+ delayMs: ev.delayMs,
322
+ errorMessage: ev.errorMessage || "",
323
+ }) +
324
+ "\n\n",
325
+ );
326
+ }
327
+ return;
328
+ }
329
+
330
+ if (ev.type === "auto_retry_end") {
331
+ if (state.active) {
332
+ state.active.res.write(
333
+ "data: " +
334
+ JSON.stringify({
335
+ type: "auto_retry_end",
336
+ success: !!ev.success,
337
+ attempt: ev.attempt,
338
+ finalError: ev.finalError,
339
+ }) +
340
+ "\n\n",
341
+ );
342
+ }
343
+ return;
344
+ }
345
+
346
+ if (ev.type === "agent_start") {
347
+ if (state.active) {
348
+ state.active.res.write("data: " + JSON.stringify({ type: "agent_start" }) + "\n\n");
349
+ }
350
+ return;
351
+ }
352
+ if (ev.type === "turn_start") {
353
+ if (state.active) {
354
+ state.active.res.write(
355
+ "data: " +
356
+ JSON.stringify({ type: "turn_start", turnIndex: ev.turnIndex, timestamp: ev.timestamp }) +
357
+ "\n\n",
358
+ );
359
+ }
360
+ return;
361
+ }
362
+ if (ev.type === "turn_end") {
363
+ if (state.active) {
364
+ state.active.res.write(
365
+ "data: " +
366
+ JSON.stringify({
367
+ type: "turn_end",
368
+ turnIndex: ev.turnIndex,
369
+ message: ev.message,
370
+ toolResults: ev.toolResults || [],
371
+ }) +
372
+ "\n\n",
373
+ );
374
+ }
375
+ return;
376
+ }
377
+ if (ev.type === "message_start") {
378
+ if (state.active) {
379
+ state.active.res.write(
380
+ "data: " + JSON.stringify({ type: "message_start", message: ev.message }) + "\n\n",
381
+ );
382
+ }
383
+ return;
384
+ }
385
+ if (ev.type === "message_end") {
386
+ if (state.active) {
387
+ state.active.res.write(
388
+ "data: " + JSON.stringify({ type: "message_end", message: ev.message }) + "\n\n",
389
+ );
390
+ }
391
+ return;
392
+ }
393
+ if (ev.type === "queue_update") {
394
+ if (state.active) {
395
+ state.active.res.write(
396
+ "data: " +
397
+ JSON.stringify({
398
+ type: "queue_update",
399
+ steering: ev.steering || [],
400
+ followUp: ev.followUp || [],
401
+ }) +
402
+ "\n\n",
403
+ );
404
+ }
405
+ return;
406
+ }
407
+ if (ev.type === "compaction_start") {
408
+ if (state.active) {
409
+ state.active.res.write(
410
+ "data: " + JSON.stringify({ type: "compaction_start", reason: ev.reason }) + "\n\n",
411
+ );
412
+ }
413
+ return;
414
+ }
415
+ if (ev.type === "compaction_end") {
416
+ if (state.active) {
417
+ state.active.res.write(
418
+ "data: " +
419
+ JSON.stringify({
420
+ type: "compaction_end",
421
+ reason: ev.reason,
422
+ result: ev.result || null,
423
+ aborted: !!ev.aborted,
424
+ willRetry: !!ev.willRetry,
425
+ }) +
426
+ "\n\n",
427
+ );
428
+ }
429
+ return;
430
+ }
431
+ if (ev.type === "extension_error") {
432
+ if (state.active) {
433
+ state.active.res.write(
434
+ "data: " +
435
+ JSON.stringify({
436
+ type: "extension_error",
437
+ extensionPath: ev.extensionPath,
438
+ event: ev.event,
439
+ error: ev.error,
440
+ }) +
441
+ "\n\n",
442
+ );
443
+ }
444
+ return;
445
+ }
446
+
447
+ // message_update: forward the raw delta event, then also extract text_delta as a "text" event
448
+ // so textOnly() keeps working without changes.
449
+ if (ev.type === "message_update") {
450
+ if (!state.active) return;
451
+ state.active.res.write(
452
+ "data: " +
453
+ JSON.stringify({
454
+ type: "message_update",
455
+ message: ev.message,
456
+ delta: ev.assistantMessageEvent,
457
+ }) +
458
+ "\n\n",
459
+ );
460
+ var aev = ev.assistantMessageEvent || {};
461
+ if (aev.type === "text_delta" && aev.delta) {
462
+ state.active.text += aev.delta;
463
+ state.active.res.write("data: " + JSON.stringify({ type: "text", text: aev.delta }) + "\n\n");
464
+ }
465
+ return;
466
+ }
467
+ if (ev.type === "agent_end") {
468
+ if (!state.active) return;
469
+ stopHeartbeat(state.active.heartbeat);
470
+ state.active.res.write(
471
+ "data: " + JSON.stringify({ type: "agent_end", messages: ev.messages || [] }) + "\n\n",
472
+ );
473
+ log(
474
+ "agent_end: " +
475
+ state.active.text.length +
476
+ " chars in " +
477
+ (Date.now() - state.active.t0) +
478
+ "ms",
479
+ );
480
+ state.active.res.write("data: [DONE]\n\n");
481
+ state.active.res.end();
482
+ state.active = null;
483
+ flush();
484
+ }
485
+ }
486
+
487
+ // Send the next queued item to Pi, if Pi is ready and idle.
488
+ // streamingBehavior items ("steer"/"followUp") bypass the active-slot gate and complete immediately.
489
+ function flush() {
490
+ if (!state.ready || !state.queue.length || !state.proc) return;
491
+ var item = state.queue[0];
492
+ if (state.active && !item.streamingBehavior) return;
493
+ state.queue.shift();
494
+ if (!item.streamingBehavior) state.active = item;
495
+ item.t0 = Date.now();
496
+ var rpcMsg = { id: "p" + item.t0, type: "prompt", message: item.message };
497
+ if (item.streamingBehavior) rpcMsg.streamingBehavior = item.streamingBehavior;
498
+ rpc(rpcMsg);
499
+ item.res.writeHead(200, {
500
+ "Content-Type": "text/event-stream",
501
+ "Cache-Control": "no-cache",
502
+ Connection: "keep-alive",
503
+ });
504
+ if (!item.streamingBehavior) item.heartbeat = startHeartbeat(item.res);
505
+ // Injections don't produce their own SSE body — their output arrives via the active prompt's stream.
506
+ if (item.streamingBehavior) {
507
+ item.res.write("data: [DONE]\n\n");
508
+ item.res.end();
509
+ flush();
510
+ }
511
+ }
512
+
513
+ // HTTP response helpers.
514
+ function respond(res, status, body) {
515
+ try {
516
+ res.writeHead(status, { "Content-Type": "application/json" });
517
+ res.end(JSON.stringify(body));
518
+ } catch {}
519
+ }
520
+
521
+ // --- HTTP server ---
522
+ startPi();
523
+
524
+ http
525
+ .createServer(function (req, res) {
526
+ // GET endpoints don't need a body.
527
+ if (req.method === "GET") {
528
+ if (req.url === "/health") {
529
+ respond(res, 200, { ok: state.ready });
530
+ return;
531
+ }
532
+ if (req.url === "/logs") {
533
+ res.writeHead(200, { "Content-Type": "text/plain" });
534
+ res.end(logBuf.join("\n"));
535
+ return;
536
+ }
537
+ if (req.url === "/messages") {
538
+ rpcWithAck({ id: "gm" + Date.now(), type: "get_messages" }, res);
539
+ return;
540
+ }
541
+ if (req.url === "/available-models") {
542
+ rpcWithAck({ id: "gam" + Date.now(), type: "get_available_models" }, res);
543
+ return;
544
+ }
545
+ if (req.url === "/state") {
546
+ rpcWithAck({ id: "gs" + Date.now(), type: "get_state" }, res);
547
+ return;
548
+ }
549
+ res.writeHead(404);
550
+ res.end();
551
+ return;
552
+ }
553
+
554
+ if (req.method !== "POST") {
555
+ res.writeHead(405);
556
+ res.end();
557
+ return;
558
+ }
559
+
560
+ var body = "";
561
+ req.on("data", function (d) {
562
+ body += d;
563
+ });
564
+ req.on("end", function () {
565
+ var data = {};
566
+ try {
567
+ if (body) data = JSON.parse(body);
568
+ } catch {
569
+ res.writeHead(400);
570
+ res.end("bad json");
571
+ return;
572
+ }
573
+
574
+ switch (req.url) {
575
+ case "/prompt":
576
+ state.queue.push({
577
+ message: data.message || "",
578
+ streamingBehavior: data.streamingBehavior,
579
+ res: res,
580
+ text: "",
581
+ t0: 0,
582
+ });
583
+ flush();
584
+ return;
585
+
586
+ case "/bash": {
587
+ // Pi returns bash output synchronously in the ack's data.output — no streaming events.
588
+ if (!state.ready || !state.proc) {
589
+ respond(res, 503, { error: "pi not ready" });
590
+ return;
591
+ }
592
+ var bashId = "b" + Date.now();
593
+ var bashTimer = setTimeout(function () {
594
+ if (state.pendingCmds[bashId]) {
595
+ stopHeartbeat(state.pendingCmds[bashId].heartbeat);
596
+ delete state.pendingCmds[bashId];
597
+ try {
598
+ res.write("data: " + JSON.stringify({ error: "bash timeout" }) + "\n\n");
599
+ res.end();
600
+ } catch {}
601
+ }
602
+ }, 30000);
603
+ res.writeHead(200, {
604
+ "Content-Type": "text/event-stream",
605
+ "Cache-Control": "no-cache",
606
+ Connection: "keep-alive",
607
+ });
608
+ state.pendingCmds[bashId] = {
609
+ res: res,
610
+ timer: bashTimer,
611
+ bash: true,
612
+ heartbeat: startHeartbeat(res),
613
+ };
614
+ rpc({ id: bashId, type: "bash", command: data.command || "" });
615
+ return;
616
+ }
617
+
618
+ case "/abort":
619
+ // End the active SSE stream immediately, drain the queue, then wait for Pi's ack.
620
+ state.queue.length = 0;
621
+ if (state.active) {
622
+ stopHeartbeat(state.active.heartbeat);
623
+ state.active.res.write("data: [DONE]\n\n");
624
+ state.active.res.end();
625
+ state.active = null;
626
+ }
627
+ rpcWithAck({ id: "a" + Date.now(), type: "abort" }, res);
628
+ return;
629
+
630
+ case "/steer":
631
+ rpcWithAck({ id: "s" + Date.now(), type: "steer", message: data.message || "" }, res);
632
+ return;
633
+
634
+ case "/follow-up":
635
+ rpcWithAck(
636
+ { id: "fu" + Date.now(), type: "follow_up", message: data.message || "" },
637
+ res,
638
+ );
639
+ return;
640
+
641
+ case "/new-session":
642
+ rpcWithAck({ id: "n" + Date.now(), type: "new_session" }, res);
643
+ return;
644
+
645
+ case "/fork":
646
+ rpcWithAck({ id: "fk" + Date.now(), type: "fork", entryId: data.entryId || "" }, res);
647
+ return;
648
+
649
+ case "/clone":
650
+ rpcWithAck({ id: "cl" + Date.now(), type: "clone" }, res);
651
+ return;
652
+
653
+ case "/switch-session":
654
+ rpcWithAck(
655
+ { id: "ss" + Date.now(), type: "switch_session", sessionPath: data.sessionPath || "" },
656
+ res,
657
+ );
658
+ return;
659
+
660
+ case "/set-model":
661
+ rpcWithAck(
662
+ {
663
+ id: "sm" + Date.now(),
664
+ type: "set_model",
665
+ provider: data.provider || "",
666
+ modelId: data.modelId || "",
667
+ },
668
+ res,
669
+ );
670
+ return;
671
+
672
+ case "/cycle-model":
673
+ rpcWithAck({ id: "cm" + Date.now(), type: "cycle_model" }, res);
674
+ return;
675
+
676
+ case "/set-thinking-level":
677
+ rpcWithAck(
678
+ { id: "stl" + Date.now(), type: "set_thinking_level", level: data.level || "medium" },
679
+ res,
680
+ );
681
+ return;
682
+
683
+ case "/cycle-thinking-level":
684
+ rpcWithAck({ id: "ctl" + Date.now(), type: "cycle_thinking_level" }, res);
685
+ return;
686
+
687
+ case "/compact": {
688
+ var compactMsg = { id: "co" + Date.now(), type: "compact" };
689
+ if (data.customInstructions) compactMsg.customInstructions = data.customInstructions;
690
+ rpcWithAck(compactMsg, res);
691
+ return;
692
+ }
693
+
694
+ case "/set-auto-compaction":
695
+ rpcWithAck(
696
+ { id: "sac" + Date.now(), type: "set_auto_compaction", enabled: !!data.enabled },
697
+ res,
698
+ );
699
+ return;
700
+
701
+ case "/set-auto-retry":
702
+ rpcWithAck(
703
+ { id: "sar" + Date.now(), type: "set_auto_retry", enabled: !!data.enabled },
704
+ res,
705
+ );
706
+ return;
707
+
708
+ case "/abort-retry":
709
+ rpcWithAck({ id: "ar" + Date.now(), type: "abort_retry" }, res);
710
+ return;
711
+
712
+ case "/abort-bash":
713
+ rpcWithAck({ id: "ab" + Date.now(), type: "abort_bash" }, res);
714
+ return;
715
+
716
+ case "/get-session-stats":
717
+ rpcWithAck({ id: "gss" + Date.now(), type: "get_session_stats" }, res);
718
+ return;
719
+
720
+ case "/get-last-assistant-text":
721
+ rpcWithAck({ id: "glat" + Date.now(), type: "get_last_assistant_text" }, res);
722
+ return;
723
+
724
+ case "/get-fork-messages":
725
+ rpcWithAck({ id: "gfm" + Date.now(), type: "get_fork_messages" }, res);
726
+ return;
727
+
728
+ case "/get-commands":
729
+ rpcWithAck({ id: "gc" + Date.now(), type: "get_commands" }, res);
730
+ return;
731
+
732
+ case "/set-session-name":
733
+ rpcWithAck({ id: "ssn" + Date.now(), type: "set_session_name", name: data.name }, res);
734
+ return;
735
+
736
+ case "/set-steering-mode":
737
+ rpcWithAck({ id: "ssm" + Date.now(), type: "set_steering_mode", mode: data.mode }, res);
738
+ return;
739
+
740
+ case "/set-follow-up-mode":
741
+ rpcWithAck({ id: "sfum" + Date.now(), type: "set_follow_up_mode", mode: data.mode }, res);
742
+ return;
743
+
744
+ case "/export-html":
745
+ rpcWithAck(
746
+ { id: "eh" + Date.now(), type: "export_html", outputPath: data.outputPath },
747
+ res,
748
+ );
749
+ return;
750
+
751
+ case "/reload-env":
752
+ // Merge any inline env the host sent, then restart Pi so it picks up the new env file.
753
+ if (data.env && typeof data.env === "object") Object.assign(process.env, data.env);
754
+ startPi();
755
+ respond(res, 200, { ok: true });
756
+ return;
757
+
758
+ default:
759
+ res.writeHead(404);
760
+ res.end("not found");
761
+ }
762
+ });
763
+ })
764
+ .listen(PORT, "0.0.0.0", function () {
765
+ process.stderr.write("alineo-bridge :" + PORT + "\n");
766
+ });