agent-neckbeard 1.1.28 → 1.1.29
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/CHANGELOG.md +5 -0
- package/README.md +3 -3
- package/dist/build.cjs +170 -15
- package/dist/build.d.cts +1 -1
- package/dist/build.d.ts +1 -1
- package/dist/build.js +3 -3
- package/dist/{chunk-JF5YPOBY.js → chunk-BPXEIXPM.js} +25 -1
- package/dist/{chunk-M7XNBKG4.js → chunk-FSBTLBB5.js} +1 -1
- package/dist/{chunk-M3FISP7J.js → chunk-YFG4EKZM.js} +146 -15
- package/dist/cli.cjs +170 -15
- package/dist/cli.js +3 -3
- package/dist/index.cjs +170 -15
- package/dist/index.d.cts +12 -3
- package/dist/index.d.ts +12 -3
- package/dist/index.js +2 -2
- package/dist/{serve-Dan1HQKN.d.ts → serve-Du2NCz9_.d.cts} +24 -2
- package/dist/{serve-Dan1HQKN.d.cts → serve-Du2NCz9_.d.ts} +24 -2
- package/dist/serve.cjs +143 -13
- package/dist/serve.d.cts +1 -1
- package/dist/serve.d.ts +1 -1
- package/dist/serve.js +1 -1
- package/docs/AGENT.md +39 -7
- package/package.json +1 -1
package/dist/serve.cjs
CHANGED
|
@@ -27,7 +27,7 @@ module.exports = __toCommonJS(serve_exports);
|
|
|
27
27
|
var import_node_http = require("http");
|
|
28
28
|
|
|
29
29
|
// src/turn-protocol.ts
|
|
30
|
-
var TURN_PROTOCOL_VERSION =
|
|
30
|
+
var TURN_PROTOCOL_VERSION = 3;
|
|
31
31
|
var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
|
|
32
32
|
var MAX_TURN_ID_LENGTH = 200;
|
|
33
33
|
function isRecord(value) {
|
|
@@ -101,6 +101,17 @@ function parseStartTurn(body) {
|
|
|
101
101
|
}
|
|
102
102
|
return { turnId, message, ...env === void 0 ? {} : { env } };
|
|
103
103
|
}
|
|
104
|
+
function parseSteerTurn(body) {
|
|
105
|
+
if (!body || typeof body !== "object") throw new RequestError(400, "Request body must be an object.");
|
|
106
|
+
const { steerId, message } = body;
|
|
107
|
+
if (typeof steerId !== "string" || !steerId || steerId.length > MAX_TURN_ID_LENGTH) {
|
|
108
|
+
throw new RequestError(400, `steerId must be a non-empty string of at most ${MAX_TURN_ID_LENGTH} characters.`);
|
|
109
|
+
}
|
|
110
|
+
if (typeof message !== "string" || !message.trim()) {
|
|
111
|
+
throw new RequestError(400, "message must be a non-empty string.");
|
|
112
|
+
}
|
|
113
|
+
return { steerId, message };
|
|
114
|
+
}
|
|
104
115
|
async function serve(options) {
|
|
105
116
|
const toWireEvent = options.toWireEvent ?? toPiJsonEvent;
|
|
106
117
|
let sessionPromise;
|
|
@@ -113,14 +124,85 @@ async function serve(options) {
|
|
|
113
124
|
turn.records.push(json);
|
|
114
125
|
for (const wake of turn.waiters) wake();
|
|
115
126
|
};
|
|
127
|
+
const reclaimSteers = (turn) => {
|
|
128
|
+
let left;
|
|
129
|
+
try {
|
|
130
|
+
left = turn.session?.clearQueue?.().steering.length ?? 0;
|
|
131
|
+
} catch {
|
|
132
|
+
left = turn.queuedSteers.length;
|
|
133
|
+
sessionPromise = void 0;
|
|
134
|
+
}
|
|
135
|
+
const leftover = left > 0 ? turn.queuedSteers.slice(-left) : [];
|
|
136
|
+
for (const steer of turn.queuedSteers) steer.state = leftover.includes(steer) ? "undelivered" : "delivered";
|
|
137
|
+
turn.queuedSteers = [];
|
|
138
|
+
turn.undeliveredSteers.push(...leftover);
|
|
139
|
+
};
|
|
116
140
|
const end = (turn, outcome, error) => {
|
|
117
|
-
if (turn.
|
|
118
|
-
|
|
119
|
-
turn.
|
|
141
|
+
if (turn.ending) return turn.ending;
|
|
142
|
+
turn.closed = true;
|
|
143
|
+
turn.sessionReady();
|
|
144
|
+
let written;
|
|
145
|
+
turn.ending = new Promise((resolve) => {
|
|
146
|
+
written = resolve;
|
|
147
|
+
});
|
|
148
|
+
reclaimSteers(turn);
|
|
149
|
+
void (async () => {
|
|
150
|
+
let timer;
|
|
151
|
+
const graceMs = turn.stopBy === void 0 ? options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS : Math.max(0, turn.stopBy - Date.now());
|
|
152
|
+
await Promise.race([
|
|
153
|
+
turn.steering,
|
|
154
|
+
new Promise((resolve) => {
|
|
155
|
+
timer = setTimeout(resolve, graceMs);
|
|
156
|
+
})
|
|
157
|
+
]);
|
|
158
|
+
clearTimeout(timer);
|
|
159
|
+
reclaimSteers(turn);
|
|
160
|
+
const undeliveredSteerIds = turn.undeliveredSteers.filter((steer) => !steer.late).map((steer) => steer.id);
|
|
161
|
+
append(turn, {
|
|
162
|
+
type: "end",
|
|
163
|
+
outcome,
|
|
164
|
+
...error === void 0 ? {} : { error },
|
|
165
|
+
...undeliveredSteerIds.length > 0 ? { undeliveredSteerIds } : {}
|
|
166
|
+
});
|
|
167
|
+
turn.ended = true;
|
|
168
|
+
written();
|
|
169
|
+
})();
|
|
170
|
+
return turn.ending;
|
|
171
|
+
};
|
|
172
|
+
const acceptSteer = (turn, id, message) => {
|
|
173
|
+
const steer = { id, state: "pending", late: false, settled: Promise.resolve() };
|
|
174
|
+
steer.settled = turn.steering.then(async () => {
|
|
175
|
+
const session = turn.session;
|
|
176
|
+
if (turn.closed || !session?.steer || !session.clearQueue) {
|
|
177
|
+
steer.state = "undelivered";
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
if (await session.steer(message) === "handled") {
|
|
182
|
+
steer.state = "handled";
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
steer.state = "queued";
|
|
186
|
+
turn.queuedSteers.push(steer);
|
|
187
|
+
if (turn.closed) {
|
|
188
|
+
reclaimSteers(turn);
|
|
189
|
+
steer.late = turn.undeliveredSteers.includes(steer);
|
|
190
|
+
}
|
|
191
|
+
} catch (error) {
|
|
192
|
+
steer.state = "failed";
|
|
193
|
+
steer.error = error;
|
|
194
|
+
turn.steers.delete(id);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
turn.steering = steer.settled;
|
|
198
|
+
turn.steers.set(id, steer);
|
|
199
|
+
return steer;
|
|
120
200
|
};
|
|
121
201
|
const endAfterGrace = (turn, outcome, error) => {
|
|
122
|
-
if (turn.
|
|
123
|
-
|
|
202
|
+
if (turn.ending || turn.finishing || turn.forceEnd) return;
|
|
203
|
+
const graceMs = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS;
|
|
204
|
+
turn.stopBy = Date.now() + graceMs;
|
|
205
|
+
turn.forceEnd = setTimeout(() => void end(turn, outcome, error), graceMs);
|
|
124
206
|
};
|
|
125
207
|
const runTurn = async (turn, request) => {
|
|
126
208
|
const previousEnv = /* @__PURE__ */ new Map();
|
|
@@ -130,18 +212,21 @@ async function serve(options) {
|
|
|
130
212
|
const timeoutMessage = `Turn exceeded ${options.maxTurnDurationMs}ms.`;
|
|
131
213
|
const timer = options.maxTurnDurationMs === void 0 ? void 0 : setTimeout(() => {
|
|
132
214
|
timedOut = true;
|
|
215
|
+
turn.closed = true;
|
|
216
|
+
reclaimSteers(turn);
|
|
133
217
|
if (session) void session.abort().catch(() => void 0);
|
|
134
218
|
endAfterGrace(turn, "failed", timeoutMessage);
|
|
135
219
|
}, options.maxTurnDurationMs);
|
|
136
220
|
const finish = async (outcome, error) => {
|
|
137
221
|
turn.finishing = true;
|
|
222
|
+
turn.closed = true;
|
|
138
223
|
if (timer) clearTimeout(timer);
|
|
139
224
|
clearTimeout(turn.forceEnd);
|
|
140
225
|
try {
|
|
141
226
|
await session?.afterTurn?.();
|
|
142
227
|
} catch {
|
|
143
228
|
}
|
|
144
|
-
end(turn, outcome, error);
|
|
229
|
+
await end(turn, outcome, error);
|
|
145
230
|
};
|
|
146
231
|
try {
|
|
147
232
|
sessionPromise ??= options.createSession();
|
|
@@ -152,26 +237,34 @@ async function serve(options) {
|
|
|
152
237
|
throw error;
|
|
153
238
|
}
|
|
154
239
|
if (timedOut) {
|
|
155
|
-
end(turn, "failed", timeoutMessage);
|
|
240
|
+
await end(turn, "failed", timeoutMessage);
|
|
156
241
|
return;
|
|
157
242
|
}
|
|
158
243
|
const started = session;
|
|
244
|
+
turn.session = session;
|
|
159
245
|
for (const [name, value] of Object.entries(request.env ?? {})) {
|
|
160
246
|
previousEnv.set(name, process.env[name]);
|
|
161
247
|
process.env[name] = value;
|
|
162
248
|
}
|
|
163
249
|
unsubscribe = session.subscribe((event) => {
|
|
164
|
-
if (turn.
|
|
250
|
+
if (turn.ending) return;
|
|
165
251
|
try {
|
|
166
252
|
append(turn, { type: "event", event: toWireEvent(event) });
|
|
167
253
|
} catch (error) {
|
|
168
|
-
end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
254
|
+
void end(turn, "failed", `Could not convert an agent event: ${error instanceof Error ? error.message : String(error)}`);
|
|
169
255
|
void started.abort().catch(() => void 0);
|
|
170
256
|
}
|
|
171
257
|
});
|
|
172
258
|
currentSessionAbort = () => started.abort();
|
|
259
|
+
turn.sessionReady();
|
|
260
|
+
if (!turn.closed) await turn.steering;
|
|
261
|
+
if (turn.ending) return;
|
|
262
|
+
if (timedOut) {
|
|
263
|
+
await end(turn, "failed", timeoutMessage);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
173
266
|
if (turn.abortRequested) {
|
|
174
|
-
end(turn, "aborted");
|
|
267
|
+
await end(turn, "aborted");
|
|
175
268
|
return;
|
|
176
269
|
}
|
|
177
270
|
await started.prompt(request.message);
|
|
@@ -184,8 +277,13 @@ async function serve(options) {
|
|
|
184
277
|
} finally {
|
|
185
278
|
if (timer) clearTimeout(timer);
|
|
186
279
|
clearTimeout(turn.forceEnd);
|
|
280
|
+
turn.closed = true;
|
|
281
|
+
turn.sessionReady();
|
|
282
|
+
await turn.ending;
|
|
187
283
|
unsubscribe?.();
|
|
188
284
|
currentSessionAbort = void 0;
|
|
285
|
+
await turn.steering;
|
|
286
|
+
reclaimSteers(turn);
|
|
189
287
|
for (const [name, value] of previousEnv) {
|
|
190
288
|
if (value === void 0) delete process.env[name];
|
|
191
289
|
else process.env[name] = value;
|
|
@@ -200,12 +298,21 @@ async function serve(options) {
|
|
|
200
298
|
if (current && !current.settled) {
|
|
201
299
|
return { status: 409, body: { error: "Another turn is running.", turnId: current.id } };
|
|
202
300
|
}
|
|
301
|
+
let sessionReady;
|
|
203
302
|
const turn = {
|
|
204
303
|
id: request.turnId,
|
|
205
304
|
records: [],
|
|
206
305
|
ended: false,
|
|
207
306
|
settled: false,
|
|
208
307
|
abortRequested: false,
|
|
308
|
+
steers: /* @__PURE__ */ new Map(),
|
|
309
|
+
queuedSteers: [],
|
|
310
|
+
undeliveredSteers: [],
|
|
311
|
+
steering: new Promise((resolve) => {
|
|
312
|
+
sessionReady = resolve;
|
|
313
|
+
}),
|
|
314
|
+
sessionReady: () => sessionReady(),
|
|
315
|
+
closed: false,
|
|
209
316
|
finishing: false,
|
|
210
317
|
waiters: /* @__PURE__ */ new Set()
|
|
211
318
|
};
|
|
@@ -270,7 +377,7 @@ data: ${turn.records[next]}
|
|
|
270
377
|
const server = (0, import_node_http.createServer)((request, response) => {
|
|
271
378
|
void (async () => {
|
|
272
379
|
const url = new URL(request.url ?? "/", "http://localhost");
|
|
273
|
-
const turnPath = /^\/turns\/([^/]+)\/(events|abort)$/u.exec(url.pathname);
|
|
380
|
+
const turnPath = /^\/turns\/([^/]+)\/(events|abort|steer)$/u.exec(url.pathname);
|
|
274
381
|
if (request.method === "GET" && url.pathname === "/health") {
|
|
275
382
|
const health = {
|
|
276
383
|
ok: true,
|
|
@@ -296,13 +403,36 @@ data: ${turn.records[next]}
|
|
|
296
403
|
return streamTurn(turn, after, request, response);
|
|
297
404
|
}
|
|
298
405
|
if (request.method === "POST" && turnPath[2] === "abort") {
|
|
299
|
-
if (!turn.
|
|
406
|
+
if (!turn.ending && !turn.finishing && !turn.abortRequested) {
|
|
300
407
|
turn.abortRequested = true;
|
|
408
|
+
turn.closed = true;
|
|
409
|
+
reclaimSteers(turn);
|
|
301
410
|
if (turn === current) void currentSessionAbort?.().catch(() => void 0);
|
|
302
411
|
endAfterGrace(turn, "aborted");
|
|
303
412
|
}
|
|
304
413
|
return sendJson(response, 202, { turnId: turn.id, ended: turn.ended });
|
|
305
414
|
}
|
|
415
|
+
if (request.method === "POST" && turnPath[2] === "steer") {
|
|
416
|
+
const { steerId, message } = parseSteerTurn(await readJsonBody(request));
|
|
417
|
+
const known = turn.steers.get(steerId);
|
|
418
|
+
if (!known && (turn !== current || turn.closed)) {
|
|
419
|
+
return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
|
|
420
|
+
}
|
|
421
|
+
const steer = known ?? acceptSteer(turn, steerId, message);
|
|
422
|
+
await steer.settled;
|
|
423
|
+
if (steer.state === "failed") throw steer.error;
|
|
424
|
+
if (steer.state === "undelivered" && !turn.closed) {
|
|
425
|
+
return sendJson(response, 501, { error: "The session does not take steering messages." });
|
|
426
|
+
}
|
|
427
|
+
if (steer.late || steer.state === "undelivered") {
|
|
428
|
+
return sendJson(response, 409, { error: "The turn is no longer running.", turnId: turn.id });
|
|
429
|
+
}
|
|
430
|
+
return sendJson(response, known ? 200 : 202, {
|
|
431
|
+
turnId: turn.id,
|
|
432
|
+
steerId,
|
|
433
|
+
...steer.state === "handled" ? { handled: true } : {}
|
|
434
|
+
});
|
|
435
|
+
}
|
|
306
436
|
}
|
|
307
437
|
sendJson(response, 404, { error: "Not found." });
|
|
308
438
|
})().catch((error) => {
|
package/dist/serve.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { d as ServeHandle, h as ServeOptions, c as ServedSession, f as TurnOutcome, T as TurnRecord, s as serve, t as toPiJsonEvent } from './serve-Du2NCz9_.cjs';
|
package/dist/serve.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { d as ServeHandle, h as ServeOptions, c as ServedSession, f as TurnOutcome, T as TurnRecord, s as serve, t as toPiJsonEvent } from './serve-Du2NCz9_.js';
|
package/dist/serve.js
CHANGED
package/docs/AGENT.md
CHANGED
|
@@ -9,7 +9,7 @@ This replaces `LegacyBundledAgent`, which bundles the agent's code on the host a
|
|
|
9
9
|
`defineAgent()` describes an agent once, in one module: its image, its sandbox, and its Pi session. Your process imports it to start sandboxes and run turns; `neckbeard build` bundles the same module as the image's entry point, which serves the session.
|
|
10
10
|
|
|
11
11
|
```ts
|
|
12
|
-
//
|
|
12
|
+
// agent.ts
|
|
13
13
|
import { defineAgent } from "agent-neckbeard";
|
|
14
14
|
import type { JsonAgentSessionEvent } from "@earendil-works/pi-coding-agent";
|
|
15
15
|
|
|
@@ -38,7 +38,7 @@ export const myAgent = defineAgent<JsonAgentSessionEvent>({
|
|
|
38
38
|
- `cwd`, relative to the sandbox user's home unless absolute (default `workspace`), is created before the session and exported as `NECKBEARD_CWD`, so the agent's scripts can find it.
|
|
39
39
|
- `persist` keeps the conversation in `~/agent/.pi/sessions/<sessionId>.jsonl`, for the `sessionId` passed to `start()`, so a restarted runtime, or a sandbox restored from a copy of that file, continues it. `sessionFilePath(homeDir, sessionId)` gives the path for copying it out and back. Otherwise the conversation lives in memory as long as the sandbox.
|
|
40
40
|
|
|
41
|
-
For a session that config can't express, pass `createSession` instead of `pi`, returning anything with Pi's `subscribe`, `prompt`, and `abort`, and optionally `afterTurn()`, which runs once each turn's outcome is known, before its `end` record and outside its deadline, as to send traces; an abort that arrives meanwhile changes nothing. Keep it bounded, since it delays the `end` record. A definition needs exactly one of them.
|
|
41
|
+
For a session that config can't express, pass `createSession` instead of `pi`, returning anything with Pi's `subscribe`, `prompt`, and `abort`, optionally `steer` and `clearQueue`, both or neither, for steering, and optionally `afterTurn()`, which runs once each turn's outcome is known, before its `end` record and outside its deadline, as to send traces; an abort that arrives meanwhile changes nothing. Keep it bounded, since it delays the `end` record. A definition needs exactly one of them.
|
|
42
42
|
|
|
43
43
|
### Tracing
|
|
44
44
|
|
|
@@ -65,7 +65,7 @@ A host runs `<registry>/<name>:<tag>`, where the tag is the first of these set:
|
|
|
65
65
|
From the agent's package, after logging in to the registry:
|
|
66
66
|
|
|
67
67
|
```sh
|
|
68
|
-
npx neckbeard push
|
|
68
|
+
npx neckbeard push agent.ts [--export <name>] [--tag <tag>]... [--cache] [--dry-run]
|
|
69
69
|
```
|
|
70
70
|
|
|
71
71
|
`push` writes the image's build context, as `neckbeard build` does, to a temporary directory it removes afterwards, so the package needn't ignore it, and builds it for `linux/amd64`, which every provider runs, with the package's `sandbox/Dockerfile` (`build.dockerfile`) and `docker build`, tagged `<registry>/<name>:<tag>` for each `--tag` (default: `resolveImageTag()`, so `GITHUB_SHA` in a GitHub workflow). It then pushes each tag, and readies each for its provider: on Daytona it builds the tag's snapshot, on E2B its template, again even when one exists, since a tag such as `master` may now name new contents, and deletes older ones, keeping three in all and never one this push built (`prepare({ refresh: true })` and `gc({ keep: 3, alsoKeep })`), so no sandbox start waits on a build. Modal pulls the image itself, and [keeps a tag's contents once pulled](https://modal.com/docs/guide/sandboxes#separating-image-builds-from-sandbox-creation), so a reused tag such as `master` can't be refreshed there: a Modal host should run an immutable tag, as a deployed host running its commit does, and `push` says so for each later tag of a Modal agent. That needs the provider's credentials, such as `DAYTONA_API_KEY`, and whatever the definition's `sandbox` function reads. `--cache` builds with `docker buildx`, reusing and updating layers cached in the registry under the image's `buildcache` tag. `--dry-run` builds without pushing or preparing, as for a pull request. `--export` picks the agent when the module exports several; by default it is the default export or the module's only agent. `pushAgent()` from `agent-neckbeard/build` does the same. A workflow:
|
|
@@ -74,12 +74,12 @@ npx neckbeard push src/agent.ts [--export <name>] [--tag <tag>]... [--cache] [--
|
|
|
74
74
|
- uses: docker/setup-buildx-action@v3
|
|
75
75
|
- uses: docker/login-action@v3
|
|
76
76
|
with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
|
|
77
|
-
- run: npx neckbeard push
|
|
77
|
+
- run: npx neckbeard push agent.ts --tag ${{ github.sha }} --tag latest --cache ${{ github.event_name == 'pull_request' && '--dry-run' || '' }}
|
|
78
78
|
working-directory: packages/my-agent
|
|
79
79
|
env: { DAYTONA_API_KEY: "${{ secrets.DAYTONA_API_KEY }}" }
|
|
80
80
|
```
|
|
81
81
|
|
|
82
|
-
`neckbeard build
|
|
82
|
+
`neckbeard build agent.ts [--export <name>] [--out dist-sandbox]` writes only the build context, for inspecting it. It replaces `dist-sandbox/`, or `--out`, with three things. It refuses an output directory that holds the package or its module, or that is not empty and was not written by an earlier build.
|
|
83
83
|
|
|
84
84
|
- `agent.mjs`: the module, bundled with an entry point that calls the agent's `serve()`. Pi's packages (`@earendil-works/*`), Braintrust for a `pi` agent whose package depends on it, the host-only provider SDKs, and each package in the definition's `build.external` stay out of the bundle, for ones that load native modules or wasm or otherwise must be installed. The build loads the module on the host to read its definition, so its top level must not need the image.
|
|
85
85
|
- `package.json`: those packages, each pinned to the version its importer resolves, as Node will in the image. The build fails when the bundle imports one package at two versions.
|
|
@@ -133,6 +133,7 @@ Every method takes the sandbox ID, so a host process that restarts, or another o
|
|
|
133
133
|
| `run(sandboxId, turn, { onRecord, signal })` | Runs a turn to its end, passing each record to `onRecord`, and returns the last assistant message's text; throws `ExecutionError` when the turn doesn't complete. Calling it again with the same `turnId` resumes the turn and replays its records from the start, so store them keyed by `seq` |
|
|
134
134
|
| `events(sandboxId, turnId, { after, signal })` | Resumes a turn's records after `after`. Throws `TurnLostError` when the runtime no longer has the turn |
|
|
135
135
|
| `abort(sandboxId, turnId)` | Stops the turn; its stream ends with an `aborted` record |
|
|
136
|
+
| `steer(sandboxId, turnId, { steerId, message })` | Queues a message for the running turn, which Pi takes after its current tool calls and before its next model call, where it shows in the stream as a user message. Returns `true` once the session has queued it, and `false` when the turn can no longer take it, so the caller can send the message as a turn of its own. Throws when queueing failed; calling again with the same `steerId` is safe. See [Steering](#steering) |
|
|
136
137
|
| `health`, `waitForIdle` | Whether a turn is running |
|
|
137
138
|
| `sandbox(sandboxId)` | A `SandboxClient` for files and commands, for staging inputs or reading results |
|
|
138
139
|
| `kill(sandboxId)` | Deletes the sandbox without starting it. One that is gone counts as deleted; any other failure throws, so cleanup can be retried, since a Daytona sandbox without `autoDeleteInterval` never expires |
|
|
@@ -157,14 +158,45 @@ The hash covers the image reference, the command (Daytona), and the resources, s
|
|
|
157
158
|
|
|
158
159
|
## Turn protocol
|
|
159
160
|
|
|
160
|
-
`serve()` speaks protocol version
|
|
161
|
+
`serve()` speaks protocol version 3 over HTTP, behind each provider's endpoint auth (`TURN_PROTOCOL_VERSION`; types in `src/turn-protocol.ts`).
|
|
161
162
|
|
|
162
163
|
- `GET /health` returns `{ ok, protocolVersion, busy, turnId }`. `busy` stays true until the turn's prompt has returned and its `env` is restored, which can be after its `end` record, as when an event fails to convert and the prompt is still stopping. `start()` rejects a runtime with another protocol version.
|
|
163
164
|
- `POST /turns` with `{ turnId, message, env? }` starts a turn and returns 202. A known `turnId`, the current or previous turn, returns 200 without starting anything; another turn while one is busy returns 409. `env` is set in `process.env` for the turn and restored after it.
|
|
164
165
|
- `GET /turns/:turnId/events?after=<seq>` opens with an SSE comment, streams the turn's records after `seq`, then live records with a heartbeat comment every 15 seconds, and closes after the `end` record. A reader already past the end of an ended turn gets the `end` record again, so it can tell the turn ended from a dropped stream. Unknown turns return 404.
|
|
165
166
|
- `POST /turns/:turnId/abort` returns 202 and aborts the session's prompt. Pi waits for a running tool before its prompt returns, so a turn that is aborted, or exceeds `maxTurnDurationMs` (which counts from the turn's start, creating the session included), and hasn't stopped within `serve()`'s `abortGraceMs` (10 seconds) gets its end record anyway. `busy` stays true until the prompt does return.
|
|
167
|
+
- `POST /turns/:turnId/steer` with `{ steerId, message }` hands the session a message for the turn that is running. See [Steering](#steering) for what each answer promises.
|
|
166
168
|
|
|
167
|
-
A record is `{ seq, type: "event", event }` or `{ seq, type: "end", outcome: "completed" | "aborted" | "failed", error? }`. `seq` starts at 0 for each turn and increases by one, and the runtime serializes each record when it is written, so a replay of a `seq` sends exactly what streamed live, and a host can store records keyed by `seq` and ignore repeats. The runtime keeps the current and previous turns in memory. A runtime that restarts, or a replaced sandbox, loses them, and a resume then fails with `TurnLostError`.
|
|
169
|
+
A record is `{ seq, type: "event", event }` or `{ seq, type: "end", outcome: "completed" | "aborted" | "failed", error?, undeliveredSteerIds? }`. `seq` starts at 0 for each turn and increases by one, and the runtime serializes each record when it is written, so a replay of a `seq` sends exactly what streamed live, and a host can store records keyed by `seq` and ignore repeats. The runtime keeps the current and previous turns in memory. A runtime that restarts, or a replaced sandbox, loses them, and a resume then fails with `TurnLostError`.
|
|
170
|
+
|
|
171
|
+
### Steering
|
|
172
|
+
|
|
173
|
+
A steer is a message for one turn. The runtime gives each steer exactly one outcome, by its `steerId`, and never lets one reach a later turn.
|
|
174
|
+
|
|
175
|
+
**What the answer means.** The request is answered once the session has finished queueing the message, which may take a while when Pi runs input hooks first.
|
|
176
|
+
|
|
177
|
+
| Status | Meaning | What the caller does |
|
|
178
|
+
|---|---|---|
|
|
179
|
+
| 202 | The session queued the message for this turn. It is not delivered yet. With `handled: true`, an input hook took the message instead of queueing it, and nothing more happens to it | Wait for the turn's records |
|
|
180
|
+
| 200 | A repeat of a steer this turn already has. It got the same outcome as the first request, which this one waited for | The same |
|
|
181
|
+
| 409 | The turn is not taking steers: it has ended, is stopping, its prompt has returned, or it stopped taking them while this one was being queued and the runtime took the message back out of the queue. The message will not be delivered | Send it as a turn of its own |
|
|
182
|
+
| 500 | Queueing threw, as when Pi rejects an extension command. The steer is forgotten | Retry with the same `steerId`, or give up |
|
|
183
|
+
| 501 | The session has no `steer()`, or no `clearQueue()` to take an untaken steer back with | |
|
|
184
|
+
|
|
185
|
+
**What happens to a queued steer.** One of two things, and the turn's records say which. Either Pi delivers it, and it appears in the stream as a user `message_start` event; Pi does that after its current tool calls, or as a further run of the same prompt when the model had already answered. Or the turn ends first and its `end` record names it in `undeliveredSteerIds`; the runtime has taken it back out of the session's queue, so nothing will act on it, and the caller decides what becomes of it. A steer is never both, and never neither.
|
|
186
|
+
|
|
187
|
+
**Order.** Steers are queued one at a time, in the order their requests arrived, starting once the session exists. An abort or the turn's deadline closes the turn to new steers at once, takes back the ones still queued before asking the session to stop, and never starts a prompt that had not started. A turn that ends any other way while its prompt is still stopping, as when an event fails to convert, takes them back the same way. The `end` record is written only after every steer being queued has settled, or after `abortGraceMs` if one is stuck in a hook, which for a turn that was told to stop is the same grace period its prompt gets, not a second one; the runtime stays `busy`, with the turn's `env` still set, until that one settles, and drops it then. If the session's `clearQueue()` throws, the runtime can't tell what is left, so it names every steer still queued as undelivered and creates a new session for the next turn.
|
|
188
|
+
|
|
189
|
+
**Retries.** `steerId` is the idempotency key, for as long as the runtime keeps the turn (the current and previous ones). A repeat never queues the message twice: while the first request is in flight it waits for it, and afterwards it reports the steer's outcome, 200 for one that was delivered and 409 for one that was not.
|
|
190
|
+
|
|
191
|
+
Where this follows others and where it does not:
|
|
192
|
+
|
|
193
|
+
- The answer means queued, not delivered, and delivery is a separate signal in the stream, as in Pi's own RPC mode (`queue_update`), Codex (`turn/steer`), Trigger.dev and OpenCode. Holding the request until delivery, as the Agent Client Protocol's v2 draft and the Vercel AI SDK's `steer()` do, would keep a request open through a sandbox tunnel for as long as a tool runs.
|
|
194
|
+
- Every accepted steer is settled exactly once and the leftovers are handed back when the turn ends, as pi-durable settles each submission `done` or `unanswered` and the AI SDK resolves each steer delivered or not. Pi itself leaves a leftover in its queue, where the next prompt picks it up.
|
|
195
|
+
- A steer that is too late is refused rather than promoted, as Codex refuses one whose `expectedTurnId` is not the active turn. Most products make it the next turn themselves; here the caller owns the queue of turns, so the caller does that.
|
|
196
|
+
- An abort takes back the queued steers first, which is what Pi documents for its own hosts ("send `clear_queue` before `abort`") and what its terminal UI does. Pi's `abort()` alone leaves them: one may be written into the stopped turn unanswered, or wait for the next prompt, depending on when the abort lands.
|
|
197
|
+
- A repeat attaches to the original and shares its outcome, as a Temporal Update with a known ID does, rather than answering 409 while the first is in flight as Stripe's idempotency keys do, so a caller needs no retry loop.
|
|
198
|
+
|
|
199
|
+
Delivered steers are told from undelivered ones by position: Pi takes its queue oldest first and identifies messages only by their text, so the ones left are the last ones the session queued. The runtime is therefore only as exact as the session's own count of its queue. Pi keeps that count by text, so a steer with the same text as the turn's own message can drop out of it before Pi delivers the steer; if the turn is then stopped, that steer counts as delivered. A custom `toWireEvent` that throws on the queue update Pi emits while it queues a steer has the same effect on that steer.
|
|
168
200
|
|
|
169
201
|
## Limits
|
|
170
202
|
|