@yaag/runtime 0.22.0 → 0.24.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.
Files changed (42) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent.ts +52 -2
  3. package/src/agent/fork.ts +7 -0
  4. package/src/agent/spawn-open.ts +25 -5
  5. package/src/agent/spawn-request.ts +123 -3
  6. package/src/agent/spawn.ts +6 -0
  7. package/src/ask/ask-hash.ts +7 -0
  8. package/src/ask-contract/ask-limit.ts +2 -4
  9. package/src/ask-contract/index.ts +2 -1
  10. package/src/ask-contract/wrap-up-steer.ts +17 -0
  11. package/src/cassette/index.ts +1 -0
  12. package/src/cassette/run-checkpoint.ts +17 -5
  13. package/src/contract/agent-policy.ts +15 -4
  14. package/src/contract/error-codes.ts +3 -2
  15. package/src/contract/index.ts +10 -0
  16. package/src/contract/spawn-options.ts +7 -1
  17. package/src/contract/system-prompt.ts +88 -0
  18. package/src/control/ask-admission.ts +24 -0
  19. package/src/control/control-commands.ts +300 -0
  20. package/src/control/index.ts +31 -0
  21. package/src/control/pause-drain.ts +105 -0
  22. package/src/control/run-controller.ts +88 -0
  23. package/src/events.ts +40 -0
  24. package/src/index.ts +30 -0
  25. package/src/public-api.ts +11 -0
  26. package/src/run/run-settlement.ts +93 -0
  27. package/src/run/run.ts +86 -32
  28. package/src/summary/summary.ts +6 -0
  29. package/src/system-prompt/agent-prompt-extension.ts +337 -0
  30. package/src/system-prompt/agent-prompt.ts +15 -0
  31. package/src/system-prompt/agent-system-prompt.ts +90 -0
  32. package/src/system-prompt/append-channel.ts +69 -0
  33. package/src/system-prompt/define-system-prompt.ts +112 -0
  34. package/src/system-prompt/index.ts +48 -0
  35. package/src/system-prompt/prompt-guards.ts +60 -0
  36. package/src/system-prompt/render-sentinel.ts +75 -0
  37. package/src/transport/append-env.ts +69 -0
  38. package/src/transport/index.ts +2 -0
  39. package/src/transport/live-transport.ts +50 -26
  40. package/src/transport/pi-state.ts +38 -4
  41. package/src/transport/transport.ts +4 -1
  42. package/src/types.ts +8 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yaag/runtime",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1,7 +1,8 @@
1
1
  import type { Static, TSchema } from "typebox";
2
2
  import type { EffectiveAskOptions } from "../ask/index.ts";
3
3
  import { exchangeAsk } from "../ask/index.ts";
4
- import { ReportResultTool } from "../ask-contract/index.ts";
4
+ import { REPORT_RESULT_WRAP_UP, ReportResultTool, wrapUpMessage } from "../ask-contract/index.ts";
5
+ import type { AskAdmission, AskInFlight } from "../control/index.ts";
5
6
  import { agentError } from "../error-factories.ts";
6
7
  import type { EventSink } from "../events.ts";
7
8
  import type { ModelErrorHistory, ModelResolution } from "../model/index.ts";
@@ -59,6 +60,8 @@ export interface AgentOptions {
59
60
  readonly idleAbortSettleMs?: number;
60
61
  /** Test-only override for the bounded wait for the Stall Watchdog probe. */
61
62
  readonly stallProbeSettleMs?: number;
63
+ /** Run-scoped Ask gate; a closed gate refuses every later Ask (ADR-0024). */
64
+ readonly askAdmission?: AskAdmission;
62
65
  }
63
66
 
64
67
  /** One Agent as an Orchestration Program sees it. Lives above the transport seam. */
