@yaag/runtime 0.28.1 → 0.29.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yaag/runtime",
3
- "version": "0.28.1",
3
+ "version": "0.29.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -13,7 +13,7 @@ import type {
13
13
  CompactionResult,
14
14
  WorktreeResolution,
15
15
  } from "../transport/index.ts";
16
- import { Connection } from "../transport/index.ts";
16
+ import { Connection, clearQueueThenAbort } from "../transport/index.ts";
17
17
  import type {
18
18
  AskOptions,
19
19
  ForkOptions,
@@ -253,7 +253,7 @@ export class Agent implements Handle {
253
253
  raiseParked();
254
254
  },
255
255
  wrapUp: () => send({ type: "steer", message: wrapUpMessage(ask, suffix) }),
256
- abort: () => send({ type: "abort" }),
256
+ abort: () => clearQueueThenAbort(send),
257
257
  };
258
258
  }
259
259
 
@@ -24,7 +24,7 @@ function activityFromFrame(frame: Frame): AgentActivity | null {
24
24
  if (frame.type === "message_update") return messageActivity(frame.assistantMessageEvent);
25
25
  if (frame.type === "tool_execution_start") return toolActivity(frame);
26
26
  if (frame.type === "compaction_start") return { type: "compacting" };
27
- if (frame.type === "auto_retry_start" || frame.type === "summarization_retry_start") {
27
+ if (frame.type === "auto_retry_start" || frame.type === "summarization_retry_scheduled") {
28
28
  return retryActivity(frame);
29
29
  }
30
30
  return null;
@@ -14,7 +14,7 @@ import { type AskLimitOutcome, type AskStalledOutcome, isYaagError } from "../er
14
14
  import { retryOnModelFailure, swapModel } from "../model/index.ts";
15
15
  import { NodeTracker } from "../node/index.ts";
16
16
  import type { AskPlayback, Frame } from "../transport/index.ts";
17
- import { FrameGapTracker } from "../transport/index.ts";
17
+ import { clearQueueThenAbort, FrameGapTracker } from "../transport/index.ts";
18
18
  import { AskActivityTracker } from "./ask-activity.ts";
19
19
  import { type AskEndOutcome, AskEvents } from "./ask-exchange-events.ts";
20
20
  import type { AskExchangeOptions } from "./ask-exchange-options.ts";
@@ -365,6 +365,17 @@ class AskExchange {
365
365
  if (!response.success) {
366
366
  throw this.#failed(response.error ?? "report_result schema command was rejected");
367
367
  }
368
+ // Live probe (pi 1.0.0, 2026-10): pi answers the schema command with
369
+ // disposition "handled" (ADR-0032). Any other value means pi sent the schema
370
+ // text to the model, so drain the stray run. A missing field (older pi) passes.
371
+ // Only a live Agent can start that run; a replayed Ask cannot.
372
+ const disposition = response.data?.disposition;
373
+ if (disposition !== undefined && disposition !== "handled") {
374
+ if (this.#playback === undefined) this.#options.connection.drainStaleTurn();
375
+ throw this.#failed(
376
+ `report_result schema command was not handled by the extension (disposition: ${String(disposition)})`,
377
+ );
378
+ }
368
379
  command.accepted();
369
380
  }
370
381
 
@@ -375,6 +386,16 @@ class AskExchange {
375
386
  message: this.#options.prompt,
376
387
  });
377
388
  if (!response.success) throw this.#failed(response.error ?? "prompt was rejected");
389
+ // pi >=0.99 reports what became of the prompt (rpc.md "Run lifecycle"). "handled":
390
+ // an extension consumed it and no run starts, so no agent_settled will come.
391
+ // A missing field (an older Cassette) and "started"/"queued" change nothing.
392
+ if (response.data?.disposition === "handled") {
393
+ throw agentError(
394
+ this.#options.agent,
395
+ "ASK_HANDLED",
396
+ "an extension handled the prompt, so pi started no run",
397
+ );
398
+ }
378
399
  }
379
400
 
380
401
  #failed(message: string): Error {
