@zvada/agent-server 0.3.24 → 0.3.25
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 +30 -0
- package/dist/client/client.js +93 -34
- package/dist/core/agents/scripted/scripted-agent.js +2 -1
- package/dist/core/agents/scripted/steps.js +1 -1
- package/dist/core/processes/identity.js +1 -0
- package/dist/core/processes/lifeline.js +9 -1
- package/dist/core/processes/process-table.js +1 -0
- package/dist/core/provision/extract.js +1 -0
- package/dist/core/runtime/agent-runtime.js +6 -3
- package/dist/core/runtime/turn.js +20 -10
- package/dist/protocol/credentials.js +2 -1
- package/dist/protocol/errors.js +12 -3
- package/dist/server/routes.js +3 -2
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/options.d.ts +4 -0
- package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/steps.d.ts +1 -1
- package/dist/types/core/processes/identity.d.ts.map +1 -1
- package/dist/types/core/processes/lifeline.d.ts.map +1 -1
- package/dist/types/core/processes/process-table.d.ts.map +1 -1
- package/dist/types/core/provision/extract.d.ts.map +1 -1
- package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
- package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/types/core/runtime/turn.d.ts +12 -7
- package/dist/types/core/runtime/turn.d.ts.map +1 -1
- package/dist/types/protocol/clis.d.ts +3 -3
- package/dist/types/protocol/conversation.d.ts +6 -6
- package/dist/types/protocol/credentials.d.ts +13 -1
- package/dist/types/protocol/credentials.d.ts.map +1 -1
- package/dist/types/protocol/errors.d.ts +6 -4
- package/dist/types/protocol/errors.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +4 -4
- package/dist/types/protocol/wire-api.d.ts +12 -12
- package/dist/types/protocol/wire.d.ts +8 -8
- package/dist/types/server/routes.d.ts.map +1 -1
- package/docs/consuming.md +26 -3
- package/docs/deploy.md +7 -0
- package/docs/harnesses.md +17 -4
- package/package.json +1 -1
- package/src/client/client.ts +114 -44
- package/src/core/agents/claude-code/options.ts +4 -0
- package/src/core/agents/scripted/scripted-agent.ts +2 -1
- package/src/core/agents/scripted/steps.ts +1 -1
- package/src/core/processes/identity.ts +1 -0
- package/src/core/processes/lifeline.ts +10 -1
- package/src/core/processes/process-table.ts +1 -0
- package/src/core/provision/extract.ts +1 -0
- package/src/core/runtime/agent-runtime.ts +6 -3
- package/src/core/runtime/turn.ts +21 -9
- package/src/protocol/credentials.ts +19 -5
- package/src/protocol/errors.ts +12 -3
- package/src/server/routes.ts +3 -2
package/docs/harnesses.md
CHANGED
|
@@ -145,6 +145,15 @@ the engine writes them (LLP 0001, D21; see
|
|
|
145
145
|
ACP server binding, a client's stdio and HTTP servers take the first path;
|
|
146
146
|
an SSE server or one named `codex_apps` is refused at `session/new` or
|
|
147
147
|
`session/resume`, naming it.
|
|
148
|
+
|
|
149
|
+
How long one MCP tool call may run is each agent's own, and the engine has
|
|
150
|
+
no field for it yet. Claude cuts a call to an HTTP server at 60 s: the tool
|
|
151
|
+
part fails with "The operation timed out." and the turn goes on. A stdio
|
|
152
|
+
server's call is not cut. `MCP_TOOL_TIMEOUT` (milliseconds) in the turn's
|
|
153
|
+
`env` lifts it (measured with `120000` and a 75 s tool). Codex cuts no call
|
|
154
|
+
by default (measured to 100 s); its own config has a
|
|
155
|
+
per-server `tool_timeout_sec`.
|
|
156
|
+
|
|
148
157
|
Below `inheritConfig: "all"` every Codex turn needs a home of its session's
|
|
149
158
|
own, so the bin refuses `--acp --harness codex-app-server` with
|
|
150
159
|
`--inherit-config project` or `none`.
|
|
@@ -651,7 +660,7 @@ refused when the script is read, never skipped.
|
|
|
651
660
|
| `{ echo: "input" }` | Says the turn's input as a model reads it (`inputToText`). |
|
|
652
661
|
| `{ echo: "config" }` | Says the turn's config as JSON: `model`, `thinkingLevel`, `cwd`, `additionalDirectories`, `systemPromptAppend`, `permissionMode`, the names of its MCP servers and the keys of its `env`, never their values. |
|
|
653
662
|
| `{ wait: ms }` | A pause; a cancel ends it. |
|
|
654
|
-
| `{ hang: true, stopTakes?: ms }` | Runs until the turn is cancelled; `stopTakes` ms more before it stops, as a harness slow to stop. The cancel is confirmed at once. |
|
|
663
|
+
| `{ hang: true, stopTakes?: ms }` | Runs until the turn is cancelled; `stopTakes` ms more before it stops, as a harness slow to stop, also when the cancel came before the hang began. The cancel is confirmed at once. |
|
|
655
664
|
| `{ fail: string, category? }` | Ends the turn in an error: of `category` when given, else what the engine's classifier makes of the text. |
|
|
656
665
|
| `{ end: true, stopReason?, usage?, cost? }` | Ends the turn: `end_turn` and zero usage by default. |
|
|
657
666
|
|
|
@@ -742,9 +751,13 @@ once. Unstable methods (`session/list`, `session/fork`, `session/delete`,
|
|
|
742
751
|
for Codex home ownership, supported transports, and live-update behavior.
|
|
743
752
|
- **Codex app-server threads have one writer** (CLI 0.160 and newer). A
|
|
744
753
|
thread still loaded by a live session cannot be resumed from another
|
|
745
|
-
process; the turn fails with `
|
|
746
|
-
writer")
|
|
747
|
-
|
|
754
|
+
process; the turn fails with `resume_busy` ("already has an active
|
|
755
|
+
writer"), and the same resume succeeds once the other process has let the
|
|
756
|
+
thread go. Close the first session (`session/close`) or let its process end
|
|
757
|
+
before resuming elsewhere. A thread that is gone fails `resume_failed` ("no
|
|
758
|
+
rollout found for thread id"): offer a fresh start for that one, not a
|
|
759
|
+
retry. Claude has no such case: its CLI takes no writer lock, so a
|
|
760
|
+
conversation is resumed or `resume_failed`.
|
|
748
761
|
- The **BYOK proxy** (`/core/proxy`) is a building block, not yet auto-wired
|
|
749
762
|
into the harnesses (they use ambient/explicit keys today).
|
|
750
763
|
- **Hook bridge** (PreToolUse/Stop decisions) is exposed for the claude
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zvada/agent-server",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.25",
|
|
4
4
|
"description": "Harness-agnostic agent execution engine: run Claude Code, Codex (app-server), and any ACP agent behind one interface with a normalized event stream, multi-turn sessions, and resume. Root export is the wire contract; /core, /server, /client are the seats.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/src/client/client.ts
CHANGED
|
@@ -121,6 +121,51 @@ function stopOn(handle: Handle, signal: AbortSignal | undefined): void {
|
|
|
121
121
|
void handle.result.then(off, off);
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
+
/** A `turn/start` this client has not sent yet: `gone` settles at its first send or its end. */
|
|
125
|
+
interface Start {
|
|
126
|
+
sessionId: string;
|
|
127
|
+
turnId: string;
|
|
128
|
+
gone: Promise<void>;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel sent right behind its start reaches the turn
|
|
132
|
+
/**
|
|
133
|
+
* The `turn/start`s this client has not sent yet, each from before its
|
|
134
|
+
* first `await` until its first send or its end. The server takes a
|
|
135
|
+
* connection's requests in order and admits a turn in its start's handler,
|
|
136
|
+
* so a cancel for one of their turns goes out after that first send. Once
|
|
137
|
+
* sent, a start delays no cancel: after a redial a cancel can overtake its
|
|
138
|
+
* re-send, and is answered `no_active_turn`. Before its first send a start
|
|
139
|
+
* waits only on the handshake, a request the client's close fails, so no
|
|
140
|
+
* cancel waits past the close.
|
|
141
|
+
*/
|
|
142
|
+
class Starts {
|
|
143
|
+
private readonly unsent = new Set<Start>();
|
|
144
|
+
|
|
145
|
+
/** Record a start; the function returned lets it go (its first send, or its end), and may be called again. */
|
|
146
|
+
begin(sessionId: string, turnId: string): () => void {
|
|
147
|
+
let settle = () => {};
|
|
148
|
+
const gone = new Promise<void>((resolve) => {
|
|
149
|
+
settle = resolve;
|
|
150
|
+
});
|
|
151
|
+
const start: Start = { sessionId, turnId, gone };
|
|
152
|
+
this.unsent.add(start);
|
|
153
|
+
return () => {
|
|
154
|
+
this.unsent.delete(start);
|
|
155
|
+
settle();
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** `send`, once no start of `turnId` (without one, of the session) is unsent; in the call when none is. */
|
|
160
|
+
after<T>(sessionId: string, turnId: string | undefined, send: () => Promise<T>): Promise<T> {
|
|
161
|
+
const waiting = [...this.unsent].filter(
|
|
162
|
+
(start) => start.sessionId === sessionId && (turnId === undefined || start.turnId === turnId),
|
|
163
|
+
);
|
|
164
|
+
if (waiting.length === 0) return send();
|
|
165
|
+
return Promise.all(waiting.map((start) => start.gone)).then(send);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
124
169
|
/** How often `prepareClis` asks again while an install runs, besides when one ends. */
|
|
125
170
|
const PREPARE_POLL_MS = 2_000;
|
|
126
171
|
|
|
@@ -136,6 +181,7 @@ const PREPARE_POLL_MS = 2_000;
|
|
|
136
181
|
export class AgentServerClient {
|
|
137
182
|
private readonly connection: Connection;
|
|
138
183
|
private readonly turns = new Turns();
|
|
184
|
+
private readonly starts = new Starts();
|
|
139
185
|
private readonly progress = new Listeners<HarnessCliProgress>();
|
|
140
186
|
private readonly authUpdates = new Listeners<AuthUpdated>();
|
|
141
187
|
private readonly streams: Streams;
|
|
@@ -270,41 +316,50 @@ export class AgentServerClient {
|
|
|
270
316
|
* it), and `onEvent` hears it to its end.
|
|
271
317
|
*/
|
|
272
318
|
async runTurn(params: TurnStartParams, options: FollowOptions = {}): Promise<TurnHandle> {
|
|
273
|
-
await this.initialize();
|
|
274
319
|
const sessionId = params.sessionId ?? generateUUIDv7();
|
|
275
320
|
const turnId = params.turnId ?? generateUUIDv7();
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const handle = this.turns.open(sessionId, turnId, true);
|
|
279
|
-
stopOn(handle, options.signal);
|
|
321
|
+
// Before the first `await`: a cancel sent right behind this call goes out after the start.
|
|
322
|
+
const release = this.starts.begin(sessionId, turnId);
|
|
280
323
|
try {
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
else
|
|
296
|
-
await this.catchUp(
|
|
297
|
-
handle,
|
|
298
|
-
accepted.deduplicated
|
|
299
|
-
? (accepted.startedSeq ?? accepted.headSeq + 1)
|
|
300
|
-
: accepted.headSeq + 1,
|
|
301
|
-
accepted.headSeq,
|
|
324
|
+
await this.initialize();
|
|
325
|
+
if (this.turns.running(sessionId))
|
|
326
|
+
throw new Error(`session ${sessionId} already has an active turn`);
|
|
327
|
+
const handle = this.turns.open(sessionId, turnId, true);
|
|
328
|
+
try {
|
|
329
|
+
stopOn(handle, options.signal);
|
|
330
|
+
// `resend` sends (or fails for no connection) before its first `await`, in this call.
|
|
331
|
+
const sending = this.connection.resend(
|
|
332
|
+
WIRE_METHODS.turnStart,
|
|
333
|
+
{ ...params, sessionId, turnId, subscribe: true },
|
|
334
|
+
// A turn that already ended streams nothing: its end is in the ack.
|
|
335
|
+
(ack) => {
|
|
336
|
+
if (!ack.terminal) this.joinAt(handle, ack.headSeq, { turnId });
|
|
337
|
+
},
|
|
302
338
|
);
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
339
|
+
release();
|
|
340
|
+
const accepted = await sending;
|
|
341
|
+
const { terminal } = accepted;
|
|
342
|
+
if (terminal && (terminal.sessionId !== sessionId || terminal.turnId !== turnId))
|
|
343
|
+
throw new Error("Turn receipt belongs to a different request");
|
|
344
|
+
// A retried start of a turn that already ended: its end, without its events
|
|
345
|
+
// (`replay` or `history` serve its transcript).
|
|
346
|
+
if (terminal) handle.push(terminal);
|
|
347
|
+
else
|
|
348
|
+
await this.catchUp(
|
|
349
|
+
handle,
|
|
350
|
+
accepted.deduplicated
|
|
351
|
+
? (accepted.startedSeq ?? accepted.headSeq + 1)
|
|
352
|
+
: accepted.headSeq + 1,
|
|
353
|
+
accepted.headSeq,
|
|
354
|
+
);
|
|
355
|
+
} catch (error) {
|
|
356
|
+
handle.fail(error);
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
return this.handleOf(handle);
|
|
360
|
+
} finally {
|
|
361
|
+
release();
|
|
306
362
|
}
|
|
307
|
-
return this.handleOf(handle);
|
|
308
363
|
}
|
|
309
364
|
|
|
310
365
|
/**
|
|
@@ -313,17 +368,26 @@ export class AgentServerClient {
|
|
|
313
368
|
* before.
|
|
314
369
|
*/
|
|
315
370
|
async startTurn(params: TurnStartParams): Promise<TurnStartResult> {
|
|
316
|
-
await this.initialize();
|
|
317
371
|
const sessionId = params.sessionId ?? generateUUIDv7();
|
|
318
372
|
const turnId = params.turnId ?? generateUUIDv7();
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
(
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
373
|
+
// As in `runTurn`: a cancel sent right behind this call goes out after the start.
|
|
374
|
+
const release = this.starts.begin(sessionId, turnId);
|
|
375
|
+
try {
|
|
376
|
+
await this.initialize();
|
|
377
|
+
// `request` sends (or fails for no connection) in this call.
|
|
378
|
+
const answer = this.connection.request(
|
|
379
|
+
WIRE_METHODS.turnStart,
|
|
380
|
+
{ ...params, sessionId, turnId },
|
|
381
|
+
(ack) => {
|
|
382
|
+
if (params.subscribe !== false && !ack.terminal)
|
|
383
|
+
this.streams.joined(sessionId, ack.headSeq, { turnId });
|
|
384
|
+
},
|
|
385
|
+
);
|
|
386
|
+
release();
|
|
387
|
+
return await answer;
|
|
388
|
+
} finally {
|
|
389
|
+
release();
|
|
390
|
+
}
|
|
327
391
|
}
|
|
328
392
|
|
|
329
393
|
/**
|
|
@@ -388,13 +452,19 @@ export class AgentServerClient {
|
|
|
388
452
|
* finished turn then returns `{outcome: "no_active_turn", activeTurnId}`
|
|
389
453
|
* instead of killing the turn that replaced it. `{outcome: "unconfirmed"}`
|
|
390
454
|
* means the harness did not acknowledge the interrupt — the agent may still
|
|
391
|
-
* be running; `turn.ended` remains the source of truth.
|
|
455
|
+
* be running; `turn.ended` remains the source of truth. A cancel for a
|
|
456
|
+
* turn this client is starting (`runTurn`, `startTurn`) goes out after
|
|
457
|
+
* that start's first send, so one sent right behind the start reaches the
|
|
458
|
+
* turn. After a reconnect a cancel can reach the server before a re-sent
|
|
459
|
+
* start, and is then answered `no_active_turn`.
|
|
392
460
|
*/
|
|
393
461
|
cancelTurn(sessionId: string, turnId?: string): Promise<TurnCancelResult> {
|
|
394
|
-
return this.
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
462
|
+
return this.starts.after(sessionId, turnId, () =>
|
|
463
|
+
this.connection.request(WIRE_METHODS.turnCancel, {
|
|
464
|
+
sessionId,
|
|
465
|
+
...(turnId !== undefined ? { turnId } : {}),
|
|
466
|
+
}),
|
|
467
|
+
);
|
|
398
468
|
}
|
|
399
469
|
|
|
400
470
|
/** Answer a `permission.requested` event. */
|
|
@@ -153,6 +153,10 @@ export interface ClaudeCodeAgentOptions {
|
|
|
153
153
|
* recorders — instead of re-deriving termination from side effects.
|
|
154
154
|
* NOTE: `replaced` sessions usually respawn immediately with context
|
|
155
155
|
* preserved; drop only resources bound to the dead subprocess.
|
|
156
|
+
* A cancel during a start answers at once; this callback for that
|
|
157
|
+
* process (`released`, as for a close) can come after the cancel's
|
|
158
|
+
* answer, and comes before that turn's end: set up the next turn's
|
|
159
|
+
* per-session resources after the turn's end, not the cancel's answer.
|
|
156
160
|
*/
|
|
157
161
|
onSessionEnd?: (sessionId: string, reason: ClaudeSessionEndReason) => void;
|
|
158
162
|
/** Operational diagnostics (interrupt timeouts). */
|
|
@@ -249,7 +249,8 @@ export class ScriptedAgent extends SessionAgent {
|
|
|
249
249
|
turn: { input: AgentInput; options: AgentExecuteOptions; signal: AbortSignal; calls: number },
|
|
250
250
|
): AsyncGenerator<ScriptedEvent, Played> {
|
|
251
251
|
const { options, signal } = turn;
|
|
252
|
-
|
|
252
|
+
// A hang takes its `stopTakes` whenever the cancel came: a product's test cancels without a sleep.
|
|
253
|
+
if (signal.aborted && !("hang" in step)) throw stopped();
|
|
253
254
|
if ("say" in step) yield { type: "text", text: step.say };
|
|
254
255
|
else if ("stream" in step) {
|
|
255
256
|
for (const [i, word] of words(step.stream).entries()) {
|
|
@@ -70,7 +70,7 @@ export const ScriptStepSchema = z.union([
|
|
|
70
70
|
z.strictObject({ echo: z.enum(["input", "config"]) }),
|
|
71
71
|
/** A pause of this many ms. */
|
|
72
72
|
z.strictObject({ wait: Ms }),
|
|
73
|
-
/** Runs until the turn is cancelled, then `stopTakes` ms more before it stops. */
|
|
73
|
+
/** Runs until the turn is cancelled, then `stopTakes` ms more before it stops, also when the cancel came first. */
|
|
74
74
|
z.strictObject({ hang: z.literal(true), stopTakes: Ms.optional() }),
|
|
75
75
|
/**
|
|
76
76
|
* Ends the turn in an error with this message: of `category` when given,
|
|
@@ -97,6 +97,7 @@ interface BunRuntime {
|
|
|
97
97
|
stdout: "ignore";
|
|
98
98
|
stderr: "ignore";
|
|
99
99
|
detached: boolean;
|
|
100
|
+
env: Record<string, string | undefined>;
|
|
100
101
|
onExit(): void;
|
|
101
102
|
},
|
|
102
103
|
): {
|
|
@@ -128,6 +129,10 @@ function startShell(ticks: string, exited: () => void, failed: () => void): Life
|
|
|
128
129
|
stdout: "ignore",
|
|
129
130
|
stderr: "ignore",
|
|
130
131
|
detached: true,
|
|
132
|
+
// @ref LLP 0007#the-environment-a-process-is-given — this process's environment now
|
|
133
|
+
// Without one, Bun gives the environment it was launched with: a
|
|
134
|
+
// secret the host deleted from `process.env` would live on here.
|
|
135
|
+
env: process.env,
|
|
131
136
|
onExit: exited,
|
|
132
137
|
});
|
|
133
138
|
child.unref();
|
|
@@ -142,7 +147,11 @@ function startShell(ticks: string, exited: () => void, failed: () => void): Life
|
|
|
142
147
|
};
|
|
143
148
|
}
|
|
144
149
|
// Node writes a pipe at once when it can (libuv's `uv_try_write`).
|
|
145
|
-
const child = spawn("/bin/sh", args, {
|
|
150
|
+
const child = spawn("/bin/sh", args, {
|
|
151
|
+
detached: true,
|
|
152
|
+
env: process.env,
|
|
153
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
154
|
+
});
|
|
146
155
|
child.unref();
|
|
147
156
|
(child.stdin as { unref?: () => void } | null)?.unref?.();
|
|
148
157
|
child.stdin?.on("error", () => {});
|
|
@@ -57,6 +57,7 @@ function linuxTable(): ProcessRow[] {
|
|
|
57
57
|
function psTable(): ProcessRow[] {
|
|
58
58
|
const out = execFileSync("/bin/ps", ["-axo", "pid=,ppid=,pgid=,stat="], {
|
|
59
59
|
encoding: "utf8",
|
|
60
|
+
env: process.env,
|
|
60
61
|
stdio: ["ignore", "pipe", "ignore"],
|
|
61
62
|
});
|
|
62
63
|
const rows: ProcessRow[] = [];
|
|
@@ -12,6 +12,7 @@ const EXTRACT_TIMEOUT_MS = 5 * 60_000;
|
|
|
12
12
|
export async function extractTarGz(tgzPath: string, destDir: string): Promise<void> {
|
|
13
13
|
await new Promise<void>((resolve, reject) => {
|
|
14
14
|
const proc = spawn("tar", ["-xzf", tgzPath, "-C", destDir], {
|
|
15
|
+
env: process.env,
|
|
15
16
|
stdio: ["ignore", "ignore", "pipe"],
|
|
16
17
|
timeout: EXTRACT_TIMEOUT_MS,
|
|
17
18
|
});
|
|
@@ -350,11 +350,14 @@ export class AgentRuntime {
|
|
|
350
350
|
* Cancel the session's in-flight turn. An idle session is a clean no-op ack
|
|
351
351
|
* (`{confirmed: true, hadTurn: false}`); `confirmed: false` means a turn
|
|
352
352
|
* existed but the harness did not acknowledge the interrupt — the agent may
|
|
353
|
-
* still be running; `turn.ended` remains the source of truth.
|
|
353
|
+
* still be running; `turn.ended` remains the source of truth. A turn
|
|
354
|
+
* admitted but not yet on its harness answers `hadTurn: false` too (the
|
|
355
|
+
* harness had nothing to interrupt), and still ends `cancelled`: the turn
|
|
356
|
+
* keeps the cancel, and its harness begins it stopped.
|
|
354
357
|
*/
|
|
355
358
|
async cancel(harness: AgentHarness, sessionId: string): Promise<CancelResult> {
|
|
356
|
-
//
|
|
357
|
-
// the agent-level abort.
|
|
359
|
+
// The turn keeps the cancel (its signal), and any harness parked on an
|
|
360
|
+
// approval is unblocked, before (and regardless of) the agent-level abort.
|
|
358
361
|
for (const turn of this.turnsOf(sessionId)) void turn.requestCancel();
|
|
359
362
|
return await this.registry.getAgent(harness).cancel(sessionId);
|
|
360
363
|
}
|
package/src/core/runtime/turn.ts
CHANGED
|
@@ -143,8 +143,14 @@ export class Turn {
|
|
|
143
143
|
private readonly processor: EventProcessor;
|
|
144
144
|
/** Its durable sink failed: the turn stops, and every later write fails with it. */
|
|
145
145
|
private sinkFailure?: EventSinkError;
|
|
146
|
-
/**
|
|
147
|
-
|
|
146
|
+
/**
|
|
147
|
+
* Aborted when `cancel` or `closeSession` asks the turn to stop: part of
|
|
148
|
+
* the signal its harness is given, so a cancel that comes before the
|
|
149
|
+
* harness has the turn is not lost.
|
|
150
|
+
*/
|
|
151
|
+
private readonly cancelled = new AbortController();
|
|
152
|
+
/** The caller's signal, the runtime's shutdown and the turn's own cancel, together. */
|
|
153
|
+
private readonly signal: AbortSignal;
|
|
148
154
|
private nativeSessionId?: string;
|
|
149
155
|
/** When the turn requested a resume: whether the harness honored it. */
|
|
150
156
|
private resumed?: boolean;
|
|
@@ -157,10 +163,11 @@ export class Turn {
|
|
|
157
163
|
readonly inputKey: string,
|
|
158
164
|
private readonly sink: EventSink,
|
|
159
165
|
/** The caller's signal and the runtime's shutdown, together. */
|
|
160
|
-
|
|
166
|
+
signal: AbortSignal,
|
|
161
167
|
private readonly host: TurnHost,
|
|
162
168
|
) {
|
|
163
169
|
const { sessionId, turnId, config } = request;
|
|
170
|
+
this.signal = AbortSignal.any([signal, this.cancelled.signal]);
|
|
164
171
|
this.sessionId = sessionId;
|
|
165
172
|
this.turnId = turnId;
|
|
166
173
|
this.harness = config.harness;
|
|
@@ -180,14 +187,19 @@ export class Turn {
|
|
|
180
187
|
this.running = Promise.resolve().then(() => this.execute());
|
|
181
188
|
}
|
|
182
189
|
|
|
190
|
+
// @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — a cancel before the harness has the turn
|
|
183
191
|
/**
|
|
184
|
-
* A cancel was asked for:
|
|
185
|
-
*
|
|
186
|
-
*
|
|
192
|
+
* A cancel was asked for: the turn's signal is aborted, so a harness that
|
|
193
|
+
* has not begun the turn yet begins it stopped; its open requests are
|
|
194
|
+
* answered as cancelled; and what the harness throws from now on is it
|
|
195
|
+
* stopping. Resolves once their `*.resolved` are written.
|
|
187
196
|
*/
|
|
188
197
|
requestCancel(): Promise<void> {
|
|
189
|
-
|
|
190
|
-
|
|
198
|
+
// Taken before the abort, which settles each request bound to the turn's
|
|
199
|
+
// signal and takes it out of the broker: the cancel would not wait for it.
|
|
200
|
+
const answered = this.requests.cancelAll();
|
|
201
|
+
this.cancelled.abort();
|
|
202
|
+
return answered;
|
|
191
203
|
}
|
|
192
204
|
|
|
193
205
|
private async execute(): Promise<RunSummary> {
|
|
@@ -253,7 +265,7 @@ export class Turn {
|
|
|
253
265
|
if (this.sinkFailure) throw this.sinkFailure;
|
|
254
266
|
// A harness asked to stop throws as it stops, whatever its words say;
|
|
255
267
|
// one that was not is failing.
|
|
256
|
-
threw = this.
|
|
268
|
+
threw = this.signal.aborted ? "cancelled" : errorInfo(error);
|
|
257
269
|
if (threw !== "cancelled") {
|
|
258
270
|
await this.emit({
|
|
259
271
|
type: "error",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { AccountInfoSchema } from "./account.ts";
|
|
3
|
-
import { AgentHarnessSchema } from "./harness.ts";
|
|
3
|
+
import { type AgentHarness, AgentHarnessSchema } from "./harness.ts";
|
|
4
4
|
|
|
5
5
|
const ApiKeySchema = z.object({
|
|
6
6
|
type: z.literal("api_key"),
|
|
@@ -60,13 +60,27 @@ const RUNS_ON = {
|
|
|
60
60
|
"codex-app-server": CodexCredentialSchema,
|
|
61
61
|
} as const;
|
|
62
62
|
|
|
63
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* The credential as the kind `harness` runs on, or why that harness cannot
|
|
65
|
+
* run it. Any harness may be asked, one only known at run time too: one that
|
|
66
|
+
* runs on no credential a product holds (ACP, scripted) answers why.
|
|
67
|
+
*/
|
|
64
68
|
export function credentialRunsOn<H extends keyof HarnessCredentials>(
|
|
65
69
|
harness: H,
|
|
66
70
|
credential: HarnessCredential,
|
|
67
|
-
): { ok: true; credential: HarnessCredentials[H] } | { ok: false; error: string }
|
|
68
|
-
|
|
69
|
-
|
|
71
|
+
): { ok: true; credential: HarnessCredentials[H] } | { ok: false; error: string };
|
|
72
|
+
export function credentialRunsOn(
|
|
73
|
+
harness: AgentHarness,
|
|
74
|
+
credential: HarnessCredential,
|
|
75
|
+
): { ok: true; credential: HarnessCredential } | { ok: false; error: string };
|
|
76
|
+
export function credentialRunsOn(
|
|
77
|
+
harness: AgentHarness,
|
|
78
|
+
credential: HarnessCredential,
|
|
79
|
+
): { ok: true; credential: HarnessCredential } | { ok: false; error: string } {
|
|
80
|
+
if (!Object.hasOwn(RUNS_ON, harness))
|
|
81
|
+
return { ok: false, error: `${harness} runs on no credential a product holds.` };
|
|
82
|
+
const parsed = RUNS_ON[harness as keyof HarnessCredentials].safeParse(credential);
|
|
83
|
+
if (parsed.success) return { ok: true, credential: parsed.data };
|
|
70
84
|
const what =
|
|
71
85
|
credential.type === "api_key" && credential.baseUrl
|
|
72
86
|
? "a key for another endpoint"
|
package/src/protocol/errors.ts
CHANGED
|
@@ -9,7 +9,9 @@ import { openVocabulary } from "./vocabulary.ts";
|
|
|
9
9
|
* unknown non-`_` values are reserved for this protocol.
|
|
10
10
|
* `usage_limit` (plan/quota exhausted) and `rate_limit` (429/backoff) are
|
|
11
11
|
* deliberately distinct — they need different user guidance; collapsing them
|
|
12
|
-
* is a display choice, never a wire merge.
|
|
12
|
+
* is a display choice, never a wire merge. So are `resume_failed` (the
|
|
13
|
+
* conversation is gone: offer a fresh start) and `resume_busy` (another
|
|
14
|
+
* process holds it now: try again once that one has let it go).
|
|
13
15
|
*/
|
|
14
16
|
export const ERROR_CATEGORIES = [
|
|
15
17
|
"auth",
|
|
@@ -22,6 +24,7 @@ export const ERROR_CATEGORIES = [
|
|
|
22
24
|
"invalid_request",
|
|
23
25
|
"process_exit",
|
|
24
26
|
"resume_failed",
|
|
27
|
+
"resume_busy",
|
|
25
28
|
"mcp_unavailable",
|
|
26
29
|
"server_restart",
|
|
27
30
|
"internal",
|
|
@@ -50,6 +53,8 @@ export type ErrorInfo = z.infer<typeof ErrorInfoSchema>;
|
|
|
50
53
|
* classifier; lives in /protocol because categories are vocabulary.
|
|
51
54
|
*/
|
|
52
55
|
const RULES: ReadonlyArray<[ErrorCategory, readonly string[]]> = [
|
|
56
|
+
// Codex 0.160 and newer: another app-server holds the thread warm.
|
|
57
|
+
["resume_busy", ["already has an active writer"]],
|
|
53
58
|
["resume_failed", ["no conversation found with session id", "no rollout found for thread id"]],
|
|
54
59
|
["abort", ["aborted", "aborterror", "cancelled", "canceled", "interrupted", "sigint"]],
|
|
55
60
|
[
|
|
@@ -142,13 +147,17 @@ export function classifyError(error: unknown): ErrorCategory {
|
|
|
142
147
|
return "internal";
|
|
143
148
|
}
|
|
144
149
|
|
|
145
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* A status code counts where it stands as a number of its own, never inside
|
|
152
|
+
* a longer number ("240129 tokens") or an identifier's alphanumeric run (a
|
|
153
|
+
* thread id's "-b401-" or "-a429-"): no letter or digit touches it.
|
|
154
|
+
*/
|
|
146
155
|
function mentions(message: string, needle: string): boolean {
|
|
147
156
|
if (!/\d$/.test(needle)) return message.includes(needle);
|
|
148
157
|
for (let at = message.indexOf(needle); at >= 0; at = message.indexOf(needle, at + 1)) {
|
|
149
158
|
const before = message[at - 1] ?? "";
|
|
150
159
|
const after = message[at + needle.length] ?? "";
|
|
151
|
-
if (
|
|
160
|
+
if (!/[a-z0-9]/.test(before) && !/[a-z0-9]/.test(after)) return true;
|
|
152
161
|
}
|
|
153
162
|
return false;
|
|
154
163
|
}
|
package/src/server/routes.ts
CHANGED
|
@@ -219,8 +219,9 @@ export function executionRoutes(host: RouteHost): Routes<ExecutionMethod> {
|
|
|
219
219
|
// running and `turn.ended` stays the source of truth. `hadTurn: false`
|
|
220
220
|
// while the server tracks an active turn is the pre-first-yield window
|
|
221
221
|
// (between the turn/start quick-ack and the harness registering its
|
|
222
|
-
// abortable turn)
|
|
223
|
-
//
|
|
222
|
+
// abortable turn): the turn keeps the cancel and its harness begins it
|
|
223
|
+
// stopped, but nothing has confirmed a stop yet, so it reports
|
|
224
|
+
// `unconfirmed`, never a clean cancel, and `turn.ended` says `cancelled`.
|
|
224
225
|
return {
|
|
225
226
|
outcome: confirmed && hadTurn ? "cancelled" : "unconfirmed",
|
|
226
227
|
turnId: active.turnId,
|