alineo 0.7.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.
package/dist/pi-bridge.js DELETED
@@ -1,999 +0,0 @@
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
- // Paths/port are fixed in the sandbox; the env overrides exist only so the bridge can be
8
- // driven against a stub `pi` in unit tests (test/pi-bridge.test.ts).
9
- var PORT = Number(process.env.ALINEO_BRIDGE_PORT) || 3001;
10
- var ENV_FILE = process.env.ALINEO_ENV_FILE || "/etc/alineo-env";
11
- var PI_CONFIG_FILE = process.env.ALINEO_PI_CONFIG || "/etc/alineo-pi.json";
12
- var PI_BIN = process.env.ALINEO_PI_BIN || "pi";
13
-
14
- // Re-read /etc/alineo-env into process.env on each Pi (re)start so setEnv() changes take effect.
15
- function loadEnv() {
16
- if (!fs.existsSync(ENV_FILE)) return;
17
- var lines = fs.readFileSync(ENV_FILE, "utf8").split("\n");
18
- for (var i = 0; i < lines.length; i++) {
19
- var m = lines[i].match(/^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/);
20
- if (m) process.env[m[1]] = m[2].replace(/\\"/g, '"').replace(/\\\\/g, "\\");
21
- }
22
- }
23
-
24
- // Build the pi CLI args from /etc/alineo-pi.json (model/provider config, written by the host).
25
- // Supports: provider, model, resume (--continue to resume the most recent session),
26
- // permissions (loads the alineo permission-gate extension by explicit path).
27
- // `POLICY_ACTIVE` gates the permission-request routing below and is set here, before Pi
28
- // is ever spawned, so there is no window where Pi could emit a gate dialog first.
29
- var POLICY_ACTIVE = false;
30
- var PERMISSION_GATE_PATH = process.env.ALINEO_PERMISSION_GATE_PATH || "/alineo-permission-gate.js";
31
- function buildPiArgs() {
32
- var args = ["--mode", "rpc", "--approve"];
33
- try {
34
- if (fs.existsSync(PI_CONFIG_FILE)) {
35
- var cfg = JSON.parse(fs.readFileSync(PI_CONFIG_FILE, "utf8"));
36
- if (cfg.provider) args.push("--provider", cfg.provider);
37
- if (cfg.model) args.push("--model", cfg.model);
38
- if (cfg.resume) args.push("--continue");
39
- if (cfg.permissions && fs.existsSync(PERMISSION_GATE_PATH)) {
40
- POLICY_ACTIVE = true;
41
- args.push("-e", PERMISSION_GATE_PATH);
42
- }
43
- }
44
- } catch {}
45
- return args;
46
- }
47
-
48
- // --- Ring-buffer logger ---
49
- var logBuf = [];
50
- function log(msg) {
51
- var entry = "[" + new Date().toISOString() + "] " + msg;
52
- if (logBuf.length >= 200) logBuf.shift();
53
- logBuf.push(entry);
54
- process.stderr.write(entry + "\n");
55
- }
56
-
57
- // OpenSandbox's generic port-proxy (what sb.proxy() routes through) proxies via an
58
- // httpx client with no read timeout configured, which falls back to httpx's 5s
59
- // default — so any gap that long between bytes written to an SSE response (model
60
- // "thinking" time, a slow tool call) gets the proxy's connection to us killed,
61
- // surfacing to the caller as either a 500 or a stream that just ends early with
62
- // nothing. A ": ping" comment line is valid SSE (clients ignore lines starting
63
- // with ":") and resets that idle timer without affecting real event data.
64
- function startHeartbeat(res) {
65
- return setInterval(function () {
66
- try {
67
- res.write(": ping\n\n");
68
- } catch {}
69
- }, 3000);
70
- }
71
- function stopHeartbeat(iv) {
72
- if (iv) clearInterval(iv);
73
- }
74
-
75
- // --- Pi process state ---
76
- // All mutable state lives in one object so it's easy to see what changes on restart.
77
- var state = {
78
- proc: null, // current ChildProcess
79
- rl: null, // readline interface on proc.stdout
80
- ready: false, // true once Pi responds to the get_state probe
81
- active: null, // { message, res, text, t0 } — the in-flight prompt, if any
82
- queue: [], // pending items: { message, streamingBehavior?, res, text, t0 }
83
- gen: 0, // incremented on every (re)start; guards against stale async callbacks
84
- pendingCmds: {}, // id → { res, timer, bash? } — commands waiting for Pi's response ack
85
- pendingPermissions: {}, // pi extension_ui_request id → { tool, target, title, timer }
86
- permissionChannel: null, // { res } — long-lived SSE sink for permission_request when no prompt is active
87
- };
88
-
89
- // Permission-gate dialogs whose title starts with this marker are held + routed to the host
90
- // instead of auto-cancelled. Must match adapters/pi-permission-gate.js's MARKER.
91
- var PERM_MARKER = "ALINEO_PERM ";
92
- var PERMISSION_TIMEOUT_MS = 300000; // 5 min, matches Cline's desktop auto-deny
93
-
94
- // Push a permission event to every live SSE sink: the active prompt stream (so a caller
95
- // iterating prompt() sees it inline) AND the dedicated /permission-stream channel (so an
96
- // attached operator sees it even between / across prompts). Both may be present.
97
- function emitPermission(obj) {
98
- var line = "data: " + JSON.stringify(obj) + "\n\n";
99
- var sinks = [state.active, state.permissionChannel];
100
- for (var i = 0; i < sinks.length; i++) {
101
- if (sinks[i] && sinks[i].res) {
102
- try {
103
- sinks[i].res.write(line);
104
- } catch {}
105
- }
106
- }
107
- }
108
-
109
- // Answer a held Pi extension_ui_request. `value` is a JSON string the gate parses;
110
- // omit it (pass null) to send { cancelled: true } instead.
111
- function answerPermission(id, value) {
112
- if (value === null) rpc({ type: "extension_ui_response", id: id, cancelled: true });
113
- else rpc({ type: "extension_ui_response", id: id, value: value });
114
- }
115
-
116
- // Auto-resolve every OTHER pending permission for the same tool — opencode's "one decision
117
- // clears the batch" for an "always" (allow) or "reject" (deny) verdict.
118
- function resolveMatchingPending(exceptId, tool, verdict) {
119
- Object.keys(state.pendingPermissions).forEach(function (pid) {
120
- if (pid === exceptId) return;
121
- var p = state.pendingPermissions[pid];
122
- if (p.tool !== tool) return;
123
- clearTimeout(p.timer);
124
- delete state.pendingPermissions[pid];
125
- answerPermission(
126
- pid,
127
- verdict === "allow"
128
- ? JSON.stringify({ verdict: "allow", scope: "once" })
129
- : JSON.stringify({ verdict: "reject" }),
130
- );
131
- emitPermission({
132
- type: "permission_resolved",
133
- requestId: pid,
134
- decision: verdict === "allow" ? { kind: "once" } : { kind: "reject" },
135
- });
136
- });
137
- }
138
-
139
- // Time a held permission request out: answer the gate as cancelled + tell the host.
140
- function expirePermission(pid) {
141
- if (!state.pendingPermissions[pid]) return;
142
- delete state.pendingPermissions[pid];
143
- answerPermission(pid, null);
144
- emitPermission({ type: "permission_resolved", requestId: pid, decision: { kind: "reject" } });
145
- }
146
-
147
- // While a caller is attached to /permission-stream a human is present, so the auto-deny
148
- // timeout is suspended; it's re-armed (fresh full window) when they disconnect.
149
- function suspendPermissionTimers() {
150
- Object.keys(state.pendingPermissions).forEach(function (pid) {
151
- var p = state.pendingPermissions[pid];
152
- if (p.timer) {
153
- clearTimeout(p.timer);
154
- p.timer = null;
155
- }
156
- });
157
- }
158
- function resumePermissionTimers() {
159
- Object.keys(state.pendingPermissions).forEach(function (pid) {
160
- var p = state.pendingPermissions[pid];
161
- if (!p.timer) {
162
- p.timer = setTimeout(function () {
163
- expirePermission(pid);
164
- }, PERMISSION_TIMEOUT_MS);
165
- }
166
- });
167
- }
168
-
169
- // Fail every held permission request (pi restart, abort, exit).
170
- function cancelPendingPermissions() {
171
- Object.keys(state.pendingPermissions).forEach(function (pid) {
172
- var p = state.pendingPermissions[pid];
173
- clearTimeout(p.timer);
174
- answerPermission(pid, null);
175
- });
176
- state.pendingPermissions = {};
177
- }
178
-
179
- // Fail all in-flight pendingCmds cleanly, handling bash (SSE) vs regular (JSON) responses.
180
- function cleanupPendingCmds(reason) {
181
- Object.keys(state.pendingCmds).forEach(function (id) {
182
- var p = state.pendingCmds[id];
183
- clearTimeout(p.timer);
184
- stopHeartbeat(p.heartbeat);
185
- if (p.bash) {
186
- try {
187
- p.res.write("data: " + JSON.stringify({ error: reason }) + "\n\n");
188
- p.res.end();
189
- } catch {}
190
- } else {
191
- respond(p.res, 500, { ok: false, error: reason });
192
- }
193
- });
194
- state.pendingCmds = {};
195
- }
196
-
197
- function startPi() {
198
- // End any in-flight SSE stream so the client isn't left hanging.
199
- if (state.active) {
200
- stopHeartbeat(state.active.heartbeat);
201
- state.active.res.write("data: " + JSON.stringify({ error: "pi restarted" }) + "\n\n");
202
- state.active.res.end();
203
- state.active = null;
204
- }
205
- cleanupPendingCmds("pi restarted");
206
- cancelPendingPermissions();
207
-
208
- if (state.rl) {
209
- try {
210
- state.rl.close();
211
- } catch {}
212
- }
213
- if (state.proc) {
214
- try {
215
- state.proc.kill("SIGTERM");
216
- } catch {}
217
- }
218
- state.proc = null;
219
- state.rl = null;
220
- state.ready = false;
221
- // NB: state.queue is intentionally preserved — queued prompts are re-sent to the new Pi.
222
-
223
- loadEnv();
224
- var args = buildPiArgs();
225
- var gen = ++state.gen;
226
- log("pi start gen=" + gen + ": " + args.join(" "));
227
-
228
- var proc = spawn(PI_BIN, args, {
229
- stdio: ["pipe", "pipe", "pipe"],
230
- env: Object.assign({}, process.env),
231
- });
232
- state.proc = proc;
233
-
234
- proc.stderr.on("data", function (chunk) {
235
- if (state.gen === gen) log("pi stderr: " + chunk.toString().trim());
236
- });
237
-
238
- state.rl = createInterface({ input: proc.stdout });
239
- state.rl.on("line", function (line) {
240
- if (state.gen === gen) handleLine(line);
241
- });
242
-
243
- proc.on("exit", function (code) {
244
- if (state.gen !== gen) return;
245
- log("pi exit gen=" + gen + " code=" + code);
246
- state.proc = null;
247
- state.ready = false;
248
- cleanupPendingCmds("pi exited");
249
- cancelPendingPermissions();
250
- if (state.active) {
251
- stopHeartbeat(state.active.heartbeat);
252
- state.active.res.write("data: " + JSON.stringify({ error: "pi exited" }) + "\n\n");
253
- state.active.res.end();
254
- state.active = null;
255
- }
256
- });
257
-
258
- // Pi needs ~500ms to initialise its RPC layer before it can handle commands.
259
- setTimeout(function () {
260
- if (state.gen !== gen || !state.proc) return;
261
- log("pi probe gen=" + gen);
262
- rpc({ id: "__probe__", type: "get_state" });
263
- }, 500);
264
- }
265
-
266
- // Write a JSON-RPC message to Pi's stdin.
267
- function rpc(msg) {
268
- if (state.proc) state.proc.stdin.write(JSON.stringify(msg) + "\n");
269
- }
270
-
271
- // Send an RPC command and hold the HTTP response open until Pi acks it.
272
- function rpcWithAck(msg, res) {
273
- state.pendingCmds[msg.id] = { res: res };
274
- rpc(msg);
275
- state.pendingCmds[msg.id].timer = setTimeout(function () {
276
- if (state.pendingCmds[msg.id]) {
277
- respond(state.pendingCmds[msg.id].res, 504, { error: "timeout" });
278
- delete state.pendingCmds[msg.id];
279
- }
280
- }, 5000);
281
- }
282
-
283
- // Dispatch a single line of output from Pi's stdout.
284
- function handleLine(line) {
285
- if (!line.trim()) return;
286
- var ev;
287
- try {
288
- ev = JSON.parse(line);
289
- } catch {
290
- return;
291
- }
292
-
293
- if (!state.ready && ev.id === "__probe__" && ev.type === "response") {
294
- state.ready = true;
295
- var m = (ev.data && ev.data.model) || {};
296
- log("pi ready model=" + m.id + " api=" + m.api);
297
- flush();
298
- return;
299
- }
300
-
301
- // A "prompt" command's own ack is not tracked in pendingCmds (only via
302
- // state.active) — if Pi rejects it outright (e.g. no API key configured for
303
- // the provider), no agent_end will ever follow, and without this the client
304
- // would hang forever behind the heartbeat instead of seeing a clean error.
305
- if (ev.type === "response" && ev.command === "prompt" && !ev.success) {
306
- if (!state.active) return;
307
- stopHeartbeat(state.active.heartbeat);
308
- log("prompt rejected: " + (ev.error || "unknown"));
309
- state.active.res.write(
310
- "data: " + JSON.stringify({ error: ev.error || "prompt rejected" }) + "\n\n",
311
- );
312
- state.active.res.end();
313
- state.active = null;
314
- flush();
315
- return;
316
- }
317
-
318
- // Resolve a pending command ack.
319
- // Bash returns output synchronously in ev.data — stream it as SSE then send [DONE].
320
- // All other commands use JSON response.
321
- if (ev.type === "response" && ev.id && state.pendingCmds[ev.id]) {
322
- var pending = state.pendingCmds[ev.id];
323
- clearTimeout(pending.timer);
324
- stopHeartbeat(pending.heartbeat);
325
- delete state.pendingCmds[ev.id];
326
- if (pending.bash) {
327
- var output = (ev.data && ev.data.output) || "";
328
- if (output)
329
- try {
330
- pending.res.write("data: " + JSON.stringify({ type: "text", text: output }) + "\n\n");
331
- } catch {}
332
- try {
333
- pending.res.write("data: [DONE]\n\n");
334
- pending.res.end();
335
- } catch {}
336
- } else if (ev.success) {
337
- respond(pending.res, 200, { ok: true, data: ev.data || null });
338
- } else {
339
- respond(pending.res, 400, { ok: false, error: ev.error || "unknown" });
340
- }
341
- return;
342
- }
343
-
344
- // Tool execution events: forward into the active prompt stream.
345
- if (ev.type === "tool_execution_start") {
346
- if (!state.active) return;
347
- state.active.res.write(
348
- "data: " +
349
- JSON.stringify({
350
- type: "tool_start",
351
- toolCallId: ev.toolCallId,
352
- toolName: ev.toolName,
353
- args: ev.args,
354
- }) +
355
- "\n\n",
356
- );
357
- return;
358
- }
359
- if (ev.type === "tool_execution_update") {
360
- if (!state.active) return;
361
- state.active.res.write(
362
- "data: " +
363
- JSON.stringify({
364
- type: "tool_update",
365
- toolCallId: ev.toolCallId,
366
- toolName: ev.toolName,
367
- partialResult: ev.partialResult,
368
- }) +
369
- "\n\n",
370
- );
371
- return;
372
- }
373
- if (ev.type === "tool_execution_end") {
374
- if (!state.active) return;
375
- state.active.res.write(
376
- "data: " +
377
- JSON.stringify({
378
- type: "tool_end",
379
- toolCallId: ev.toolCallId,
380
- toolName: ev.toolName,
381
- result: ev.result,
382
- isError: !!ev.isError,
383
- }) +
384
- "\n\n",
385
- );
386
- return;
387
- }
388
-
389
- // Extension UI requests from Pi extensions.
390
- // Dialog methods (select/confirm/input/editor) block Pi waiting for extension_ui_response.
391
- // We auto-cancel them immediately so Pi never stalls — even when there is no active prompt.
392
- // Fire-and-forget methods need no response; we just forward them.
393
- if (ev.type === "extension_ui_request") {
394
- // alineo permission-gate dialog: title is `ALINEO_PERM {json}`. Hold it open, route it
395
- // to the host as a permission_request, and wait for POST /permission-response.
396
- if (
397
- POLICY_ACTIVE &&
398
- ev.method === "select" &&
399
- ev.id &&
400
- typeof ev.title === "string" &&
401
- ev.title.indexOf(PERM_MARKER) === 0
402
- ) {
403
- var meta = {};
404
- try {
405
- meta = JSON.parse(ev.title.slice(PERM_MARKER.length));
406
- } catch {}
407
- var entry = {
408
- tool: meta.tool || "unknown",
409
- target: meta.target || "",
410
- title: meta.title || "Approve tool call",
411
- since: Date.now(),
412
- timer: null,
413
- };
414
- // No auto-deny clock while a human is watching the permission stream.
415
- if (!state.permissionChannel) {
416
- entry.timer = setTimeout(function () {
417
- expirePermission(ev.id);
418
- }, PERMISSION_TIMEOUT_MS);
419
- }
420
- state.pendingPermissions[ev.id] = entry;
421
- emitPermission({
422
- type: "permission_request",
423
- requestId: ev.id,
424
- tool: entry.tool,
425
- target: entry.target,
426
- title: entry.title,
427
- });
428
- return;
429
- }
430
-
431
- var DIALOG_METHODS = ["select", "confirm", "input", "editor"];
432
- var isDialog = DIALOG_METHODS.indexOf(ev.method) !== -1;
433
- var uiParams = {};
434
- Object.keys(ev).forEach(function (k) {
435
- if (k !== "type" && k !== "id") uiParams[k] = ev[k];
436
- });
437
- if (state.active) {
438
- state.active.res.write(
439
- "data: " +
440
- JSON.stringify({
441
- type: "extension_ui",
442
- method: ev.method,
443
- params: uiParams,
444
- isDialog: isDialog,
445
- requestId: isDialog ? ev.id : undefined,
446
- }) +
447
- "\n\n",
448
- );
449
- }
450
- if (isDialog && ev.id) {
451
- rpc({ type: "extension_ui_response", id: ev.id, cancelled: true });
452
- }
453
- return;
454
- }
455
-
456
- if (ev.type === "auto_retry_start") {
457
- if (state.active) {
458
- state.active.res.write(
459
- "data: " +
460
- JSON.stringify({
461
- type: "auto_retry_start",
462
- attempt: ev.attempt,
463
- maxAttempts: ev.maxAttempts,
464
- delayMs: ev.delayMs,
465
- errorMessage: ev.errorMessage || "",
466
- }) +
467
- "\n\n",
468
- );
469
- }
470
- return;
471
- }
472
-
473
- if (ev.type === "auto_retry_end") {
474
- if (state.active) {
475
- state.active.res.write(
476
- "data: " +
477
- JSON.stringify({
478
- type: "auto_retry_end",
479
- success: !!ev.success,
480
- attempt: ev.attempt,
481
- finalError: ev.finalError,
482
- }) +
483
- "\n\n",
484
- );
485
- }
486
- return;
487
- }
488
-
489
- if (ev.type === "agent_start") {
490
- if (state.active) {
491
- state.active.res.write("data: " + JSON.stringify({ type: "agent_start" }) + "\n\n");
492
- }
493
- return;
494
- }
495
- if (ev.type === "turn_start") {
496
- if (state.active) {
497
- state.active.res.write(
498
- "data: " +
499
- JSON.stringify({ type: "turn_start", turnIndex: ev.turnIndex, timestamp: ev.timestamp }) +
500
- "\n\n",
501
- );
502
- }
503
- return;
504
- }
505
- if (ev.type === "turn_end") {
506
- if (state.active) {
507
- state.active.res.write(
508
- "data: " +
509
- JSON.stringify({
510
- type: "turn_end",
511
- turnIndex: ev.turnIndex,
512
- message: ev.message,
513
- toolResults: ev.toolResults || [],
514
- }) +
515
- "\n\n",
516
- );
517
- }
518
- return;
519
- }
520
- if (ev.type === "message_start") {
521
- if (state.active) {
522
- state.active.res.write(
523
- "data: " + JSON.stringify({ type: "message_start", message: ev.message }) + "\n\n",
524
- );
525
- }
526
- return;
527
- }
528
- if (ev.type === "message_end") {
529
- if (state.active) {
530
- state.active.res.write(
531
- "data: " + JSON.stringify({ type: "message_end", message: ev.message }) + "\n\n",
532
- );
533
- }
534
- return;
535
- }
536
- if (ev.type === "queue_update") {
537
- if (state.active) {
538
- state.active.res.write(
539
- "data: " +
540
- JSON.stringify({
541
- type: "queue_update",
542
- steering: ev.steering || [],
543
- followUp: ev.followUp || [],
544
- }) +
545
- "\n\n",
546
- );
547
- }
548
- return;
549
- }
550
- if (ev.type === "compaction_start") {
551
- if (state.active) {
552
- state.active.res.write(
553
- "data: " + JSON.stringify({ type: "compaction_start", reason: ev.reason }) + "\n\n",
554
- );
555
- }
556
- return;
557
- }
558
- if (ev.type === "compaction_end") {
559
- if (state.active) {
560
- state.active.res.write(
561
- "data: " +
562
- JSON.stringify({
563
- type: "compaction_end",
564
- reason: ev.reason,
565
- result: ev.result || null,
566
- aborted: !!ev.aborted,
567
- willRetry: !!ev.willRetry,
568
- }) +
569
- "\n\n",
570
- );
571
- }
572
- return;
573
- }
574
- if (ev.type === "extension_error") {
575
- if (state.active) {
576
- state.active.res.write(
577
- "data: " +
578
- JSON.stringify({
579
- type: "extension_error",
580
- extensionPath: ev.extensionPath,
581
- event: ev.event,
582
- error: ev.error,
583
- }) +
584
- "\n\n",
585
- );
586
- }
587
- return;
588
- }
589
-
590
- // message_update: forward the raw delta event, then also extract text_delta as a "text" event
591
- // so textOnly() keeps working without changes.
592
- if (ev.type === "message_update") {
593
- if (!state.active) return;
594
- state.active.res.write(
595
- "data: " +
596
- JSON.stringify({
597
- type: "message_update",
598
- message: ev.message,
599
- delta: ev.assistantMessageEvent,
600
- }) +
601
- "\n\n",
602
- );
603
- var aev = ev.assistantMessageEvent || {};
604
- if (aev.type === "text_delta" && aev.delta) {
605
- state.active.text += aev.delta;
606
- state.active.res.write("data: " + JSON.stringify({ type: "text", text: aev.delta }) + "\n\n");
607
- }
608
- return;
609
- }
610
- if (ev.type === "agent_end") {
611
- if (!state.active) return;
612
- stopHeartbeat(state.active.heartbeat);
613
- state.active.res.write(
614
- "data: " + JSON.stringify({ type: "agent_end", messages: ev.messages || [] }) + "\n\n",
615
- );
616
- log(
617
- "agent_end: " +
618
- state.active.text.length +
619
- " chars in " +
620
- (Date.now() - state.active.t0) +
621
- "ms",
622
- );
623
- state.active.res.write("data: [DONE]\n\n");
624
- state.active.res.end();
625
- state.active = null;
626
- flush();
627
- }
628
- }
629
-
630
- // Send the next queued item to Pi, if Pi is ready and idle.
631
- // streamingBehavior items ("steer"/"followUp") bypass the active-slot gate and complete immediately.
632
- function flush() {
633
- if (!state.ready || !state.queue.length || !state.proc) return;
634
- var item = state.queue[0];
635
- if (state.active && !item.streamingBehavior) return;
636
- state.queue.shift();
637
- if (!item.streamingBehavior) state.active = item;
638
- item.t0 = Date.now();
639
- var rpcMsg = { id: "p" + item.t0, type: "prompt", message: item.message };
640
- if (item.streamingBehavior) rpcMsg.streamingBehavior = item.streamingBehavior;
641
- rpc(rpcMsg);
642
- item.res.writeHead(200, {
643
- "Content-Type": "text/event-stream",
644
- "Cache-Control": "no-cache",
645
- Connection: "keep-alive",
646
- });
647
- if (!item.streamingBehavior) item.heartbeat = startHeartbeat(item.res);
648
- // Injections don't produce their own SSE body — their output arrives via the active prompt's stream.
649
- if (item.streamingBehavior) {
650
- item.res.write("data: [DONE]\n\n");
651
- item.res.end();
652
- flush();
653
- }
654
- }
655
-
656
- // HTTP response helpers.
657
- function respond(res, status, body) {
658
- try {
659
- res.writeHead(status, { "Content-Type": "application/json" });
660
- res.end(JSON.stringify(body));
661
- } catch {}
662
- }
663
-
664
- // --- HTTP server ---
665
- startPi();
666
-
667
- http
668
- .createServer(function (req, res) {
669
- // GET endpoints don't need a body.
670
- if (req.method === "GET") {
671
- if (req.url === "/health") {
672
- respond(res, 200, { ok: state.ready });
673
- return;
674
- }
675
- if (req.url === "/logs") {
676
- res.writeHead(200, { "Content-Type": "text/plain" });
677
- res.end(logBuf.join("\n"));
678
- return;
679
- }
680
- if (req.url === "/permission-stream") {
681
- // Long-lived SSE sink so permission_request events surface even when no prompt()
682
- // stream is open. One at a time — a new subscriber replaces the old.
683
- if (state.permissionChannel) {
684
- try {
685
- state.permissionChannel.res.end();
686
- } catch {}
687
- }
688
- res.writeHead(200, {
689
- "Content-Type": "text/event-stream",
690
- "Cache-Control": "no-cache",
691
- Connection: "keep-alive",
692
- });
693
- var pHeartbeat = startHeartbeat(res);
694
- state.permissionChannel = { res: res };
695
- // A reconnecting operator needs to see what's still outstanding, and the auto-deny
696
- // clock pauses while they're attached.
697
- suspendPermissionTimers();
698
- Object.keys(state.pendingPermissions).forEach(function (pid) {
699
- var p = state.pendingPermissions[pid];
700
- try {
701
- res.write(
702
- "data: " +
703
- JSON.stringify({
704
- type: "permission_request",
705
- requestId: pid,
706
- tool: p.tool,
707
- target: p.target,
708
- title: p.title,
709
- }) +
710
- "\n\n",
711
- );
712
- } catch {}
713
- });
714
- req.on("close", function () {
715
- stopHeartbeat(pHeartbeat);
716
- if (state.permissionChannel && state.permissionChannel.res === res) {
717
- state.permissionChannel = null;
718
- resumePermissionTimers();
719
- }
720
- });
721
- return;
722
- }
723
- if (req.url === "/pending-permissions") {
724
- var pending = Object.keys(state.pendingPermissions).map(function (pid) {
725
- var p = state.pendingPermissions[pid];
726
- return {
727
- requestId: pid,
728
- tool: p.tool,
729
- target: p.target,
730
- title: p.title,
731
- since: p.since || 0,
732
- };
733
- });
734
- respond(res, 200, { ok: true, data: { pending: pending } });
735
- return;
736
- }
737
- if (req.url === "/messages") {
738
- rpcWithAck({ id: "gm" + Date.now(), type: "get_messages" }, res);
739
- return;
740
- }
741
- if (req.url === "/available-models") {
742
- rpcWithAck({ id: "gam" + Date.now(), type: "get_available_models" }, res);
743
- return;
744
- }
745
- if (req.url === "/state") {
746
- rpcWithAck({ id: "gs" + Date.now(), type: "get_state" }, res);
747
- return;
748
- }
749
- res.writeHead(404);
750
- res.end();
751
- return;
752
- }
753
-
754
- if (req.method !== "POST") {
755
- res.writeHead(405);
756
- res.end();
757
- return;
758
- }
759
-
760
- var body = "";
761
- req.on("data", function (d) {
762
- body += d;
763
- });
764
- req.on("end", function () {
765
- var data = {};
766
- try {
767
- if (body) data = JSON.parse(body);
768
- } catch {
769
- res.writeHead(400);
770
- res.end("bad json");
771
- return;
772
- }
773
-
774
- switch (req.url) {
775
- case "/prompt":
776
- state.queue.push({
777
- message: data.message || "",
778
- streamingBehavior: data.streamingBehavior,
779
- res: res,
780
- text: "",
781
- t0: 0,
782
- });
783
- flush();
784
- return;
785
-
786
- case "/bash": {
787
- // Pi returns bash output synchronously in the ack's data.output — no streaming events.
788
- if (!state.ready || !state.proc) {
789
- respond(res, 503, { error: "pi not ready" });
790
- return;
791
- }
792
- var bashId = "b" + Date.now();
793
- var bashTimer = setTimeout(function () {
794
- if (state.pendingCmds[bashId]) {
795
- stopHeartbeat(state.pendingCmds[bashId].heartbeat);
796
- delete state.pendingCmds[bashId];
797
- try {
798
- res.write("data: " + JSON.stringify({ error: "bash timeout" }) + "\n\n");
799
- res.end();
800
- } catch {}
801
- }
802
- }, 30000);
803
- res.writeHead(200, {
804
- "Content-Type": "text/event-stream",
805
- "Cache-Control": "no-cache",
806
- Connection: "keep-alive",
807
- });
808
- state.pendingCmds[bashId] = {
809
- res: res,
810
- timer: bashTimer,
811
- bash: true,
812
- heartbeat: startHeartbeat(res),
813
- };
814
- rpc({ id: bashId, type: "bash", command: data.command || "" });
815
- return;
816
- }
817
-
818
- case "/abort":
819
- // End the active SSE stream immediately, drain the queue, then wait for Pi's ack.
820
- // A held permission request would leave Pi's tool_call hook awaiting forever —
821
- // reject each so the abort can actually unwind.
822
- cancelPendingPermissions();
823
- state.queue.length = 0;
824
- if (state.active) {
825
- stopHeartbeat(state.active.heartbeat);
826
- state.active.res.write("data: [DONE]\n\n");
827
- state.active.res.end();
828
- state.active = null;
829
- }
830
- rpcWithAck({ id: "a" + Date.now(), type: "abort" }, res);
831
- return;
832
-
833
- case "/steer":
834
- rpcWithAck({ id: "s" + Date.now(), type: "steer", message: data.message || "" }, res);
835
- return;
836
-
837
- case "/permission-response": {
838
- var pp = state.pendingPermissions[data.requestId];
839
- if (!pp) {
840
- respond(res, 404, { ok: false, error: "no such pending permission" });
841
- return;
842
- }
843
- clearTimeout(pp.timer);
844
- delete state.pendingPermissions[data.requestId];
845
- var decision = data.decision || {};
846
- if (decision.kind === "once") {
847
- answerPermission(data.requestId, JSON.stringify({ verdict: "allow", scope: "once" }));
848
- } else if (decision.kind === "always") {
849
- answerPermission(data.requestId, JSON.stringify({ verdict: "allow", scope: "always" }));
850
- resolveMatchingPending(data.requestId, pp.tool, "allow");
851
- } else {
852
- answerPermission(
853
- data.requestId,
854
- JSON.stringify({ verdict: "reject", feedback: decision.feedback || "" }),
855
- );
856
- resolveMatchingPending(data.requestId, pp.tool, "reject");
857
- }
858
- emitPermission({
859
- type: "permission_resolved",
860
- requestId: data.requestId,
861
- decision: decision,
862
- });
863
- respond(res, 200, { ok: true });
864
- return;
865
- }
866
-
867
- case "/follow-up":
868
- rpcWithAck(
869
- { id: "fu" + Date.now(), type: "follow_up", message: data.message || "" },
870
- res,
871
- );
872
- return;
873
-
874
- case "/new-session":
875
- rpcWithAck({ id: "n" + Date.now(), type: "new_session" }, res);
876
- return;
877
-
878
- case "/fork":
879
- rpcWithAck({ id: "fk" + Date.now(), type: "fork", entryId: data.entryId || "" }, res);
880
- return;
881
-
882
- case "/clone":
883
- rpcWithAck({ id: "cl" + Date.now(), type: "clone" }, res);
884
- return;
885
-
886
- case "/switch-session":
887
- rpcWithAck(
888
- { id: "ss" + Date.now(), type: "switch_session", sessionPath: data.sessionPath || "" },
889
- res,
890
- );
891
- return;
892
-
893
- case "/set-model":
894
- rpcWithAck(
895
- {
896
- id: "sm" + Date.now(),
897
- type: "set_model",
898
- provider: data.provider || "",
899
- modelId: data.modelId || "",
900
- },
901
- res,
902
- );
903
- return;
904
-
905
- case "/cycle-model":
906
- rpcWithAck({ id: "cm" + Date.now(), type: "cycle_model" }, res);
907
- return;
908
-
909
- case "/set-thinking-level":
910
- rpcWithAck(
911
- { id: "stl" + Date.now(), type: "set_thinking_level", level: data.level || "medium" },
912
- res,
913
- );
914
- return;
915
-
916
- case "/cycle-thinking-level":
917
- rpcWithAck({ id: "ctl" + Date.now(), type: "cycle_thinking_level" }, res);
918
- return;
919
-
920
- case "/compact": {
921
- var compactMsg = { id: "co" + Date.now(), type: "compact" };
922
- if (data.customInstructions) compactMsg.customInstructions = data.customInstructions;
923
- rpcWithAck(compactMsg, res);
924
- return;
925
- }
926
-
927
- case "/set-auto-compaction":
928
- rpcWithAck(
929
- { id: "sac" + Date.now(), type: "set_auto_compaction", enabled: !!data.enabled },
930
- res,
931
- );
932
- return;
933
-
934
- case "/set-auto-retry":
935
- rpcWithAck(
936
- { id: "sar" + Date.now(), type: "set_auto_retry", enabled: !!data.enabled },
937
- res,
938
- );
939
- return;
940
-
941
- case "/abort-retry":
942
- rpcWithAck({ id: "ar" + Date.now(), type: "abort_retry" }, res);
943
- return;
944
-
945
- case "/abort-bash":
946
- rpcWithAck({ id: "ab" + Date.now(), type: "abort_bash" }, res);
947
- return;
948
-
949
- case "/get-session-stats":
950
- rpcWithAck({ id: "gss" + Date.now(), type: "get_session_stats" }, res);
951
- return;
952
-
953
- case "/get-last-assistant-text":
954
- rpcWithAck({ id: "glat" + Date.now(), type: "get_last_assistant_text" }, res);
955
- return;
956
-
957
- case "/get-fork-messages":
958
- rpcWithAck({ id: "gfm" + Date.now(), type: "get_fork_messages" }, res);
959
- return;
960
-
961
- case "/get-commands":
962
- rpcWithAck({ id: "gc" + Date.now(), type: "get_commands" }, res);
963
- return;
964
-
965
- case "/set-session-name":
966
- rpcWithAck({ id: "ssn" + Date.now(), type: "set_session_name", name: data.name }, res);
967
- return;
968
-
969
- case "/set-steering-mode":
970
- rpcWithAck({ id: "ssm" + Date.now(), type: "set_steering_mode", mode: data.mode }, res);
971
- return;
972
-
973
- case "/set-follow-up-mode":
974
- rpcWithAck({ id: "sfum" + Date.now(), type: "set_follow_up_mode", mode: data.mode }, res);
975
- return;
976
-
977
- case "/export-html":
978
- rpcWithAck(
979
- { id: "eh" + Date.now(), type: "export_html", outputPath: data.outputPath },
980
- res,
981
- );
982
- return;
983
-
984
- case "/reload-env":
985
- // Merge any inline env the host sent, then restart Pi so it picks up the new env file.
986
- if (data.env && typeof data.env === "object") Object.assign(process.env, data.env);
987
- startPi();
988
- respond(res, 200, { ok: true });
989
- return;
990
-
991
- default:
992
- res.writeHead(404);
993
- res.end("not found");
994
- }
995
- });
996
- })
997
- .listen(PORT, "0.0.0.0", function () {
998
- process.stderr.write("alineo-bridge :" + PORT + "\n");
999
- });