@yaag/runtime 0.21.0 → 0.23.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/src/run/run.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  createCheckpointFlusher,
14
14
  flushingSink,
15
15
  interruptedResumeWarning,
16
+ keepsCheckpoint,
16
17
  loadCassette,
17
18
  type ProgramIdentity,
18
19
  prepareRecordDestination,
@@ -28,7 +29,8 @@ import {
28
29
  writeRecordingDiagnostic,
29
30
  } from "../cassette/index.ts";
30
31
  import { type EffectiveConfig, EMPTY_EFFECTIVE_CONFIG } from "../config/index.ts";
31
- import { isYaagError, YaagError } from "../errors.ts";
32
+ import { controlRequests, createAskAdmission, type RunController } from "../control/index.ts";
33
+ import { YaagError } from "../errors.ts";
32
34
  import type { EventSink, LifecycleEvent, RunOutcome, StampedEventSink } from "../events.ts";
33
35
  import { selectProfile } from "../profile/index.ts";
34
36
  import { applyEvent, initialSummary, type RunSummary } from "../summary/index.ts";
@@ -43,6 +45,7 @@ import {
43
45
  import { validateArgs } from "./args-validation.ts";
44
46
  import { type OrchestrationProgram, programDefinition } from "./define-run.ts";
45
47
  import type { RunContext } from "./run-context.ts";
48
+ import { type RunSettlement, settleRun } from "./run-settlement.ts";
46
49
 
47
50
  export interface RunOptions {
48
51
  /** Where Agents come from. Defaults to real `pi --mode rpc` processes. */
@@ -72,6 +75,12 @@ export interface RunOptions {
72
75
  readonly resume?: string;
73
76
  /** Ends the Run early; every Agent is still reaped and costed. */
74
77
  readonly signal?: AbortSignal;
78
+ /**
79
+ * External Run control: a bounded pause drain, or a stop (ADR-0024). A stop
80
+ * outranks a pause, before or during its drain. `signal` keeps working, and
81
+ * an abort is folded in as a stop.
82
+ */
83
+ readonly control?: RunController;
75
84
  /** Overrides the default checkpoint directory a stopped Run publishes into (ADR-0021). */
76
85
  readonly checkpointDir?: string;
77
86
  /**
@@ -187,10 +196,12 @@ export async function executeRun<Args, Result>(
187
196
  });
188
197
  const agents: Agent[] = [];
189
198
  const startedAt = Date.now();
199
+ const askAdmission = createAskAdmission();
190
200
  const spawnGate = makeSpawn({
191
201
  factory,
192
202
  agents,
193
203
  emit,
204
+ askAdmission,
194
205
  sessionDir: options.sessionDir,
195
206
  programFile: options.programFile,
196
207
  configExtensions: options.config?.extensions ?? EMPTY_EFFECTIVE_CONFIG.extensions,
@@ -211,16 +222,19 @@ export async function executeRun<Args, Result>(
211
222
 
212
223
  // The program's settlement is held rather than rethrown from a `finally`, so
213
224
  // publication can displace it when the checkpoint fails (ADR-0021).
214
- let outcome: RunOutcome = "failed";
215
- let settled: Settlement<Result>;
216
- try {
217
- const value = await Promise.race([definition.run(ctx), stopped(options.signal)]);
218
- outcome = "completed";
219
- settled = { ok: true, value };
220
- } catch (error) {
221
- outcome = stopOutcome(error);
222
- settled = { ok: false, error };
223
- }
225
+ const settlement = await settleRun({
226
+ program: () => definition.run(ctx),
227
+ requests: controlRequests(options.control, options.signal),
228
+ agents,
229
+ closeAdmission: () => {
230
+ askAdmission.close();
231
+ spawnGate.close();
232
+ },
233
+ });
234
+ const outcome: RunOutcome = settlement.outcome;
235
+ const settled = heldSettlement(settlement);
236
+ // Idempotent: a settlement that never drained has not closed admission yet.
237
+ askAdmission.close();
224
238
  spawnGate.close();
225
239
  await reapAll({ agents, emit });
226
240
  // No flush may land after the settled artifact, or an acknowledged Run would
@@ -233,7 +247,7 @@ export async function executeRun<Args, Result>(
233
247
  emit,
234
248
  durationMs: Date.now() - startedAt,
235
249
  summary,
236
- ...endingFrom(publication, outcome),
250
+ ...endingFrom({ publication, outcome, destination, record: options.record }),
237
251
  });
238
252
  if (publication.kind === "displaced") throw publication.error;
239
253
  if (!settled.ok) throw settled.error;
@@ -284,9 +298,29 @@ type Settlement<Result> =
284
298
  | { readonly ok: true; readonly value: Result }
285
299
  | { readonly ok: false; readonly error: unknown };
286
300
 
287
- /** The stop signal is the only rejection that is not a Run failure (ADR-0022). */
288
- function stopOutcome(error: unknown): RunOutcome {
289
- return isYaagError(error) && error.code === "RUN_STOPPED" ? "stopped" : "failed";
301
+ /**
302
+ * Turns one settlement into the result the Run holds until its Checkpoint has
303
+ * landed. A stopped or paused Run rejects with its own code, so the caller can
304
+ * tell an ended Run from a failed one (ADR-0024).
305
+ */
306
+ function heldSettlement<Result>(settlement: RunSettlement<Result>): Settlement<Result> {
307
+ switch (settlement.outcome) {
308
+ case "completed":
309
+ return { ok: true, value: settlement.value };
310
+ case "failed":
311
+ return { ok: false, error: settlement.error };
312
+ case "paused":
313
+ // The cut-short Agents are named here, so the rejection says which Asks
314
+ // the deadline ended rather than leaving that to the Checkpoint alone.
315
+ return { ok: false, error: new YaagError("RUN_PAUSED", pauseMessage(settlement.cutShort)) };
316
+ case "stopped":
317
+ return { ok: false, error: new YaagError("RUN_STOPPED", "run stopped") };
318
+ }
319
+ }
320
+
321
+ /** Names the Asks a pause deadline cut short, or reports a clean drain. */
322
+ function pauseMessage(cutShort: readonly string[]): string {
323
+ return cutShort.length === 0 ? "run paused" : `run paused, cutting short: ${cutShort.join(", ")}`;
290
324
  }
291
325
 
292
326
  /**
@@ -337,17 +371,6 @@ function selectLiveFactory(selection: FactorySelection): TransportFactory {
337
371
  return selection.resume === null ? live : resumeTransport(selection.resume, live);
338
372
  }
339
373
 
340
- /** Rejects when the Run is stopped; never resolves. */
341
- function stopped(signal: AbortSignal | undefined): Promise<never> {
342
- return new Promise<never>((_resolve, reject) => {
343
- if (!signal) return;
344
- if (signal.aborted) reject(new YaagError("RUN_STOPPED", "run stopped"));
345
- signal.addEventListener("abort", () => reject(new YaagError("RUN_STOPPED", "run stopped")), {
346
- once: true,
347
- });
348
- });
349
- }
350
-
351
374
  interface ReapOptions {
352
375
  readonly agents: readonly Agent[];
353
376
  readonly emit: EventSink;
@@ -385,19 +408,39 @@ interface RunEndOptions {
385
408
  readonly summary: RunSummary;
386
409
  /** Publication error text when a requested Checkpoint was lost (ticket 04). */
387
410
  readonly checkpointLost?: string;
411
+ /** Path of the published Checkpoint a paused or stopped Run resumes from (ADR-0054). */
412
+ readonly checkpoint?: string;
388
413
  }
389
414
 
390
415
  /**
391
416
  * Folds one publication result into how the Run ends. A displaced publication
392
417
  * takes the outcome; a lost Checkpoint keeps it and reports the loss instead.
393
418
  */
394
- function endingFrom(
395
- publication: RunCheckpointResult,
396
- outcome: RunOutcome,
397
- ): { readonly outcome: RunOutcome; readonly checkpointLost?: string } {
419
+ function endingFrom(options: {
420
+ readonly publication: RunCheckpointResult;
421
+ readonly outcome: RunOutcome;
422
+ readonly destination: string;
423
+ /** The `--record` destination, or undefined; it decides what is kept. */
424
+ readonly record: string | undefined;
425
+ }): {
426
+ readonly outcome: RunOutcome;
427
+ readonly checkpointLost?: string;
428
+ readonly checkpoint?: string;
429
+ } {
430
+ const { publication, outcome, destination, record } = options;
398
431
  switch (publication.kind) {
399
432
  case "published":
400
- return { outcome };
433
+ // A Run names a Checkpoint only when publication kept the artifact, and
434
+ // only a paused or stopped Run resumes from one (ADR-0054). `keepsCheckpoint`
435
+ // is the one rule for the first half, so no Run can name a file that
436
+ // publication just deleted.
437
+ return {
438
+ outcome,
439
+ ...((outcome === "paused" || outcome === "stopped") &&
440
+ keepsCheckpoint({ outcome, ...(record === undefined ? {} : { record }) })
441
+ ? { checkpoint: destination }
442
+ : {}),
443
+ };
401
444
  case "lost":
402
445
  return { outcome, checkpointLost: publication.message };
403
446
  case "displaced":
@@ -406,10 +449,18 @@ function endingFrom(
406
449
  }
407
450
 
408
451
  /** Emits the Run's acknowledgement, the last Lifecycle Event of every Run. */
409
- function emitRunEnd({ emit, outcome, durationMs, summary, checkpointLost }: RunEndOptions): void {
452
+ function emitRunEnd({
453
+ emit,
454
+ outcome,
455
+ durationMs,
456
+ summary,
457
+ checkpointLost,
458
+ checkpoint,
459
+ }: RunEndOptions): void {
410
460
  emit({
411
461
  type: "run_end",
412
462
  ...(checkpointLost === undefined ? {} : { checkpointLost }),
463
+ ...(checkpoint === undefined ? {} : { checkpoint }),
413
464
  ok: outcome === "completed",
414
465
  outcome,
415
466
  durationMs,
@@ -78,6 +78,11 @@ export interface EndedRunSummary extends RunSummaryBase {
78
78
  * artifact too. Carries the publication error text (ticket 04).
79
79
  */
80
80
  readonly checkpointLost?: string;
81
+ /**
82
+ * Path of the Checkpoint the Run published; null when it kept none
83
+ * (ADR-0054). Only a paused or stopped Run names one.
84
+ */
85
+ readonly checkpoint: string | null;
81
86
  }
82
87
 
83
88
  /**
@@ -218,6 +223,7 @@ function endRun(
218
223
  endedAt: at,
219
224
  durationMs: event.durationMs,
220
225
  worstFrameGapMs: event.worstFrameGapMs,
226
+ checkpoint: event.checkpoint ?? null,
221
227
  ...(event.checkpointLost === undefined ? {} : { checkpointLost: event.checkpointLost }),
222
228
  };
223
229
  }