@@ -83,7 +86,9 @@ export class Agent implements Handle {
83
86
  readonly #reportResultTool = new ReportResultTool();
84
87
  readonly #sessionFile: string | undefined;
85
88
  readonly #fork: ForkSpawner | undefined;
89
+ readonly #askAdmission: AskAdmission | undefined;
86
90
  #busy = false;
91
+ #inFlight: AskInFlight | null = null;
87
92
  #incomplete = false;
88
93
  #askIndex = 0;
89
94
  #settledAsks = 0;
@@ -107,6 +112,7 @@ export class Agent implements Handle {
107
112
  this.#askLimitGraceMs = options.askLimitGraceMs;
108
113
  this.#idleAbortSettleMs = options.idleAbortSettleMs;
109
114
  this.#stallProbeSettleMs = options.stallProbeSettleMs;
115
+ this.#askAdmission = options.askAdmission;
110
116
  this.#usage = new AgentUsage((snapshot) =>
111
117
  this.#emit({ type: "agent_usage", agent: this.name, ...snapshot }),
112
118
  );
@@ -124,6 +130,8 @@ export class Agent implements Handle {
124
130
  ): Promise<Static<Schema>>;
125
131
  async ask(prompt: string, options?: AskOptions): Promise<string>;
126
132
  async ask(prompt: string, options?: EffectiveAskOptions): Promise<unknown> {
133
+ if (this.#askAdmission?.closed === true)
134
+ throw agentError(this.name, "RUN_CLOSED", "run is settling — no new Ask");
127
135
  if (this.#connection.dead)
128
136
  throw agentError(this.name, "AGENT_DIED", "agent is no longer running");
129
137
  if (this.#busy) {
@@ -134,6 +142,9 @@ export class Agent implements Handle {
134
142
  );
135
143
  }
136
144
  this.#busy = true;
145
+ const effective: EffectiveAskOptions = { ...this.#askDefaults, ...options };
146
+ const inFlight = this.#openInFlight(effective);
147
+ this.#inFlight = inFlight;
137
148
  const index = this.#askIndex++;
138
149
  try {
139
150
  return await exchangeAsk({
@@ -142,7 +153,7 @@ export class Agent implements Handle {
142
153
  transport: this.#transport,
143
154
  prompt,
144
155
  index,
145
- ask: { ...this.#askDefaults, ...options },
156
+ ask: effective,
146
157
  spawnOptions: this.#spawnOptions,
147
158
  definitionName: this.#definitionName,
148
159
  reportResultTool: this.#reportResultTool,
@@ -167,12 +178,51 @@ export class Agent implements Handle {
167
178
  });
168
179
  } finally {
169
180
  this.#busy = false;
181
+ this.#inFlight = null;
182
+ inFlight.settle();
170
183
  // A failed Ask settles the conversation as much as a successful one: the
171
184
  // fork point is the boundary, not the outcome.
172
185
  this.#settledAsks += 1;
173
186
  }
174
187
  }
175
188
 
189
+ /**
190
+ * The Ask this Agent runs right now, as the pause drain controls it, or null
191
+ * between Asks. An Orchestration Program never sees it: `Handle` omits it.
192
+ */
193
+ get askInFlight(): AskInFlight | null {
194
+ return this.#inFlight;
195
+ }
196
+
197
+ /**
198
+ * Builds the drain's controls of one Ask. Both commands report a refusal as
199
+ * false and never throw, so a dead Agent cannot throw into the drain.
200
+ */
201
+ #openInFlight(ask: EffectiveAskOptions): AskInFlight & { settle(): void } {
202
+ let settle: () => void = () => {};
203
+ const settled = new Promise<void>((resolve) => {
204
+ settle = resolve;
205
+ });
206
+ // A structured Ask keeps reporting through report_result, so its wrap-up
207
+ // carries the same suffix the soft-budget path uses (ADR-0032). Legacy
208
+ // extraction exists on playback only, where no drain runs.
209
+ const suffix = "outputSchema" in ask ? REPORT_RESULT_WRAP_UP : undefined;
210
+ const send = async (frame: Parameters<Connection["command"]>[0]): Promise<boolean> => {
211
+ try {
212
+ return (await this.#connection.command(frame)).success;
213
+ } catch {
214
+ return false;
215
+ }
216
+ };
217
+ return {
218
+ agent: this.name,
219
+ settled,
220
+ settle,
221
+ wrapUp: () => send({ type: "steer", message: wrapUpMessage(ask, suffix) }),
222
+ abort: () => send({ type: "abort" }),
223
+ };
224
+ }
225
+
176
226
  /** Replaces this Agent's context with a summary of it (ADR-0043). */
177
227
  compact(instructions?: string): Promise<CompactionResult> {
178
228
  if (this.#connection.dead)
package/src/agent/fork.ts CHANGED
@@ -45,6 +45,12 @@ export interface ForkRequest {
45
45
  readonly askDefaults: AskOptions | undefined;
46
46
  readonly fork: ForkIdentity;
47
47
  readonly compact: boolean | string | undefined;
48
+ /**
49
+ * True when the fork carries the text its source already rendered. An
50
+ * explicit `fork({ systemPrompt: … })` override is author-written and stays
51
+ * guarded (ADR-0060).
52
+ */
53
+ readonly inheritedPrompt: boolean;
48
54
  }
49
55
 
50
56
  /**
@@ -73,6 +79,7 @@ export function forkRequest(source: ForkSource, overrides?: ForkOptions): ForkRe
73
79
  ...(source.worktree === undefined ? {} : { worktreeFrom: source.worktree }),
74
80
  },
75
81
  compact,
82
+ inheritedPrompt: explicit.systemPrompt === undefined && inherited.systemPrompt !== undefined,
76
83
  };
77
84
  }
78
85
 
@@ -20,7 +20,12 @@ import type { ForkIdentity, ForkSpawner } from "./fork.ts";
20
20
  import type { SpawnDependencies } from "./spawn.ts";
21
21
  import { resolveSpawnExtensions } from "./spawn-extensions.ts";
22
22
  import { resolveParent } from "./spawn-parent.ts";
23
- import { openRequest, withSelection } from "./spawn-request.ts";
23
+ import {
24
+ openRequest,
25
+ type RenderedSpawnOptions,
26
+ renderPolicyPrompt,
27
+ withSelection,
28
+ } from "./spawn-request.ts";
24
29
 
25
30
  /** One request the open path serves: a plain spawn, or a fork of another Agent. */
26
31
  export interface OpenAgentRequest {
@@ -31,6 +36,8 @@ export interface OpenAgentRequest {
31
36
  readonly askDefaults: AskOptions | undefined;
32
37
  /** Definition identity stays separate from a topology-overridden Agent name. */
33
38
  readonly definitionName: string | undefined;
39
+ /** The prompt is a fork's inherited rendered text, not author-written. */
40
+ readonly inheritedPrompt?: boolean;
34
41
  /** Present only for a fork; adds `origin: "fork"` and the `--fork` source. */
35
42
  readonly fork?: ForkIdentity;
36
43
  /**
@@ -72,11 +79,18 @@ export async function openAgent(
72
79
  // append to it, so a resolver sees every candidate that already failed.
73
80
  const history = new ModelErrorHistory();
74
81
  try {
82
+ // The Prompt Definition renders once, above every other spawn step, so the
83
+ // peek, the fallback loop and every attempt share one text (ADR-0064).
84
+ const rendered: RenderedSpawnOptions = renderPolicyPrompt({
85
+ options: request.spawnOptions,
86
+ agent: { name, runName: deps.runName },
87
+ ...(request.inheritedPrompt === true ? { inheritedPrompt: true } : {}),
88
+ });
75
89
  // Extension paths do not vary per candidate, so a bad path fails once, generically.
76
90
  const extensions = await resolveSpawnExtensions({
77
91
  configExtensions: deps.configExtensions,
78
- declared: request.spawnOptions.extensions,
79
- useConfigExtensions: request.spawnOptions.configExtensions !== false,
92
+ declared: rendered.extensions,
93
+ useConfigExtensions: rendered.configExtensions !== false,
80
94
  ...(deps.programFile === undefined ? {} : { programFile: deps.programFile }),
81
95
  projectRoot: cwd,
82
96
  }).catch((error: unknown) => {
@@ -107,11 +121,12 @@ export async function openAgent(
107
121
  const attempt = async (
108
122
  selection: ModelSelection,
109
123
  ): Promise<{ opened: OpenedTransport; spawnOptions: ResolvedSpawnOptions }> => {
110
- const settled = withSelection(request.spawnOptions, selection);
124
+ const settled = withSelection(rendered, selection);
111
125
  return {
112
126
  opened: await openTransport({
113
127
  factory: deps.factory,
114
128
  name,
129
+ runName: deps.runName,
115
130
  cwd,
116
131
  spawnOptions: settled,
117
132
  ...extensionFields,
@@ -127,8 +142,9 @@ export async function openAgent(
127
142
  const recorded = deps.factory.recordedSpawn?.(
128
143
  openRequest({
129
144
  name,
145
+ runName: deps.runName,
130
146
  cwd,
131
- spawnOptions: request.spawnOptions,
147
+ spawnOptions: rendered,
132
148
  ...extensionFields,
133
149
  ...forkFields,
134
150
  ...(parent === undefined ? {} : { parent }),
@@ -174,6 +190,7 @@ export async function openAgent(
174
190
  : { modelFallback: { resolution, history, candidate: spawnOptions.model } }),
175
191
  ...(sessionFile === undefined ? {} : { sessionFile }),
176
192
  fork: deps.forkSpawner,
193
+ ...(deps.askAdmission === undefined ? {} : { askAdmission: deps.askAdmission }),
177
194
  ...(request.askDefaults === undefined ? {} : { askDefaults: request.askDefaults }),
178
195
  ...(request.definitionName === undefined ? {} : { definitionName: request.definitionName }),
179
196
  });
@@ -212,6 +229,8 @@ function isSpawnFailure(error: unknown): error is YaagError {
212
229
  interface OpenTransportOptions {
213
230
  readonly factory: TransportFactory;
214
231
  readonly name: string;
232
+ /** The Run name; the peek and the open must pass the same one (ADR-0013). */
233
+ readonly runName: string;
215
234
  readonly cwd: string;
216
235
  readonly spawnOptions: ResolvedSpawnOptions;
217
236
  readonly resolvedExtensionPaths?: readonly string[];
@@ -236,6 +255,7 @@ async function openTransport(options: OpenTransportOptions): Promise<OpenedTrans
236
255
  const transport = await options.factory.open(
237
256
  openRequest({
238
257
  name: options.name,
258
+ runName: options.runName,
239
259
  cwd: options.cwd,
240
260
  spawnOptions: options.spawnOptions,
241
261
  ...(options.resolvedExtensionPaths === undefined
@@ -1,12 +1,105 @@
1
+ import type { SystemPromptAgent } from "../contract/index.ts";
2
+ import { YaagError } from "../errors.ts";
1
3
  import type { ModelSelection } from "../model/index.ts";
4
+ import {
5
+ assertKnownSentinels,
6
+ assertNoLeakedSentinel,
7
+ dropsProgramAppend,
8
+ isSystemPromptDefinition,
9
+ programAppendWarning,
10
+ renderSystemPrompt,
11
+ yaagSystemPrompt,
12
+ } from "../system-prompt/index.ts";
2
13
  import type { OpenOptions, WorktreeResolution } from "../transport/index.ts";
3
14
  import type { ResolvedSpawnOptions, SpawnOptions } from "../types.ts";
4
15
 
16
+ /** Spawn options whose `systemPrompt`, if set, is already a plain string. */
17
+ export type RenderedSpawnOptions = Omit<SpawnOptions, "systemPrompt"> & {
18
+ readonly systemPrompt?: string;
19
+ };
20
+
21
+ /**
22
+ * Renders a Prompt Definition into its text, once per spawn (ADR-0064).
23
+ *
24
+ * The open path calls this above every other spawn step, so the peek, the model
25
+ * fallback loop and every attempt share one rendered text and the builder runs
26
+ * exactly once. Options with no prompt, or with a plain string, pass through
27
+ * untouched: rendering only replaces a definition with its string and never
28
+ * fills the default.
29
+ *
30
+ * This seam is also where a leaked or an unknown Render Sentinel rejects the
31
+ * spawn, before any Agent process starts (ADR-0060, ADR-0063), and where a
32
+ * spawn whose prompt drops `appendSystemPrompt` writes its one warning.
33
+ */
34
+ export function renderPolicyPrompt(request: RenderPolicyPromptOptions): RenderedSpawnOptions {
35
+ const { options, agent } = request;
36
+ const warn = request.warn ?? writeSpawnDiagnostic;
37
+ // The one place the guard policy lives: both branches below route through it,
38
+ // so the append warning cannot drift between a string and a definition.
39
+ const guard = (text: string, rendered: boolean): string => {
40
+ // Text yaag rendered itself — a definition's output, or a fork's inherited
41
+ // string — legitimately holds sentinels, so the leak guard must not fire.
42
+ if (rendered) assertKnownSentinels(text, agent.name);
43
+ else assertNoLeakedSentinel(text, agent.name);
44
+ if (options.appendSystemPrompt !== undefined && dropsProgramAppend(text)) {
45
+ warn(programAppendWarning(agent.name));
46
+ }
47
+ return text;
48
+ };
49
+ // Destructured rather than cast: `rest` has no `systemPrompt` at all, so each
50
+ // branch below builds the rendered shape from proven parts. An absent prompt
51
+ // stays absent, and no key with an `undefined` value enters recorded options.
52
+ const { systemPrompt: value, ...rest } = options;
53
+ // The default Agent System Prompt fills later in `openRequest`, and it always
54
+ // carries the `programAppend` sentinel, so no guard and no warning is due.
55
+ if (value === undefined) return rest;
56
+ if (typeof value === "string") {
57
+ return { ...rest, systemPrompt: guard(value, request.inheritedPrompt === true) };
58
+ }
59
+ if (!isSystemPromptDefinition(value)) {
60
+ throw new YaagError(
61
+ "SPAWN_FAILED",
62
+ `agent "${agent.name}": systemPrompt must be a string or a defineSystemPrompt definition`,
63
+ agent.name,
64
+ );
65
+ }
66
+ return { ...rest, systemPrompt: guard(renderSystemPrompt({ definition: value, agent }), true) };
67
+ }
68
+
69
+ /**
70
+ * Writes one spawn diagnostic line, best effort.
71
+ *
72
+ * Own writer rather than the recording one: `cassette/` is the wrong owner for
73
+ * a spawn diagnostic, and a closed stderr must never fail a spawn.
74
+ */
75
+ function writeSpawnDiagnostic(line: string): void {
76
+ try {
77
+ process.stderr.write(`${line}\n`);
78
+ } catch {
79
+ // best effort
80
+ }
81
+ }
82
+
83
+ /** What one prompt render needs: the options, the Agent, and where a warning goes. */
84
+ export interface RenderPolicyPromptOptions {
85
+ readonly options: SpawnOptions;
86
+ readonly agent: SystemPromptAgent;
87
+ /**
88
+ * True when `systemPrompt` is the text a fork's source already rendered. The
89
+ * leak guard is then skipped: the sentinels in it are yaag's own.
90
+ */
91
+ readonly inheritedPrompt?: boolean;
92
+ /** Where one warning line goes; the seam's own stderr writer by default. */
93
+ readonly warn?: (line: string) => void;
94
+ }
95
+
5
96
  /** Everything one spawn needs to build its open request, before a model settles. */
6
97
  export interface OpenRequestOptions {
7
98
  readonly name: string;
99
+ /** The Run name, printed in the Agent System Prompt; `run_start.program`. */
100
+ readonly runName: string;
8
101
  readonly cwd: string;
9
- readonly spawnOptions: SpawnOptions;
102
+ readonly spawnOptions: RenderedSpawnOptions;
10
103
  readonly resolvedExtensionPaths?: readonly string[];
11
104
  readonly declaredExtensions?: readonly string[];
12
105
  /** Resolved parent Agent name (Parent Link); spawn identity only, never argv. */
@@ -28,6 +121,31 @@ export interface OpenRequestOptions {
28
121
  * array or resolver spec. That request is what a Cassette-backed factory peeks
29
122
  * at, which is why the resume peek blanks model and thinking before it compares
30
123
  * the request with the recorded spawn (ADR-0039).
124
+ *
125
+ * A spawn that sets no `systemPrompt` gets the Agent System Prompt here, so the
126
+ * consumers downstream of this seam — the Cassette spawn options, the replay
127
+ * divergence fields, and the Run record — see a plain string (ADR-0055,
128
+ * ADR-0064).
129
+ *
130
+ * The **Ask hash is deliberately not one of them.** `askHash` reads
131
+ * `ResolvedSpawnOptions`, the output of `withSelection`, which this function
132
+ * never touches, so a default spawn hashes `systemPrompt: null` while its spawn
133
+ * identity records the rendered text. That is on purpose: the default text
134
+ * prints `Agent: <name>` and `Run: <runName>`, so feeding it to `askHash` would
135
+ * make Ask identity depend on the Agent name and the Run name — exactly the two
136
+ * things `askMarkerContext` strips from Ask identity. Nothing is lost, because
137
+ * spawn identity already covers the prompt (`replay-divergence.ts`), and a
138
+ * changed prompt therefore diverges at spawn rather than at Ask 0.
139
+ *
140
+ * A value the program did set travels literally. Note the empty string is a
141
+ * value a program set and it survives this seam unchanged, but `piCommand`
142
+ * tests `options.systemPrompt` for truthiness, so `""` drops `--system-prompt`
143
+ * and the Agent falls back to pi's own prompt. The guarantee here is a seam
144
+ * guarantee, not an end-to-end one.
145
+ *
146
+ * A Prompt Definition never reaches this function: `renderPolicyPrompt` above
147
+ * replaced it with its text once, at the top of the open path, so no consumer —
148
+ * the Ask hash included — can ever see a function (ADR-0064).
31
149
  */
32
150
  export function openRequest(options: OpenRequestOptions): OpenOptions {
33
151
  const spawnOptions = options.spawnOptions;
@@ -37,7 +155,9 @@ export function openRequest(options: OpenRequestOptions): OpenOptions {
37
155
  cwd: options.cwd,
38
156
  name: options.name,
39
157
  ...(model === undefined ? {} : { model }),
40
- ...(spawnOptions.systemPrompt === undefined ? {} : { systemPrompt: spawnOptions.systemPrompt }),
158
+ systemPrompt:
159
+ spawnOptions.systemPrompt ??
160
+ yaagSystemPrompt({ agent: { name: options.name, runName: options.runName } }),
41
161
  ...(thinking === undefined ? {} : { thinking }),
42
162
  ...(spawnOptions.appendSystemPrompt === undefined
43
163
  ? {}
@@ -72,7 +192,7 @@ export function openRequest(options: OpenRequestOptions): OpenOptions {
72
192
 
73
193
  /** Replaces the caller's `model`/`thinking` forms with one attempt's settled selection. */
74
194
  export function withSelection(
75
- options: SpawnOptions,
195
+ options: RenderedSpawnOptions,
76
196
  selection: ModelSelection,
77
197
  ): ResolvedSpawnOptions {
78
198
  // `parent` is dropped here as well: a Handle must never reach recorded options.
@@ -1,4 +1,5 @@
1
1
  import type { ConfigExtension } from "../config/index.ts";
2
+ import type { AskAdmission } from "../control/index.ts";
2
3
  import { YaagError } from "../errors.ts";
3
4
  import type { EventSink } from "../events.ts";
4
5
  import type { ActiveProfile, ProfiledDefinition } from "../profile/index.ts";
@@ -20,10 +21,14 @@ export interface SpawnDependencies {
20
21
  readonly emit: EventSink;
21
22
  readonly sessionDir: string | undefined;
22
23
  readonly programFile: string | undefined;
24
+ /** The Run name every Agent System Prompt of this Run prints. */
25
+ readonly runName: string;
23
26
  /** Effective Config entries, in merge order; empty when the Run has no config. */
24
27
  readonly configExtensions: readonly ConfigExtension[];
25
28
  /** The Profile this Run activated; absent for a program without Profiles. */
26
29
  readonly profile?: ActiveProfile;
30
+ /** Run-scoped Ask gate handed to every Agent this gate opens (ADR-0024). */
31
+ readonly askAdmission?: AskAdmission;
27
32
  }
28
33
 
29
34
  /** A RunContext spawn function that can synchronously stop accepting new Agents. */
@@ -51,6 +56,7 @@ export function makeSpawn(deps: SpawnDependencies): SpawnGate {
51
56
  parent: request.parent,
52
57
  askDefaults: request.askDefaults,
53
58
  definitionName: undefined,
59
+ inheritedPrompt: request.inheritedPrompt,
54
60
  fork: request.fork,
55
61
  });
56
62
  if (request.compact !== undefined && request.compact !== false) {
@@ -32,6 +32,13 @@ export function askHash(options: AskHashOptions): string {
32
32
  JSON.stringify({
33
33
  cwd: spawnOptions.cwd ?? null,
34
34
  model: spawnOptions.model ?? null,
35
+ // An unset `systemPrompt` hashes as null on purpose, even though the
36
+ // Agent really reads the Agent System Prompt: that default is filled in
37
+ // downstream, at the open-request seam, and never reaches
38
+ // `ResolvedSpawnOptions`. Hashing it would make Ask identity depend on
39
+ // the Agent name and the Run name the text embeds, which the Ask marker
40
+ // context strips deliberately. Spawn identity, not Ask identity, carries
41
+ // the Agent System Prompt (ADR-0055, ADR-0064).
35
42
  systemPrompt: spawnOptions.systemPrompt ?? null,
36
43
  ...(spawnOptions.thinking === undefined ? {} : { thinking: spawnOptions.thinking }),
37
44
  ...(spawnOptions.appendSystemPrompt === undefined
@@ -2,6 +2,7 @@ import type { AskLimitKind, AskLimitOutcome } from "../errors.ts";
2
2
  import 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
+ import { wrapUpMessage } from "./wrap-up-steer.ts";
5
6
 
6
7
  /**
7
8
  * True for a call to yaag's private result tool.
@@ -15,8 +16,6 @@ function isReportResult(frame: Frame): boolean {
15
16
  return frame.toolName === REPORT_RESULT_TOOL_NAME;
16
17
  }
17
18
 
18
- /** The message sent when an Ask uses its allotted soft budget. */
19
- export const DEFAULT_WRAP_UP_PROMPT = "Please wrap up now and provide your final answer.";
20
19
  /** Fixed time allowed to conclude after a duration limit trips. */
21
20
  export const ASK_LIMIT_DURATION_GRACE_MS = 5_000;
22
21
 
@@ -164,8 +163,7 @@ export class AskLimit {
164
163
  }
165
164
 
166
165
  #wrapUpMessage(): string {
167
- const wrapUp = this.#ask.wrapUpPrompt ?? DEFAULT_WRAP_UP_PROMPT;
168
- return this.#wrapUpSuffix === undefined ? wrapUp : `${wrapUp} ${this.#wrapUpSuffix}`;
166
+ return wrapUpMessage(this.#ask, this.#wrapUpSuffix);
169
167
  }
170
168
 
171
169
  #abort(): void {
@@ -9,7 +9,7 @@ export {
9
9
  validateCanonicalOutputSchema,
10
10
  validateExtractionPolicy,
11
11
  } from "./ask-contract-identity.ts";
12
- export { AskLimit, DEFAULT_WRAP_UP_PROMPT } from "./ask-limit.ts";
12
+ export { AskLimit } from "./ask-limit.ts";
13
13
  export {
14
14
  type AskOutputExtractionPolicy,
15
15
  DEFAULT_MAX_STEERS,
@@ -34,3 +34,4 @@ export {
34
34
  resolvePlaybackReportedResult,
35
35
  } from "./report-result-output.ts";
36
36
  export { ReportResultSteering } from "./report-result-steering.ts";
37
+ export { DEFAULT_WRAP_UP_PROMPT, wrapUpMessage } from "./wrap-up-steer.ts";
@@ -0,0 +1,17 @@
1
+ import type { AskOptions } from "../types.ts";
2
+
3
+ /** The message sent when an Ask uses its allotted soft budget. */
4
+ export const DEFAULT_WRAP_UP_PROMPT = "Please wrap up now and provide your final answer.";
5
+
6
+ /**
7
+ * The wrap-up steer text of one Ask.
8
+ *
9
+ * Every wrap-up path shares it — the soft Ask budget of `AskLimit` and the
10
+ * bounded pause drain (ADR-0024) — so an Agent reads the same words whichever
11
+ * mechanism asks it to conclude. The optional suffix keeps a structured Ask
12
+ * reporting its result through `report_result` (ADR-0032).
13
+ */
14
+ export function wrapUpMessage(ask: AskOptions, suffix?: string): string {
15
+ const wrapUp = ask.wrapUpPrompt ?? DEFAULT_WRAP_UP_PROMPT;
16
+ return suffix === undefined ? wrapUp : `${wrapUp} ${suffix}`;
17
+ }
@@ -34,6 +34,7 @@ export {
34
34
  } from "./resume-identity.ts";
35
35
  export { resumeTransport } from "./resume-transport.ts";
36
36
  export {
37
+ keepsCheckpoint,
37
38
  type ProgramIdentity,
38
39
  prepareRecordDestination,
39
40
  publishRunCheckpoint,
@@ -15,7 +15,7 @@ export type RunIdentity = Omit<CassetteRun, "outcome">;
15
15
  * `--record` path itself, or one name in the checkpoint directory.
16
16
  */
17
17
  export interface RunCheckpointOptions {
18
- /** Terminal outcome of the Run; only `stopped` keeps the artifact without `record`. */
18
+ /** Terminal outcome; `stopped` and `paused` keep the artifact without `record`. */
19
19
  readonly outcome: RunOutcome;
20
20
  readonly collector: CassetteCollector;
21
21
  /** Explicit `--record` destination, or undefined when the Run only checkpoints. */
@@ -41,12 +41,12 @@ export type RunCheckpointResult =
41
41
  /**
42
42
  * Publishes the collected Cassette when the Run must be restorable: always under
43
43
  * `--record`, and additionally into the checkpoint directory when the Run
44
- * stopped (ADR-0021/0024).
44
+ * stopped or paused (ADR-0021/0024).
45
45
  */
46
46
  export async function publishRunCheckpoint(
47
47
  options: RunCheckpointOptions,
48
48
  ): Promise<RunCheckpointResult> {
49
- if (!keepsArtifact(options)) {
49
+ if (!keepsCheckpoint(options)) {
50
50
  // A clean settlement without --record publishes nothing, so the in-flight
51
51
  // artifact this Run flushed goes away with it (ADR-0031).
52
52
  await discardCheckpoint(options.destination);
@@ -88,8 +88,20 @@ export async function publishRunCheckpoint(
88
88
  }
89
89
  }
90
90
 
91
- function keepsArtifact(options: RunCheckpointOptions): boolean {
92
- return options.record !== undefined || options.outcome === "stopped";
91
+ /**
92
+ * Whether a Run keeps its artifact: `--record` names a destination, or the Run
93
+ * paused or stopped. Every other Run discards the in-flight artifact, so it
94
+ * names no Checkpoint on `run_end` either — `run.ts` reads this same rule
95
+ * (ADR-0054). A paused Run promises restorability, so it keeps its artifact
96
+ * and can name its path.
97
+ */
98
+ export function keepsCheckpoint(options: {
99
+ readonly record?: string;
100
+ readonly outcome: RunOutcome;
101
+ }): boolean {
102
+ return (
103
+ options.record !== undefined || options.outcome === "stopped" || options.outcome === "paused"
104
+ );
93
105
  }
94
106
 
95
107
  /**
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { AskOptions } from "./handle.ts";
10
10
  import type { ModelSpec, ThinkingSpec } from "./model-spec.ts";
11
+ import type { LiteralPromptText, SystemPromptDefinition } from "./system-prompt.ts";
11
12
 
12
13
  /** What one Agent is, independent of where it runs. */
13
14
  export interface AgentPolicy {
@@ -33,11 +34,21 @@ export interface AgentPolicy {
33
34
  */
34
35
  readonly thinking?: ThinkingSpec;
35
36
  /**
36
- * Replaces pi's default system prompt (`pi --system-prompt`), which removes
37
- * pi's own documentation and tool guidance from the Agent.
37
+ * Replaces the Agent System Prompt, the text an Agent reads by default. The
38
+ * text is passed to the Agent literally, so it also removes the runtime
39
+ * facts, the tool list and the Rules the Agent System Prompt states.
40
+ *
41
+ * A `defineSystemPrompt(...)` definition instead builds the text at spawn
42
+ * time, with the Agent name and the Render Sentinels of the Prompt Context
43
+ * (ADR-0064). yaag renders it once per spawn; every consumer downstream of
44
+ * the spawn-request seam sees the rendered string.
45
+ *
46
+ * A value from `yaagSystemPrompt()` or from a `ctx.render*()` call belongs
47
+ * inside a `defineSystemPrompt` definition: the type rejects it here, and
48
+ * yaag also rejects it at run time, before the Agent starts (ADR-0060).
38
49
  */
39
- readonly systemPrompt?: string;
40
- /** Adds text after pi's default system prompt, which stays (`pi --append-system-prompt`). */
50
+ readonly systemPrompt?: LiteralPromptText | SystemPromptDefinition;
51
+ /** Adds text inside the Agent System Prompt, which stays. */
41
52
  readonly appendSystemPrompt?: string;
42
53
  /**
43
54
  * Restores pi discovery. Omission or false selects ADR-0026's hermetic baseline.
@@ -61,8 +61,9 @@ export type YaagErrorCode =
61
61
  | "PROFILE_NOT_FOUND" // a selected Profile is not declared by the program (ADR-0052)
62
62
  | "PROFILE_REQUIRED" // a Profiled Definition was spawned by a program that declares no Profiles
63
63
  | "ROLE_NOT_FOUND" // a factory read a Role the program does not declare
64
- | "RUN_CLOSED" // spawn was requested after the Run began settling
64
+ | "RUN_CLOSED" // spawn or Ask requested after the Run began settling
65
+ | "RUN_PAUSED" // an external pause drain settled the Run (ADR-0024)
65
66
  | "RUN_STOPPED" // the Run's abort signal fired before the program completed
66
67
  | "WORKTREE_REFUSED" // base cwd is not a clean Git repository
67
68
  | "MODEL_RESOLUTION_FAILED" // the resolver gave up, or every candidate failed; carries the history
68
- | "SPAWN_FAILED"; // pi failed to start, e.g. a broken tool contract or a startup timeout
69
+ | "SPAWN_FAILED"; // the spawn was refused, e.g. a guarded system prompt, a broken tool contract or a startup timeout
@@ -33,3 +33,13 @@ export type {
33
33
  SpawnOptions,
34
34
  SpawnOverrides,
35
35
  } from "./spawn-options.ts";
36
+ export type {
37
+ LiteralPromptText,
38
+ PromptAudience,
39
+ PromptText,
40
+ SystemPromptAgent,
41
+ SystemPromptBuilder,
42
+ SystemPromptContext,
43
+ SystemPromptDefinition,
44
+ SystemPromptInput,
45
+ } from "./system-prompt.ts";
@@ -35,10 +35,16 @@ export interface SpawnOptions extends AgentPolicy {
35
35
  * Link to a name, which travels in `OpenOptions` and stays out of Ask identity.
36
36
  * `askDefaults` is omitted too: the Ask hash sees the defaults through the
37
37
  * merged Ask options, so they never enter the recorded spawn options.
38
+ *
39
+ * `systemPrompt` narrows to a string: a Prompt Definition renders at the
40
+ * spawn-request seam, so no consumer of this shape can ever see a function
41
+ * (ADR-0064). An unset prompt stays unset here; the default text is filled in
42
+ * `openRequest` alone, so the Ask hash keeps hashing `systemPrompt: null`.
38
43
  */
39
44
  export interface ResolvedSpawnOptions
40
- extends Omit<SpawnOptions, "model" | "thinking" | "parent" | "askDefaults"> {
45
+ extends Omit<SpawnOptions, "model" | "thinking" | "parent" | "askDefaults" | "systemPrompt"> {
41
46
  readonly model?: string;
47
+ readonly systemPrompt?: string;
42
48
  readonly thinking?: ThinkingLevel;
43
49
  }
44
50