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/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { DEFAULT_PROVIDER_ID, DEFAULT_PROVIDER_ID as DEFAULT_PROVIDER_ID$1, LedgerEvent, WorkflowError, requireCapability } from "@alineo-labs/core";
|
|
2
|
+
import { AgentSpecSchema, ProjectConfigSchema, deprecatedSpecFields, normalizeAgentSpec, resourceRefOf } from "@alineo-labs/schema";
|
|
3
|
+
import { clientFromConfig } from "@alineo-labs/sandbox";
|
|
3
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
-
import { LedgerEvent, WorkflowError } from "@alineo-labs/core";
|
|
5
5
|
import { getLogger } from "@alineo-labs/logger";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -10,6 +10,7 @@ import "zod";
|
|
|
10
10
|
import { fileURLToPath } from "node:url";
|
|
11
11
|
import { createHash } from "node:crypto";
|
|
12
12
|
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
13
|
+
import { errorCodeOf } from "@alineo-labs/errors";
|
|
13
14
|
import { createServer } from "node:http";
|
|
14
15
|
//#region ../config-shared/dist/index.mjs
|
|
15
16
|
/** The file name every alineo project config uses. */
|
|
@@ -216,6 +217,7 @@ function parseBoolean(raw, name) {
|
|
|
216
217
|
*/
|
|
217
218
|
function projectConfigFromEnv(env) {
|
|
218
219
|
const out = {};
|
|
220
|
+
if (env.ALINEO_PROVIDER !== void 0) out.provider = env.ALINEO_PROVIDER;
|
|
219
221
|
if (env.ALINEO_SERVER_URL !== void 0) out.serverUrl = env.ALINEO_SERVER_URL;
|
|
220
222
|
if (env.ALINEO_API_KEY !== void 0) out.apiKey = env.ALINEO_API_KEY;
|
|
221
223
|
if (env.ALINEO_USE_SERVER_PROXY !== void 0) out.useServerProxy = parseBoolean(env.ALINEO_USE_SERVER_PROXY, "ALINEO_USE_SERVER_PROXY");
|
|
@@ -275,7 +277,7 @@ var PromptTimeoutError = class extends WorkflowError {
|
|
|
275
277
|
timeoutMs;
|
|
276
278
|
bridgeUrl;
|
|
277
279
|
constructor(timeoutMs, bridgeUrl) {
|
|
278
|
-
super(`Prompt produced no activity for ${timeoutMs / 1e3}s (bridge ${bridgeUrl}) -- the underlying agent process may be stuck
|
|
280
|
+
super(`Prompt produced no activity for ${timeoutMs / 1e3}s (bridge ${bridgeUrl}) -- the underlying agent process may be stuck`, "PROMPT_TIMEOUT", { details: { timeoutMs } });
|
|
279
281
|
this.timeoutMs = timeoutMs;
|
|
280
282
|
this.bridgeUrl = bridgeUrl;
|
|
281
283
|
this.name = "PromptTimeoutError";
|
|
@@ -294,7 +296,7 @@ var PromptTimeoutError = class extends WorkflowError {
|
|
|
294
296
|
var BridgeDisconnectedError = class extends WorkflowError {
|
|
295
297
|
bridgeUrl;
|
|
296
298
|
constructor(bridgeUrl) {
|
|
297
|
-
super(`Bridge connection closed (${bridgeUrl}) before signalling the turn was done -- the underlying agent process likely died
|
|
299
|
+
super(`Bridge connection closed (${bridgeUrl}) before signalling the turn was done -- the underlying agent process likely died`, "BRIDGE_DISCONNECTED");
|
|
298
300
|
this.bridgeUrl = bridgeUrl;
|
|
299
301
|
this.name = "BridgeDisconnectedError";
|
|
300
302
|
}
|
|
@@ -309,7 +311,7 @@ var BridgeDisconnectedError = class extends WorkflowError {
|
|
|
309
311
|
var AgentSpecValidationError = class extends WorkflowError {
|
|
310
312
|
issues;
|
|
311
313
|
constructor(message, issues) {
|
|
312
|
-
super(message);
|
|
314
|
+
super(message, "SPEC_INVALID");
|
|
313
315
|
this.issues = issues;
|
|
314
316
|
this.name = "AgentSpecValidationError";
|
|
315
317
|
}
|
|
@@ -348,7 +350,205 @@ function validateAgentSpec(data) {
|
|
|
348
350
|
message: issue.message,
|
|
349
351
|
code: issue.code
|
|
350
352
|
})));
|
|
351
|
-
|
|
353
|
+
const input = result.data;
|
|
354
|
+
const spec = normalizeAgentSpec(input);
|
|
355
|
+
for (const { field, use } of deprecatedSpecFields(input)) {
|
|
356
|
+
if (warned.has(`${spec.name}:${field}`)) continue;
|
|
357
|
+
warned.add(`${spec.name}:${field}`);
|
|
358
|
+
log$2.warn(`agent spec "${spec.name}" sets '${field}', which is deprecated. Use '${use}'.`);
|
|
359
|
+
}
|
|
360
|
+
return spec;
|
|
361
|
+
}
|
|
362
|
+
const log$2 = getLogger("agent");
|
|
363
|
+
/** One warning per spec and field per process, not one per start. */
|
|
364
|
+
const warned = /* @__PURE__ */ new Set();
|
|
365
|
+
//#endregion
|
|
366
|
+
//#region src/harness/capabilities.ts
|
|
367
|
+
/**
|
|
368
|
+
* What Pi declares. Each value is what `PiAdapter` and `pi-bridge.ts` do today:
|
|
369
|
+
* `/steer`, `/follow-up`, `/fork`, `/compact`, `/set-model`, the permission gate, and
|
|
370
|
+
* `thinking_delta` events.
|
|
371
|
+
*/
|
|
372
|
+
const PI_CAPABILITIES = {
|
|
373
|
+
steer: true,
|
|
374
|
+
followUp: true,
|
|
375
|
+
resume: true,
|
|
376
|
+
fork: true,
|
|
377
|
+
compact: true,
|
|
378
|
+
setModel: true,
|
|
379
|
+
permissions: true,
|
|
380
|
+
reasoning: true
|
|
381
|
+
};
|
|
382
|
+
//#endregion
|
|
383
|
+
//#region src/harness/pi-events.ts
|
|
384
|
+
/** The text of an error-ish `unknown`. */
|
|
385
|
+
function messageOf(e) {
|
|
386
|
+
return typeof e === "string" ? e : "";
|
|
387
|
+
}
|
|
388
|
+
/** A message's id, when Pi gives one. Pi's message shape is open, so check before use. */
|
|
389
|
+
function messageIdOf(message) {
|
|
390
|
+
if (message && typeof message === "object" && "id" in message) {
|
|
391
|
+
const id = message.id;
|
|
392
|
+
if (typeof id === "string" && id.length > 0) return id;
|
|
393
|
+
}
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Map one event of Pi's bridge stream to harness events. Zero, one or more come back.
|
|
398
|
+
*
|
|
399
|
+
* Every Pi event maps to exactly one harness event, and that event carries the Pi event as
|
|
400
|
+
* `raw`. Nothing is dropped. A `thinking_delta` inside `message_update` is `reasoning`.
|
|
401
|
+
* Every other `message_update` delta (text, tool-call, and so on) is a `vendor` event
|
|
402
|
+
* named `message_update`: the text of a `text_delta` already arrives as its own `text`
|
|
403
|
+
* event, so a neutral consumer ignores the vendor one.
|
|
404
|
+
*
|
|
405
|
+
* `agent_end` becomes `done`. The bridge ends a turn with `agent_end`. The error path
|
|
406
|
+
* (a bridge `{error}` frame, a timeout, an abort) is not an event on this stream. The
|
|
407
|
+
* adapter that reads the stream must emit `done` with `reason: "error"` or `"aborted"`.
|
|
408
|
+
*/
|
|
409
|
+
function fromPiEvent(ev) {
|
|
410
|
+
const raw = ev;
|
|
411
|
+
switch (ev.type) {
|
|
412
|
+
case "agent_start": return [{
|
|
413
|
+
type: "run_start",
|
|
414
|
+
raw
|
|
415
|
+
}];
|
|
416
|
+
case "agent_end": return [{
|
|
417
|
+
type: "done",
|
|
418
|
+
reason: "completed",
|
|
419
|
+
raw
|
|
420
|
+
}];
|
|
421
|
+
case "text": return [{
|
|
422
|
+
type: "text",
|
|
423
|
+
text: ev.text,
|
|
424
|
+
raw
|
|
425
|
+
}];
|
|
426
|
+
case "turn_start": return [{
|
|
427
|
+
type: "turn_start",
|
|
428
|
+
turnIndex: ev.turnIndex,
|
|
429
|
+
raw
|
|
430
|
+
}];
|
|
431
|
+
case "turn_end": return [{
|
|
432
|
+
type: "turn_end",
|
|
433
|
+
turnIndex: ev.turnIndex,
|
|
434
|
+
raw
|
|
435
|
+
}];
|
|
436
|
+
case "message_start": return [{
|
|
437
|
+
type: "message_start",
|
|
438
|
+
messageId: messageIdOf(ev.message),
|
|
439
|
+
raw
|
|
440
|
+
}];
|
|
441
|
+
case "message_end": return [{
|
|
442
|
+
type: "message_end",
|
|
443
|
+
messageId: messageIdOf(ev.message),
|
|
444
|
+
raw
|
|
445
|
+
}];
|
|
446
|
+
case "message_update": {
|
|
447
|
+
const delta = ev.delta;
|
|
448
|
+
if (delta && typeof delta === "object" && "type" in delta) {
|
|
449
|
+
const d = delta;
|
|
450
|
+
if (d.type === "thinking_delta" && typeof d.delta === "string") return [{
|
|
451
|
+
type: "reasoning",
|
|
452
|
+
text: d.delta,
|
|
453
|
+
raw
|
|
454
|
+
}];
|
|
455
|
+
}
|
|
456
|
+
return [{
|
|
457
|
+
type: "vendor",
|
|
458
|
+
harness: "pi",
|
|
459
|
+
name: "message_update",
|
|
460
|
+
data: ev,
|
|
461
|
+
raw
|
|
462
|
+
}];
|
|
463
|
+
}
|
|
464
|
+
case "tool_start": return [{
|
|
465
|
+
type: "tool_start",
|
|
466
|
+
toolCallId: ev.toolCallId,
|
|
467
|
+
toolName: ev.toolName,
|
|
468
|
+
args: ev.args,
|
|
469
|
+
raw
|
|
470
|
+
}];
|
|
471
|
+
case "tool_update": return [{
|
|
472
|
+
type: "tool_update",
|
|
473
|
+
toolCallId: ev.toolCallId,
|
|
474
|
+
toolName: ev.toolName,
|
|
475
|
+
partial: ev.partialResult,
|
|
476
|
+
raw
|
|
477
|
+
}];
|
|
478
|
+
case "tool_end": return [{
|
|
479
|
+
type: "tool_end",
|
|
480
|
+
toolCallId: ev.toolCallId,
|
|
481
|
+
toolName: ev.toolName,
|
|
482
|
+
result: ev.result,
|
|
483
|
+
isError: ev.isError,
|
|
484
|
+
raw
|
|
485
|
+
}];
|
|
486
|
+
case "permission_request": return [{
|
|
487
|
+
type: "permission_request",
|
|
488
|
+
requestId: ev.requestId,
|
|
489
|
+
tool: ev.tool,
|
|
490
|
+
target: ev.target,
|
|
491
|
+
title: ev.title,
|
|
492
|
+
raw
|
|
493
|
+
}];
|
|
494
|
+
case "permission_resolved": return [{
|
|
495
|
+
type: "permission_resolved",
|
|
496
|
+
requestId: ev.requestId,
|
|
497
|
+
decision: ev.decision,
|
|
498
|
+
raw
|
|
499
|
+
}];
|
|
500
|
+
case "compaction_start": return [{
|
|
501
|
+
type: "compaction",
|
|
502
|
+
phase: "start",
|
|
503
|
+
reason: ev.reason,
|
|
504
|
+
raw
|
|
505
|
+
}];
|
|
506
|
+
case "compaction_end": return [{
|
|
507
|
+
type: "compaction",
|
|
508
|
+
phase: "end",
|
|
509
|
+
reason: ev.reason,
|
|
510
|
+
aborted: ev.aborted,
|
|
511
|
+
willRetry: ev.willRetry,
|
|
512
|
+
raw
|
|
513
|
+
}];
|
|
514
|
+
case "auto_retry_start": return [{
|
|
515
|
+
type: "retry",
|
|
516
|
+
phase: "start",
|
|
517
|
+
attempt: ev.attempt,
|
|
518
|
+
maxAttempts: ev.maxAttempts,
|
|
519
|
+
delayMs: ev.delayMs,
|
|
520
|
+
error: messageOf(ev.errorMessage),
|
|
521
|
+
raw
|
|
522
|
+
}];
|
|
523
|
+
case "auto_retry_end": return [{
|
|
524
|
+
type: "retry",
|
|
525
|
+
phase: "end",
|
|
526
|
+
attempt: ev.attempt,
|
|
527
|
+
success: ev.success,
|
|
528
|
+
error: messageOf(ev.finalError),
|
|
529
|
+
raw
|
|
530
|
+
}];
|
|
531
|
+
case "queue_update": return [{
|
|
532
|
+
type: "queue",
|
|
533
|
+
steering: ev.steering,
|
|
534
|
+
followUp: ev.followUp,
|
|
535
|
+
raw
|
|
536
|
+
}];
|
|
537
|
+
case "extension_ui": return [{
|
|
538
|
+
type: "vendor",
|
|
539
|
+
harness: "pi",
|
|
540
|
+
name: "extension_ui",
|
|
541
|
+
data: ev,
|
|
542
|
+
raw
|
|
543
|
+
}];
|
|
544
|
+
case "extension_error": return [{
|
|
545
|
+
type: "vendor",
|
|
546
|
+
harness: "pi",
|
|
547
|
+
name: "extension_error",
|
|
548
|
+
data: ev,
|
|
549
|
+
raw
|
|
550
|
+
}];
|
|
551
|
+
}
|
|
352
552
|
}
|
|
353
553
|
//#endregion
|
|
354
554
|
//#region src/permissions.ts
|
|
@@ -510,7 +710,7 @@ function hasOutputRedirect(seg) {
|
|
|
510
710
|
/**
|
|
511
711
|
* Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
|
|
512
712
|
* recognised pure reader with no output redirection; `false` = something needs a human.
|
|
513
|
-
* Mirrored verbatim in `
|
|
713
|
+
* Mirrored verbatim in `bridge/pi-permission-gate.ts`.
|
|
514
714
|
*/
|
|
515
715
|
function isReadOnlyBashCommand(command) {
|
|
516
716
|
const segments = command.split(/&&|\|\||[;\n|]/).map((s) => s.trim()).filter(Boolean);
|
|
@@ -531,9 +731,218 @@ function isReadOnlyBashCommand(command) {
|
|
|
531
731
|
});
|
|
532
732
|
}
|
|
533
733
|
//#endregion
|
|
734
|
+
//#region src/harness/bridge.ts
|
|
735
|
+
/**
|
|
736
|
+
* Read a script the build produced (`dist/<name>`), to write into a sandbox. Resolved beside
|
|
737
|
+
* this module first (the published package, where `index.mjs` sits in `dist/`), then in the
|
|
738
|
+
* package's own `dist/` (running from `src/` in dev and tests). Read lazily, so importing
|
|
739
|
+
* this module does not need a build.
|
|
740
|
+
*/
|
|
741
|
+
function readBuiltScript(name) {
|
|
742
|
+
const candidates = [new URL(`./${name}`, import.meta.url), new URL(`../../dist/${name}`, import.meta.url)];
|
|
743
|
+
for (const url of candidates) try {
|
|
744
|
+
return readFileSync(fileURLToPath(url), "utf8");
|
|
745
|
+
} catch {}
|
|
746
|
+
throw new Error(`alineo: ${name} not found. Run \`bun run build\` in packages/agent.`);
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* What every harness that runs behind an in-sandbox HTTP bridge shares: finding the bridge,
|
|
750
|
+
* waiting for it, streaming a turn from it, closing the streams it leaves open, and the
|
|
751
|
+
* permission endpoints. A subclass adds its own install, configure and turn mapping.
|
|
752
|
+
*
|
|
753
|
+
* The bridge contract (what a bridge script must serve):
|
|
754
|
+
* - `GET /health` returns `{ ok: true }` once it can take a turn.
|
|
755
|
+
* - `POST /abort` ends the running turn.
|
|
756
|
+
* - `POST /permission-response` takes `{ requestId, decision }`.
|
|
757
|
+
* - `GET /pending-permissions` returns `{ ok, data: { pending: PendingPermission[] } }`.
|
|
758
|
+
* - A turn is an SSE stream of JSON frames, ended by `data: [DONE]`. A frame `{ error }` fails it.
|
|
759
|
+
*/
|
|
760
|
+
var BridgeHarness = class {
|
|
761
|
+
_bridgeUrl = null;
|
|
762
|
+
/**
|
|
763
|
+
* Controllers for streams `sseStream` deliberately left open (its early return on `[DONE]`,
|
|
764
|
+
* to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE` documents).
|
|
765
|
+
* `AbortController.abort()`, not `reader.cancel()`: Bun's `fetch()` tears down the
|
|
766
|
+
* underlying connection reliably on an abort signal, but was observed to leave the socket
|
|
767
|
+
* referenced after `reader.cancel()` on the bridge's long-lived, heartbeat-pinged
|
|
768
|
+
* connections.
|
|
769
|
+
*
|
|
770
|
+
* Known limitation: a script making two or more such calls before close() can still hang
|
|
771
|
+
* even though every controller here aborts cleanly on the client side. Root cause is the
|
|
772
|
+
* same class of bug as opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination
|
|
773
|
+
* confusing the control server's proxy relay). Tracked in our own #189.
|
|
774
|
+
*/
|
|
775
|
+
pendingStreams = /* @__PURE__ */ new Set();
|
|
776
|
+
get bridgeUrl() {
|
|
777
|
+
if (!this._bridgeUrl) throw new Error(`${this.id}: bridge not started`);
|
|
778
|
+
return this._bridgeUrl;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the *same*
|
|
782
|
+
* exec command that starts `node`, which a forked sandbox needs: the container's OS-level
|
|
783
|
+
* env still carries whatever the parent had baked in at snapshot time. A plain
|
|
784
|
+
* `sb.exec("unset ...")` beforehand would not work: each `exec()` is its own shell session.
|
|
785
|
+
*/
|
|
786
|
+
async start(sb, opts) {
|
|
787
|
+
const vars = opts?.unsetVars;
|
|
788
|
+
const prefix = vars && vars.length > 0 ? `unset ${vars.join(" ")}; ` : "";
|
|
789
|
+
await sb.exec(`${prefix}node ${this.bridgeScriptPath} &`);
|
|
790
|
+
const { url } = await sb.proxy(3001);
|
|
791
|
+
this._bridgeUrl = url;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Rebind to a bridge that is already running. `sb.proxy(port)` is a pure URL lookup: it
|
|
795
|
+
* starts nothing, so nothing in the sandbox changes. Follow with `waitReady()`, because the
|
|
796
|
+
* container can be alive while the bridge process inside it is not.
|
|
797
|
+
*/
|
|
798
|
+
async reattach(sb) {
|
|
799
|
+
const { url } = await sb.proxy(3001);
|
|
800
|
+
this._bridgeUrl = url;
|
|
801
|
+
}
|
|
802
|
+
async waitReady(timeoutMs = 3e4) {
|
|
803
|
+
const deadline = Date.now() + timeoutMs;
|
|
804
|
+
while (Date.now() < deadline) {
|
|
805
|
+
try {
|
|
806
|
+
const res = await fetch(`${this.bridgeUrl}/health`);
|
|
807
|
+
if (res.ok) {
|
|
808
|
+
if ((await res.json()).ok) return;
|
|
809
|
+
}
|
|
810
|
+
} catch {}
|
|
811
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
812
|
+
}
|
|
813
|
+
throw new Error(`alineo-bridge did not become ready within ${timeoutMs / 1e3}s`);
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Force-close the streams left open (see `pendingStreams`). They sit ESTABLISHED, keeping
|
|
817
|
+
* the event loop alive, because the bridge's own `: ping` heartbeat means no server-side
|
|
818
|
+
* timeout ever ends a dangling one. Call once, as the agent closes.
|
|
819
|
+
*/
|
|
820
|
+
dispose() {
|
|
821
|
+
for (const controller of this.pendingStreams) controller.abort();
|
|
822
|
+
this.pendingStreams.clear();
|
|
823
|
+
}
|
|
824
|
+
async abort() {
|
|
825
|
+
await rpcPost(this.bridgeUrl, "/abort");
|
|
826
|
+
}
|
|
827
|
+
async resolvePermission(requestId, decision) {
|
|
828
|
+
await rpcPost(this.bridgeUrl, "/permission-response", {
|
|
829
|
+
requestId,
|
|
830
|
+
decision
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
async listPendingPermissions() {
|
|
834
|
+
return (await rpcGet(this.bridgeUrl, "/pending-permissions")).pending;
|
|
835
|
+
}
|
|
836
|
+
/** Open a turn stream on the bridge. */
|
|
837
|
+
stream(path, body, inactivityTimeoutMs) {
|
|
838
|
+
return sseStream(this.bridgeUrl, path, body, this.pendingStreams, inactivityTimeoutMs);
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
async function rpcPost(bridgeUrl, path, body = {}) {
|
|
842
|
+
const res = await fetch(`${bridgeUrl}${path}`, {
|
|
843
|
+
method: "POST",
|
|
844
|
+
headers: { "Content-Type": "application/json" },
|
|
845
|
+
body: JSON.stringify(body)
|
|
846
|
+
});
|
|
847
|
+
if (!res.ok) {
|
|
848
|
+
const err = await res.json().catch(() => ({}));
|
|
849
|
+
throw new Error(`${path} failed: ${err.error ?? res.status}`);
|
|
850
|
+
}
|
|
851
|
+
return (await res.json()).data;
|
|
852
|
+
}
|
|
853
|
+
async function rpcGet(bridgeUrl, path) {
|
|
854
|
+
const res = await fetch(`${bridgeUrl}${path}`);
|
|
855
|
+
if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
|
|
856
|
+
return (await res.json()).data;
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* How long to tolerate zero real `AgentEvent`s before treating the stream as stuck. The
|
|
860
|
+
* bridge's own `: ping` keep-alive (every 3s, see bridge/pi-bridge.ts's `startHeartbeat`) exists only
|
|
861
|
+
* to defeat OpenSandbox's proxy idle-timeout -- it keeps `reader.read()` resolving regardless
|
|
862
|
+
* of whether Pi itself is making progress, so this can't just be "no read() in N seconds". The
|
|
863
|
+
* timer below is instead reset only when a real event is parsed and yielded (or `[DONE]`
|
|
864
|
+
* arrives), so a connection that's alive-but-silent for this long still times out.
|
|
865
|
+
*
|
|
866
|
+
* 60s (the original default) was too tight for a common, legitimate pattern: Pi's own `bash`
|
|
867
|
+
* tool is not incrementally streamed (see the `bash()` doc comment in session-control.ts), so
|
|
868
|
+
* a single tool call that spins up a whole child sandbox -- e.g. a master session running
|
|
869
|
+
* `alineo spawn` on itself, as in examples/rlm-repo-fanout -- produces zero AgentEvents for as
|
|
870
|
+
* long as that tool call takes, which regularly exceeded 60s (child sandbox provisioning +
|
|
871
|
+
* Pi CLI install alone routinely took 30-150s+ in practice) and tripped this timeout mid-run
|
|
872
|
+
* even though the session was making real progress. Raised to 3 minutes as a still-bounded
|
|
873
|
+
* but realistic ceiling for that pattern; pass `inactivityTimeoutMs` explicitly to `prompt()`
|
|
874
|
+
* for sessions that need something tighter or looser.
|
|
875
|
+
*/
|
|
876
|
+
const DEFAULT_INACTIVITY_TIMEOUT_MS = 18e4;
|
|
877
|
+
async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeoutMs = DEFAULT_INACTIVITY_TIMEOUT_MS) {
|
|
878
|
+
const controller = new AbortController();
|
|
879
|
+
const res = await fetch(`${bridgeUrl}${path}`, {
|
|
880
|
+
method: "POST",
|
|
881
|
+
headers: { "Content-Type": "application/json" },
|
|
882
|
+
body: JSON.stringify(body),
|
|
883
|
+
signal: controller.signal,
|
|
884
|
+
keepalive: false
|
|
885
|
+
});
|
|
886
|
+
if (!res.ok || !res.body) throw new Error(`Bridge ${path} error: ${res.status}`);
|
|
887
|
+
pendingStreams.add(controller);
|
|
888
|
+
const reader = res.body.getReader();
|
|
889
|
+
const decoder = new TextDecoder();
|
|
890
|
+
let buf = "";
|
|
891
|
+
let lastEventAt = Date.now();
|
|
892
|
+
const pendingPermissions = /* @__PURE__ */ new Set();
|
|
893
|
+
let reachedNaturalEnd = false;
|
|
894
|
+
try {
|
|
895
|
+
while (true) {
|
|
896
|
+
const awaitingHuman = pendingPermissions.size > 0;
|
|
897
|
+
const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
|
|
898
|
+
if (!awaitingHuman && remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
899
|
+
const result = await Promise.race([reader.read(), new Promise((resolve) => {
|
|
900
|
+
setTimeout(() => {
|
|
901
|
+
resolve("timeout");
|
|
902
|
+
}, awaitingHuman ? inactivityTimeoutMs : Math.max(remainingMs, 1));
|
|
903
|
+
})]);
|
|
904
|
+
if (result === "timeout") {
|
|
905
|
+
if (pendingPermissions.size > 0) {
|
|
906
|
+
lastEventAt = Date.now();
|
|
907
|
+
continue;
|
|
908
|
+
}
|
|
909
|
+
throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
910
|
+
}
|
|
911
|
+
const { done, value } = result;
|
|
912
|
+
if (done) {
|
|
913
|
+
reachedNaturalEnd = true;
|
|
914
|
+
throw new BridgeDisconnectedError(bridgeUrl);
|
|
915
|
+
}
|
|
916
|
+
buf += decoder.decode(value, { stream: true });
|
|
917
|
+
const lines = buf.split("\n");
|
|
918
|
+
buf = lines.pop() ?? "";
|
|
919
|
+
for (const line of lines) {
|
|
920
|
+
if (!line.startsWith("data: ")) continue;
|
|
921
|
+
const payload = line.slice(6).trim();
|
|
922
|
+
if (payload === "[DONE]") return;
|
|
923
|
+
const raw = JSON.parse(payload);
|
|
924
|
+
if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
|
|
925
|
+
if (raw.requestId !== void 0) {
|
|
926
|
+
if (raw.type === "permission_request") pendingPermissions.add(raw.requestId);
|
|
927
|
+
else if (raw.type === "permission_resolved") pendingPermissions.delete(raw.requestId);
|
|
928
|
+
}
|
|
929
|
+
lastEventAt = Date.now();
|
|
930
|
+
yield raw;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
} finally {
|
|
934
|
+
if (reachedNaturalEnd) {
|
|
935
|
+
pendingStreams.delete(controller);
|
|
936
|
+
reader.releaseLock();
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
//#endregion
|
|
534
941
|
//#region src/adapters/pi.ts
|
|
535
|
-
|
|
536
|
-
const
|
|
942
|
+
/** Node CJS bridge script: written to `/alineo-bridge.js` and run with `node`. */
|
|
943
|
+
const bridgeScript$2 = () => readBuiltScript("pi-bridge.cjs");
|
|
944
|
+
/** The permission-gate extension: written to `/alineo-permission-gate.js`, loaded by Pi via `-e`. */
|
|
945
|
+
const permissionGateScript = () => readBuiltScript("pi-permission-gate.mjs");
|
|
537
946
|
function toShellExports(env) {
|
|
538
947
|
return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
|
|
539
948
|
}
|
|
@@ -594,54 +1003,29 @@ function parseShellExports(content) {
|
|
|
594
1003
|
while (m = re.exec(content)) result[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
|
|
595
1004
|
return result;
|
|
596
1005
|
}
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
* close() can still hang even though every controller here does abort cleanly on the
|
|
613
|
-
* client side -- root cause traced to the same class of bug as
|
|
614
|
-
* opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination confusing the
|
|
615
|
-
* OpenSandbox control server's own proxy relay, which is what `bridgeUrl` is proxied
|
|
616
|
-
* through). Tracked in our own #189; not fixable from this file alone.
|
|
617
|
-
*/
|
|
618
|
-
pendingStreams = /* @__PURE__ */ new Set();
|
|
619
|
-
get bridgeUrl() {
|
|
620
|
-
if (!this._bridgeUrl) throw new Error("PiAdapter: bridge not started");
|
|
621
|
-
return this._bridgeUrl;
|
|
622
|
-
}
|
|
623
|
-
/**
|
|
624
|
-
* Force-close any prompt/bash streams `sseStream` deliberately left open (its early
|
|
625
|
-
* return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
|
|
626
|
-
* documents — see that method's comment). Those connections sit ESTABLISHED, keeping
|
|
627
|
-
* Bun's event loop alive indefinitely, until something force-closes them -- unlike
|
|
628
|
-
* execd's exec/code streams (see `ExecClient.disposeConnections()`), the bridge's own
|
|
629
|
-
* `: ping` heartbeat (every 3s, see pi-bridge.js) means there's no bounded server-side
|
|
630
|
-
* timeout to eventually resolve a dangling one on its own. Call this once the agent is
|
|
631
|
-
* being torn down anyway (from `agent.close()`) instead of leaving the process to hang
|
|
632
|
-
* forever on whichever stream's `[DONE]` arrived last.
|
|
633
|
-
*/
|
|
634
|
-
disposeConnections() {
|
|
635
|
-
for (const controller of this.pendingStreams) controller.abort();
|
|
636
|
-
this.pendingStreams.clear();
|
|
637
|
-
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Pi 1.2.x depends on `@aws-sdk/credential-provider-http@^3.972.77`, a version the npm registry
|
|
1008
|
+
* does not serve (newest is 3.972.76), so a fresh `npm install -g` of 1.2.x fails with ETARGET.
|
|
1009
|
+
* Naming 3.972.76 in the same command makes npm resolve to it. Drop this once the registry
|
|
1010
|
+
* serves a version that satisfies Pi 1.2.x.
|
|
1011
|
+
*/
|
|
1012
|
+
const PI_1_2_AWS_SDK_PIN = "@aws-sdk/credential-provider-http@3.972.76";
|
|
1013
|
+
/** True for an exact, caret, or tilde specifier on the 1.2 line, such as `1.2.0` or `^1.2.0`. */
|
|
1014
|
+
function needsAwsSdkPin(versionSpecifier) {
|
|
1015
|
+
return versionSpecifier !== void 0 && /^[\^~]?1\.2(\.|$)/.test(versionSpecifier);
|
|
1016
|
+
}
|
|
1017
|
+
var PiAdapter = class extends BridgeHarness {
|
|
1018
|
+
id = "pi";
|
|
1019
|
+
capabilities = PI_CAPABILITIES;
|
|
1020
|
+
bridgeScriptPath = "/alineo-bridge.js";
|
|
638
1021
|
/** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
|
|
639
1022
|
async install(sb, spec) {
|
|
640
1023
|
const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
|
|
641
1024
|
if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
|
|
642
1025
|
const versionSpecifier = spec.harnessVersion?.trim();
|
|
643
1026
|
const pkg = versionSpecifier ? `@earendil-works/pi-coding-agent@${versionSpecifier}` : "@earendil-works/pi-coding-agent";
|
|
644
|
-
|
|
1027
|
+
const extra = needsAwsSdkPin(versionSpecifier) ? ` ${PI_1_2_AWS_SDK_PIN}` : "";
|
|
1028
|
+
await sb.exec(`npm install -g --ignore-scripts ${pkg}${extra}`);
|
|
645
1029
|
}
|
|
646
1030
|
/**
|
|
647
1031
|
* Write config files and the bridge script. Always runs on every start (fresh install
|
|
@@ -656,61 +1040,71 @@ var PiAdapter = class {
|
|
|
656
1040
|
if (permissions) piConfig.permissions = permissions;
|
|
657
1041
|
await sb.writeFile("/etc/alineo-pi.json", JSON.stringify(piConfig));
|
|
658
1042
|
await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
|
|
659
|
-
await sb.writeFile("/alineo-bridge.js",
|
|
660
|
-
if (permissions) await sb.writeFile("/alineo-permission-gate.js",
|
|
1043
|
+
await sb.writeFile("/alineo-bridge.js", bridgeScript$2());
|
|
1044
|
+
if (permissions) await sb.writeFile("/alineo-permission-gate.js", permissionGateScript());
|
|
661
1045
|
}
|
|
662
|
-
/**
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
this.
|
|
1046
|
+
/** `start()` under its older name. */
|
|
1047
|
+
startBridge(sb, unsetVars) {
|
|
1048
|
+
return this.start(sb, { unsetVars });
|
|
1049
|
+
}
|
|
1050
|
+
/** `fork(entryId)` in the harness-neutral shape. Pi switches its own session in place. */
|
|
1051
|
+
async forkAt(messageId) {
|
|
1052
|
+
await this.fork(messageId);
|
|
1053
|
+
return { sessionRef: null };
|
|
1054
|
+
}
|
|
1055
|
+
/** `reattach()` under its older name. */
|
|
1056
|
+
reattachBridge(sb) {
|
|
1057
|
+
return this.reattach(sb);
|
|
1058
|
+
}
|
|
1059
|
+
/** `dispose()` under its older name. */
|
|
1060
|
+
disposeConnections() {
|
|
1061
|
+
this.dispose();
|
|
678
1062
|
}
|
|
679
1063
|
/**
|
|
680
|
-
*
|
|
681
|
-
*
|
|
682
|
-
*
|
|
683
|
-
* itself: no killed process, no dropped in-flight turn, no reset Pi conversation state.
|
|
1064
|
+
* One turn as harness events, ending in exactly one `done`. A failure (the bridge sends an
|
|
1065
|
+
* error frame, the stream times out or drops) becomes an `error` event then `done`: it
|
|
1066
|
+
* does not throw, and the `error` event's `raw` is the original error.
|
|
684
1067
|
*
|
|
685
|
-
*
|
|
686
|
-
*
|
|
687
|
-
*
|
|
1068
|
+
* A stream that ends with no `agent_end` is `aborted`. The bridge ends a stream that way
|
|
1069
|
+
* only when someone called `/abort`, from this process or another. A message sent with
|
|
1070
|
+
* `streamingBehavior` also ends with no `agent_end`: that is `completed`.
|
|
688
1071
|
*/
|
|
689
|
-
async
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
1072
|
+
async *runTurn(input) {
|
|
1073
|
+
let finished = false;
|
|
1074
|
+
try {
|
|
1075
|
+
const stream = this.prompt(input.message, {
|
|
1076
|
+
streamingBehavior: input.streamingBehavior,
|
|
1077
|
+
inactivityTimeoutMs: input.inactivityTimeoutMs
|
|
1078
|
+
});
|
|
1079
|
+
for await (const ev of stream) for (const out of fromPiEvent(ev)) {
|
|
1080
|
+
if (out.type === "done") finished = true;
|
|
1081
|
+
yield out;
|
|
1082
|
+
}
|
|
1083
|
+
} catch (e) {
|
|
1084
|
+
yield {
|
|
1085
|
+
type: "error",
|
|
1086
|
+
message: e instanceof Error ? e.message : String(e),
|
|
1087
|
+
raw: e
|
|
1088
|
+
};
|
|
1089
|
+
yield {
|
|
1090
|
+
type: "done",
|
|
1091
|
+
reason: "error"
|
|
1092
|
+
};
|
|
1093
|
+
return;
|
|
703
1094
|
}
|
|
704
|
-
|
|
1095
|
+
if (!finished) yield {
|
|
1096
|
+
type: "done",
|
|
1097
|
+
reason: input.streamingBehavior ? "completed" : "aborted"
|
|
1098
|
+
};
|
|
705
1099
|
}
|
|
706
1100
|
prompt(message, opts) {
|
|
707
|
-
return
|
|
1101
|
+
return this.stream("/prompt", {
|
|
708
1102
|
message,
|
|
709
1103
|
streamingBehavior: opts?.streamingBehavior
|
|
710
|
-
},
|
|
1104
|
+
}, opts?.inactivityTimeoutMs);
|
|
711
1105
|
}
|
|
712
1106
|
bash(command) {
|
|
713
|
-
return
|
|
1107
|
+
return this.stream("/bash", { command });
|
|
714
1108
|
}
|
|
715
1109
|
async steer(message) {
|
|
716
1110
|
const res = await fetch(`${this.bridgeUrl}/steer`, {
|
|
@@ -723,20 +1117,6 @@ var PiAdapter = class {
|
|
|
723
1117
|
throw new Error(`steer failed: ${body.error ?? res.status}`);
|
|
724
1118
|
}
|
|
725
1119
|
}
|
|
726
|
-
async abort() {
|
|
727
|
-
await rpcPost(this.bridgeUrl, "/abort");
|
|
728
|
-
}
|
|
729
|
-
/** Resolve a pending `permission_request` (see `AgentEvent`'s `permission_request`). */
|
|
730
|
-
async resolvePermission(requestId, decision) {
|
|
731
|
-
await rpcPost(this.bridgeUrl, "/permission-response", {
|
|
732
|
-
requestId,
|
|
733
|
-
decision
|
|
734
|
-
});
|
|
735
|
-
}
|
|
736
|
-
/** Tool calls currently paused awaiting a human decision. */
|
|
737
|
-
async listPendingPermissions() {
|
|
738
|
-
return (await rpcGet(this.bridgeUrl, "/pending-permissions")).pending;
|
|
739
|
-
}
|
|
740
1120
|
async followUp(message) {
|
|
741
1121
|
await rpcPost(this.bridgeUrl, "/follow-up", { message });
|
|
742
1122
|
}
|
|
@@ -809,115 +1189,554 @@ var PiAdapter = class {
|
|
|
809
1189
|
async getMessages() {
|
|
810
1190
|
return (await rpcGet(this.bridgeUrl, "/messages")).messages;
|
|
811
1191
|
}
|
|
812
|
-
async getAvailableModels() {
|
|
813
|
-
return (await rpcGet(this.bridgeUrl, "/available-models")).models;
|
|
1192
|
+
async getAvailableModels() {
|
|
1193
|
+
return (await rpcGet(this.bridgeUrl, "/available-models")).models;
|
|
1194
|
+
}
|
|
1195
|
+
async getState() {
|
|
1196
|
+
return rpcGet(this.bridgeUrl, "/state");
|
|
1197
|
+
}
|
|
1198
|
+
async reloadEnv(env) {
|
|
1199
|
+
await rpcPost(this.bridgeUrl, "/reload-env", { env });
|
|
1200
|
+
await this.waitReady();
|
|
1201
|
+
}
|
|
1202
|
+
async getLogs() {
|
|
1203
|
+
return (await fetch(`${this.bridgeUrl}/logs`)).text();
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
//#endregion
|
|
1207
|
+
//#region src/adapters/claude-code.ts
|
|
1208
|
+
/**
|
|
1209
|
+
* What Claude Code declares. Each `false` is a thing the bridge does not do today, not a
|
|
1210
|
+
* limit of the SDK: `steer` and `followUp` have no mid-turn injection in single-prompt mode,
|
|
1211
|
+
* `compact` and `setModel` are not wired, and `reasoning` needs extended thinking turned on.
|
|
1212
|
+
*/
|
|
1213
|
+
const CLAUDE_CODE_CAPABILITIES = {
|
|
1214
|
+
steer: false,
|
|
1215
|
+
followUp: false,
|
|
1216
|
+
resume: true,
|
|
1217
|
+
fork: true,
|
|
1218
|
+
compact: false,
|
|
1219
|
+
setModel: false,
|
|
1220
|
+
permissions: true,
|
|
1221
|
+
reasoning: false
|
|
1222
|
+
};
|
|
1223
|
+
const SDK_PACKAGE = "@anthropic-ai/claude-agent-sdk";
|
|
1224
|
+
/** Node CJS bridge script: written to `/alineo-bridge.js` and run with `node`. */
|
|
1225
|
+
const bridgeScript$1 = () => readBuiltScript("claude-bridge.cjs");
|
|
1226
|
+
/**
|
|
1227
|
+
* Claude Code, driven through the Claude Agent SDK by a bridge in the sandbox. The bridge's
|
|
1228
|
+
* frames are already `HarnessEvent`s, so `runTurn` forwards them.
|
|
1229
|
+
*
|
|
1230
|
+
* @experimental The harness layer is being built. Expect changes before it is stable.
|
|
1231
|
+
*/
|
|
1232
|
+
var ClaudeCodeAdapter = class extends BridgeHarness {
|
|
1233
|
+
id = "claude-code";
|
|
1234
|
+
capabilities = CLAUDE_CODE_CAPABILITIES;
|
|
1235
|
+
bridgeScriptPath = "/alineo-bridge.js";
|
|
1236
|
+
/** Install the Agent SDK globally, and any spec packages. Slow: a snapshot captures it. */
|
|
1237
|
+
async install(sb, spec) {
|
|
1238
|
+
const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
|
|
1239
|
+
if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
|
|
1240
|
+
const version = spec.harnessVersion?.trim();
|
|
1241
|
+
const pkg = version ? `${SDK_PACKAGE}@${version}` : SDK_PACKAGE;
|
|
1242
|
+
await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
|
|
1243
|
+
}
|
|
1244
|
+
async configure(sb, spec, resolvedEnv, opts) {
|
|
1245
|
+
const config = { model: spec.model };
|
|
1246
|
+
if (opts?.resume) config.resume = true;
|
|
1247
|
+
const permissions = normalizePermissions(spec.permissions);
|
|
1248
|
+
if (permissions) config.permissions = permissions;
|
|
1249
|
+
await sb.writeFile("/etc/alineo-claude.json", JSON.stringify(config));
|
|
1250
|
+
await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
|
|
1251
|
+
await sb.writeFile("/alineo-bridge.js", bridgeScript$1());
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* One turn as harness events. The bridge already speaks `HarnessEvent`, so the frames pass
|
|
1255
|
+
* through. A bridge error frame, timeout or dropped stream is an `error` then `done`, and
|
|
1256
|
+
* does not throw. A stream that ends with no `done` is `aborted`.
|
|
1257
|
+
*/
|
|
1258
|
+
async *runTurn(input) {
|
|
1259
|
+
let finished = false;
|
|
1260
|
+
try {
|
|
1261
|
+
for await (const frame of this.stream("/prompt", { message: input.message }, input.inactivityTimeoutMs)) {
|
|
1262
|
+
yield frame;
|
|
1263
|
+
if (frame.type === "done") {
|
|
1264
|
+
finished = true;
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
} catch (e) {
|
|
1269
|
+
yield {
|
|
1270
|
+
type: "error",
|
|
1271
|
+
message: e instanceof Error ? e.message : String(e),
|
|
1272
|
+
raw: e
|
|
1273
|
+
};
|
|
1274
|
+
yield {
|
|
1275
|
+
type: "done",
|
|
1276
|
+
reason: "error"
|
|
1277
|
+
};
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
if (!finished) yield {
|
|
1281
|
+
type: "done",
|
|
1282
|
+
reason: "aborted"
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
async forkAt(messageId) {
|
|
1286
|
+
return { sessionRef: (await rpcPost(this.bridgeUrl, "/fork", { entryId: messageId })).sessionRef };
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
//#endregion
|
|
1290
|
+
//#region src/adapters/codex.ts
|
|
1291
|
+
/**
|
|
1292
|
+
* What Codex declares, each backed by an `app-server` method: `turn/steer`,
|
|
1293
|
+
* `thread/compact/start`, `thread/fork`, the approval requests, and reasoning deltas.
|
|
1294
|
+
* `followUp` and `setModel` are not wired.
|
|
1295
|
+
*/
|
|
1296
|
+
const CODEX_CAPABILITIES = {
|
|
1297
|
+
steer: true,
|
|
1298
|
+
followUp: false,
|
|
1299
|
+
resume: true,
|
|
1300
|
+
fork: true,
|
|
1301
|
+
compact: true,
|
|
1302
|
+
setModel: false,
|
|
1303
|
+
permissions: true,
|
|
1304
|
+
reasoning: true
|
|
1305
|
+
};
|
|
1306
|
+
const CODEX_PACKAGE = "@openai/codex";
|
|
1307
|
+
/** Node CJS bridge script: written to `/alineo-bridge.js` and run with `node`. */
|
|
1308
|
+
const bridgeScript = () => readBuiltScript("codex-bridge.cjs");
|
|
1309
|
+
/**
|
|
1310
|
+
* Codex, driven through `codex app-server` (JSON-RPC over stdio) by a bridge in the sandbox.
|
|
1311
|
+
* The bridge's frames are already `HarnessEvent`s, so `runTurn` forwards them.
|
|
1312
|
+
*
|
|
1313
|
+
* Fork granularity is the turn: every message of a turn has the turn id as its `messageId`,
|
|
1314
|
+
* because `thread/fork` takes `lastTurnId`.
|
|
1315
|
+
*
|
|
1316
|
+
* @experimental The harness layer is being built. Expect changes before it is stable.
|
|
1317
|
+
*/
|
|
1318
|
+
var CodexAdapter = class extends BridgeHarness {
|
|
1319
|
+
id = "codex";
|
|
1320
|
+
capabilities = CODEX_CAPABILITIES;
|
|
1321
|
+
bridgeScriptPath = "/alineo-bridge.js";
|
|
1322
|
+
async install(sb, spec) {
|
|
1323
|
+
const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
|
|
1324
|
+
if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
|
|
1325
|
+
const version = spec.harnessVersion?.trim();
|
|
1326
|
+
const pkg = version ? `${CODEX_PACKAGE}@${version}` : CODEX_PACKAGE;
|
|
1327
|
+
await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
|
|
1328
|
+
}
|
|
1329
|
+
async configure(sb, spec, resolvedEnv, opts) {
|
|
1330
|
+
const config = { model: spec.model };
|
|
1331
|
+
if (opts?.resume) config.resume = true;
|
|
1332
|
+
const permissions = normalizePermissions(spec.permissions);
|
|
1333
|
+
if (permissions) config.permissions = permissions;
|
|
1334
|
+
await sb.writeFile("/etc/alineo-codex.json", JSON.stringify(config));
|
|
1335
|
+
await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
|
|
1336
|
+
await sb.writeFile("/alineo-bridge.js", bridgeScript());
|
|
1337
|
+
}
|
|
1338
|
+
async *runTurn(input) {
|
|
1339
|
+
let finished = false;
|
|
1340
|
+
try {
|
|
1341
|
+
for await (const frame of this.stream("/prompt", { message: input.message }, input.inactivityTimeoutMs)) {
|
|
1342
|
+
yield frame;
|
|
1343
|
+
if (frame.type === "done") {
|
|
1344
|
+
finished = true;
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
} catch (e) {
|
|
1349
|
+
yield {
|
|
1350
|
+
type: "error",
|
|
1351
|
+
message: e instanceof Error ? e.message : String(e),
|
|
1352
|
+
raw: e
|
|
1353
|
+
};
|
|
1354
|
+
yield {
|
|
1355
|
+
type: "done",
|
|
1356
|
+
reason: "error"
|
|
1357
|
+
};
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
if (!finished) yield {
|
|
1361
|
+
type: "done",
|
|
1362
|
+
reason: "aborted"
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
/** `turn/steer` into the running turn. Refused with `no turn in progress` between turns. */
|
|
1366
|
+
async steer(message) {
|
|
1367
|
+
await rpcPost(this.bridgeUrl, "/steer", { message });
|
|
1368
|
+
}
|
|
1369
|
+
async compact() {
|
|
1370
|
+
await rpcPost(this.bridgeUrl, "/compact");
|
|
1371
|
+
return {};
|
|
1372
|
+
}
|
|
1373
|
+
/** `thread/fork`. `messageId` is a turn id, from a `message_start` of this adapter. */
|
|
1374
|
+
async forkAt(messageId) {
|
|
1375
|
+
return { sessionRef: (await rpcPost(this.bridgeUrl, "/fork", { entryId: messageId })).sessionRef };
|
|
1376
|
+
}
|
|
1377
|
+
};
|
|
1378
|
+
//#endregion
|
|
1379
|
+
//#region src/harness/registry.ts
|
|
1380
|
+
const constructors = {
|
|
1381
|
+
pi: () => new PiAdapter(),
|
|
1382
|
+
"claude-code": () => new ClaudeCodeAdapter(),
|
|
1383
|
+
codex: () => new CodexAdapter()
|
|
1384
|
+
};
|
|
1385
|
+
/** The ids `createHarness()` accepts. */
|
|
1386
|
+
function registeredHarnesses() {
|
|
1387
|
+
return Object.keys(constructors);
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Create the adapter for a harness id. The only place an adapter class is constructed.
|
|
1391
|
+
* Throws `SPEC_INVALID` for an id nothing registered.
|
|
1392
|
+
*/
|
|
1393
|
+
function createHarness(id) {
|
|
1394
|
+
const make = constructors[id];
|
|
1395
|
+
if (!make) throw new WorkflowError(`Unknown harness "${String(id)}"`, "SPEC_INVALID", {
|
|
1396
|
+
details: {
|
|
1397
|
+
harness: String(id),
|
|
1398
|
+
registered: registeredHarnesses().join(",")
|
|
1399
|
+
},
|
|
1400
|
+
hint: `Set "harness" to one of: ${registeredHarnesses().join(", ")}.`
|
|
1401
|
+
});
|
|
1402
|
+
return make();
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Refuse a call the harness declared it cannot do, before anything is sent. Same idea as
|
|
1406
|
+
* `requireCapability` for sandbox providers.
|
|
1407
|
+
*/
|
|
1408
|
+
function requireHarnessCapability(adapter, capability) {
|
|
1409
|
+
if (adapter.capabilities[capability]) return;
|
|
1410
|
+
throw new WorkflowError(`The ${adapter.id} harness does not support ${capability}`, "CAPABILITY_UNSUPPORTED", { details: {
|
|
1411
|
+
capability,
|
|
1412
|
+
harness: adapter.id
|
|
1413
|
+
} });
|
|
1414
|
+
}
|
|
1415
|
+
//#endregion
|
|
1416
|
+
//#region src/harness/fake.ts
|
|
1417
|
+
const ALL_ON = {
|
|
1418
|
+
steer: true,
|
|
1419
|
+
followUp: true,
|
|
1420
|
+
resume: true,
|
|
1421
|
+
fork: true,
|
|
1422
|
+
compact: true,
|
|
1423
|
+
setModel: true,
|
|
1424
|
+
permissions: true,
|
|
1425
|
+
reasoning: true
|
|
1426
|
+
};
|
|
1427
|
+
/**
|
|
1428
|
+
* A harness that runs no process: it plays a `FakeScenario` in memory. For tests that need
|
|
1429
|
+
* a `HarnessAdapter` and for proving the conformance suite itself is satisfiable. It is not
|
|
1430
|
+
* registered, so a spec cannot select it.
|
|
1431
|
+
*
|
|
1432
|
+
* @experimental The harness layer is being built. Expect changes before it is stable.
|
|
1433
|
+
*/
|
|
1434
|
+
var FakeHarness = class {
|
|
1435
|
+
scenario;
|
|
1436
|
+
id = "fake";
|
|
1437
|
+
capabilities;
|
|
1438
|
+
/** Lifecycle calls in order, for assertions. */
|
|
1439
|
+
calls = [];
|
|
1440
|
+
/** Messages `steer` and `followUp` accepted. */
|
|
1441
|
+
received = [];
|
|
1442
|
+
steer;
|
|
1443
|
+
followUp;
|
|
1444
|
+
forkAt;
|
|
1445
|
+
compact;
|
|
1446
|
+
turnActive = false;
|
|
1447
|
+
release = null;
|
|
1448
|
+
pending = /* @__PURE__ */ new Map();
|
|
1449
|
+
constructor(scenario, capabilities = {}) {
|
|
1450
|
+
this.scenario = scenario;
|
|
1451
|
+
this.capabilities = {
|
|
1452
|
+
...ALL_ON,
|
|
1453
|
+
...capabilities
|
|
1454
|
+
};
|
|
1455
|
+
if (this.capabilities.steer) this.steer = (message) => {
|
|
1456
|
+
if (!this.turnActive) return Promise.reject(/* @__PURE__ */ new Error("no turn in progress"));
|
|
1457
|
+
this.received.push(message);
|
|
1458
|
+
return Promise.resolve();
|
|
1459
|
+
};
|
|
1460
|
+
if (this.capabilities.compact) this.compact = () => {
|
|
1461
|
+
this.received.push("compact");
|
|
1462
|
+
return Promise.resolve({});
|
|
1463
|
+
};
|
|
1464
|
+
if (this.capabilities.fork) this.forkAt = (messageId) => {
|
|
1465
|
+
this.received.push(`fork:${messageId}`);
|
|
1466
|
+
return Promise.resolve({ sessionRef: `fake-fork-of-${messageId}` });
|
|
1467
|
+
};
|
|
1468
|
+
if (this.capabilities.followUp) this.followUp = (message) => {
|
|
1469
|
+
this.received.push(message);
|
|
1470
|
+
return Promise.resolve();
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
install(_sb, _spec) {
|
|
1474
|
+
this.calls.push("install");
|
|
1475
|
+
return Promise.resolve();
|
|
1476
|
+
}
|
|
1477
|
+
configure() {
|
|
1478
|
+
this.calls.push("configure");
|
|
1479
|
+
return Promise.resolve();
|
|
1480
|
+
}
|
|
1481
|
+
start() {
|
|
1482
|
+
this.calls.push("start");
|
|
1483
|
+
return Promise.resolve();
|
|
1484
|
+
}
|
|
1485
|
+
reattach() {
|
|
1486
|
+
this.calls.push("reattach");
|
|
1487
|
+
return Promise.resolve();
|
|
1488
|
+
}
|
|
1489
|
+
waitReady() {
|
|
1490
|
+
this.calls.push("waitReady");
|
|
1491
|
+
return Promise.resolve();
|
|
1492
|
+
}
|
|
1493
|
+
async *runTurn(_input) {
|
|
1494
|
+
this.turnActive = true;
|
|
1495
|
+
const s = this.scenario;
|
|
1496
|
+
try {
|
|
1497
|
+
yield { type: "run_start" };
|
|
1498
|
+
switch (s.kind) {
|
|
1499
|
+
case "text":
|
|
1500
|
+
yield {
|
|
1501
|
+
type: "text",
|
|
1502
|
+
text: s.text
|
|
1503
|
+
};
|
|
1504
|
+
break;
|
|
1505
|
+
case "tool":
|
|
1506
|
+
yield {
|
|
1507
|
+
type: "tool_start",
|
|
1508
|
+
toolCallId: "t1",
|
|
1509
|
+
toolName: s.toolName,
|
|
1510
|
+
args: {}
|
|
1511
|
+
};
|
|
1512
|
+
yield {
|
|
1513
|
+
type: "tool_end",
|
|
1514
|
+
toolCallId: "t1",
|
|
1515
|
+
toolName: s.toolName,
|
|
1516
|
+
result: s.result,
|
|
1517
|
+
isError: false
|
|
1518
|
+
};
|
|
1519
|
+
break;
|
|
1520
|
+
case "fail":
|
|
1521
|
+
yield {
|
|
1522
|
+
type: "error",
|
|
1523
|
+
message: s.message
|
|
1524
|
+
};
|
|
1525
|
+
yield {
|
|
1526
|
+
type: "done",
|
|
1527
|
+
reason: "error"
|
|
1528
|
+
};
|
|
1529
|
+
return;
|
|
1530
|
+
case "hang":
|
|
1531
|
+
await new Promise((resolve) => {
|
|
1532
|
+
this.release = resolve;
|
|
1533
|
+
});
|
|
1534
|
+
yield {
|
|
1535
|
+
type: "done",
|
|
1536
|
+
reason: "aborted"
|
|
1537
|
+
};
|
|
1538
|
+
return;
|
|
1539
|
+
case "permission": {
|
|
1540
|
+
const requestId = "perm-1";
|
|
1541
|
+
const info = {
|
|
1542
|
+
requestId,
|
|
1543
|
+
tool: s.tool,
|
|
1544
|
+
target: s.target,
|
|
1545
|
+
title: `Run ${s.tool}: ${s.target}`,
|
|
1546
|
+
since: Date.now()
|
|
1547
|
+
};
|
|
1548
|
+
const decided = new Promise((settle) => {
|
|
1549
|
+
this.pending.set(requestId, {
|
|
1550
|
+
info,
|
|
1551
|
+
settle
|
|
1552
|
+
});
|
|
1553
|
+
});
|
|
1554
|
+
yield {
|
|
1555
|
+
type: "permission_request",
|
|
1556
|
+
requestId,
|
|
1557
|
+
tool: s.tool,
|
|
1558
|
+
target: s.target,
|
|
1559
|
+
title: info.title
|
|
1560
|
+
};
|
|
1561
|
+
const decision = await decided;
|
|
1562
|
+
this.pending.delete(requestId);
|
|
1563
|
+
yield {
|
|
1564
|
+
type: "permission_resolved",
|
|
1565
|
+
requestId,
|
|
1566
|
+
decision
|
|
1567
|
+
};
|
|
1568
|
+
if (decision.kind === "reject") yield {
|
|
1569
|
+
type: "text",
|
|
1570
|
+
text: "The call was declined."
|
|
1571
|
+
};
|
|
1572
|
+
else {
|
|
1573
|
+
yield {
|
|
1574
|
+
type: "tool_start",
|
|
1575
|
+
toolCallId: "t1",
|
|
1576
|
+
toolName: s.tool,
|
|
1577
|
+
args: { target: s.target }
|
|
1578
|
+
};
|
|
1579
|
+
yield {
|
|
1580
|
+
type: "tool_end",
|
|
1581
|
+
toolCallId: "t1",
|
|
1582
|
+
toolName: s.tool,
|
|
1583
|
+
result: "ok",
|
|
1584
|
+
isError: false
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
break;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
yield {
|
|
1591
|
+
type: "done",
|
|
1592
|
+
reason: "completed"
|
|
1593
|
+
};
|
|
1594
|
+
} finally {
|
|
1595
|
+
this.turnActive = false;
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
abort() {
|
|
1599
|
+
this.release?.();
|
|
1600
|
+
this.release = null;
|
|
1601
|
+
return Promise.resolve();
|
|
814
1602
|
}
|
|
815
|
-
|
|
816
|
-
|
|
1603
|
+
resolvePermission(requestId, decision) {
|
|
1604
|
+
const p = this.pending.get(requestId);
|
|
1605
|
+
if (!p) return Promise.reject(/* @__PURE__ */ new Error("no such pending permission"));
|
|
1606
|
+
p.settle(decision);
|
|
1607
|
+
return Promise.resolve();
|
|
817
1608
|
}
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
await this.waitReady();
|
|
1609
|
+
listPendingPermissions() {
|
|
1610
|
+
return Promise.resolve([...this.pending.values()].map((p) => p.info));
|
|
821
1611
|
}
|
|
822
|
-
|
|
823
|
-
|
|
1612
|
+
dispose() {
|
|
1613
|
+
this.calls.push("dispose");
|
|
824
1614
|
}
|
|
825
1615
|
};
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
method: "POST",
|
|
829
|
-
headers: { "Content-Type": "application/json" },
|
|
830
|
-
body: JSON.stringify(body)
|
|
831
|
-
});
|
|
832
|
-
if (!res.ok) {
|
|
833
|
-
const err = await res.json().catch(() => ({}));
|
|
834
|
-
throw new Error(`${path} failed: ${err.error ?? res.status}`);
|
|
835
|
-
}
|
|
836
|
-
return (await res.json()).data;
|
|
837
|
-
}
|
|
838
|
-
async function rpcGet(bridgeUrl, path) {
|
|
839
|
-
const res = await fetch(`${bridgeUrl}${path}`);
|
|
840
|
-
if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
|
|
841
|
-
return (await res.json()).data;
|
|
842
|
-
}
|
|
1616
|
+
//#endregion
|
|
1617
|
+
//#region src/harness/legacy.ts
|
|
843
1618
|
/**
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
* to defeat OpenSandbox's proxy idle-timeout -- it keeps `reader.read()` resolving regardless
|
|
847
|
-
* of whether Pi itself is making progress, so this can't just be "no read() in N seconds". The
|
|
848
|
-
* timer below is instead reset only when a real event is parsed and yielded (or `[DONE]`
|
|
849
|
-
* arrives), so a connection that's alive-but-silent for this long still times out.
|
|
1619
|
+
* Project a harness event onto the public `AgentEvent` that `prompt()` has always yielded.
|
|
1620
|
+
* `null` means the event has no `AgentEvent` form.
|
|
850
1621
|
*
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
*
|
|
854
|
-
*
|
|
855
|
-
* long as that tool call takes, which regularly exceeded 60s (child sandbox provisioning +
|
|
856
|
-
* Pi CLI install alone routinely took 30-150s+ in practice) and tripped this timeout mid-run
|
|
857
|
-
* even though the session was making real progress. Raised to 3 minutes as a still-bounded
|
|
858
|
-
* but realistic ceiling for that pattern; pass `inactivityTimeoutMs` explicitly to `prompt()`
|
|
859
|
-
* for sessions that need something tighter or looser.
|
|
1622
|
+
* Pi's events pass through unchanged: `fromPiEvent` keeps each one as `raw`, so the
|
|
1623
|
+
* projection is the identity and no Pi caller sees a difference. Every other harness is
|
|
1624
|
+
* projected from the neutral fields. This is a bridge for compatibility. It is removed
|
|
1625
|
+
* when `AgentEvent` is retired in favor of `HarnessEvent`.
|
|
860
1626
|
*/
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
if (pendingPermissions.size > 0) {
|
|
891
|
-
lastEventAt = Date.now();
|
|
892
|
-
continue;
|
|
893
|
-
}
|
|
894
|
-
throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
|
|
895
|
-
}
|
|
896
|
-
const { done, value } = result;
|
|
897
|
-
if (done) {
|
|
898
|
-
reachedNaturalEnd = true;
|
|
899
|
-
throw new BridgeDisconnectedError(bridgeUrl);
|
|
1627
|
+
function toAgentEvent(ev, harnessId) {
|
|
1628
|
+
if (harnessId === "pi" && ev.raw !== void 0) return ev.raw;
|
|
1629
|
+
switch (ev.type) {
|
|
1630
|
+
case "run_start": return { type: "agent_start" };
|
|
1631
|
+
case "done": return ev.reason === "completed" ? {
|
|
1632
|
+
type: "agent_end",
|
|
1633
|
+
messages: []
|
|
1634
|
+
} : null;
|
|
1635
|
+
case "text": return {
|
|
1636
|
+
type: "text",
|
|
1637
|
+
text: ev.text
|
|
1638
|
+
};
|
|
1639
|
+
case "reasoning": return null;
|
|
1640
|
+
case "turn_start": return {
|
|
1641
|
+
type: "turn_start",
|
|
1642
|
+
turnIndex: ev.turnIndex,
|
|
1643
|
+
timestamp: Date.now()
|
|
1644
|
+
};
|
|
1645
|
+
case "turn_end": return {
|
|
1646
|
+
type: "turn_end",
|
|
1647
|
+
turnIndex: ev.turnIndex,
|
|
1648
|
+
message: null,
|
|
1649
|
+
toolResults: []
|
|
1650
|
+
};
|
|
1651
|
+
case "message_start": return {
|
|
1652
|
+
type: "message_start",
|
|
1653
|
+
message: {
|
|
1654
|
+
role: "assistant",
|
|
1655
|
+
id: ev.messageId
|
|
900
1656
|
}
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
if (payload === "[DONE]") return;
|
|
908
|
-
const raw = JSON.parse(payload);
|
|
909
|
-
if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
|
|
910
|
-
if (raw.type === "permission_request") pendingPermissions.add(raw.requestId);
|
|
911
|
-
else if (raw.type === "permission_resolved") pendingPermissions.delete(raw.requestId);
|
|
912
|
-
lastEventAt = Date.now();
|
|
913
|
-
yield raw;
|
|
1657
|
+
};
|
|
1658
|
+
case "message_end": return {
|
|
1659
|
+
type: "message_end",
|
|
1660
|
+
message: {
|
|
1661
|
+
role: "assistant",
|
|
1662
|
+
id: ev.messageId
|
|
914
1663
|
}
|
|
915
|
-
}
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
1664
|
+
};
|
|
1665
|
+
case "tool_start": return {
|
|
1666
|
+
type: "tool_start",
|
|
1667
|
+
toolCallId: ev.toolCallId,
|
|
1668
|
+
toolName: ev.toolName,
|
|
1669
|
+
args: ev.args
|
|
1670
|
+
};
|
|
1671
|
+
case "tool_update": return {
|
|
1672
|
+
type: "tool_update",
|
|
1673
|
+
toolCallId: ev.toolCallId,
|
|
1674
|
+
toolName: ev.toolName,
|
|
1675
|
+
partialResult: ev.partial
|
|
1676
|
+
};
|
|
1677
|
+
case "tool_end": return {
|
|
1678
|
+
type: "tool_end",
|
|
1679
|
+
toolCallId: ev.toolCallId,
|
|
1680
|
+
toolName: ev.toolName,
|
|
1681
|
+
result: ev.result,
|
|
1682
|
+
isError: ev.isError
|
|
1683
|
+
};
|
|
1684
|
+
case "permission_request": return {
|
|
1685
|
+
type: "permission_request",
|
|
1686
|
+
requestId: ev.requestId,
|
|
1687
|
+
tool: ev.tool,
|
|
1688
|
+
target: ev.target,
|
|
1689
|
+
title: ev.title
|
|
1690
|
+
};
|
|
1691
|
+
case "permission_resolved": return {
|
|
1692
|
+
type: "permission_resolved",
|
|
1693
|
+
requestId: ev.requestId,
|
|
1694
|
+
decision: ev.decision
|
|
1695
|
+
};
|
|
1696
|
+
case "compaction": return ev.phase === "start" ? {
|
|
1697
|
+
type: "compaction_start",
|
|
1698
|
+
reason: asCompactionReason(ev.reason)
|
|
1699
|
+
} : {
|
|
1700
|
+
type: "compaction_end",
|
|
1701
|
+
reason: asCompactionReason(ev.reason),
|
|
1702
|
+
result: null,
|
|
1703
|
+
aborted: ev.aborted ?? false,
|
|
1704
|
+
willRetry: ev.willRetry ?? false
|
|
1705
|
+
};
|
|
1706
|
+
case "retry": return ev.phase === "start" ? {
|
|
1707
|
+
type: "auto_retry_start",
|
|
1708
|
+
attempt: ev.attempt,
|
|
1709
|
+
maxAttempts: ev.maxAttempts ?? ev.attempt,
|
|
1710
|
+
delayMs: ev.delayMs ?? 0,
|
|
1711
|
+
errorMessage: ev.error ?? ""
|
|
1712
|
+
} : {
|
|
1713
|
+
type: "auto_retry_end",
|
|
1714
|
+
success: ev.success ?? false,
|
|
1715
|
+
attempt: ev.attempt,
|
|
1716
|
+
finalError: ev.error
|
|
1717
|
+
};
|
|
1718
|
+
case "queue": return {
|
|
1719
|
+
type: "queue_update",
|
|
1720
|
+
steering: ev.steering,
|
|
1721
|
+
followUp: ev.followUp
|
|
1722
|
+
};
|
|
1723
|
+
case "vendor":
|
|
1724
|
+
case "error": return null;
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
function asCompactionReason(reason) {
|
|
1728
|
+
return reason === "threshold" || reason === "overflow" ? reason : "manual";
|
|
1729
|
+
}
|
|
1730
|
+
/**
|
|
1731
|
+
* Run a turn and yield `AgentEvent`s, as `prompt()` always has. A failed turn throws the
|
|
1732
|
+
* original error, so callers that catch `PromptTimeoutError` or `BridgeDisconnectedError`
|
|
1733
|
+
* keep working. A failure with no error object throws a plain `Error` with its message.
|
|
1734
|
+
*/
|
|
1735
|
+
async function* legacyStream(adapter, input) {
|
|
1736
|
+
for await (const h of adapter.runTurn(input)) {
|
|
1737
|
+
if (h.type === "error") throw h.raw instanceof Error ? h.raw : new Error(h.message);
|
|
1738
|
+
const ev = toAgentEvent(h, adapter.id);
|
|
1739
|
+
if (ev) yield ev;
|
|
921
1740
|
}
|
|
922
1741
|
}
|
|
923
1742
|
//#endregion
|
|
@@ -962,23 +1781,45 @@ var AgentSnapshotStore = class {
|
|
|
962
1781
|
await mkdir(dirname(this.path), { recursive: true });
|
|
963
1782
|
await writeFile(this.path, JSON.stringify(data, null, 2));
|
|
964
1783
|
}
|
|
965
|
-
|
|
966
|
-
|
|
1784
|
+
/**
|
|
1785
|
+
* OpenSandbox keeps the key it always had, so every existing file keeps working. Another
|
|
1786
|
+
* provider's records get its id as a prefix, so two providers sharing one file never read
|
|
1787
|
+
* or replace each other's snapshot ids.
|
|
1788
|
+
*/
|
|
1789
|
+
_key(specName, setupHash, provider) {
|
|
1790
|
+
return provider === DEFAULT_PROVIDER_ID$1 ? `${specName}:${setupHash}` : `${provider}:${specName}:${setupHash}`;
|
|
967
1791
|
}
|
|
968
|
-
async get(specName, setupHash) {
|
|
969
|
-
return (await this._read())[this._key(specName, setupHash)] ?? null;
|
|
1792
|
+
async get(specName, setupHash, provider = DEFAULT_PROVIDER_ID$1) {
|
|
1793
|
+
return (await this._read())[this._key(specName, setupHash, provider)] ?? null;
|
|
970
1794
|
}
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
1795
|
+
/**
|
|
1796
|
+
* Writes are read-modify-write on one file. Two at once (several specs finishing their setup
|
|
1797
|
+
* together, as when alineod restores a whole swarm onto a new machine) would each read the old
|
|
1798
|
+
* file and the second write would drop the first record. This chain runs them one at a time.
|
|
1799
|
+
* It guards one process: a second process on the same file is not supported.
|
|
1800
|
+
*/
|
|
1801
|
+
writing = Promise.resolve();
|
|
1802
|
+
serialized(fn) {
|
|
1803
|
+
const run = this.writing.then(fn, fn);
|
|
1804
|
+
this.writing = run.catch(() => {});
|
|
1805
|
+
return run;
|
|
1806
|
+
}
|
|
1807
|
+
save(record) {
|
|
1808
|
+
return this.serialized(async () => {
|
|
1809
|
+
const data = await this._read();
|
|
1810
|
+
const provider = record.provider ?? DEFAULT_PROVIDER_ID$1;
|
|
1811
|
+
for (const k of Object.keys(data)) if (data[k].specName === record.specName && (data[k].provider ?? DEFAULT_PROVIDER_ID$1) === provider) delete data[k];
|
|
1812
|
+
data[this._key(record.specName, record.setupHash, provider)] = record;
|
|
1813
|
+
await this._write(data);
|
|
1814
|
+
});
|
|
976
1815
|
}
|
|
977
1816
|
/** Remove all snapshot records for the given spec name. */
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
1817
|
+
delete(specName) {
|
|
1818
|
+
return this.serialized(async () => {
|
|
1819
|
+
const data = await this._read();
|
|
1820
|
+
for (const k of Object.keys(data)) if (data[k].specName === specName) delete data[k];
|
|
1821
|
+
await this._write(data);
|
|
1822
|
+
});
|
|
982
1823
|
}
|
|
983
1824
|
async list() {
|
|
984
1825
|
return Object.values(await this._read());
|
|
@@ -994,6 +1835,10 @@ var AgentSnapshotStore = class {
|
|
|
994
1835
|
* (M3, 3.4 — same question, same answer), which previously had its own private copy covering
|
|
995
1836
|
* only the first case below.
|
|
996
1837
|
*
|
|
1838
|
+
* The stable signal is an alineo error code: `SANDBOX_NOT_FOUND`, or `SANDBOX_NOT_RUNNING` with
|
|
1839
|
+
* `details.state` of `Terminated` or `Failed`. The message and `.code` string checks below are a
|
|
1840
|
+
* fallback for errors that carry no alineo code, and may go once every thrower sets one.
|
|
1841
|
+
*
|
|
997
1842
|
* Two distinct ways a sandbox can be "gone," both confirmed against OpenSandbox's actual
|
|
998
1843
|
* behavior (DeepWiki, not just its higher-level docs — same discipline M1.4/M2's research used):
|
|
999
1844
|
*
|
|
@@ -1009,6 +1854,12 @@ var AgentSnapshotStore = class {
|
|
|
1009
1854
|
*/
|
|
1010
1855
|
function isSandboxGone(err) {
|
|
1011
1856
|
if (!err || typeof err !== "object") return false;
|
|
1857
|
+
const alineoCode = errorCodeOf(err);
|
|
1858
|
+
if (alineoCode === "SANDBOX_NOT_FOUND") return true;
|
|
1859
|
+
if (alineoCode === "SANDBOX_NOT_RUNNING") {
|
|
1860
|
+
const state = err.details?.state;
|
|
1861
|
+
return typeof state === "string" && ["terminated", "failed"].includes(state.toLowerCase());
|
|
1862
|
+
}
|
|
1012
1863
|
const code = err.code;
|
|
1013
1864
|
if (typeof code === "string" && code.endsWith("SANDBOX_NOT_FOUND")) return true;
|
|
1014
1865
|
const message = err.message;
|
|
@@ -1018,19 +1869,66 @@ function isSandboxGone(err) {
|
|
|
1018
1869
|
}
|
|
1019
1870
|
//#endregion
|
|
1020
1871
|
//#region src/restore.ts
|
|
1872
|
+
/**
|
|
1873
|
+
* Every checkpoint recorded for this sandbox, newest first. Restore tries them in this order, so
|
|
1874
|
+
* one lost or unreadable tarball costs a turn of history and not the whole conversation.
|
|
1875
|
+
*/
|
|
1876
|
+
async function findCheckpoints(adapter, name, sandboxId) {
|
|
1877
|
+
return (await adapter.readAll(name, sandboxId)).filter((e) => e.event === LedgerEvent.AgentCheckpointed).map((e) => e.payload).reverse();
|
|
1878
|
+
}
|
|
1021
1879
|
/** `undefined` if this sandbox was never checkpointed — not an error; the caller falls back
|
|
1022
1880
|
* to whatever state a bare snapshot restore already produced. */
|
|
1023
1881
|
async function findLatestCheckpoint(adapter, name, sandboxId) {
|
|
1024
|
-
return (await adapter
|
|
1882
|
+
return (await findCheckpoints(adapter, name, sandboxId))[0];
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* The bytes of one checkpoint. Local file first, because it needs no network. If that is gone (a
|
|
1886
|
+
* new host, a wiped disk) and the checkpoint has a `remoteRef` the store recognises, download it.
|
|
1887
|
+
*
|
|
1888
|
+
* @throws if neither source has it. The message names both attempts.
|
|
1889
|
+
*/
|
|
1890
|
+
async function fetchCheckpoint(checkpoint, opts = {}) {
|
|
1891
|
+
let localError;
|
|
1892
|
+
try {
|
|
1893
|
+
return await readFile(checkpoint.snapshotRef);
|
|
1894
|
+
} catch (err) {
|
|
1895
|
+
localError = err;
|
|
1896
|
+
}
|
|
1897
|
+
const key = checkpoint.remoteRef && opts.blobStore ? opts.blobStore.keyOf(checkpoint.remoteRef) : void 0;
|
|
1898
|
+
if (key === void 0 || !opts.blobStore) throw new Error(`checkpoint for turn ${checkpoint.turn} is not on this host (${checkpoint.snapshotRef}: ${localError instanceof Error ? localError.message : String(localError)})` + (checkpoint.remoteRef ? ` and ${checkpoint.remoteRef} cannot be fetched: no BlobStore that owns it was given` : " and it has no off-box copy"));
|
|
1899
|
+
try {
|
|
1900
|
+
return await opts.blobStore.get(key);
|
|
1901
|
+
} catch (err) {
|
|
1902
|
+
throw new Error(`checkpoint for turn ${checkpoint.turn} is not on this host and ${checkpoint.remoteRef} could not be fetched: ${err instanceof Error ? err.message : String(err)}`);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
/**
|
|
1906
|
+
* The newest checkpoint whose tarball can be read, with its bytes, or `undefined` when none can.
|
|
1907
|
+
* `skipped` lists what was passed over and why, for the caller to log.
|
|
1908
|
+
*/
|
|
1909
|
+
async function pickRestorable(candidates, opts = {}) {
|
|
1910
|
+
const skipped = [];
|
|
1911
|
+
for (const checkpoint of candidates) try {
|
|
1912
|
+
return {
|
|
1913
|
+
checkpoint,
|
|
1914
|
+
bytes: await fetchCheckpoint(checkpoint, opts),
|
|
1915
|
+
skipped
|
|
1916
|
+
};
|
|
1917
|
+
} catch (err) {
|
|
1918
|
+
skipped.push({
|
|
1919
|
+
turn: checkpoint.turn,
|
|
1920
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
1921
|
+
});
|
|
1922
|
+
}
|
|
1923
|
+
return null;
|
|
1025
1924
|
}
|
|
1026
1925
|
/**
|
|
1027
|
-
* Extract
|
|
1028
|
-
*
|
|
1029
|
-
*
|
|
1030
|
-
*
|
|
1926
|
+
* Extract checkpoint bytes into `sb`, overwriting whatever a fresh container's own setup left in
|
|
1927
|
+
* place at the same paths. Byte-safe on both ends (`writeFileBytes`/raw `tar xzf`) — the same
|
|
1928
|
+
* corruption risk `takeCheckpoint()`'s doc comment already covers on the capture side applies
|
|
1929
|
+
* symmetrically here on restore.
|
|
1031
1930
|
*/
|
|
1032
|
-
async function
|
|
1033
|
-
const bytes = await readFile(snapshotRef);
|
|
1931
|
+
async function extractCheckpoint(sb, bytes) {
|
|
1034
1932
|
const tmpTarPath = `/tmp/alineo-restore-${crypto.randomUUID()}.tar.gz`;
|
|
1035
1933
|
try {
|
|
1036
1934
|
await sb.writeFileBytes(tmpTarPath, bytes);
|
|
@@ -1041,6 +1939,17 @@ async function restoreCheckpoint(sb, snapshotRef) {
|
|
|
1041
1939
|
} catch {}
|
|
1042
1940
|
}
|
|
1043
1941
|
}
|
|
1942
|
+
/**
|
|
1943
|
+
* Extract a checkpoint tarball into `sb`. `snapshotRef` is the host path `takeCheckpoint()` stored
|
|
1944
|
+
* it at. Pass `remoteRef` and `blobStore` to fall back to object storage when that file is gone.
|
|
1945
|
+
*/
|
|
1946
|
+
async function restoreCheckpoint(sb, snapshotRef, opts = {}) {
|
|
1947
|
+
await extractCheckpoint(sb, await fetchCheckpoint({
|
|
1948
|
+
turn: 0,
|
|
1949
|
+
snapshotRef,
|
|
1950
|
+
remoteRef: opts.remoteRef
|
|
1951
|
+
}, { blobStore: opts.blobStore }));
|
|
1952
|
+
}
|
|
1044
1953
|
//#endregion
|
|
1045
1954
|
//#region src/agent/validation.ts
|
|
1046
1955
|
/**
|
|
@@ -1294,6 +2203,8 @@ async function loadAgent(specInput, opts) {
|
|
|
1294
2203
|
target
|
|
1295
2204
|
}))
|
|
1296
2205
|
} : void 0;
|
|
2206
|
+
const client = clientFromConfig(config, { adapter: opts.adapter });
|
|
2207
|
+
if (heldCredentials.length > 0 && opts.onEgressRequest) requireCapability(client.provider, "egress");
|
|
1297
2208
|
const egressGate = heldCredentials.length > 0 && opts.onEgressRequest ? new EgressApprovalGate({
|
|
1298
2209
|
heldCredentials: heldCredentials.map((b) => ({
|
|
1299
2210
|
name: b.name,
|
|
@@ -1308,15 +2219,9 @@ async function loadAgent(specInput, opts) {
|
|
|
1308
2219
|
await egressGate.start();
|
|
1309
2220
|
egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK = egressGate.webhookUrl;
|
|
1310
2221
|
}
|
|
1311
|
-
const client = new Sandbox({
|
|
1312
|
-
baseUrl: config.serverUrl,
|
|
1313
|
-
apiKey: config.apiKey,
|
|
1314
|
-
adapter: opts.adapter,
|
|
1315
|
-
useServerProxy: config.useServerProxy
|
|
1316
|
-
});
|
|
1317
2222
|
const store = new AgentSnapshotStore(snapshotsPath(config.adapterPath));
|
|
1318
2223
|
const setupHash = computeSetupHash(spec);
|
|
1319
|
-
const adapter =
|
|
2224
|
+
const adapter = createHarness(spec.harness);
|
|
1320
2225
|
let sb;
|
|
1321
2226
|
let fromSnapshot = false;
|
|
1322
2227
|
if (!opts.rebuild) {
|
|
@@ -1385,6 +2290,7 @@ async function loadAgent(specInput, opts) {
|
|
|
1385
2290
|
await store.save({
|
|
1386
2291
|
specName: spec.name,
|
|
1387
2292
|
setupHash,
|
|
2293
|
+
provider: DEFAULT_PROVIDER_ID$1,
|
|
1388
2294
|
snapshotId,
|
|
1389
2295
|
createdAt: Date.now()
|
|
1390
2296
|
});
|
|
@@ -1406,7 +2312,7 @@ async function loadAgent(specInput, opts) {
|
|
|
1406
2312
|
await adapter.configure(sb, spec, resolvedEnv);
|
|
1407
2313
|
log.info("starting bridge");
|
|
1408
2314
|
const t4 = Date.now();
|
|
1409
|
-
await adapter.
|
|
2315
|
+
await adapter.start(sb);
|
|
1410
2316
|
await adapter.waitReady();
|
|
1411
2317
|
log.info("bridge ready", { elapsed: elapsed(t4) });
|
|
1412
2318
|
} catch (err) {
|
|
@@ -1456,22 +2362,44 @@ async function restoreFromCheckpoint(originalSandboxId, spec, opts, runId, log)
|
|
|
1456
2362
|
config: opts.config,
|
|
1457
2363
|
runId
|
|
1458
2364
|
});
|
|
1459
|
-
const
|
|
1460
|
-
if (
|
|
2365
|
+
const candidates = await findCheckpoints(opts.adapter, spec.name, originalSandboxId);
|
|
2366
|
+
if (candidates.length === 0) {
|
|
1461
2367
|
log.warn("no checkpoint found for this agent — continuing with a blank session", { originalSandboxId });
|
|
1462
|
-
return
|
|
2368
|
+
return {
|
|
2369
|
+
...fresh,
|
|
2370
|
+
restore: { checkpointTurn: null }
|
|
2371
|
+
};
|
|
2372
|
+
}
|
|
2373
|
+
const picked = await pickRestorable(candidates, { blobStore: opts.blobStore });
|
|
2374
|
+
for (const s of picked?.skipped ?? []) log.warn("checkpoint is unavailable — trying an older one", {
|
|
2375
|
+
turn: s.turn,
|
|
2376
|
+
reason: s.reason
|
|
2377
|
+
});
|
|
2378
|
+
if (!picked) {
|
|
2379
|
+
log.warn("no checkpoint tarball could be read — continuing with a blank session", {
|
|
2380
|
+
originalSandboxId,
|
|
2381
|
+
tried: candidates.length
|
|
2382
|
+
});
|
|
2383
|
+
return {
|
|
2384
|
+
...fresh,
|
|
2385
|
+
restore: { checkpointTurn: null }
|
|
2386
|
+
};
|
|
1463
2387
|
}
|
|
2388
|
+
const latest = picked.checkpoint;
|
|
1464
2389
|
log.info("restoring checkpoint", {
|
|
1465
2390
|
turn: latest.turn,
|
|
1466
2391
|
sandboxId: fresh.sandbox.sandboxId
|
|
1467
2392
|
});
|
|
1468
2393
|
try {
|
|
1469
2394
|
await fresh.sandbox.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
|
|
1470
|
-
await
|
|
2395
|
+
await extractCheckpoint(fresh.sandbox, picked.bytes);
|
|
1471
2396
|
await fresh.adapter.configure(fresh.sandbox, spec, fresh.env, { resume: true });
|
|
1472
|
-
await fresh.adapter.
|
|
2397
|
+
await fresh.adapter.start(fresh.sandbox);
|
|
1473
2398
|
await fresh.adapter.waitReady();
|
|
1474
|
-
return
|
|
2399
|
+
return {
|
|
2400
|
+
...fresh,
|
|
2401
|
+
restore: { checkpointTurn: latest.turn }
|
|
2402
|
+
};
|
|
1475
2403
|
} catch (err) {
|
|
1476
2404
|
await fresh.sandbox.close().catch(cleanupFailed(log, { sandboxId: fresh.sandbox.sandboxId }));
|
|
1477
2405
|
throw err;
|
|
@@ -1484,12 +2412,7 @@ async function restoreFromCheckpoint(originalSandboxId, spec, opts, runId, log)
|
|
|
1484
2412
|
async function resumeAgent(sandboxId, opts) {
|
|
1485
2413
|
const t0 = Date.now();
|
|
1486
2414
|
const config = resolveProjectConfig(opts.config);
|
|
1487
|
-
const client =
|
|
1488
|
-
baseUrl: config.serverUrl,
|
|
1489
|
-
apiKey: config.apiKey,
|
|
1490
|
-
adapter: opts.adapter,
|
|
1491
|
-
useServerProxy: config.useServerProxy
|
|
1492
|
-
});
|
|
2415
|
+
const client = clientFromConfig(config, { adapter: opts.adapter });
|
|
1493
2416
|
let spec;
|
|
1494
2417
|
if (opts.spec) spec = validateAgentSpec(opts.spec);
|
|
1495
2418
|
else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
|
|
@@ -1529,12 +2452,12 @@ async function resumeAgent(sandboxId, opts) {
|
|
|
1529
2452
|
}
|
|
1530
2453
|
log.info("connected", { elapsed: elapsed(t1) });
|
|
1531
2454
|
await sb.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
|
|
1532
|
-
const adapter =
|
|
2455
|
+
const adapter = createHarness(spec.harness);
|
|
1533
2456
|
resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
|
|
1534
2457
|
await adapter.configure(sb, spec, resolvedEnv, { resume: true });
|
|
1535
2458
|
log.info("starting bridge");
|
|
1536
2459
|
const t2 = Date.now();
|
|
1537
|
-
await adapter.
|
|
2460
|
+
await adapter.start(sb);
|
|
1538
2461
|
await adapter.waitReady();
|
|
1539
2462
|
log.info("bridge ready", { elapsed: elapsed(t2) });
|
|
1540
2463
|
await reconcileDroppedPermissions(opts.adapter, sb, spec.name, sandboxId);
|
|
@@ -1591,12 +2514,7 @@ async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
|
|
|
1591
2514
|
async function reattachAgent(sandboxId, opts) {
|
|
1592
2515
|
const t0 = Date.now();
|
|
1593
2516
|
const config = resolveProjectConfig(opts.config);
|
|
1594
|
-
const client =
|
|
1595
|
-
baseUrl: config.serverUrl,
|
|
1596
|
-
apiKey: config.apiKey,
|
|
1597
|
-
adapter: opts.adapter,
|
|
1598
|
-
useServerProxy: config.useServerProxy
|
|
1599
|
-
});
|
|
2517
|
+
const client = clientFromConfig(config, { adapter: opts.adapter });
|
|
1600
2518
|
let spec;
|
|
1601
2519
|
if (opts.spec) spec = validateAgentSpec(opts.spec);
|
|
1602
2520
|
else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
|
|
@@ -1637,8 +2555,8 @@ async function reattachAgent(sandboxId, opts) {
|
|
|
1637
2555
|
throw err;
|
|
1638
2556
|
}
|
|
1639
2557
|
log.info("connected", { elapsed: elapsed(t1) });
|
|
1640
|
-
const adapter =
|
|
1641
|
-
await adapter.
|
|
2558
|
+
const adapter = createHarness(spec.harness);
|
|
2559
|
+
await adapter.reattach(sb);
|
|
1642
2560
|
const t2 = Date.now();
|
|
1643
2561
|
if (!opts.skipReadyCheck) await adapter.waitReady(5e3);
|
|
1644
2562
|
log.info("bridge reattached", {
|
|
@@ -1661,12 +2579,7 @@ async function reattachAgent(sandboxId, opts) {
|
|
|
1661
2579
|
*/
|
|
1662
2580
|
async function attachAgent(sandboxId, opts) {
|
|
1663
2581
|
const config = resolveProjectConfig(opts.config);
|
|
1664
|
-
const client =
|
|
1665
|
-
baseUrl: config.serverUrl,
|
|
1666
|
-
apiKey: config.apiKey,
|
|
1667
|
-
adapter: opts.adapter,
|
|
1668
|
-
useServerProxy: config.useServerProxy
|
|
1669
|
-
});
|
|
2582
|
+
const client = clientFromConfig(config, { adapter: opts.adapter });
|
|
1670
2583
|
const resources = opts.resources ?? config.defaults.resources;
|
|
1671
2584
|
const sb = await client.connect(sandboxId, opts.name, { resources });
|
|
1672
2585
|
let envFile;
|
|
@@ -1682,15 +2595,16 @@ async function attachAgent(sandboxId, opts) {
|
|
|
1682
2595
|
const piConfig = JSON.parse(await sb.readFile("/etc/alineo-pi.json"));
|
|
1683
2596
|
if (piConfig.model) model = piConfig.model;
|
|
1684
2597
|
} catch {}
|
|
2598
|
+
const stubSpec = {
|
|
2599
|
+
name: opts.name,
|
|
2600
|
+
harness: "pi",
|
|
2601
|
+
model
|
|
2602
|
+
};
|
|
1685
2603
|
return {
|
|
1686
2604
|
sandbox: sb,
|
|
1687
|
-
spec:
|
|
1688
|
-
name: opts.name,
|
|
1689
|
-
harness: "pi",
|
|
1690
|
-
model
|
|
1691
|
-
},
|
|
2605
|
+
spec: stubSpec,
|
|
1692
2606
|
env,
|
|
1693
|
-
adapter:
|
|
2607
|
+
adapter: createHarness(stubSpec.harness),
|
|
1694
2608
|
fromSnapshot: false,
|
|
1695
2609
|
runId
|
|
1696
2610
|
};
|
|
@@ -1727,14 +2641,14 @@ async function spawnChild(self, childSpecPath, opts = {}) {
|
|
|
1727
2641
|
elapsed: elapsed(t0),
|
|
1728
2642
|
sandboxId: forkedSb.sandboxId
|
|
1729
2643
|
});
|
|
1730
|
-
const adapter =
|
|
2644
|
+
const adapter = createHarness(childSpec.harness);
|
|
1731
2645
|
try {
|
|
1732
2646
|
for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
|
|
1733
2647
|
childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
|
|
1734
2648
|
await adapter.configure(forkedSb, childSpec, childEnv);
|
|
1735
2649
|
log.info("starting bridge");
|
|
1736
2650
|
const t1 = Date.now();
|
|
1737
|
-
await adapter.
|
|
2651
|
+
await adapter.start(forkedSb, { unsetVars: Object.keys(self.env) });
|
|
1738
2652
|
await adapter.waitReady();
|
|
1739
2653
|
log.info("bridge ready", { elapsed: elapsed(t1) });
|
|
1740
2654
|
} catch (err) {
|
|
@@ -1779,8 +2693,23 @@ async function forkChildMemory(parentMemory, parentRef, child) {
|
|
|
1779
2693
|
}
|
|
1780
2694
|
}
|
|
1781
2695
|
//#endregion
|
|
2696
|
+
//#region src/agent/pi.ts
|
|
2697
|
+
/**
|
|
2698
|
+
* The agent's adapter as a `PiAdapter`, for an operation only Pi has (`exportHtml`,
|
|
2699
|
+
* `cycleModel`, and so on). Throws `CAPABILITY_UNSUPPORTED` naming the operation and the
|
|
2700
|
+
* harness when the agent runs a different one. It is the single place `Alineo` narrows from
|
|
2701
|
+
* `HarnessAdapter` to a concrete class.
|
|
2702
|
+
*/
|
|
2703
|
+
function pi(a, operation) {
|
|
2704
|
+
if (a.adapter instanceof PiAdapter) return a.adapter;
|
|
2705
|
+
throw new WorkflowError(`The ${a.adapter.id} harness does not support ${operation}`, "CAPABILITY_UNSUPPORTED", { details: {
|
|
2706
|
+
operation,
|
|
2707
|
+
harness: a.adapter.id
|
|
2708
|
+
} });
|
|
2709
|
+
}
|
|
2710
|
+
//#endregion
|
|
1782
2711
|
//#region src/agent/session-control.ts
|
|
1783
|
-
const log = getLogger("agent");
|
|
2712
|
+
const log$1 = getLogger("agent");
|
|
1784
2713
|
/**
|
|
1785
2714
|
* Wrap a raw adapter stream so that every permission event is mirrored to the ledger
|
|
1786
2715
|
* (`PermissionRequested` / `PermissionResolved`) and, when `onPermission` is given, each
|
|
@@ -1803,7 +2732,7 @@ async function* instrument(a, stream, onPermission) {
|
|
|
1803
2732
|
title: ev.title
|
|
1804
2733
|
};
|
|
1805
2734
|
Promise.resolve(onPermission(req)).then((decision) => a.adapter.resolvePermission(ev.requestId, decision)).catch((err) => {
|
|
1806
|
-
log.warn("onPermission handler failed", {
|
|
2735
|
+
log$1.warn("onPermission handler failed", {
|
|
1807
2736
|
requestId: ev.requestId,
|
|
1808
2737
|
err
|
|
1809
2738
|
});
|
|
@@ -1821,7 +2750,11 @@ async function* instrument(a, stream, onPermission) {
|
|
|
1821
2750
|
}
|
|
1822
2751
|
/** Send a prompt to Pi and stream the response. Pi manages its own session context. */
|
|
1823
2752
|
function prompt(a, message, opts) {
|
|
1824
|
-
return instrument(a, a.adapter
|
|
2753
|
+
return instrument(a, legacyStream(a.adapter, {
|
|
2754
|
+
message,
|
|
2755
|
+
streamingBehavior: opts?.streamingBehavior,
|
|
2756
|
+
inactivityTimeoutMs: opts?.inactivityTimeoutMs
|
|
2757
|
+
}), opts?.onPermission);
|
|
1825
2758
|
}
|
|
1826
2759
|
/**
|
|
1827
2760
|
* Run a shell command inside Pi's working context. Not incrementally
|
|
@@ -1829,7 +2762,7 @@ function prompt(a, message, opts) {
|
|
|
1829
2762
|
* arrives as a single `text` event once the command completes.
|
|
1830
2763
|
*/
|
|
1831
2764
|
function bash(a, command) {
|
|
1832
|
-
return instrument(a, a.
|
|
2765
|
+
return instrument(a, pi(a, "bash").bash(command));
|
|
1833
2766
|
}
|
|
1834
2767
|
/** Snapshot of tool calls currently paused awaiting a human decision. */
|
|
1835
2768
|
async function listPendingPermissions(a) {
|
|
@@ -1837,7 +2770,8 @@ async function listPendingPermissions(a) {
|
|
|
1837
2770
|
}
|
|
1838
2771
|
/** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
|
|
1839
2772
|
async function steer(a, message) {
|
|
1840
|
-
|
|
2773
|
+
requireHarnessCapability(a.adapter, "steer");
|
|
2774
|
+
await a.adapter.steer?.(message);
|
|
1841
2775
|
}
|
|
1842
2776
|
/** Abort Pi's current operation. */
|
|
1843
2777
|
async function abort(a) {
|
|
@@ -1852,15 +2786,16 @@ async function resolvePermission(a, requestId, decision) {
|
|
|
1852
2786
|
}
|
|
1853
2787
|
/** Queue a message to be sent to Pi after it finishes its current task. */
|
|
1854
2788
|
async function followUp(a, message) {
|
|
1855
|
-
|
|
2789
|
+
requireHarnessCapability(a.adapter, "followUp");
|
|
2790
|
+
await a.adapter.followUp?.(message);
|
|
1856
2791
|
}
|
|
1857
2792
|
/** Start a fresh Pi session, clearing all prior context. */
|
|
1858
2793
|
async function newSession(a) {
|
|
1859
|
-
return a.
|
|
2794
|
+
return pi(a, "newSession").newSession();
|
|
1860
2795
|
}
|
|
1861
2796
|
/** Enable or disable Pi's automatic context compaction. */
|
|
1862
2797
|
async function setAutoCompaction(a, enabled) {
|
|
1863
|
-
return a.
|
|
2798
|
+
return pi(a, "setAutoCompaction").setAutoCompaction(enabled);
|
|
1864
2799
|
}
|
|
1865
2800
|
/**
|
|
1866
2801
|
* Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
|
|
@@ -1869,68 +2804,68 @@ async function setAutoCompaction(a, enabled) {
|
|
|
1869
2804
|
* events in the stream.
|
|
1870
2805
|
*/
|
|
1871
2806
|
async function setAutoRetry(a, enabled) {
|
|
1872
|
-
return a.
|
|
2807
|
+
return pi(a, "setAutoRetry").setAutoRetry(enabled);
|
|
1873
2808
|
}
|
|
1874
2809
|
/**
|
|
1875
2810
|
* Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
|
|
1876
2811
|
* operation, emitting `auto_retry_end` with `success: false`.
|
|
1877
2812
|
*/
|
|
1878
2813
|
async function abortRetry(a) {
|
|
1879
|
-
return a.
|
|
2814
|
+
return pi(a, "abortRetry").abortRetry();
|
|
1880
2815
|
}
|
|
1881
2816
|
/** Abort a currently-executing bash command without cancelling the whole prompt. */
|
|
1882
2817
|
async function abortBash(a) {
|
|
1883
|
-
return a.
|
|
2818
|
+
return pi(a, "abortBash").abortBash();
|
|
1884
2819
|
}
|
|
1885
2820
|
/**
|
|
1886
2821
|
* Control how Pi processes queued steering messages.
|
|
1887
2822
|
* `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
|
|
1888
2823
|
*/
|
|
1889
2824
|
async function setSteeringMode(a, mode) {
|
|
1890
|
-
return a.
|
|
2825
|
+
return pi(a, "setSteeringMode").setSteeringMode(mode);
|
|
1891
2826
|
}
|
|
1892
2827
|
/**
|
|
1893
2828
|
* Control how Pi processes queued follow-up messages.
|
|
1894
2829
|
* `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
|
|
1895
2830
|
*/
|
|
1896
2831
|
async function setFollowUpMode(a, mode) {
|
|
1897
|
-
return a.
|
|
2832
|
+
return pi(a, "setFollowUpMode").setFollowUpMode(mode);
|
|
1898
2833
|
}
|
|
1899
2834
|
/** Set a display name for the current Pi session. */
|
|
1900
2835
|
async function setSessionName(a, name) {
|
|
1901
|
-
return a.
|
|
2836
|
+
return pi(a, "setSessionName").setSessionName(name);
|
|
1902
2837
|
}
|
|
1903
2838
|
//#endregion
|
|
1904
2839
|
//#region src/agent/model.ts
|
|
1905
2840
|
/** Set Pi's reasoning level (for models that support extended thinking). */
|
|
1906
2841
|
async function setThinkingLevel(a, level) {
|
|
1907
|
-
return a.
|
|
2842
|
+
return pi(a, "setThinkingLevel").setThinkingLevel(level);
|
|
1908
2843
|
}
|
|
1909
2844
|
/** Switch Pi to a specific model. Returns the activated model. */
|
|
1910
2845
|
async function setModel(a, provider, modelId) {
|
|
1911
|
-
return a.
|
|
2846
|
+
return pi(a, "setModel").setModel(provider, modelId);
|
|
1912
2847
|
}
|
|
1913
2848
|
/** Cycle Pi to the next available model. Returns null if only one model is configured. */
|
|
1914
2849
|
async function cycleModel(a) {
|
|
1915
|
-
return a.
|
|
2850
|
+
return pi(a, "cycleModel").cycleModel();
|
|
1916
2851
|
}
|
|
1917
2852
|
/** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
|
|
1918
2853
|
async function cycleThinkingLevel(a) {
|
|
1919
|
-
return a.
|
|
2854
|
+
return pi(a, "cycleThinkingLevel").cycleThinkingLevel();
|
|
1920
2855
|
}
|
|
1921
2856
|
/** List all models available to Pi under the current provider configuration. */
|
|
1922
2857
|
async function getAvailableModels(a) {
|
|
1923
|
-
return a.
|
|
2858
|
+
return pi(a, "getAvailableModels").getAvailableModels();
|
|
1924
2859
|
}
|
|
1925
2860
|
//#endregion
|
|
1926
2861
|
//#region src/agent/introspection.ts
|
|
1927
2862
|
/** Retrieve token usage, cost, and message counts for the current session. */
|
|
1928
2863
|
async function getSessionStats(a) {
|
|
1929
|
-
return a.
|
|
2864
|
+
return pi(a, "getSessionStats").getSessionStats();
|
|
1930
2865
|
}
|
|
1931
2866
|
/** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
|
|
1932
2867
|
async function getLastAssistantText(a) {
|
|
1933
|
-
return a.
|
|
2868
|
+
return pi(a, "getLastAssistantText").getLastAssistantText();
|
|
1934
2869
|
}
|
|
1935
2870
|
/**
|
|
1936
2871
|
* List the points in the current session a conversation can be branched from.
|
|
@@ -1940,15 +2875,15 @@ async function getLastAssistantText(a) {
|
|
|
1940
2875
|
* vocabulary, alineo speaks its own on the way out.
|
|
1941
2876
|
*/
|
|
1942
2877
|
async function getBranchPoints(a) {
|
|
1943
|
-
return a.
|
|
2878
|
+
return pi(a, "getForkMessages").getForkMessages();
|
|
1944
2879
|
}
|
|
1945
2880
|
/** List Pi's available slash commands, including extensions, prompt templates, and skills. */
|
|
1946
2881
|
async function getCommands(a) {
|
|
1947
|
-
return a.
|
|
2882
|
+
return pi(a, "getCommands").getCommands();
|
|
1948
2883
|
}
|
|
1949
2884
|
/** Retrieve Pi's full conversation history for the current session. */
|
|
1950
2885
|
async function getMessages(a) {
|
|
1951
|
-
return a.
|
|
2886
|
+
return pi(a, "getMessages").getMessages();
|
|
1952
2887
|
}
|
|
1953
2888
|
/**
|
|
1954
2889
|
* Retrieve Pi's current session state: active model, thinking level, streaming/compaction
|
|
@@ -1956,11 +2891,11 @@ async function getMessages(a) {
|
|
|
1956
2891
|
* other way to observe the *current* model or thinking level (as opposed to the full list).
|
|
1957
2892
|
*/
|
|
1958
2893
|
async function getState(a) {
|
|
1959
|
-
return a.
|
|
2894
|
+
return pi(a, "getState").getState();
|
|
1960
2895
|
}
|
|
1961
2896
|
/** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
|
|
1962
2897
|
async function getLogs(a) {
|
|
1963
|
-
return a.
|
|
2898
|
+
return pi(a, "getLogs").getLogs();
|
|
1964
2899
|
}
|
|
1965
2900
|
//#endregion
|
|
1966
2901
|
//#region src/agent/lifecycle.ts
|
|
@@ -1971,15 +2906,15 @@ async function getLogs(a) {
|
|
|
1971
2906
|
* bridge endpoint is literally `/fork`), and alineo speaks its own on the way out.
|
|
1972
2907
|
*/
|
|
1973
2908
|
async function branchSession(a, entryId) {
|
|
1974
|
-
return a.
|
|
2909
|
+
return pi(a, "fork").fork(entryId);
|
|
1975
2910
|
}
|
|
1976
2911
|
/** Branch the harness conversation at its current position. */
|
|
1977
2912
|
async function duplicateSession(a) {
|
|
1978
|
-
return a.
|
|
2913
|
+
return pi(a, "clone").clone();
|
|
1979
2914
|
}
|
|
1980
2915
|
/** Switch Pi to a different session file on disk. */
|
|
1981
2916
|
async function switchSession(a, sessionPath) {
|
|
1982
|
-
return a.
|
|
2917
|
+
return pi(a, "switchSession").switchSession(sessionPath);
|
|
1983
2918
|
}
|
|
1984
2919
|
/**
|
|
1985
2920
|
* Export a static HTML transcript of the current session to the sandbox filesystem.
|
|
@@ -1987,11 +2922,11 @@ async function switchSession(a, sessionPath) {
|
|
|
1987
2922
|
* to retrieve it.
|
|
1988
2923
|
*/
|
|
1989
2924
|
async function exportHtml(a, outputPath) {
|
|
1990
|
-
return a.
|
|
2925
|
+
return pi(a, "exportHtml").exportHtml(outputPath);
|
|
1991
2926
|
}
|
|
1992
2927
|
/** Manually trigger Pi's context compaction. */
|
|
1993
2928
|
async function compact(a, customInstructions) {
|
|
1994
|
-
return a.
|
|
2929
|
+
return pi(a, "compact").compact(customInstructions);
|
|
1995
2930
|
}
|
|
1996
2931
|
/**
|
|
1997
2932
|
* Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
|
|
@@ -2003,11 +2938,11 @@ async function setEnv(a, vars) {
|
|
|
2003
2938
|
...vars
|
|
2004
2939
|
};
|
|
2005
2940
|
await a.sandbox.writeFile("/etc/alineo-env", toShellExports(a.env));
|
|
2006
|
-
await a.
|
|
2941
|
+
await pi(a, "reloadEnv").reloadEnv(a.env);
|
|
2007
2942
|
}
|
|
2008
2943
|
/** Delete the sandbox container and release all resources. Always call in a `finally` block. */
|
|
2009
2944
|
async function close(a) {
|
|
2010
|
-
a.adapter.
|
|
2945
|
+
a.adapter.dispose();
|
|
2011
2946
|
await a.egressGate?.stop().catch(() => {});
|
|
2012
2947
|
await a.sandbox.close();
|
|
2013
2948
|
}
|
|
@@ -2054,6 +2989,10 @@ var Alineo = class Alineo {
|
|
|
2054
2989
|
* `false` on the first load for a given spec, or after `{ rebuild: true }`.
|
|
2055
2990
|
*/
|
|
2056
2991
|
fromSnapshot;
|
|
2992
|
+
/**
|
|
2993
|
+
* The harness this agent runs, as the harness-neutral interface. For a harness's own
|
|
2994
|
+
* methods use `harness()`.
|
|
2995
|
+
*/
|
|
2057
2996
|
adapter;
|
|
2058
2997
|
env;
|
|
2059
2998
|
/**
|
|
@@ -2107,7 +3046,13 @@ var Alineo = class Alineo {
|
|
|
2107
3046
|
* Stopped by `close()`.
|
|
2108
3047
|
*/
|
|
2109
3048
|
egressGate;
|
|
2110
|
-
|
|
3049
|
+
/**
|
|
3050
|
+
* Set when `resume()` or `reattach()` found the sandbox gone and returned an agent on a fresh
|
|
3051
|
+
* one. `checkpointTurn` is the turn it was restored from, or `null` when there was no
|
|
3052
|
+
* checkpoint and the session is blank. Absent on every other agent.
|
|
3053
|
+
*/
|
|
3054
|
+
restore;
|
|
3055
|
+
constructor(sandbox, spec, env, adapter, fromSnapshot, runId, egressGate, restore) {
|
|
2111
3056
|
this.sandbox = sandbox;
|
|
2112
3057
|
this.sandboxId = sandbox.sandboxId;
|
|
2113
3058
|
this.name = spec.name;
|
|
@@ -2118,6 +3063,7 @@ var Alineo = class Alineo {
|
|
|
2118
3063
|
this.fromSnapshot = fromSnapshot;
|
|
2119
3064
|
this.runId = runId;
|
|
2120
3065
|
this.egressGate = egressGate;
|
|
3066
|
+
this.restore = restore;
|
|
2121
3067
|
}
|
|
2122
3068
|
/** Egress requests currently awaiting a decision (see `AgentSpec.env` `approval: "hold"`). */
|
|
2123
3069
|
pendingEgressRequests() {
|
|
@@ -2195,7 +3141,7 @@ var Alineo = class Alineo {
|
|
|
2195
3141
|
*/
|
|
2196
3142
|
static async resume(sandboxId, opts) {
|
|
2197
3143
|
const r = await resumeAgent(sandboxId, opts);
|
|
2198
|
-
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
|
|
3144
|
+
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, void 0, r.restore);
|
|
2199
3145
|
agent.memory = opts.memory;
|
|
2200
3146
|
return agent;
|
|
2201
3147
|
}
|
|
@@ -2230,7 +3176,7 @@ var Alineo = class Alineo {
|
|
|
2230
3176
|
*/
|
|
2231
3177
|
static async reattach(sandboxId, opts) {
|
|
2232
3178
|
const r = await reattachAgent(sandboxId, opts);
|
|
2233
|
-
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
|
|
3179
|
+
const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, void 0, r.restore);
|
|
2234
3180
|
agent.memory = opts.memory;
|
|
2235
3181
|
return agent;
|
|
2236
3182
|
}
|
|
@@ -2310,6 +3256,23 @@ var Alineo = class Alineo {
|
|
|
2310
3256
|
await forkChildMemory(this.memory, this.resourceRef, child);
|
|
2311
3257
|
return child;
|
|
2312
3258
|
}
|
|
3259
|
+
/**
|
|
3260
|
+
* The harness's own adapter, typed for that harness, for what it has and the others do not.
|
|
3261
|
+
* `agent.harness("pi")` gives Pi's `exportHtml()`, `cycleModel()`, `getCommands()` and the
|
|
3262
|
+
* rest. Throws `CAPABILITY_UNSUPPORTED` when this agent runs a different harness.
|
|
3263
|
+
*
|
|
3264
|
+
* Prefer the methods on `Alineo` itself where they exist: they work on every harness
|
|
3265
|
+
* that declares the capability.
|
|
3266
|
+
*
|
|
3267
|
+
* @experimental The harness layer is being built. Expect changes before it is stable.
|
|
3268
|
+
*/
|
|
3269
|
+
harness(id) {
|
|
3270
|
+
if (this.adapter.id !== id) throw new WorkflowError(`This agent runs the ${this.adapter.id} harness, not ${String(id)}`, "CAPABILITY_UNSUPPORTED", { details: {
|
|
3271
|
+
harness: this.adapter.id,
|
|
3272
|
+
requested: String(id)
|
|
3273
|
+
} });
|
|
3274
|
+
return this.adapter;
|
|
3275
|
+
}
|
|
2313
3276
|
/** Send a prompt to Pi and stream the response. Pi manages its own session context. */
|
|
2314
3277
|
prompt(message, opts) {
|
|
2315
3278
|
return prompt(this, message, opts);
|
|
@@ -2318,6 +3281,8 @@ var Alineo = class Alineo {
|
|
|
2318
3281
|
* Run a shell command inside Pi's working context. Not incrementally
|
|
2319
3282
|
* streamed — Pi returns bash output synchronously, so the full output
|
|
2320
3283
|
* arrives as a single `text` event once the command completes.
|
|
3284
|
+
*
|
|
3285
|
+
* @deprecated Use `agent.harness("pi").bash()`. Moves off `Alineo` because only Pi has it.
|
|
2321
3286
|
*/
|
|
2322
3287
|
bash(command) {
|
|
2323
3288
|
return bash(this, command);
|
|
@@ -2366,7 +3331,10 @@ var Alineo = class Alineo {
|
|
|
2366
3331
|
async setThinkingLevel(level) {
|
|
2367
3332
|
return setThinkingLevel(this, level);
|
|
2368
3333
|
}
|
|
2369
|
-
/** Enable or disable Pi's automatic context compaction.
|
|
3334
|
+
/** Enable or disable Pi's automatic context compaction.
|
|
3335
|
+
*
|
|
3336
|
+
* @deprecated Use `agent.harness("pi").setAutoCompaction()`. Moves off `Alineo` because only Pi has it.
|
|
3337
|
+
*/
|
|
2370
3338
|
async setAutoCompaction(enabled) {
|
|
2371
3339
|
return setAutoCompaction(this, enabled);
|
|
2372
3340
|
}
|
|
@@ -2375,6 +3343,8 @@ var Alineo = class Alineo {
|
|
|
2375
3343
|
* Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
|
|
2376
3344
|
* Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
|
|
2377
3345
|
* events in the stream.
|
|
3346
|
+
*
|
|
3347
|
+
* @deprecated Use `agent.harness("pi").setAutoRetry()`. Moves off `Alineo` because only Pi has it.
|
|
2378
3348
|
*/
|
|
2379
3349
|
async setAutoRetry(enabled) {
|
|
2380
3350
|
return setAutoRetry(this, enabled);
|
|
@@ -2382,11 +3352,16 @@ var Alineo = class Alineo {
|
|
|
2382
3352
|
/**
|
|
2383
3353
|
* Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
|
|
2384
3354
|
* operation, emitting `auto_retry_end` with `success: false`.
|
|
3355
|
+
*
|
|
3356
|
+
* @deprecated Use `agent.harness("pi").abortRetry()`. Moves off `Alineo` because only Pi has it.
|
|
2385
3357
|
*/
|
|
2386
3358
|
async abortRetry() {
|
|
2387
3359
|
return abortRetry(this);
|
|
2388
3360
|
}
|
|
2389
|
-
/** Abort a currently-executing bash command without cancelling the whole prompt.
|
|
3361
|
+
/** Abort a currently-executing bash command without cancelling the whole prompt.
|
|
3362
|
+
*
|
|
3363
|
+
* @deprecated Use `agent.harness("pi").abortBash()`. Moves off `Alineo` because only Pi has it.
|
|
3364
|
+
*/
|
|
2390
3365
|
async abortBash() {
|
|
2391
3366
|
return abortBash(this);
|
|
2392
3367
|
}
|
|
@@ -2405,17 +3380,25 @@ var Alineo = class Alineo {
|
|
|
2405
3380
|
async getBranchPoints() {
|
|
2406
3381
|
return getBranchPoints(this);
|
|
2407
3382
|
}
|
|
2408
|
-
/** List Pi's available slash commands, including extensions, prompt templates, and skills.
|
|
3383
|
+
/** List Pi's available slash commands, including extensions, prompt templates, and skills.
|
|
3384
|
+
*
|
|
3385
|
+
* @deprecated Use `agent.harness("pi").getCommands()`. Moves off `Alineo` because only Pi has it.
|
|
3386
|
+
*/
|
|
2409
3387
|
async getCommands() {
|
|
2410
3388
|
return getCommands(this);
|
|
2411
3389
|
}
|
|
2412
|
-
/** Set a display name for the current Pi session.
|
|
3390
|
+
/** Set a display name for the current Pi session.
|
|
3391
|
+
*
|
|
3392
|
+
* @deprecated Use `agent.harness("pi").setSessionName()`. Moves off `Alineo` because only Pi has it.
|
|
3393
|
+
*/
|
|
2413
3394
|
async setSessionName(name) {
|
|
2414
3395
|
return setSessionName(this, name);
|
|
2415
3396
|
}
|
|
2416
3397
|
/**
|
|
2417
3398
|
* Control how Pi processes queued steering messages.
|
|
2418
3399
|
* `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
|
|
3400
|
+
*
|
|
3401
|
+
* @deprecated Use `agent.harness("pi").setSteeringMode()`. Moves off `Alineo` because only Pi has it.
|
|
2419
3402
|
*/
|
|
2420
3403
|
async setSteeringMode(mode) {
|
|
2421
3404
|
return setSteeringMode(this, mode);
|
|
@@ -2423,6 +3406,8 @@ var Alineo = class Alineo {
|
|
|
2423
3406
|
/**
|
|
2424
3407
|
* Control how Pi processes queued follow-up messages.
|
|
2425
3408
|
* `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
|
|
3409
|
+
*
|
|
3410
|
+
* @deprecated Use `agent.harness("pi").setFollowUpMode()`. Moves off `Alineo` because only Pi has it.
|
|
2426
3411
|
*/
|
|
2427
3412
|
async setFollowUpMode(mode) {
|
|
2428
3413
|
return setFollowUpMode(this, mode);
|
|
@@ -2431,6 +3416,8 @@ var Alineo = class Alineo {
|
|
|
2431
3416
|
* Export a static HTML transcript of the current session to the sandbox filesystem.
|
|
2432
3417
|
* Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
|
|
2433
3418
|
* to retrieve it.
|
|
3419
|
+
*
|
|
3420
|
+
* @deprecated Use `agent.harness("pi").exportHtml()`. Moves off `Alineo` because only Pi has it.
|
|
2434
3421
|
*/
|
|
2435
3422
|
async exportHtml(outputPath) {
|
|
2436
3423
|
return exportHtml(this, outputPath);
|
|
@@ -2460,11 +3447,17 @@ var Alineo = class Alineo {
|
|
|
2460
3447
|
async setModel(provider, modelId) {
|
|
2461
3448
|
return setModel(this, provider, modelId);
|
|
2462
3449
|
}
|
|
2463
|
-
/** Cycle Pi to the next available model. Returns null if only one model is configured.
|
|
3450
|
+
/** Cycle Pi to the next available model. Returns null if only one model is configured.
|
|
3451
|
+
*
|
|
3452
|
+
* @deprecated Use `agent.harness("pi").cycleModel()`. Moves off `Alineo` because only Pi has it.
|
|
3453
|
+
*/
|
|
2464
3454
|
async cycleModel() {
|
|
2465
3455
|
return cycleModel(this);
|
|
2466
3456
|
}
|
|
2467
|
-
/** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking.
|
|
3457
|
+
/** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking.
|
|
3458
|
+
*
|
|
3459
|
+
* @deprecated Use `agent.harness("pi").cycleThinkingLevel()`. Moves off `Alineo` because only Pi has it.
|
|
3460
|
+
*/
|
|
2468
3461
|
async cycleThinkingLevel() {
|
|
2469
3462
|
return cycleThinkingLevel(this);
|
|
2470
3463
|
}
|
|
@@ -2511,7 +3504,118 @@ async function* textOnly(stream) {
|
|
|
2511
3504
|
for await (const ev of stream) if (ev.type === "text") yield ev.text;
|
|
2512
3505
|
}
|
|
2513
3506
|
//#endregion
|
|
3507
|
+
//#region src/blob-store.ts
|
|
3508
|
+
/** `s` without leading and trailing slashes. A loop, not a regex: no backtracking on odd input. */
|
|
3509
|
+
function trimSlashes(s) {
|
|
3510
|
+
let start = 0;
|
|
3511
|
+
let end = s.length;
|
|
3512
|
+
while (start < end && s[start] === "/") start++;
|
|
3513
|
+
while (end > start && s[end - 1] === "/") end--;
|
|
3514
|
+
return s.slice(start, end);
|
|
3515
|
+
}
|
|
3516
|
+
/** Joins path parts with one `/` between them, ignoring empty parts and stray slashes. */
|
|
3517
|
+
function joinKey(...parts) {
|
|
3518
|
+
return parts.map(trimSlashes).filter((p) => p !== "").join("/");
|
|
3519
|
+
}
|
|
3520
|
+
/** S3, R2, MinIO: anything `Bun.S3Client` talks to. Runs under Bun only. */
|
|
3521
|
+
var S3BlobStore = class {
|
|
3522
|
+
client;
|
|
3523
|
+
bucket;
|
|
3524
|
+
prefix;
|
|
3525
|
+
constructor(opts) {
|
|
3526
|
+
this.bucket = opts.bucket;
|
|
3527
|
+
this.prefix = joinKey(opts.prefix ?? "");
|
|
3528
|
+
this.client = opts.client ?? new Bun.S3Client({
|
|
3529
|
+
bucket: opts.bucket,
|
|
3530
|
+
endpoint: opts.endpoint,
|
|
3531
|
+
region: opts.region,
|
|
3532
|
+
accessKeyId: opts.accessKeyId,
|
|
3533
|
+
secretAccessKey: opts.secretAccessKey
|
|
3534
|
+
});
|
|
3535
|
+
}
|
|
3536
|
+
full(key) {
|
|
3537
|
+
return joinKey(this.prefix, key);
|
|
3538
|
+
}
|
|
3539
|
+
async put(key, body) {
|
|
3540
|
+
await this.client.file(this.full(key)).write(typeof body === "string" ? Bun.file(body) : body);
|
|
3541
|
+
}
|
|
3542
|
+
async get(key) {
|
|
3543
|
+
return this.client.file(this.full(key)).bytes();
|
|
3544
|
+
}
|
|
3545
|
+
async delete(key) {
|
|
3546
|
+
await this.client.delete(this.full(key));
|
|
3547
|
+
}
|
|
3548
|
+
async list(prefix) {
|
|
3549
|
+
const out = [];
|
|
3550
|
+
const root = this.prefix === "" ? "" : `${this.prefix}/`;
|
|
3551
|
+
let token;
|
|
3552
|
+
do {
|
|
3553
|
+
const page = await this.client.list({
|
|
3554
|
+
prefix: this.full(prefix),
|
|
3555
|
+
continuationToken: token
|
|
3556
|
+
});
|
|
3557
|
+
for (const item of page.contents ?? []) out.push({
|
|
3558
|
+
key: item.key.startsWith(root) ? item.key.slice(root.length) : item.key,
|
|
3559
|
+
lastModified: item.lastModified ? Date.parse(item.lastModified) : 0
|
|
3560
|
+
});
|
|
3561
|
+
token = page.isTruncated ? page.nextContinuationToken : void 0;
|
|
3562
|
+
} while (token);
|
|
3563
|
+
return out;
|
|
3564
|
+
}
|
|
3565
|
+
refOf(key) {
|
|
3566
|
+
return `s3://${this.bucket}/${this.full(key)}`;
|
|
3567
|
+
}
|
|
3568
|
+
keyOf(ref) {
|
|
3569
|
+
const head = `s3://${this.bucket}/${this.prefix === "" ? "" : `${this.prefix}/`}`;
|
|
3570
|
+
return ref.startsWith(head) ? ref.slice(head.length) : void 0;
|
|
3571
|
+
}
|
|
3572
|
+
};
|
|
3573
|
+
/**
|
|
3574
|
+
* Keeps blobs in a Map. The store the unit tests use, and a reference for what a `BlobStore` must
|
|
3575
|
+
* do. `now` lets a test age a blob without waiting.
|
|
3576
|
+
*/
|
|
3577
|
+
var MemoryBlobStore = class {
|
|
3578
|
+
now;
|
|
3579
|
+
blobs = /* @__PURE__ */ new Map();
|
|
3580
|
+
constructor(now = Date.now) {
|
|
3581
|
+
this.now = now;
|
|
3582
|
+
}
|
|
3583
|
+
async put(key, body) {
|
|
3584
|
+
const bytes = typeof body === "string" ? await Bun.file(body).bytes() : body.slice();
|
|
3585
|
+
this.blobs.set(key, {
|
|
3586
|
+
bytes,
|
|
3587
|
+
at: this.now()
|
|
3588
|
+
});
|
|
3589
|
+
}
|
|
3590
|
+
get(key) {
|
|
3591
|
+
const hit = this.blobs.get(key);
|
|
3592
|
+
if (!hit) return Promise.reject(/* @__PURE__ */ new Error(`no such blob: ${key}`));
|
|
3593
|
+
return Promise.resolve(hit.bytes.slice());
|
|
3594
|
+
}
|
|
3595
|
+
delete(key) {
|
|
3596
|
+
this.blobs.delete(key);
|
|
3597
|
+
return Promise.resolve();
|
|
3598
|
+
}
|
|
3599
|
+
list(prefix) {
|
|
3600
|
+
return Promise.resolve([...this.blobs].filter(([key]) => key.startsWith(prefix)).map(([key, v]) => ({
|
|
3601
|
+
key,
|
|
3602
|
+
lastModified: v.at
|
|
3603
|
+
})));
|
|
3604
|
+
}
|
|
3605
|
+
refOf(key) {
|
|
3606
|
+
return `mem://${key}`;
|
|
3607
|
+
}
|
|
3608
|
+
keyOf(ref) {
|
|
3609
|
+
return ref.startsWith("mem://") ? ref.slice(6) : void 0;
|
|
3610
|
+
}
|
|
3611
|
+
/** Test seam: every key, so a test can assert what was written or deleted. */
|
|
3612
|
+
keys() {
|
|
3613
|
+
return [...this.blobs.keys()].sort();
|
|
3614
|
+
}
|
|
3615
|
+
};
|
|
3616
|
+
//#endregion
|
|
2514
3617
|
//#region src/checkpoint.ts
|
|
3618
|
+
const log = getLogger("checkpoint");
|
|
2515
3619
|
/**
|
|
2516
3620
|
* Turn-level checkpointing (durability-roadmap.md M3, 3.2) — deliberately NOT
|
|
2517
3621
|
* `sb.checkpoint()`. That method calls OpenSandbox's own snapshot primitive, which on the
|
|
@@ -2552,12 +3656,32 @@ const DEFAULT_CHECKPOINT_EXCLUDE_GLOBS = ["__pycache__", ".pytest_cache"];
|
|
|
2552
3656
|
*/
|
|
2553
3657
|
const CHECKPOINT_ROOT = "root";
|
|
2554
3658
|
/**
|
|
3659
|
+
* `/workspace` is the working directory most specs and cookbooks use, and it sits outside
|
|
3660
|
+
* `/root`, so a checkpoint of `/root` alone restored the Pi conversation but not the files the
|
|
3661
|
+
* agent had worked on (confirmed live, 2026-10-16). It is tarred too when it exists. Measured
|
|
3662
|
+
* cost: a cloned repo is 3.5 MB and 0.5 s. A web app's `node_modules` is nearly all of the cost
|
|
3663
|
+
* (20 MB and 5 s for 417 packages, against 0.1 MB and 0.03 s without), so dependency
|
|
3664
|
+
* directories are left out of this path only. Under `/root` they can hold Pi's own packages, so
|
|
3665
|
+
* they stay in.
|
|
3666
|
+
*/
|
|
3667
|
+
const CHECKPOINT_WORKSPACE = "workspace";
|
|
3668
|
+
/** Left out of `CHECKPOINT_WORKSPACE`. The agent installs these again after a restore. */
|
|
3669
|
+
const DEFAULT_WORKSPACE_EXCLUDES = [`${CHECKPOINT_WORKSPACE}/node_modules`, `${CHECKPOINT_WORKSPACE}/*/node_modules`];
|
|
3670
|
+
/**
|
|
2555
3671
|
* durability-roadmap M3, 3.5: restore (3.3) only ever reads the *latest* checkpoint — an older
|
|
2556
3672
|
* one is slack for debugging/manual rollback, not a live requirement. 3 was decided without
|
|
2557
3673
|
* real usage data to justify more (measured sizes are sub-30MB, typically far less once the
|
|
2558
3674
|
* exclusion list applies), and is cheap to revisit if real retention pressure ever shows up.
|
|
2559
3675
|
*/
|
|
2560
3676
|
const DEFAULT_CHECKPOINT_RETENTION = 3;
|
|
3677
|
+
/**
|
|
3678
|
+
* durability-roadmap M4, 4.1: an off-box blob is deleted only when it is both beyond the retention
|
|
3679
|
+
* count AND at least this old. The ledger can be restored from a replica that trails the live one
|
|
3680
|
+
* by a few seconds, so after a disk loss it may name a checkpoint that is no longer the newest. The
|
|
3681
|
+
* margin keeps that older blob alive long enough to be found. The restore also falls back from a
|
|
3682
|
+
* missing blob to the next older checkpoint, so this is a second line of defence.
|
|
3683
|
+
*/
|
|
3684
|
+
const DEFAULT_REMOTE_PRUNE_MIN_AGE_MS = 6e5;
|
|
2561
3685
|
/** Derive the checkpoints directory from the ledger adapter's own path, same convention as
|
|
2562
3686
|
* `./snapshots.ts`'s `snapshotsPath()`. */
|
|
2563
3687
|
function checkpointsPath(adapterPath) {
|
|
@@ -2585,6 +3709,19 @@ async function pruneOldCheckpoints(dir, retain) {
|
|
|
2585
3709
|
await Promise.all(withTimes.slice(retain).map((f) => rm(join(dir, f.name), { force: true })));
|
|
2586
3710
|
}
|
|
2587
3711
|
/**
|
|
3712
|
+
* Delete this sandbox's old off-box checkpoints: all but the newest `retain`, and only those older
|
|
3713
|
+
* than `minAgeMs`. Best-effort like the local prune: a failure is returned to the caller to log and
|
|
3714
|
+
* never thrown, because the checkpoint it follows already succeeded.
|
|
3715
|
+
*/
|
|
3716
|
+
async function pruneRemoteCheckpoints(store, sandboxId, opts) {
|
|
3717
|
+
const now = opts.now ?? Date.now();
|
|
3718
|
+
const blobs = await store.list(`${sandboxId}/`);
|
|
3719
|
+
blobs.sort((a, b) => b.lastModified - a.lastModified);
|
|
3720
|
+
const doomed = blobs.slice(opts.retain).filter((b) => now - b.lastModified >= opts.minAgeMs).map((b) => b.key);
|
|
3721
|
+
await Promise.all(doomed.map((key) => store.delete(key)));
|
|
3722
|
+
return doomed;
|
|
3723
|
+
}
|
|
3724
|
+
/**
|
|
2588
3725
|
* Tar `CHECKPOINT_ROOT` (minus the default excludes) inside the sandbox, pull the bytes out
|
|
2589
3726
|
* byte-safe (`sb.readFileBytes()`, never `readFile()`'s UTF-8 path — a gzip tarball is not
|
|
2590
3727
|
* valid UTF-8), write them to `checkpointsDir`, and record `AgentCheckpointed` on the sandbox's
|
|
@@ -2605,26 +3742,59 @@ async function takeCheckpoint(sb, checkpointsDir, opts) {
|
|
|
2605
3742
|
const excludeArgs = [
|
|
2606
3743
|
...DEFAULT_CHECKPOINT_EXCLUDES.map((p) => `--exclude=${CHECKPOINT_ROOT}/${p}`),
|
|
2607
3744
|
...DEFAULT_CHECKPOINT_EXCLUDE_GLOBS.map((p) => `--exclude=*/${p}`),
|
|
3745
|
+
...DEFAULT_WORKSPACE_EXCLUDES.map((p) => `--exclude=${p}`),
|
|
2608
3746
|
...(opts.excludeGlobs ?? []).map((p) => `--exclude=${p}`)
|
|
2609
3747
|
];
|
|
2610
3748
|
try {
|
|
2611
|
-
await sb.exec(`tar czf ${tmpTarPath} -C / ${excludeArgs.join(" ")} ${CHECKPOINT_ROOT}`);
|
|
3749
|
+
await sb.exec(`tar czf ${tmpTarPath} -C / ${excludeArgs.join(" ")} ${CHECKPOINT_ROOT} $([ -d /${CHECKPOINT_WORKSPACE} ] && echo ${CHECKPOINT_WORKSPACE})`);
|
|
2612
3750
|
const bytes = await sb.readFileBytes(tmpTarPath);
|
|
2613
3751
|
const createdAt = Date.now();
|
|
2614
3752
|
const dir = join(checkpointsDir, sb.sandboxId);
|
|
2615
3753
|
await mkdir(dir, { recursive: true });
|
|
2616
3754
|
const snapshotRef = join(dir, `${opts.turn}-${createdAt}.tar.gz`);
|
|
2617
3755
|
await writeFile(snapshotRef, bytes);
|
|
3756
|
+
let remoteRef;
|
|
3757
|
+
let uploadError;
|
|
3758
|
+
const retain = opts.retain ?? 3;
|
|
3759
|
+
if (opts.blobStore) {
|
|
3760
|
+
const key = `${sb.sandboxId}/${opts.turn}-${createdAt}.tar.gz`;
|
|
3761
|
+
try {
|
|
3762
|
+
await opts.blobStore.put(key, snapshotRef);
|
|
3763
|
+
remoteRef = opts.blobStore.refOf(key);
|
|
3764
|
+
} catch (err) {
|
|
3765
|
+
uploadError = err instanceof Error ? err.message : String(err);
|
|
3766
|
+
log.warn("off-box upload failed -- the checkpoint stays on the host disk only", {
|
|
3767
|
+
sandboxId: sb.sandboxId,
|
|
3768
|
+
turn: opts.turn,
|
|
3769
|
+
error: uploadError
|
|
3770
|
+
});
|
|
3771
|
+
}
|
|
3772
|
+
}
|
|
2618
3773
|
await sb.emit(LedgerEvent.AgentCheckpointed, -1, {
|
|
2619
3774
|
turn: opts.turn,
|
|
2620
|
-
snapshotRef
|
|
3775
|
+
snapshotRef,
|
|
3776
|
+
...remoteRef ? { remoteRef } : {},
|
|
3777
|
+
...uploadError ? { uploadError } : {}
|
|
2621
3778
|
});
|
|
2622
3779
|
try {
|
|
2623
|
-
await pruneOldCheckpoints(dir,
|
|
3780
|
+
await pruneOldCheckpoints(dir, retain);
|
|
2624
3781
|
} catch {}
|
|
3782
|
+
if (opts.blobStore && remoteRef) try {
|
|
3783
|
+
await pruneRemoteCheckpoints(opts.blobStore, sb.sandboxId, {
|
|
3784
|
+
retain,
|
|
3785
|
+
minAgeMs: opts.remoteMinAgeMs ?? 6e5
|
|
3786
|
+
});
|
|
3787
|
+
} catch (err) {
|
|
3788
|
+
log.warn("off-box checkpoint pruning failed", {
|
|
3789
|
+
sandboxId: sb.sandboxId,
|
|
3790
|
+
error: err instanceof Error ? err.message : String(err)
|
|
3791
|
+
});
|
|
3792
|
+
}
|
|
2625
3793
|
return {
|
|
2626
3794
|
turn: opts.turn,
|
|
2627
3795
|
snapshotRef,
|
|
3796
|
+
remoteRef,
|
|
3797
|
+
uploadError,
|
|
2628
3798
|
createdAt
|
|
2629
3799
|
};
|
|
2630
3800
|
} finally {
|
|
@@ -2634,4 +3804,4 @@ async function takeCheckpoint(sb, checkpointsDir, opts) {
|
|
|
2634
3804
|
}
|
|
2635
3805
|
}
|
|
2636
3806
|
//#endregion
|
|
2637
|
-
export { AgentSnapshotStore, AgentSpecValidationError, Alineo, BridgeDisconnectedError, CHECKPOINT_ROOT, DEFAULT_CHECKPOINT_EXCLUDES, DEFAULT_CHECKPOINT_RETENTION, EgressApprovalGate, PromptTimeoutError, checkpointsPath, computeSetupHash, findLatestCheckpoint, isReadOnlyBashCommand, isSandboxGone, restoreCheckpoint, snapshotsPath, takeCheckpoint, textOnly, validateAgentSpec };
|
|
3807
|
+
export { AgentSnapshotStore, AgentSpecValidationError, Alineo, BridgeDisconnectedError, CHECKPOINT_ROOT, CLAUDE_CODE_CAPABILITIES, CODEX_CAPABILITIES, ClaudeCodeAdapter, CodexAdapter, DEFAULT_CHECKPOINT_EXCLUDES, DEFAULT_CHECKPOINT_RETENTION, DEFAULT_PROVIDER_ID, DEFAULT_REMOTE_PRUNE_MIN_AGE_MS, EgressApprovalGate, FakeHarness, MemoryBlobStore, PI_CAPABILITIES, PromptTimeoutError, S3BlobStore, checkpointsPath, computeSetupHash, createHarness, extractCheckpoint, fetchCheckpoint, findCheckpoints, findLatestCheckpoint, fromPiEvent, isReadOnlyBashCommand, isSandboxGone, pickRestorable, pruneRemoteCheckpoints, registeredHarnesses, requireHarnessCapability, restoreCheckpoint, snapshotsPath, takeCheckpoint, textOnly, validateAgentSpec };
|