@@ -491,7 +512,7 @@ class AskExchange {
491
512
 
492
513
  async #abort(): Promise<void> {
493
514
  const settled = this.#armSettlement();
494
- const response = await this.#options.connection.command({ type: "abort" });
515
+ const response = await clearQueueThenAbort((frame) => this.#options.connection.command(frame));
495
516
  if (!response.success) throw this.#failed(response.error ?? "abort was rejected");
496
517
  await this.#verify(settled, true);
497
518
  }
@@ -1,5 +1,5 @@
1
1
  import type { AskStalledOutcome } from "../errors.ts";
2
- import type { Frame } from "../transport/index.ts";
2
+ import { clearQueueThenAbort, type Frame } from "../transport/index.ts";
3
3
 
4
4
  /** Fixed time allowed for `agent_settled` to arrive after the idle abort. */
5
5
  export const IDLE_ABORT_SETTLE_MS = 5_000;
@@ -27,9 +27,8 @@ export class IdleKillSignal extends Error {
27
27
  * Per-Ask silence watchdog, a sibling of `AskLimit` (ADR-0020).
28
28
  *
29
29
  * The timer starts at prompt send and resets on every frame. On expiry it
30
- * sends `abort` and nothing else — a queued `steer` would be delivered as a new
31
- * turn the instant abort ends the hung one, and `agent_settled` would never
32
- * arrive.
30
+ * never steers, because a steer cannot end a stall (ADR-0020). It sends
31
+ * `clear_queue`, then `abort`, so no stale steer survives into the next Ask.
33
32
  */
34
33
  export class IdleWatch {
35
34
  readonly #idleMs: number;
@@ -148,7 +147,7 @@ export class IdleWatch {
148
147
 
149
148
  async #sendAbort(): Promise<void> {
150
149
  try {
151
- if (!(await this.#command({ type: "abort" }))) {
150
+ if (!(await clearQueueThenAbort(this.#command))) {
152
151
  this.#rejectFailure(new Error("idle abort command was rejected"));
153
152
  }
154
153
  } catch (error) {
@@ -1,5 +1,5 @@
1
1
  import type { AskLimitKind, AskLimitOutcome } from "../errors.ts";
2
- import type { Frame } from "../transport/index.ts";
2
+ import { clearQueueThenAbort, type Frame } from "../transport/index.ts";
3
3
  import type { AskOptions } from "../types.ts";
4
4
  import { REPORT_RESULT_TOOL_NAME } from "./report-result.ts";
5
5
  import { REQUEST_USER_INPUT_TOOL_NAME } from "./request-user-input.ts";
@@ -192,9 +192,10 @@ export class AskLimit {
192
192
  async #sendAbort(): Promise<void> {
193
193
  if (this.#completed || this.#aborted || this.#trip === null) return;
194
194
  // `command()` writes synchronously; latch before its response can race settlement.
195
+ // The queue is cleared first: pi 1.0.0 keeps a queued wrap-up steer across abort.
195
196
  this.#aborted = true;
196
197
  try {
197
- if (!(await this.#command({ type: "abort" }))) {
198
+ if (!(await clearQueueThenAbort(this.#command))) {
198
199
  this.#rejectFailure("limit control command was rejected");
199
200
  return;
200
201
  }
@@ -13,6 +13,9 @@ import type { Frame } from "../transport/index.ts";
13
13
  * frames). `cassette-frame-shape.test.ts` guards that a shaped frame drives
14
14
  * each of them to the same output as the live frame did.
15
15
  *
16
+ * A pi 1.0.0 `role: "system"` message on `message_start` and `message_end`
17
+ * keeps only its role: the frame stays, so replay sees the same sequence.
18
+ *
16
19
  * A new reader that needs a dropped field extends this function; a Cassette
17
20
  * recorded before that lacks the field, and the reader must tolerate it.
18
21
  */
@@ -26,7 +29,9 @@ export function shapeFrame(frame: Frame): Frame {
26
29
  return without(frame, "message");
27
30
  case "message_start":
28
31
  // The user prompt is the `prompt` frame in `sentFrames`.
29
- return isUserMessage(frame.message) ? without(frame, "message") : frame;
32
+ return hasRole(frame.message, "user") ? without(frame, "message") : shapeSystemMessage(frame);
33
+ case "message_end":
34
+ return shapeSystemMessage(frame);
30
35
  case "message_update":
31
36
  // Running usage per delta; the final usage rides on `message_end`.
32
37
  return without(frame, "usage");
@@ -53,8 +58,18 @@ function without(value: Readonly<Record<string, unknown>>, key: string): Record<
53
58
  return rest;
54
59
  }
55
60
 
56
- function isUserMessage(message: unknown): boolean {
57
- return isRecord(message) && message.role === "user";
61
+ /**
62
+ * A pi 1.0.0 `role: "system"` message keeps only its role. Its body holds the
63
+ * unexpanded prompt sections and the tool schemas, which no reader reads;
64
+ * the Cassette spawn record already holds the prompt.
65
+ */
66
+ function shapeSystemMessage(frame: Frame): Frame {
67
+ if (!hasRole(frame.message, "system")) return frame;
68
+ return { ...frame, message: { role: "system" } };
69
+ }
70
+
71
+ function hasRole(message: unknown, role: string): boolean {
72
+ return isRecord(message) && message.role === role;
58
73
  }
59
74
 
60
75
  function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
@@ -156,14 +156,21 @@ export class CassetteReplay {
156
156
  * Any non-first prompt within an Ask is a recorded correction (ADR-0027
157
157
  * amendment). A recorded `get_state` is a Stall Watchdog probe: replay is
158
158
  * never silent, so it never probes, and the recorded exchange is consumed
159
- * here instead of blocking the frames that follow it (ADR-0029).
159
+ * here instead of blocking the frames that follow it (ADR-0029). A recorded
160
+ * `clear_queue` may precede a recorded `abort` (ADR-0020) and is a control too.
160
161
  *
161
162
  * A recorded `get_available_models`/`set_model` pair is deliberately not a
162
163
  * control: replay re-runs the mid-Ask Model Resolution and sends those
163
164
  * commands itself, so `send()` matches them like any other frame (ADR-0039).
164
165
  */
165
166
  #isRecordedControl(frame: Frame): boolean {
166
- if (frame.type === "steer" || frame.type === "abort" || frame.type === "get_state") return true;
167
+ if (
168
+ frame.type === "steer" ||
169
+ frame.type === "clear_queue" ||
170
+ frame.type === "abort" ||
171
+ frame.type === "get_state"
172
+ )
173
+ return true;
167
174
  return frame.type === "prompt" && this.#sentCursor > this.#promptFloor;
168
175
  }
169
176
 
@@ -227,12 +234,13 @@ export class CassetteReplay {
227
234
  }
228
235
 
229
236
  /**
230
- * Renames a consumed probe's id, so its recorded response cannot answer an
237
+ * Renames a consumed probe's or `clear_queue`'s id, so its recorded response cannot answer an
231
238
  * unrelated live command that reuses that id. Replay sends no probe and
232
239
  * numbers its own commands from zero, so those ids do collide.
233
240
  */
234
241
  #retireId(expected: Frame): void {
235
- if (expected.type !== "get_state" || typeof expected.id !== "string") return;
242
+ if (expected.type !== "get_state" && expected.type !== "clear_queue") return;
243
+ if (typeof expected.id !== "string") return;
236
244
  this.#ids.set(expected.id, `cassette-${expected.id}`);
237
245
  }
238
246
 
@@ -47,6 +47,7 @@ export type YaagErrorCode =
47
47
  | "ASK_TIMEOUT" // timeoutMs elapsed
48
48
  | "ASK_LIMIT" // soft Ask budget exceeded after grace
49
49
  | "ASK_STALLED" // no frame arrived within the silence budget; escalated, then kill
50
+ | "ASK_HANDLED" // an extension handled the prompt; pi started no run
50
51
  | "COMPACT_DURING_ASK" // compact() was called while an Ask was in flight
51
52
  | "COMPACT_FAILED" // pi refused or could not summarize the context
52
53
  | "FORK_DURING_ASK" // fork() was called while the source Ask was in flight
@@ -14,28 +14,29 @@
14
14
  * The prompt reaches this extension on one of two channels. When it asks for
15
15
  * `piDefaultPrompt`, yaag spends no `--system-prompt` and sends the text in
16
16
  * `YAAG_SYSTEM_PROMPT` instead; pi then builds its own default prompt, this
17
- * extension receives it as `event.systemPrompt`, and `piDefaultPrompt` is
18
- * exact (ADR-0063 amendment 2). The two channels fail differently, and the env
17
+ * extension receives it as `event.systemPrompt`, and `piDefaultPrompt` is exact
18
+ * (ADR-0063 amendment 2). Since pi 1.0.0 that default is pi's XML-sectioned
19
+ * prompt (ADR-0063 amendment 3). The two channels fail differently, and the env
19
20
  * channel fails quietly: a broken or unloaded extension leaves the flag channel
20
21
  * showing raw `<<<yaag:render:…>>>` markers to the model, while on the env
21
22
  * channel the Agent silently runs on pi's own default prompt and the program's
22
- * text is dropped. Otherwise the text arrives on the flag, and
23
- * the paragraph below states what `piDefaultPrompt` would mean there.
23
+ * text is dropped. Otherwise the text arrives on the flag, and the paragraph
24
+ * below states what `piDefaultPrompt` would mean there.
24
25
  *
25
- * On the flag channel `event.systemPrompt` as received is *not* pi's guideline-bearing default
26
- * prompt, and `piDefaultPrompt` therefore does not print one. On this channel
27
- * yaag passed `--system-prompt`, so pi takes its `customPrompt` branch
28
- * (`dist/core/system-prompt.js:15-33`), which emits
29
- * `customPrompt + append + context + skills + cwd line` and no tool or
30
- * guideline text at all. What arrives here is this module's own still
31
- * *unexpanded* sentinel text plus those tails — so `piDefaultPrompt` expands to
32
- * text that still contains raw `<<<yaag:render:...>>>` markers, and
33
- * `expandPrompt` does not re-scan what it inserted. That is harmless only
34
- * because the default text has no `piDefaultPrompt` slot today. The flag
35
- * channel therefore never carries pi's guideline prompt. This is why a prompt
36
- * that asks for `piDefaultPrompt` takes the env channel described above, where
37
- * pi builds its default prompt itself and the helper is exact
38
- * (ADR-0063 amendment 2, `pi-state.ts:piEnv`).
26
+ * On the flag channel `event.systemPrompt` as received is *not* pi's
27
+ * guideline-bearing default prompt, and `piDefaultPrompt` therefore does not
28
+ * print one. On this channel yaag passed `--system-prompt`, so pi 1.0.0 puts
29
+ * `customPrompt` in the `preamble` section and builds no `<tools>`, `<rules>`
30
+ * or `<docs>` section (`dist/core/system-prompt.js:76-94`). It adds only the
31
+ * `<addendum>`, `<project_context>`, `<skills>` and `<cwd>` sections
32
+ * (`:95-105`). What arrives here is this module's own still *unexpanded*
33
+ * sentinel text plus those tails — so `piDefaultPrompt` expands to text that
34
+ * still contains raw `<<<yaag:render:...>>>` markers, and `expandPrompt` does
35
+ * not re-scan what it inserted. That is harmless only because the default text
36
+ * has no `piDefaultPrompt` slot today. The flag channel therefore never carries
37
+ * pi's guideline prompt. This is why a prompt that asks for `piDefaultPrompt`
38
+ * takes the env channel described above, where pi builds its default prompt
39
+ * itself and the helper is exact (ADR-0063 amendment 2, `pi-state.ts:piEnv`).
39
40
  *
40
41
  * Types are declared locally rather than imported from pi: this file is passed
41
42
  * to `pi -e` as a path and must load without yaag's dependency graph. pi loads
@@ -265,8 +266,10 @@ function readStrings(value: unknown): readonly string[] {
265
266
  }
266
267
 
267
268
  /**
268
- * The tool lines, in pi's own format: a tool appears only when the caller gave
269
- * it a one-line snippet (pi `dist/core/system-prompt.js` lines 42-44).
269
+ * The tool lines, in pi's own line format: a tool appears only when the caller
270
+ * gave it a one-line snippet (pi 1.0.0 `dist/core/system-prompt.js:82-83`).
271
+ * pi wraps these lines in a `<tools>` section with one more sentence (`:84`);
272
+ * this slot holds the lines only.
270
273
  */
271
274
  function renderTools(options: SystemPromptOptions): string {
272
275
  const snippets: Record<string, unknown> =
@@ -280,8 +283,11 @@ function renderTools(options: SystemPromptOptions): string {
280
283
  }
281
284
 
282
285
  /**
283
- * The `<project_context>` block, byte-for-byte with pi
284
- * `dist/core/system-prompt.js` lines 20-27.
286
+ * The `<project_context>` block, in the pi 0.84 layout. pi 1.0.0 renders the
287
+ * same file entries (`renderProjectContext`, `dist/core/system-prompt.js:24-29`)
288
+ * in a `<project_context>` section (`:97-98`, `:110-114`), with no blank line
289
+ * after the opening tag and none before the closing tag. So this block is the
290
+ * same content as pi's text, not byte-identical with it (ADR-0063 amendment 3).
285
291
  */
286
292
  function renderContextFiles(value: unknown): string {
287
293
  const files = Array.isArray(value) ? (value as ContextFile[]) : [];
@@ -296,8 +302,10 @@ function renderContextFiles(value: unknown): string {
296
302
  }
297
303
 
298
304
  /**
299
- * The `<available_skills>` block, in pi's format (`dist/core/skills.js` lines
300
- * 275-305). Skills appear only when a tool that can read their files is active.
305
+ * The `<available_skills>` block, in pi's format
306
+ * (`dist/core/skills.js:275-298`). pi trims this text and wraps it in a
307
+ * `<skills>` section (`system-prompt.js:99-104`). Skills appear only when a
308
+ * tool that can read their files is active.
301
309
  */
302
310
  function renderSkills(options: SystemPromptOptions): string {
303
311
  const tools = readStrings(options.selectedTools);
@@ -0,0 +1,15 @@
1
+ import type { Frame } from "./transport.ts";
2
+
3
+ /**
4
+ * Sends `clear_queue`, then `abort`, and resolves with the abort's answer.
5
+ * pi 1.0.0 keeps queued steering across `abort` and delivers it after the next
6
+ * prompt (rpc-commands.md "clear_queue"; ADR-0020). `command` must write its
7
+ * frame synchronously. pi handles stdin lines in order, and `clear_queue`
8
+ * empties the queue synchronously before the abort line is handled, so the
9
+ * clear's answer is not awaited. A refused clear never blocks the abort.
10
+ * Rejects when the abort command rejects.
11
+ */
12
+ export function clearQueueThenAbort<T>(command: (frame: Frame) => Promise<T>): Promise<T> {
13
+ void command({ type: "clear_queue" }).then(undefined, () => {});
14
+ return command({ type: "abort" });
15
+ }
@@ -38,6 +38,8 @@ export interface FakePromptScript {
38
38
  readonly lastText?: string | null;
39
39
  /** Makes this script's prompt RPC response fail, before any frame playback. */
40
40
  readonly promptError?: string;
41
+ /** `data.disposition` of this script's prompt response; omission sends no `data`, as pi before 0.99 did. */
42
+ readonly promptDisposition?: "started" | "queued" | "handled";
41
43
  }
42
44
 
43
45
  /**
@@ -62,6 +64,8 @@ export interface FakeTransportOptions extends FakePromptScript {
62
64
  readonly compactError?: string;
63
65
  /** Makes the private report_result schema command fail. */
64
66
  readonly schemaCommandError?: string;
67
+ /** `data.disposition` of the schema command response; omission sends no `data`. */
68
+ readonly schemaCommandDisposition?: string;
65
69
  /** The snapshot answered to `get_available_models`; defaults to this fake's own model. */
66
70
  readonly models?: readonly AvailableModel[];
67
71
  /** The model this fake reports before any swap; defaults to a placeholder id. */
@@ -121,6 +125,7 @@ export class FakeTransport implements AgentTransport {
121
125
  this.sent.push(frame);
122
126
  if (frame.type === "prompt") void this.#answerPrompt(frame);
123
127
  if (frame.type === "steer") void this.#answerSteer(frame);
128
+ if (frame.type === "clear_queue") this.#answerClearQueue(frame);
124
129
  if (frame.type === "abort") void this.#answerAbort(frame);
125
130
  if (frame.type === "get_last_assistant_text") this.#answerLastText(frame);
126
131
  if (frame.type === "get_state") this.#answerState(frame);
@@ -193,17 +198,21 @@ export class FakeTransport implements AgentTransport {
193
198
  // pi answers an extension command without starting a turn, so the private
194
199
  // schema command selects no script and plays no frames (ADR-0032).
195
200
  if (isReportResultCommandFrame(frame)) {
196
- this.#answerControl(frame, this.#options.schemaCommandError);
201
+ const disposition = this.#options.schemaCommandDisposition;
202
+ const data = disposition === undefined ? undefined : { disposition };
203
+ this.#answerControl(frame, this.#options.schemaCommandError, data);
197
204
  return;
198
205
  }
199
206
  const script = this.#selectPromptScript();
200
207
  const error = script.promptError ?? this.#options.promptError;
208
+ const disposition = script.promptDisposition ?? this.#options.promptDisposition;
201
209
  const response = {
202
210
  type: "response",
203
211
  command: "prompt",
204
212
  id: frame.id,
205
213
  success: error === undefined,
206
214
  ...(error === undefined ? {} : { error }),
215
+ ...(disposition === undefined ? {} : { data: { disposition } }),
207
216
  };
208
217
  if (this.#options.promptResponse !== "after-settle") this.#queue.push(response);
209
218
  await this.#enqueue(script.frames, script.frameDelayMs);
@@ -244,13 +253,25 @@ export class FakeTransport implements AgentTransport {
244
253
  return frame.message === (this.#currentScript?.wrapUpPrompt ?? DEFAULT_WRAP_UP_PROMPT);
245
254
  }
246
255
 
247
- #answerControl(frame: Frame, error?: string): void {
256
+ #answerControl(frame: Frame, error?: string, data?: Record<string, unknown>): void {
248
257
  this.#queue.push({
249
258
  type: "response",
250
259
  command: frame.type,
251
260
  id: frame.id,
252
261
  success: error === undefined,
253
262
  ...(error === undefined ? {} : { error }),
263
+ ...(data === undefined ? {} : { data }),
264
+ });
265
+ }
266
+
267
+ /** pi 1.0.0 answers `clear_queue` with the messages it removed. */
268
+ #answerClearQueue(frame: Frame): void {
269
+ this.#queue.push({
270
+ type: "response",
271
+ command: "clear_queue",
272
+ id: frame.id,
273
+ success: true,
274
+ data: { steering: [], followUp: [] },
254
275
  });
255
276
  }
256
277
 
@@ -6,6 +6,7 @@
6
6
  // One name for one concept: the recorded selection type lives in `model/`,
7
7
  // which `transport/` already depends on (ADR-0039).
8
8
  export type { RecordedSpawnSelection } from "../model/index.ts";
9
+ export { clearQueueThenAbort } from "./abort-command.ts";
9
10
  export { type AppendChannel, openAppendChannel } from "./append-env.ts";
10
11
  export { type CommandResponse, Connection } from "./connection.ts";
11
12
  export {
@@ -92,9 +92,12 @@ function appendCapabilities(
92
92
  // extension appends to the already assembled Agent System Prompt.
93
93
  //
94
94
  // It means the extension receives pi's own default prompt only on the
95
- // environment channel above: with `--system-prompt` pi takes its
96
- // `customPrompt` branch, which never builds the guideline prompt (pi
97
- // `dist/core/system-prompt.js:15-33`). See the header of
95
+ // environment channel above. With `--system-prompt`, pi 1.0.0 puts the text
96
+ // in `preamble` and builds no `<tools>`, `<rules>` or `<docs>` section (pi
97
+ // `dist/core/system-prompt.js:76-94`). On the environment channel,
98
+ // `piDefaultPrompt` is pi's XML-sectioned default: the preamble, then
99
+ // `<tools>`, `<rules>` and `<docs>`, then pi's tail sections, which always
100
+ // include `<cwd>`. See the header of
98
101
  // `agent-prompt-extension.ts` for both channels.
99
102
  cmd.push("-e", AGENT_PROMPT_EXTENSION_PATH);
100
103
  for (const path of options.resolvedExtensionPaths ?? []) cmd.push("-e", path);