@operad-io/harness-codex 0.1.1 → 0.3.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.
@@ -0,0 +1,585 @@
1
+ /**
2
+ * A small client for Codex's own `codex app-server`: JSON-RPC 2.0, one message
3
+ * per line, on the app-server's stdio (ADR 0022 D3, D8). The protocol was read
4
+ * from the installed Codex: `codex app-server generate-ts` and
5
+ * `codex app-server generate-json-schema` (codex-cli 0.166.0).
6
+ *
7
+ * The client is a state machine, not a process owner. `runAgent` starts
8
+ * `codex app-server` and hands each stdout line to `handleLine`; the client
9
+ * answers through the `reply` function `runAgent` gives it. `first` is the
10
+ * `initialize` request, which the caller passes as the run's stdin.
11
+ *
12
+ * The run is: `initialize`, `initialized`, then `thread/start` (or
13
+ * `thread/resume` when a session is resumed), then `turn/start`. The item
14
+ * stream goes to `onNotification` while the turn runs. Approval requests go to
15
+ * `onPermission`. `cancel` sends `turn/interrupt`; `steer` sends `turn/steer`.
16
+ * `ended` settles once with how the turn ended, or with the stage that failed.
17
+ *
18
+ * The client keeps no timers: how long a silent agent may be silent is the
19
+ * caller's `stallMs` and `wallMs` of `runAgent`.
20
+ */
21
+
22
+ import { isRecord } from "@operad-io/engine";
23
+
24
+ /** The token counts of one turn, as Codex reports them. */
25
+ export interface AppServerUsage {
26
+ readonly totalTokens?: number;
27
+ readonly inputTokens?: number;
28
+ readonly outputTokens?: number;
29
+ readonly cachedReadTokens?: number;
30
+ readonly cachedWriteTokens?: number;
31
+ readonly thoughtTokens?: number;
32
+ /** The model's context window when the app-server reports it. */
33
+ readonly modelContextWindow?: number;
34
+ }
35
+
36
+ /** An error response of the app-server, or the error of a failed turn. */
37
+ export interface AppServerError {
38
+ readonly code: number;
39
+ readonly message: string;
40
+ readonly data?: unknown;
41
+ }
42
+
43
+ /** The stage of the run an error came from. */
44
+ export type AppServerStage = "initialize" | "session" | "prompt";
45
+
46
+ /** How a turn ended, or the stage that failed before it could. */
47
+ export type AppServerEnd =
48
+ | {
49
+ readonly kind: "stopped";
50
+ /** `completed`, `interrupted` or `failed`. */
51
+ readonly stopReason: string;
52
+ readonly usage: AppServerUsage | null;
53
+ readonly sessionId: string;
54
+ readonly error: AppServerError | null;
55
+ }
56
+ | {
57
+ readonly kind: "error";
58
+ readonly stage: AppServerStage;
59
+ readonly error: AppServerError;
60
+ readonly sessionId: string | null;
61
+ };
62
+
63
+ /** One approval request of the app-server. */
64
+ export interface AppServerPermissionRequest {
65
+ /** `item/commandExecution/requestApproval`, `item/fileChange/requestApproval`, or a legacy name. */
66
+ readonly method: string;
67
+ /** The item, call or approval id the request is about. */
68
+ readonly toolCallId: string;
69
+ readonly params: Readonly<Record<string, unknown>>;
70
+ /** The item as the app-server described it, when an item event came first. */
71
+ readonly item: Readonly<Record<string, unknown>> | undefined;
72
+ }
73
+
74
+ /** An MCP server the thread starts, as Codex's own config takes it. */
75
+ export interface AppServerMcpServer {
76
+ readonly name: string;
77
+ readonly command: string;
78
+ readonly args: readonly string[];
79
+ readonly env?: Readonly<Record<string, string>> | undefined;
80
+ }
81
+
82
+ /** One question of a `item/tool/requestUserInput` request. */
83
+ export interface AppServerQuestion {
84
+ readonly id: string;
85
+ readonly question: string;
86
+ readonly header?: string | undefined;
87
+ readonly options?: readonly { readonly label: string; readonly description?: string | undefined }[] | undefined;
88
+ /** True when Codex itself offers an answer in the person's own words. */
89
+ readonly isOther?: boolean | undefined;
90
+ /** True when the answer is a secret that must not be kept as a fact. */
91
+ readonly isSecret?: boolean | undefined;
92
+ }
93
+
94
+ /** A `item/tool/requestUserInput` request of the app-server. */
95
+ export interface AppServerQuestionRequest {
96
+ readonly method: string;
97
+ readonly itemId: string;
98
+ readonly threadId: string | null;
99
+ readonly turnId: string | null;
100
+ readonly questions: readonly AppServerQuestion[];
101
+ }
102
+
103
+ /** One question's answer as the app-server reads it. */
104
+ export type AppServerQuestionAnswers = Readonly<Record<string, readonly string[]>>;
105
+
106
+ export interface AppServerClientOptions {
107
+ readonly cwd: string;
108
+ /** The prompt as app-server `UserInput` entries. */
109
+ readonly prompt: readonly Readonly<Record<string, unknown>>[];
110
+ /** Continue this thread. */
111
+ readonly resumeSession?: string | undefined;
112
+ readonly model?: string | undefined;
113
+ readonly effort?: string | undefined;
114
+ /** Codex's approval policy: `on-request` asks instead of deciding. */
115
+ readonly approvalPolicy: string;
116
+ /** Codex's sandbox mode: `workspace-write` stays on. */
117
+ readonly sandbox: string;
118
+ /** MCP servers the thread starts, through Codex's own `mcp_servers` config. */
119
+ readonly mcpServers?: readonly AppServerMcpServer[] | undefined;
120
+ readonly clientName: string;
121
+ readonly clientVersion?: string | undefined;
122
+ /** Each notification of the running turn, in order: method and params. */
123
+ readonly onNotification: (method: string, params: Readonly<Record<string, unknown>>) => void | Promise<void>;
124
+ /** True lets the call run once; false refuses it. */
125
+ readonly onPermission: (request: AppServerPermissionRequest) => Promise<boolean>;
126
+ /**
127
+ * The agent's own questions, as one form the person fills in (ADR 0026 D6).
128
+ * Resolves with one answer per question id; absent refuses the request.
129
+ */
130
+ readonly onQuestion?: ((request: AppServerQuestionRequest) => Promise<AppServerQuestionAnswers>) | undefined;
131
+ }
132
+
133
+ type Phase = "initialize" | "session" | "turn" | "done";
134
+
135
+ type Stage = AppServerStage | "steer" | "cancel";
136
+
137
+ function errorOf(value: unknown): AppServerError {
138
+ if (!isRecord(value)) return { code: -32603, message: "the app-server sent an error without a body" };
139
+ return {
140
+ code: typeof value.code === "number" ? value.code : -32603,
141
+ message: typeof value.message === "string" ? value.message : "the app-server sent an error without a message",
142
+ ...(value.data === undefined ? {} : { data: value.data }),
143
+ };
144
+ }
145
+
146
+ function turnErrorOf(value: unknown): AppServerError | undefined {
147
+ if (!isRecord(value)) return undefined;
148
+ const message = typeof value.message === "string" ? value.message : "the turn failed";
149
+ return { code: 0, message, data: value };
150
+ }
151
+
152
+ function numberField(value: Readonly<Record<string, unknown>>, key: string): number | undefined {
153
+ const found = value[key];
154
+ return typeof found === "number" && Number.isFinite(found) ? found : undefined;
155
+ }
156
+
157
+ /**
158
+ * The questions of an `item/tool/requestUserInput` payload. A question without
159
+ * an id or text cannot be answered, so it is left out.
160
+ */
161
+ export function questionsOf(value: unknown): AppServerQuestion[] {
162
+ if (!Array.isArray(value)) return [];
163
+ const questions: AppServerQuestion[] = [];
164
+ for (const raw of value) {
165
+ if (!isRecord(raw)) continue;
166
+ const id = raw["id"];
167
+ const question = raw["question"];
168
+ if (typeof id !== "string" || id.length === 0) continue;
169
+ if (typeof question !== "string" || question.trim().length === 0) continue;
170
+ const options: { label: string; description?: string }[] = [];
171
+ if (Array.isArray(raw["options"])) {
172
+ for (const option of raw["options"]) {
173
+ if (!isRecord(option)) continue;
174
+ const label = option["label"];
175
+ if (typeof label !== "string" || label.trim().length === 0) continue;
176
+ const description = option["description"];
177
+ options.push({
178
+ label,
179
+ ...(typeof description === "string" && description.trim().length > 0 ? { description } : {}),
180
+ });
181
+ }
182
+ }
183
+ const header = raw["header"];
184
+ questions.push({
185
+ id,
186
+ question,
187
+ ...(typeof header === "string" && header.length > 0 ? { header } : {}),
188
+ ...(options.length === 0 ? {} : { options }),
189
+ ...(raw["isOther"] === true ? { isOther: true } : {}),
190
+ ...(raw["isSecret"] === true ? { isSecret: true } : {}),
191
+ });
192
+ }
193
+ return questions;
194
+ }
195
+
196
+ /**
197
+ * The questions a person may be asked: a secret answer would be kept in the
198
+ * pending item and the fact log, so a secret question is never put to them.
199
+ */
200
+ export function personQuestions(request: AppServerQuestionRequest): readonly AppServerQuestion[] {
201
+ return request.questions.filter((question) => question.isSecret !== true);
202
+ }
203
+
204
+ /** The counts of the last turn from a `thread/tokenUsage/updated` payload. */
205
+ export function usageOf(value: unknown): AppServerUsage | null {
206
+ if (!isRecord(value)) return null;
207
+ const last = isRecord(value["last"]) ? value["last"] : undefined;
208
+ const total = isRecord(value["total"]) ? value["total"] : undefined;
209
+ const counts = last ?? total;
210
+ if (counts === undefined) return null;
211
+ const totalTokens = numberField(counts, "totalTokens");
212
+ const inputTokens = numberField(counts, "inputTokens");
213
+ const outputTokens = numberField(counts, "outputTokens");
214
+ const cachedReadTokens = numberField(counts, "cachedInputTokens");
215
+ const cachedWriteTokens = numberField(counts, "cacheWriteInputTokens");
216
+ const thoughtTokens = numberField(counts, "reasoningOutputTokens");
217
+ const modelContextWindow = numberField(value, "modelContextWindow");
218
+ return {
219
+ ...(totalTokens === undefined ? {} : { totalTokens }),
220
+ ...(inputTokens === undefined ? {} : { inputTokens }),
221
+ ...(outputTokens === undefined ? {} : { outputTokens }),
222
+ ...(cachedReadTokens === undefined ? {} : { cachedReadTokens }),
223
+ ...(cachedWriteTokens === undefined ? {} : { cachedWriteTokens }),
224
+ ...(thoughtTokens === undefined ? {} : { thoughtTokens }),
225
+ ...(modelContextWindow === undefined ? {} : { modelContextWindow }),
226
+ };
227
+ }
228
+
229
+ function mcpConfig(servers: readonly AppServerMcpServer[] | undefined): Record<string, unknown> | undefined {
230
+ if (servers === undefined || servers.length === 0) return undefined;
231
+ const found: Record<string, unknown> = {};
232
+ for (const server of servers) {
233
+ found[server.name] = {
234
+ command: server.command,
235
+ args: [...server.args],
236
+ ...(server.env === undefined ? {} : { env: { ...server.env } }),
237
+ };
238
+ }
239
+ return found;
240
+ }
241
+
242
+ export class AppServerClient {
243
+ /** The first line the caller sends: the `initialize` request. */
244
+ readonly first: string;
245
+ /** Settles once, when the turn ended or a stage failed. */
246
+ readonly ended: Promise<AppServerEnd>;
247
+ /** Resolves once the turn has been asked for. */
248
+ readonly started: Promise<void>;
249
+ /**
250
+ * Resolves with the turn id once `turn/start` is answered. It never settles
251
+ * when the turn never starts, so a caller can keep its messages until then.
252
+ */
253
+ readonly turnKnown: Promise<string>;
254
+
255
+ private readonly options: AppServerClientOptions;
256
+ private resolveStarted: () => void = () => undefined;
257
+ private resolveTurn: (turn: string) => void = () => undefined;
258
+ private reply: ((text: string) => void) | undefined;
259
+ private nextId = 1;
260
+ private phase: Phase = "initialize";
261
+ private session: string | null = null;
262
+ private turn: string | null = null;
263
+ private settle: (end: AppServerEnd) => void = () => undefined;
264
+ /** What each request in flight waits for, by id. A `steer` and a `cancel` are fire-and-forget. */
265
+ private readonly pending = new Map<number, Stage>();
266
+ private readonly items = new Map<string, Readonly<Record<string, unknown>>>();
267
+ private cancelling = false;
268
+ private promptSent = false;
269
+ private usage: AppServerUsage | null = null;
270
+ private noticedError: AppServerError | null = null;
271
+
272
+ constructor(options: AppServerClientOptions) {
273
+ this.options = options;
274
+ this.ended = new Promise<AppServerEnd>((resolve) => {
275
+ this.settle = resolve;
276
+ });
277
+ this.started = new Promise<void>((resolve) => {
278
+ this.resolveStarted = resolve;
279
+ });
280
+ this.turnKnown = new Promise<string>((resolve) => {
281
+ this.resolveTurn = resolve;
282
+ });
283
+ this.first = this.request(
284
+ "initialize",
285
+ {
286
+ clientInfo: {
287
+ name: options.clientName,
288
+ title: options.clientName,
289
+ version: options.clientVersion ?? "0.0.0",
290
+ },
291
+ capabilities: { experimentalApi: true, requestAttestation: false },
292
+ },
293
+ "initialize",
294
+ );
295
+ }
296
+
297
+ /** The thread the run uses; null before the app-server opened one. */
298
+ get sessionId(): string | null {
299
+ return this.session;
300
+ }
301
+
302
+ /** True from the moment the turn is asked for: updates belong to this run. */
303
+ get active(): boolean {
304
+ return this.phase === "turn" && this.promptSent;
305
+ }
306
+
307
+ /** Whether the run ended (the turn completed, or a stage failed). */
308
+ get finished(): boolean {
309
+ return this.phase === "done";
310
+ }
311
+
312
+ private request(method: string, params: Record<string, unknown>, stage: Stage): string {
313
+ const id = this.nextId;
314
+ this.nextId += 1;
315
+ this.pending.set(id, stage);
316
+ return JSON.stringify({ jsonrpc: "2.0", id, method, params });
317
+ }
318
+
319
+ private send(line: string): void {
320
+ this.reply?.(line);
321
+ }
322
+
323
+ private end(end: AppServerEnd): void {
324
+ if (this.phase === "done") return;
325
+ this.phase = "done";
326
+ this.settle(end);
327
+ }
328
+
329
+ private fail(stage: AppServerStage, error: AppServerError): void {
330
+ this.end({ kind: "error", stage, error, sessionId: this.session });
331
+ }
332
+
333
+ private threadParams(): Record<string, unknown> {
334
+ const config = mcpConfig(this.options.mcpServers);
335
+ return {
336
+ cwd: this.options.cwd,
337
+ approvalPolicy: this.options.approvalPolicy,
338
+ approvalsReviewer: "user",
339
+ sandbox: this.options.sandbox,
340
+ ...(this.options.model === undefined ? {} : { model: this.options.model }),
341
+ ...(config === undefined ? {} : { config: { mcp_servers: config } }),
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Sends a message to the running turn. False until the turn id is known, so
347
+ * a caller keeps the message instead of treating it as taken: a turn whose
348
+ * `turn/start` fails never exists, and nothing could deliver it.
349
+ */
350
+ steer(text: string): boolean {
351
+ if (this.phase === "done" || this.cancelling || this.turn === null || this.session === null) return false;
352
+ this.sendSteer(text);
353
+ return true;
354
+ }
355
+
356
+ private sendSteer(text: string): void {
357
+ if (this.session === null || this.turn === null) return;
358
+ this.send(
359
+ this.request(
360
+ "turn/steer",
361
+ {
362
+ threadId: this.session,
363
+ expectedTurnId: this.turn,
364
+ input: [{ type: "text", text, text_elements: [] }],
365
+ },
366
+ "steer",
367
+ ),
368
+ );
369
+ }
370
+
371
+ /**
372
+ * Asks the running turn to stop. The app-server answers the turn with the
373
+ * status `interrupted`, which `ended` reports. A cancel that arrives after
374
+ * `turn/start` was sent but before its answer is kept and sent as
375
+ * `turn/interrupt` once the turn id arrives. False when no turn is running,
376
+ * so there is nothing to interrupt.
377
+ */
378
+ cancel(): boolean {
379
+ if (this.cancelling || this.phase !== "turn" || !this.promptSent || this.session === null) return false;
380
+ this.cancelling = true;
381
+ if (this.turn !== null) this.sendInterrupt();
382
+ return true;
383
+ }
384
+
385
+ private sendInterrupt(): void {
386
+ if (this.session === null || this.turn === null) return;
387
+ this.send(this.request("turn/interrupt", { threadId: this.session, turnId: this.turn }, "cancel"));
388
+ }
389
+
390
+ /** Takes one line of the app-server's stdout. */
391
+ handleLine(line: string, reply: (text: string) => void): void {
392
+ this.reply = reply;
393
+ let message: unknown;
394
+ try {
395
+ message = JSON.parse(line);
396
+ } catch {
397
+ return;
398
+ }
399
+ if (!isRecord(message)) return;
400
+ const { id, method } = message;
401
+ if (typeof method === "string") {
402
+ if (typeof id === "number" || typeof id === "string") this.handleServerRequest(id, method, message.params);
403
+ else this.handleNotification(method, message.params);
404
+ return;
405
+ }
406
+ if (typeof id === "number") this.handleResponse(id, message);
407
+ }
408
+
409
+ private handleNotification(method: string, params: unknown): void {
410
+ if (!isRecord(params)) return;
411
+ if (method === "thread/tokenUsage/updated") {
412
+ // A resumed thread first reports its earlier usage; only this turn counts.
413
+ if (this.phase === "turn" && this.promptSent) this.usage = usageOf(params["tokenUsage"]);
414
+ return;
415
+ }
416
+ if (method === "error") {
417
+ const error = isRecord(params["error"]) ? params["error"] : undefined;
418
+ this.noticedError = turnErrorOf(error) ?? this.noticedError;
419
+ void this.options.onNotification(method, params);
420
+ return;
421
+ }
422
+ if (method === "turn/completed") {
423
+ const turn = isRecord(params["turn"]) ? params["turn"] : {};
424
+ const status = typeof turn["status"] === "string" ? turn["status"] : "failed";
425
+ const fromTurn = turnErrorOf(turn["error"]);
426
+ this.end({
427
+ kind: "stopped",
428
+ stopReason: status,
429
+ usage: this.usage,
430
+ sessionId: this.session ?? "",
431
+ error: fromTurn ?? this.noticedError,
432
+ });
433
+ return;
434
+ }
435
+ if (method === "item/started" || method === "item/completed") {
436
+ const item = params["item"];
437
+ if (isRecord(item) && typeof item["id"] === "string") this.items.set(item["id"], item);
438
+ } else if (method === "item/fileChange/patchUpdated") {
439
+ const id = params["itemId"];
440
+ const item = typeof id === "string" ? this.items.get(id) : undefined;
441
+ if (typeof id === "string" && item !== undefined && Array.isArray(params["changes"])) {
442
+ this.items.set(id, { ...item, changes: params["changes"] });
443
+ }
444
+ }
445
+ void this.options.onNotification(method, params);
446
+ }
447
+
448
+ private handleServerRequest(id: number | string, method: string, params: unknown): void {
449
+ const body = isRecord(params) ? params : {};
450
+ const answer = (result: Record<string, unknown>): void => {
451
+ this.send(JSON.stringify({ jsonrpc: "2.0", id, result }));
452
+ };
453
+ const refuse = (message: string): void => {
454
+ this.send(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32601, message } }));
455
+ };
456
+ if (method === "item/tool/requestUserInput") {
457
+ const itemId = typeof body["itemId"] === "string" ? body["itemId"] : "";
458
+ const request: AppServerQuestionRequest = {
459
+ method,
460
+ itemId,
461
+ threadId: typeof body["threadId"] === "string" ? body["threadId"] : null,
462
+ turnId: typeof body["turnId"] === "string" ? body["turnId"] : null,
463
+ questions: questionsOf(body["questions"]),
464
+ };
465
+ const onQuestion = this.options.onQuestion;
466
+ if (onQuestion === undefined || request.questions.length === 0) {
467
+ refuse(`method not supported: ${method}`);
468
+ return;
469
+ }
470
+ // The reader does not wait: a person may take long to answer, and the
471
+ // app-server's other lines (the answer to an interrupt) must still be read.
472
+ void (async () => {
473
+ let answers: AppServerQuestionAnswers = {};
474
+ if (!this.cancelling) {
475
+ try {
476
+ answers = await onQuestion(request);
477
+ } catch {
478
+ answers = {};
479
+ }
480
+ }
481
+ const byId: Record<string, { readonly answers: readonly string[] }> = {};
482
+ for (const [key, labels] of Object.entries(answers)) byId[key] = { answers: labels };
483
+ answer({ answers: byId });
484
+ })();
485
+ return;
486
+ }
487
+ const itemId = typeof body["itemId"] === "string" ? body["itemId"] : typeof body["callId"] === "string" ? body["callId"] : "";
488
+ const legacyCommand = method === "execCommandApproval";
489
+ const legacyPatch = method === "applyPatchApproval";
490
+ if (method !== "item/commandExecution/requestApproval" && method !== "item/fileChange/requestApproval" && !legacyCommand && !legacyPatch) {
491
+ refuse(`method not supported: ${method}`);
492
+ return;
493
+ }
494
+ const item = itemId.length === 0 ? undefined : this.items.get(itemId);
495
+ // The reader does not wait: a person may take long to answer, and the
496
+ // app-server's other lines (the answer to an interrupt) must still be read.
497
+ void (async () => {
498
+ let allow = false;
499
+ if (!this.cancelling) {
500
+ try {
501
+ allow = await this.options.onPermission({ method, toolCallId: itemId, params: body, item });
502
+ } catch {
503
+ allow = false;
504
+ }
505
+ }
506
+ if (legacyCommand || legacyPatch) {
507
+ answer({
508
+ decision: allow
509
+ ? "approved"
510
+ : { denied: { rejection: "the access profile refused this call" } },
511
+ });
512
+ } else {
513
+ answer({ decision: allow ? "accept" : "decline" });
514
+ }
515
+ })();
516
+ }
517
+
518
+ private handleResponse(id: number, message: Record<string, unknown>): void {
519
+ const stage = this.pending.get(id);
520
+ if (stage === undefined) return;
521
+ this.pending.delete(id);
522
+ if (isRecord(message.error)) {
523
+ if (stage === "steer" || stage === "cancel") return;
524
+ this.fail(stage, errorOf(message.error));
525
+ return;
526
+ }
527
+ if (stage === "steer" || stage === "cancel") return;
528
+ const result = isRecord(message.result) ? message.result : {};
529
+ switch (stage) {
530
+ case "initialize": {
531
+ this.phase = "session";
532
+ this.send(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }));
533
+ const resume = this.options.resumeSession;
534
+ if (resume !== undefined) {
535
+ this.session = resume;
536
+ this.send(this.request("thread/resume", { threadId: resume, excludeTurns: true, ...this.threadParams() }, "session"));
537
+ } else {
538
+ this.send(this.request("thread/start", this.threadParams(), "session"));
539
+ }
540
+ return;
541
+ }
542
+ case "session": {
543
+ const thread = isRecord(result["thread"]) ? result["thread"] : {};
544
+ const idValue = thread["id"];
545
+ if (typeof idValue !== "string" || idValue.length === 0) {
546
+ this.fail("session", { code: -32603, message: "the app-server opened a thread without an id" });
547
+ return;
548
+ }
549
+ this.session = idValue;
550
+ this.phase = "turn";
551
+ // Updates can arrive before the turn/start response; they belong to
552
+ // this run from the moment its turn is asked for.
553
+ this.promptSent = true;
554
+ this.resolveStarted();
555
+ this.send(
556
+ this.request(
557
+ "turn/start",
558
+ {
559
+ threadId: idValue,
560
+ input: [...this.options.prompt],
561
+ ...(this.options.model === undefined ? {} : { model: this.options.model }),
562
+ ...(this.options.effort === undefined ? {} : { effort: this.options.effort }),
563
+ },
564
+ "prompt",
565
+ ),
566
+ );
567
+ return;
568
+ }
569
+ case "prompt": {
570
+ const turn = isRecord(result["turn"]) ? result["turn"] : {};
571
+ const turnId = turn["id"];
572
+ if (typeof turnId !== "string" || turnId.length === 0) {
573
+ this.fail("prompt", { code: -32603, message: "the app-server started a turn without an id" });
574
+ return;
575
+ }
576
+ this.turn = turnId;
577
+ // A caller waits for this before it hands over messages, and a cancel
578
+ // kept while the turn id was on its way now has a turn to act on.
579
+ this.resolveTurn(turnId);
580
+ if (this.cancelling) this.sendInterrupt();
581
+ return;
582
+ }
583
+ }
584
+ }
585
+ }