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/README.md +1 -1
- package/dist/claude-bridge.cjs +633 -0
- package/dist/codex-bridge.cjs +855 -0
- package/dist/index.d.mts +941 -85
- package/dist/index.mjs +1488 -318
- package/dist/pi-bridge.cjs +905 -0
- package/dist/pi-permission-gate.mjs +288 -0
- package/package.json +7 -6
- package/dist/pi-bridge.js +0 -999
- package/dist/pi-permission-gate.js +0 -337
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# alineo
|
|
2
2
|
|
|
3
|
-
Run [Pi](https://pi
|
|
3
|
+
Run [Pi](https://github.com/earendil-works/pi) coding agents inside isolated [alineo](https://alineo.tech) sandbox containers. Pi can read and write files, run shell commands, and execute scripts — streamed back through a simple TypeScript API.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
bun add alineo
|
|
@@ -0,0 +1,633 @@
|
|
|
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_path = require("node:path");
|
|
5
|
+
let node_url = require("node:url");
|
|
6
|
+
//#region src/permissions.ts
|
|
7
|
+
/**
|
|
8
|
+
* First tokens that make a shell command a pure reader — used by the `"classify"` action
|
|
9
|
+
* and by the `bash` rule `"readonly"` installs. Deliberately conservative: an unrecognised
|
|
10
|
+
* command falls through to `ask`, never to `allow`.
|
|
11
|
+
*/
|
|
12
|
+
const SAFE_BASH_COMMANDS = [
|
|
13
|
+
"ls",
|
|
14
|
+
"cat",
|
|
15
|
+
"head",
|
|
16
|
+
"tail",
|
|
17
|
+
"grep",
|
|
18
|
+
"rg",
|
|
19
|
+
"egrep",
|
|
20
|
+
"fgrep",
|
|
21
|
+
"zgrep",
|
|
22
|
+
"find",
|
|
23
|
+
"pwd",
|
|
24
|
+
"whoami",
|
|
25
|
+
"id",
|
|
26
|
+
"env",
|
|
27
|
+
"printenv",
|
|
28
|
+
"echo",
|
|
29
|
+
"printf",
|
|
30
|
+
"which",
|
|
31
|
+
"type",
|
|
32
|
+
"file",
|
|
33
|
+
"stat",
|
|
34
|
+
"wc",
|
|
35
|
+
"date",
|
|
36
|
+
"uname",
|
|
37
|
+
"hostname",
|
|
38
|
+
"df",
|
|
39
|
+
"du",
|
|
40
|
+
"tree",
|
|
41
|
+
"basename",
|
|
42
|
+
"dirname",
|
|
43
|
+
"realpath",
|
|
44
|
+
"readlink",
|
|
45
|
+
"true",
|
|
46
|
+
"false",
|
|
47
|
+
"cmp",
|
|
48
|
+
"diff",
|
|
49
|
+
"column",
|
|
50
|
+
"nl",
|
|
51
|
+
"less",
|
|
52
|
+
"more",
|
|
53
|
+
"tac",
|
|
54
|
+
"hexdump",
|
|
55
|
+
"xxd",
|
|
56
|
+
"od",
|
|
57
|
+
"strings",
|
|
58
|
+
"sha1sum",
|
|
59
|
+
"sha256sum",
|
|
60
|
+
"md5sum",
|
|
61
|
+
"cksum"
|
|
62
|
+
];
|
|
63
|
+
/** `git <sub>` combinations that only read. */
|
|
64
|
+
const SAFE_GIT_SUBCOMMANDS = [
|
|
65
|
+
"status",
|
|
66
|
+
"log",
|
|
67
|
+
"diff",
|
|
68
|
+
"show",
|
|
69
|
+
"branch",
|
|
70
|
+
"remote",
|
|
71
|
+
"rev-parse",
|
|
72
|
+
"describe",
|
|
73
|
+
"blame",
|
|
74
|
+
"tag",
|
|
75
|
+
"config",
|
|
76
|
+
"ls-files",
|
|
77
|
+
"ls-tree",
|
|
78
|
+
"shortlog",
|
|
79
|
+
"reflog",
|
|
80
|
+
"cat-file",
|
|
81
|
+
"for-each-ref",
|
|
82
|
+
"whatchanged",
|
|
83
|
+
"rev-list",
|
|
84
|
+
"name-rev",
|
|
85
|
+
"symbolic-ref",
|
|
86
|
+
"count-objects"
|
|
87
|
+
];
|
|
88
|
+
const WRAPPER_COMMANDS = /* @__PURE__ */ new Set([
|
|
89
|
+
"env",
|
|
90
|
+
"command",
|
|
91
|
+
"nice",
|
|
92
|
+
"stdbuf",
|
|
93
|
+
"time"
|
|
94
|
+
]);
|
|
95
|
+
/**
|
|
96
|
+
* True if `seg` contains a file output redirection (`> file`, `>> file`). A `>` immediately
|
|
97
|
+
* followed by `&` (`2>&1`, `>&2`), preceded by a digit (`2>`, stderr), or preceded by `&`
|
|
98
|
+
* is a file-descriptor op, not a file write. Linear scan — no regex (ReDoS-safe).
|
|
99
|
+
*/
|
|
100
|
+
function hasOutputRedirect(seg) {
|
|
101
|
+
for (let i = 0; i < seg.length; i++) {
|
|
102
|
+
if (seg[i] !== ">") continue;
|
|
103
|
+
const next = seg[i + 1];
|
|
104
|
+
const prev = seg[i - 1];
|
|
105
|
+
if (next === "&" || prev === "&" || prev >= "0" && prev <= "9") continue;
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
|
|
112
|
+
* recognised pure reader with no output redirection; `false` = something needs a human.
|
|
113
|
+
* Mirrored verbatim in `bridge/pi-permission-gate.ts`.
|
|
114
|
+
*/
|
|
115
|
+
function isReadOnlyBashCommand(command) {
|
|
116
|
+
const segments = command.split(/&&|\|\||[;\n|]/).map((s) => s.trim()).filter(Boolean);
|
|
117
|
+
if (segments.length === 0) return false;
|
|
118
|
+
return segments.every((seg) => {
|
|
119
|
+
if (hasOutputRedirect(seg)) return false;
|
|
120
|
+
let tokens = seg.split(/\s+/).filter(Boolean);
|
|
121
|
+
while (tokens.length > 0 && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) tokens = tokens.slice(1);
|
|
122
|
+
while (tokens.length > 1 && WRAPPER_COMMANDS.has(tokens[0])) tokens = tokens.slice(1);
|
|
123
|
+
if (tokens[0] === "timeout" && tokens.length > 2) tokens = tokens.slice(2);
|
|
124
|
+
const first = tokens[0] ?? "";
|
|
125
|
+
const slash = first.lastIndexOf("/");
|
|
126
|
+
const cmd = slash === -1 ? first : first.slice(slash + 1);
|
|
127
|
+
if (!cmd) return false;
|
|
128
|
+
if (SAFE_BASH_COMMANDS.includes(cmd)) return true;
|
|
129
|
+
if (cmd === "git" && SAFE_GIT_SUBCOMMANDS.includes(tokens[1] ?? "")) return true;
|
|
130
|
+
return false;
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
/** Compile a rule glob to an anchored RegExp. `*` → `.*`, `?` → `.`, everything else literal. */
|
|
134
|
+
function globToRegExp(glob) {
|
|
135
|
+
const body = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
136
|
+
return new RegExp(`^${body}$`, "s");
|
|
137
|
+
}
|
|
138
|
+
function ruleMatches(rule, tool, target) {
|
|
139
|
+
if (!globToRegExp(rule.tool).test(tool)) return false;
|
|
140
|
+
if (rule.pattern !== void 0 && !globToRegExp(rule.pattern).test(target)) return false;
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Resolve a tool call to an action: the last matching rule's, or the policy default.
|
|
145
|
+
* `disabledTools` short-circuits to `"deny"`. `"classify"` is resolved here to `"allow"`
|
|
146
|
+
* or `"ask"` (bash reader-triage; any other tool → `"ask"`).
|
|
147
|
+
*/
|
|
148
|
+
function evaluatePolicy(policy, tool, target) {
|
|
149
|
+
if (policy.disabledTools.includes(tool)) return { action: "deny" };
|
|
150
|
+
let match;
|
|
151
|
+
for (const rule of policy.rules) if (ruleMatches(rule, tool, target)) match = rule;
|
|
152
|
+
if ((match ? match.action : policy.default) === "classify") return {
|
|
153
|
+
action: tool === "bash" && isReadOnlyBashCommand(target) ? "allow" : "ask",
|
|
154
|
+
rule: match
|
|
155
|
+
};
|
|
156
|
+
return match ? {
|
|
157
|
+
action: match.action,
|
|
158
|
+
rule: match
|
|
159
|
+
} : { action: policy.default };
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/bridge/claude-bridge.ts
|
|
163
|
+
/**
|
|
164
|
+
* The in-sandbox bridge for Claude Code: drives the Claude Agent SDK and serves the same
|
|
165
|
+
* HTTP+SSE contract as the Pi bridge (`harness/bridge.ts`), but each frame is already a
|
|
166
|
+
* `HarnessEvent`, because the SDK's messages map straight onto the neutral vocabulary.
|
|
167
|
+
*
|
|
168
|
+
* Bundled to one CommonJS file (`dist/claude-bridge.cjs`) and written into the sandbox at
|
|
169
|
+
* `/alineo-bridge.js`. The Agent SDK is installed globally in the sandbox image and loaded
|
|
170
|
+
* with a dynamic import, so it is not part of the bundle.
|
|
171
|
+
*
|
|
172
|
+
* One turn is one `query()` call. A follow-up turn resumes the session by id.
|
|
173
|
+
*/
|
|
174
|
+
const PORT = Number(process.env.ALINEO_BRIDGE_PORT) || 3001;
|
|
175
|
+
const ENV_FILE = process.env.ALINEO_ENV_FILE || "/etc/alineo-env";
|
|
176
|
+
const CONFIG_FILE = process.env.ALINEO_CLAUDE_CONFIG || "/etc/alineo-claude.json";
|
|
177
|
+
/** Test seam: a stub SDK module. In the sandbox the SDK is found under `npm root -g`. */
|
|
178
|
+
const SDK_PATH_OVERRIDE = process.env.ALINEO_CLAUDE_SDK_PATH;
|
|
179
|
+
const PERMISSION_TIMEOUT_MS = 3e5;
|
|
180
|
+
const logBuf = [];
|
|
181
|
+
function log(msg) {
|
|
182
|
+
const entry = "[" + (/* @__PURE__ */ new Date()).toISOString() + "] " + msg;
|
|
183
|
+
if (logBuf.length >= 200) logBuf.shift();
|
|
184
|
+
logBuf.push(entry);
|
|
185
|
+
process.stderr.write(entry + "\n");
|
|
186
|
+
}
|
|
187
|
+
function loadEnv() {
|
|
188
|
+
if (!(0, node_fs.existsSync)(ENV_FILE)) return;
|
|
189
|
+
for (const line of (0, node_fs.readFileSync)(ENV_FILE, "utf8").split("\n")) {
|
|
190
|
+
const m = line.match(/^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/);
|
|
191
|
+
if (m) process.env[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function loadConfig() {
|
|
195
|
+
try {
|
|
196
|
+
return JSON.parse((0, node_fs.readFileSync)(CONFIG_FILE, "utf8"));
|
|
197
|
+
} catch {
|
|
198
|
+
return {};
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
async function loadSdk() {
|
|
202
|
+
const path = SDK_PATH_OVERRIDE ?? (0, node_path.join)((0, node_child_process.execSync)("npm root -g", { encoding: "utf8" }).trim(), "@anthropic-ai/claude-agent-sdk/sdk.mjs");
|
|
203
|
+
return await import((0, node_url.pathToFileURL)(path).href);
|
|
204
|
+
}
|
|
205
|
+
function send(res, frame) {
|
|
206
|
+
try {
|
|
207
|
+
res.write("data: " + JSON.stringify(frame) + "\n\n");
|
|
208
|
+
} catch {}
|
|
209
|
+
}
|
|
210
|
+
function respond(res, status, body) {
|
|
211
|
+
try {
|
|
212
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
213
|
+
res.end(JSON.stringify(body));
|
|
214
|
+
} catch {}
|
|
215
|
+
}
|
|
216
|
+
function startHeartbeat(res) {
|
|
217
|
+
return setInterval(() => {
|
|
218
|
+
try {
|
|
219
|
+
res.write(": ping\n\n");
|
|
220
|
+
} catch {}
|
|
221
|
+
}, 3e3);
|
|
222
|
+
}
|
|
223
|
+
const state = {
|
|
224
|
+
sdk: null,
|
|
225
|
+
ready: false,
|
|
226
|
+
sessionId: null,
|
|
227
|
+
active: null,
|
|
228
|
+
pending: /* @__PURE__ */ new Map(),
|
|
229
|
+
alwaysAllow: /* @__PURE__ */ new Set(),
|
|
230
|
+
rateHits: /* @__PURE__ */ new Map(),
|
|
231
|
+
config: {}
|
|
232
|
+
};
|
|
233
|
+
/** Claude's tool names are capitalised. Policy rules use Pi's lowercase vocabulary. */
|
|
234
|
+
const TOOL_ALIASES = {
|
|
235
|
+
bash: "bash",
|
|
236
|
+
read: "read",
|
|
237
|
+
write: "write",
|
|
238
|
+
edit: "edit",
|
|
239
|
+
multiedit: "edit",
|
|
240
|
+
notebookedit: "edit",
|
|
241
|
+
grep: "grep",
|
|
242
|
+
glob: "find",
|
|
243
|
+
ls: "ls"
|
|
244
|
+
};
|
|
245
|
+
function policyToolName(toolName) {
|
|
246
|
+
return TOOL_ALIASES[toolName.toLowerCase()] ?? toolName.toLowerCase();
|
|
247
|
+
}
|
|
248
|
+
function targetOf(tool, input) {
|
|
249
|
+
const s = (v) => typeof v === "string" ? v : "";
|
|
250
|
+
switch (tool) {
|
|
251
|
+
case "bash": return s(input.command);
|
|
252
|
+
case "read":
|
|
253
|
+
case "write":
|
|
254
|
+
case "edit":
|
|
255
|
+
case "ls": return s(input.file_path) || s(input.path);
|
|
256
|
+
case "grep":
|
|
257
|
+
case "find": return s(input.pattern);
|
|
258
|
+
default: try {
|
|
259
|
+
return JSON.stringify(input);
|
|
260
|
+
} catch {
|
|
261
|
+
return "";
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function underLimit(key, limit) {
|
|
266
|
+
if (!limit) return true;
|
|
267
|
+
const now = Date.now();
|
|
268
|
+
const hits = (state.rateHits.get(key) ?? []).filter((t) => t >= now - limit.windowMs);
|
|
269
|
+
if (hits.length >= limit.count) {
|
|
270
|
+
state.rateHits.set(key, hits);
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
hits.push(now);
|
|
274
|
+
state.rateHits.set(key, hits);
|
|
275
|
+
return true;
|
|
276
|
+
}
|
|
277
|
+
function emitToActive(frame) {
|
|
278
|
+
if (state.active) send(state.active.res, frame);
|
|
279
|
+
}
|
|
280
|
+
const canUseTool = async (toolName, input, options) => {
|
|
281
|
+
const policy = state.config.permissions;
|
|
282
|
+
const allow = {
|
|
283
|
+
behavior: "allow",
|
|
284
|
+
updatedInput: input
|
|
285
|
+
};
|
|
286
|
+
if (!policy) return allow;
|
|
287
|
+
const tool = policyToolName(toolName);
|
|
288
|
+
if (policy.restrictToTools.length > 0 && !policy.restrictToTools.includes(tool)) return {
|
|
289
|
+
behavior: "deny",
|
|
290
|
+
message: `The operator's policy does not allow the ${toolName} tool.`
|
|
291
|
+
};
|
|
292
|
+
const target = targetOf(tool, input);
|
|
293
|
+
const key = `${tool} ${target}`;
|
|
294
|
+
if (state.alwaysAllow.has(key)) return allow;
|
|
295
|
+
const { action, rule } = evaluatePolicy(policy, tool, target);
|
|
296
|
+
if (action === "allow") return allow;
|
|
297
|
+
if (action === "deny") return {
|
|
298
|
+
behavior: "deny",
|
|
299
|
+
message: `The operator's policy denies this tool call: ${tool} ${target}`.trim()
|
|
300
|
+
};
|
|
301
|
+
if (action === "rate_limit") return underLimit(key, rule?.limit) ? allow : {
|
|
302
|
+
behavior: "deny",
|
|
303
|
+
message: `Rate limit reached for ${tool}. Wait before trying again.`
|
|
304
|
+
};
|
|
305
|
+
const requestId = options.toolUseID;
|
|
306
|
+
const title = options.title || `Run ${tool}: ${target}`;
|
|
307
|
+
const decision = await new Promise((resolve) => {
|
|
308
|
+
const settle = (d) => {
|
|
309
|
+
clearTimeout(timer);
|
|
310
|
+
options.signal.removeEventListener("abort", onAbort);
|
|
311
|
+
state.pending.delete(requestId);
|
|
312
|
+
resolve(d);
|
|
313
|
+
};
|
|
314
|
+
const onAbort = () => {
|
|
315
|
+
settle({
|
|
316
|
+
kind: "reject",
|
|
317
|
+
feedback: "The turn was aborted."
|
|
318
|
+
});
|
|
319
|
+
};
|
|
320
|
+
const timer = setTimeout(() => {
|
|
321
|
+
settle({
|
|
322
|
+
kind: "reject",
|
|
323
|
+
feedback: "Approval timed out."
|
|
324
|
+
});
|
|
325
|
+
}, PERMISSION_TIMEOUT_MS);
|
|
326
|
+
options.signal.addEventListener("abort", onAbort);
|
|
327
|
+
state.pending.set(requestId, {
|
|
328
|
+
requestId,
|
|
329
|
+
tool,
|
|
330
|
+
target,
|
|
331
|
+
title,
|
|
332
|
+
since: Date.now(),
|
|
333
|
+
settle,
|
|
334
|
+
timer
|
|
335
|
+
});
|
|
336
|
+
emitToActive({
|
|
337
|
+
type: "permission_request",
|
|
338
|
+
requestId,
|
|
339
|
+
tool,
|
|
340
|
+
target,
|
|
341
|
+
title
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
emitToActive({
|
|
345
|
+
type: "permission_resolved",
|
|
346
|
+
requestId,
|
|
347
|
+
decision
|
|
348
|
+
});
|
|
349
|
+
if (decision.kind === "once") return allow;
|
|
350
|
+
if (decision.kind === "always") {
|
|
351
|
+
state.alwaysAllow.add(key);
|
|
352
|
+
for (const other of [...state.pending.values()]) if (other.tool === tool) other.settle({ kind: "once" });
|
|
353
|
+
return allow;
|
|
354
|
+
}
|
|
355
|
+
return {
|
|
356
|
+
behavior: "deny",
|
|
357
|
+
message: decision.feedback ? `The operator declined this and said: ${decision.feedback}` : "The operator declined this tool call."
|
|
358
|
+
};
|
|
359
|
+
};
|
|
360
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
361
|
+
/** Map one SDK message to zero or more frames. `streamed` tracks text already sent as deltas. */
|
|
362
|
+
function mapMessage(msg, ctx) {
|
|
363
|
+
switch (msg.type) {
|
|
364
|
+
case "system":
|
|
365
|
+
if (msg.subtype === "init" && msg.session_id) {
|
|
366
|
+
state.sessionId = msg.session_id;
|
|
367
|
+
return [{
|
|
368
|
+
type: "run_start",
|
|
369
|
+
sessionRef: msg.session_id
|
|
370
|
+
}];
|
|
371
|
+
}
|
|
372
|
+
return [];
|
|
373
|
+
case "stream_event": {
|
|
374
|
+
const d = msg.event?.type === "content_block_delta" ? msg.event.delta : void 0;
|
|
375
|
+
if (d?.type === "text_delta" && d.text) {
|
|
376
|
+
ctx.streamed = true;
|
|
377
|
+
return [{
|
|
378
|
+
type: "text",
|
|
379
|
+
text: d.text
|
|
380
|
+
}];
|
|
381
|
+
}
|
|
382
|
+
if (d?.type === "thinking_delta" && d.thinking) return [{
|
|
383
|
+
type: "reasoning",
|
|
384
|
+
text: d.thinking
|
|
385
|
+
}];
|
|
386
|
+
return [];
|
|
387
|
+
}
|
|
388
|
+
case "assistant": {
|
|
389
|
+
const messageId = msg.uuid ?? null;
|
|
390
|
+
const blocks = Array.isArray(msg.message?.content) ? msg.message.content : [];
|
|
391
|
+
const out = [{
|
|
392
|
+
type: "message_start",
|
|
393
|
+
messageId
|
|
394
|
+
}];
|
|
395
|
+
for (const b of blocks) {
|
|
396
|
+
if (b.type === "text" && b.text && !ctx.streamed && !msg.error) out.push({
|
|
397
|
+
type: "text",
|
|
398
|
+
text: b.text
|
|
399
|
+
});
|
|
400
|
+
if (b.type === "tool_use" && b.id && b.name) {
|
|
401
|
+
toolNames.set(b.id, b.name);
|
|
402
|
+
out.push({
|
|
403
|
+
type: "tool_start",
|
|
404
|
+
toolCallId: b.id,
|
|
405
|
+
toolName: b.name,
|
|
406
|
+
args: b.input ?? {}
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
out.push({
|
|
411
|
+
type: "message_end",
|
|
412
|
+
messageId
|
|
413
|
+
});
|
|
414
|
+
ctx.streamed = false;
|
|
415
|
+
return out;
|
|
416
|
+
}
|
|
417
|
+
case "user": {
|
|
418
|
+
const blocks = Array.isArray(msg.message?.content) ? msg.message.content : [];
|
|
419
|
+
const out = [];
|
|
420
|
+
for (const b of blocks) if (b.type === "tool_result" && b.tool_use_id) out.push({
|
|
421
|
+
type: "tool_end",
|
|
422
|
+
toolCallId: b.tool_use_id,
|
|
423
|
+
toolName: toolNames.get(b.tool_use_id) ?? "unknown",
|
|
424
|
+
result: b.content ?? null,
|
|
425
|
+
isError: !!b.is_error
|
|
426
|
+
});
|
|
427
|
+
return out;
|
|
428
|
+
}
|
|
429
|
+
case "result":
|
|
430
|
+
if (msg.subtype === "success" && !msg.is_error) return [{
|
|
431
|
+
type: "done",
|
|
432
|
+
reason: "completed"
|
|
433
|
+
}];
|
|
434
|
+
return [{
|
|
435
|
+
type: "error",
|
|
436
|
+
message: msg.result || msg.errors?.join("; ") || msg.subtype || "the turn failed"
|
|
437
|
+
}, {
|
|
438
|
+
type: "done",
|
|
439
|
+
reason: "error"
|
|
440
|
+
}];
|
|
441
|
+
default: return [];
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async function runTurn(res, message) {
|
|
445
|
+
const abort = new AbortController();
|
|
446
|
+
const heartbeat = startHeartbeat(res);
|
|
447
|
+
state.active = {
|
|
448
|
+
res,
|
|
449
|
+
abort,
|
|
450
|
+
heartbeat
|
|
451
|
+
};
|
|
452
|
+
res.writeHead(200, {
|
|
453
|
+
"Content-Type": "text/event-stream",
|
|
454
|
+
"Cache-Control": "no-cache",
|
|
455
|
+
Connection: "keep-alive"
|
|
456
|
+
});
|
|
457
|
+
let finished = false;
|
|
458
|
+
try {
|
|
459
|
+
const sdk = state.sdk;
|
|
460
|
+
if (!sdk) throw new Error("the Claude Agent SDK is not loaded");
|
|
461
|
+
loadEnv();
|
|
462
|
+
const options = {
|
|
463
|
+
abortController: abort,
|
|
464
|
+
canUseTool,
|
|
465
|
+
includePartialMessages: true,
|
|
466
|
+
permissionMode: "default",
|
|
467
|
+
settingSources: [],
|
|
468
|
+
systemPrompt: state.config.systemPrompt ?? {
|
|
469
|
+
type: "preset",
|
|
470
|
+
preset: "claude_code"
|
|
471
|
+
},
|
|
472
|
+
env: { ...process.env }
|
|
473
|
+
};
|
|
474
|
+
if (state.config.model) options.model = state.config.model;
|
|
475
|
+
if (state.sessionId) options.resume = state.sessionId;
|
|
476
|
+
else if (state.config.resume) options.continue = true;
|
|
477
|
+
const ctx = { streamed: false };
|
|
478
|
+
const q = sdk.query({
|
|
479
|
+
prompt: message,
|
|
480
|
+
options
|
|
481
|
+
});
|
|
482
|
+
for await (const msg of q) for (const frame of mapMessage(msg, ctx)) {
|
|
483
|
+
send(res, frame);
|
|
484
|
+
if (frame.type === "done") finished = true;
|
|
485
|
+
}
|
|
486
|
+
if (!finished) send(res, {
|
|
487
|
+
type: "done",
|
|
488
|
+
reason: abort.signal.aborted ? "aborted" : "error"
|
|
489
|
+
});
|
|
490
|
+
} catch (e) {
|
|
491
|
+
const text = e instanceof Error ? e.message : String(e);
|
|
492
|
+
if (finished) log("sdk threw after the result: " + text);
|
|
493
|
+
else if (abort.signal.aborted) send(res, {
|
|
494
|
+
type: "done",
|
|
495
|
+
reason: "aborted"
|
|
496
|
+
});
|
|
497
|
+
else {
|
|
498
|
+
log("turn failed: " + text);
|
|
499
|
+
send(res, { error: text });
|
|
500
|
+
}
|
|
501
|
+
} finally {
|
|
502
|
+
clearInterval(heartbeat);
|
|
503
|
+
for (const p of [...state.pending.values()]) p.settle({
|
|
504
|
+
kind: "reject",
|
|
505
|
+
feedback: "The turn ended."
|
|
506
|
+
});
|
|
507
|
+
state.active = null;
|
|
508
|
+
try {
|
|
509
|
+
res.write("data: [DONE]\n\n");
|
|
510
|
+
res.end();
|
|
511
|
+
} catch {}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async function main() {
|
|
515
|
+
loadEnv();
|
|
516
|
+
state.config = loadConfig();
|
|
517
|
+
try {
|
|
518
|
+
state.sdk = await loadSdk();
|
|
519
|
+
state.ready = true;
|
|
520
|
+
log("claude agent sdk loaded");
|
|
521
|
+
} catch (e) {
|
|
522
|
+
log("could not load the claude agent sdk: " + (e instanceof Error ? e.message : String(e)));
|
|
523
|
+
}
|
|
524
|
+
(0, node_http.createServer)((req, res) => {
|
|
525
|
+
if (req.method === "GET") {
|
|
526
|
+
if (req.url === "/health") return respond(res, 200, { ok: state.ready });
|
|
527
|
+
if (req.url === "/logs") {
|
|
528
|
+
res.writeHead(200, { "Content-Type": "text/plain" });
|
|
529
|
+
res.end(logBuf.join("\n"));
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
if (req.url === "/state") return respond(res, 200, {
|
|
533
|
+
ok: true,
|
|
534
|
+
data: { sessionId: state.sessionId }
|
|
535
|
+
});
|
|
536
|
+
if (req.url === "/pending-permissions") return respond(res, 200, {
|
|
537
|
+
ok: true,
|
|
538
|
+
data: { pending: [...state.pending.values()].map((p) => ({
|
|
539
|
+
requestId: p.requestId,
|
|
540
|
+
tool: p.tool,
|
|
541
|
+
target: p.target,
|
|
542
|
+
title: p.title,
|
|
543
|
+
since: p.since
|
|
544
|
+
})) }
|
|
545
|
+
});
|
|
546
|
+
res.writeHead(404);
|
|
547
|
+
res.end();
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (req.method !== "POST") {
|
|
551
|
+
res.writeHead(405);
|
|
552
|
+
res.end();
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
let body = "";
|
|
556
|
+
req.on("data", (d) => {
|
|
557
|
+
body += d;
|
|
558
|
+
});
|
|
559
|
+
req.on("end", () => {
|
|
560
|
+
let data = {};
|
|
561
|
+
try {
|
|
562
|
+
if (body) data = JSON.parse(body);
|
|
563
|
+
} catch {
|
|
564
|
+
res.writeHead(400);
|
|
565
|
+
res.end("bad json");
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
switch (req.url) {
|
|
569
|
+
case "/prompt":
|
|
570
|
+
if (!state.ready) return respond(res, 503, {
|
|
571
|
+
ok: false,
|
|
572
|
+
error: "claude sdk not loaded"
|
|
573
|
+
});
|
|
574
|
+
if (state.active) return respond(res, 409, {
|
|
575
|
+
ok: false,
|
|
576
|
+
error: "a turn is already running"
|
|
577
|
+
});
|
|
578
|
+
runTurn(res, data.message ?? "");
|
|
579
|
+
return;
|
|
580
|
+
case "/abort":
|
|
581
|
+
if (state.active) state.active.abort.abort();
|
|
582
|
+
return respond(res, 200, {
|
|
583
|
+
ok: true,
|
|
584
|
+
data: null
|
|
585
|
+
});
|
|
586
|
+
case "/fork": {
|
|
587
|
+
const sdk = state.sdk;
|
|
588
|
+
if (!sdk || !state.sessionId) return respond(res, 409, {
|
|
589
|
+
ok: false,
|
|
590
|
+
error: "there is no session to fork yet"
|
|
591
|
+
});
|
|
592
|
+
if (state.active) return respond(res, 409, {
|
|
593
|
+
ok: false,
|
|
594
|
+
error: "a turn is running"
|
|
595
|
+
});
|
|
596
|
+
sdk.forkSession(state.sessionId, { upToMessageId: data.entryId }).then((forked) => {
|
|
597
|
+
state.sessionId = forked.sessionId;
|
|
598
|
+
respond(res, 200, {
|
|
599
|
+
ok: true,
|
|
600
|
+
data: { sessionRef: forked.sessionId }
|
|
601
|
+
});
|
|
602
|
+
}).catch((e) => {
|
|
603
|
+
respond(res, 500, {
|
|
604
|
+
ok: false,
|
|
605
|
+
error: e instanceof Error ? e.message : String(e)
|
|
606
|
+
});
|
|
607
|
+
});
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
case "/permission-response": {
|
|
611
|
+
const p = state.pending.get(data.requestId ?? "");
|
|
612
|
+
if (!p) return respond(res, 404, {
|
|
613
|
+
ok: false,
|
|
614
|
+
error: "no such pending permission"
|
|
615
|
+
});
|
|
616
|
+
const d = data.decision ?? {};
|
|
617
|
+
p.settle(d.kind === "once" ? { kind: "once" } : d.kind === "always" ? { kind: "always" } : {
|
|
618
|
+
kind: "reject",
|
|
619
|
+
feedback: d.feedback
|
|
620
|
+
});
|
|
621
|
+
return respond(res, 200, { ok: true });
|
|
622
|
+
}
|
|
623
|
+
default:
|
|
624
|
+
res.writeHead(404);
|
|
625
|
+
res.end("not found");
|
|
626
|
+
}
|
|
627
|
+
});
|
|
628
|
+
}).listen(PORT, "0.0.0.0", () => {
|
|
629
|
+
process.stderr.write("alineo-bridge :" + PORT + "\n");
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
main();
|
|
633
|
+
//#endregion
|