@praudent/dagma 0.0.0-stage → 0.1.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 (177) hide show
  1. package/dist/admin-ui/assets/index-CHJ8lsZp.js +120 -0
  2. package/dist/admin-ui/assets/index-XyqtD-IA.css +1 -0
  3. package/dist/admin-ui/index.html +12 -0
  4. package/dist/blueprint/agent.d.ts +148 -0
  5. package/dist/blueprint/agent.js +1 -0
  6. package/dist/blueprint/declaration-site.d.ts +7 -0
  7. package/dist/blueprint/declaration-site.js +8 -0
  8. package/dist/blueprint/declared-structure.d.ts +145 -0
  9. package/dist/blueprint/declared-structure.js +213 -0
  10. package/dist/blueprint/define-run-state.d.ts +79 -0
  11. package/dist/blueprint/define-run-state.js +89 -0
  12. package/dist/blueprint/load-blueprint.d.ts +28 -0
  13. package/dist/blueprint/load-blueprint.js +85 -0
  14. package/dist/blueprint/outcomes.d.ts +76 -0
  15. package/dist/blueprint/outcomes.js +10 -0
  16. package/dist/blueprint/phase.d.ts +153 -0
  17. package/dist/blueprint/phase.js +1 -0
  18. package/dist/blueprint/places.d.ts +26 -0
  19. package/dist/blueprint/places.js +37 -0
  20. package/dist/blueprint/prompt-file.d.ts +81 -0
  21. package/dist/blueprint/prompt-file.js +131 -0
  22. package/dist/blueprint/reply-reader.d.ts +36 -0
  23. package/dist/blueprint/reply-reader.js +38 -0
  24. package/dist/blueprint/run-settings.d.ts +38 -0
  25. package/dist/blueprint/run-settings.js +1 -0
  26. package/dist/blueprint/serializer.d.ts +14 -0
  27. package/dist/blueprint/serializer.js +4 -0
  28. package/dist/blueprint/write-scope.d.ts +39 -0
  29. package/dist/blueprint/write-scope.js +106 -0
  30. package/dist/command.d.ts +2 -0
  31. package/dist/command.js +148 -0
  32. package/dist/commands/calls-answering.d.ts +16 -0
  33. package/dist/commands/calls-answering.js +63 -0
  34. package/dist/commands/json-file.d.ts +6 -0
  35. package/dist/commands/json-file.js +19 -0
  36. package/dist/commands/run-command.d.ts +23 -0
  37. package/dist/commands/run-command.js +172 -0
  38. package/dist/commands/typed-answers.d.ts +10 -0
  39. package/dist/commands/typed-answers.js +43 -0
  40. package/dist/config.d.ts +27 -0
  41. package/dist/config.js +20 -0
  42. package/dist/devtool-server/app-pages.d.ts +12 -0
  43. package/dist/devtool-server/app-pages.js +68 -0
  44. package/dist/devtool-server/blueprint-description.d.ts +21 -0
  45. package/dist/devtool-server/blueprint-description.js +27 -0
  46. package/dist/devtool-server/connected-runs.d.ts +36 -0
  47. package/dist/devtool-server/connected-runs.js +201 -0
  48. package/dist/devtool-server/devtool-server.d.ts +17 -0
  49. package/dist/devtool-server/devtool-server.js +294 -0
  50. package/dist/devtool-server/devtool-shapes.d.ts +312 -0
  51. package/dist/devtool-server/devtool-shapes.js +24 -0
  52. package/dist/devtool-server/listed-runs.d.ts +17 -0
  53. package/dist/devtool-server/listed-runs.js +42 -0
  54. package/dist/devtool-server/print-blueprint.d.ts +1 -0
  55. package/dist/devtool-server/print-blueprint.js +36 -0
  56. package/dist/example/added-species.d.ts +21 -0
  57. package/dist/example/added-species.js +19 -0
  58. package/dist/example/cover.d.ts +21 -0
  59. package/dist/example/cover.js +67 -0
  60. package/dist/example/cross-references.d.ts +21 -0
  61. package/dist/example/cross-references.js +77 -0
  62. package/dist/example/entry-drafts.d.ts +21 -0
  63. package/dist/example/entry-drafts.js +63 -0
  64. package/dist/example/entry-merge.d.ts +108 -0
  65. package/dist/example/entry-merge.js +284 -0
  66. package/dist/example/field-guide.d.ts +26 -0
  67. package/dist/example/field-guide.js +40 -0
  68. package/dist/example/guide-page.d.ts +21 -0
  69. package/dist/example/guide-page.js +15 -0
  70. package/dist/example/missing-species.d.ts +21 -0
  71. package/dist/example/missing-species.js +59 -0
  72. package/dist/example/run-state.d.ts +803 -0
  73. package/dist/example/run-state.js +58 -0
  74. package/dist/example/serializers.d.ts +32 -0
  75. package/dist/example/serializers.js +42 -0
  76. package/dist/example/species-list.d.ts +47 -0
  77. package/dist/example/species-list.js +93 -0
  78. package/dist/index.d.ts +35 -0
  79. package/dist/index.js +25 -0
  80. package/dist/inference/anthropic-api.d.ts +37 -0
  81. package/dist/inference/anthropic-api.js +197 -0
  82. package/dist/inference/anthropic-prices.d.ts +18 -0
  83. package/dist/inference/anthropic-prices.js +39 -0
  84. package/dist/inference/anthropic-request.d.ts +51 -0
  85. package/dist/inference/anthropic-request.js +208 -0
  86. package/dist/inference/bedrock-api.d.ts +45 -0
  87. package/dist/inference/bedrock-api.js +242 -0
  88. package/dist/inference/bedrock-prices.d.ts +22 -0
  89. package/dist/inference/bedrock-prices.js +79 -0
  90. package/dist/inference/bedrock-request.d.ts +27 -0
  91. package/dist/inference/bedrock-request.js +193 -0
  92. package/dist/inference/call-queue-shapes.d.ts +273 -0
  93. package/dist/inference/call-queue-shapes.js +82 -0
  94. package/dist/inference/call-queue.d.ts +109 -0
  95. package/dist/inference/call-queue.js +408 -0
  96. package/dist/inference/gemini-api.d.ts +44 -0
  97. package/dist/inference/gemini-api.js +191 -0
  98. package/dist/inference/gemini-prices.d.ts +19 -0
  99. package/dist/inference/gemini-prices.js +33 -0
  100. package/dist/inference/gemini-request.d.ts +25 -0
  101. package/dist/inference/gemini-request.js +126 -0
  102. package/dist/inference/inference.d.ts +84 -0
  103. package/dist/inference/inference.js +9 -0
  104. package/dist/inference/openai-api.d.ts +29 -0
  105. package/dist/inference/openai-api.js +138 -0
  106. package/dist/inference/openai-prices.d.ts +12 -0
  107. package/dist/inference/openai-prices.js +25 -0
  108. package/dist/inference/openai-request.d.ts +50 -0
  109. package/dist/inference/openai-request.js +100 -0
  110. package/dist/inference/own-worker.d.ts +6 -0
  111. package/dist/inference/own-worker.js +16 -0
  112. package/dist/inference/scripted.d.ts +146 -0
  113. package/dist/inference/scripted.js +67 -0
  114. package/dist/run/assignments/agent-call.d.ts +32 -0
  115. package/dist/run/assignments/agent-call.js +218 -0
  116. package/dist/run/assignments/agent-phase.d.ts +14 -0
  117. package/dist/run/assignments/agent-phase.js +243 -0
  118. package/dist/run/assignments/assignment-memory.d.ts +42 -0
  119. package/dist/run/assignments/assignment-memory.js +52 -0
  120. package/dist/run/assignments/assignment.d.ts +17 -0
  121. package/dist/run/assignments/assignment.js +252 -0
  122. package/dist/run/assignments/model-settings.d.ts +39 -0
  123. package/dist/run/assignments/model-settings.js +57 -0
  124. package/dist/run/assignments/prepared-call.d.ts +28 -0
  125. package/dist/run/assignments/prepared-call.js +115 -0
  126. package/dist/run/assignments/tool-call.d.ts +26 -0
  127. package/dist/run/assignments/tool-call.js +108 -0
  128. package/dist/run/blueprint-mistake.d.ts +8 -0
  129. package/dist/run/blueprint-mistake.js +14 -0
  130. package/dist/run/code-phase.d.ts +11 -0
  131. package/dist/run/code-phase.js +59 -0
  132. package/dist/run/create-run.d.ts +36 -0
  133. package/dist/run/create-run.js +119 -0
  134. package/dist/run/execute-run.d.ts +7 -0
  135. package/dist/run/execute-run.js +158 -0
  136. package/dist/run/record/apply-event.d.ts +13 -0
  137. package/dist/run/record/apply-event.js +256 -0
  138. package/dist/run/record/events.d.ts +187 -0
  139. package/dist/run/record/events.js +1 -0
  140. package/dist/run/record/postgres-run-store.d.ts +13 -0
  141. package/dist/run/record/postgres-run-store.js +189 -0
  142. package/dist/run/record/progress-projection.d.ts +83 -0
  143. package/dist/run/record/progress-projection.js +167 -0
  144. package/dist/run/record/progress.d.ts +207 -0
  145. package/dist/run/record/progress.js +63 -0
  146. package/dist/run/record/run-store.d.ts +74 -0
  147. package/dist/run/record/run-store.js +1 -0
  148. package/dist/run/record/run-summary.d.ts +8 -0
  149. package/dist/run/record/run-summary.js +19 -0
  150. package/dist/run/record/run-types.d.ts +95 -0
  151. package/dist/run/record/run-types.js +1 -0
  152. package/dist/run/record/state-changes.d.ts +42 -0
  153. package/dist/run/record/state-changes.js +157 -0
  154. package/dist/run/resume-run.d.ts +25 -0
  155. package/dist/run/resume-run.js +99 -0
  156. package/dist/run/run-endings.d.ts +20 -0
  157. package/dist/run/run-endings.js +20 -0
  158. package/dist/run/run-option-shapes.d.ts +176 -0
  159. package/dist/run/run-option-shapes.js +47 -0
  160. package/dist/run/run-session.d.ts +144 -0
  161. package/dist/run/run-session.js +278 -0
  162. package/dist/worker/answer-queued-call.d.ts +19 -0
  163. package/dist/worker/answer-queued-call.js +100 -0
  164. package/dist/worker/launchers/claude-code.d.ts +7 -0
  165. package/dist/worker/launchers/claude-code.js +156 -0
  166. package/dist/worker/launchers/codex.d.ts +6 -0
  167. package/dist/worker/launchers/codex.js +141 -0
  168. package/dist/worker/launchers/launch.d.ts +31 -0
  169. package/dist/worker/launchers/launch.js +6 -0
  170. package/dist/worker/launchers/program-run.d.ts +30 -0
  171. package/dist/worker/launchers/program-run.js +92 -0
  172. package/dist/worker/launchers/tool-server.d.ts +26 -0
  173. package/dist/worker/launchers/tool-server.js +90 -0
  174. package/dist/worker/worker.d.ts +13 -0
  175. package/dist/worker/worker.js +170 -0
  176. package/package.json +43 -4
  177. package/README.md +0 -3
@@ -0,0 +1,63 @@
1
+ import { deepFreeze } from './state-changes.js';
2
+ /** The name of the checkpoint a run starts from. */
3
+ export const START_CHECKPOINT_NAME = '0-start';
4
+ /** How an assignment's lane, key and repeat are written in `finishedAssignments`. */
5
+ export const assignmentIdentity = ({ lane, key, repeat, }) => JSON.stringify([lane, key, repeat]);
6
+ /** The lane, key and repeat an identity was written from. */
7
+ export const partsOfAssignmentIdentity = (identity) => {
8
+ const [lane, key, repeat] = JSON.parse(identity);
9
+ return { lane, key, repeat };
10
+ };
11
+ /** A copy whose keys are all ordinary ones: names from a blueprint or a model, such as
12
+ * `constructor`, must not reach Object's own. */
13
+ const keyedByName = (record) => Object.assign(Object.create(null), record);
14
+ /** The progress of a run that has made no events yet, from its starting checkpoint. */
15
+ export function progressAtStart({ start }) {
16
+ const finishedAssignments = keyedByName({});
17
+ for (const [place, identities] of Object.entries(start.finishedAssignments))
18
+ finishedAssignments[place] = keyedByName(identities);
19
+ /** Where a run started from a checkpoint stands: at the end of that checkpoint's place. */
20
+ const position = () => {
21
+ if (!start.phase)
22
+ return {};
23
+ const finished = { stage: 'finished', fromCheckpoint: true };
24
+ // After a place on a side line the visit goes on, and its trunk phase is still open.
25
+ return start.openVisit
26
+ ? {
27
+ phasePosition: { phase: start.openVisit.during, stage: 'running' },
28
+ openVisit: { ...start.openVisit, position: { place: start.phase, ...finished } },
29
+ }
30
+ : { phasePosition: { phase: start.phase, ...finished } };
31
+ };
32
+ return {
33
+ seq: 0,
34
+ status: 'running',
35
+ state: deepFreeze(start.state),
36
+ overrides: [],
37
+ stoppedAfterPhase: false,
38
+ sideLineVisits: keyedByName(start.sideLineVisits),
39
+ ...position(),
40
+ assignments: Object.create(null),
41
+ assignmentIds: [],
42
+ finishedAssignments,
43
+ questions: Object.create(null),
44
+ questionIds: [],
45
+ codePhases: Object.create(null),
46
+ artifacts: keyedByName(start.artifacts),
47
+ calls: Object.create(null),
48
+ checkpointsSaved: 0,
49
+ totals: {
50
+ calls: 0,
51
+ corrections: 0,
52
+ tokens: { input: 0, cached: 0, output: 0, reasoning: 0 },
53
+ callsNotReporting: { input: 0, cached: 0, output: 0, reasoning: 0 },
54
+ durationMs: 0,
55
+ costUsd: 0,
56
+ programCostUsd: 0,
57
+ },
58
+ };
59
+ }
60
+ /** Whether every question in the list has an answer. */
61
+ export function allAnswered({ progress, questionIds, }) {
62
+ return questionIds.every((id) => progress.questions[id]?.answer !== undefined);
63
+ }
@@ -0,0 +1,74 @@
1
+ import type { DeclaredStructure } from '../../blueprint/declared-structure.js';
2
+ import type { Artifact } from '../../blueprint/outcomes.js';
3
+ import type { RunEvent, SavedArtifact } from './events.js';
4
+ import type { Checkpoint } from './progress.js';
5
+ import type { CallFile, RunSummary } from './run-types.js';
6
+ /** Persistence port for Dagma runs. Postgres (`postgresRunStore`) is the single runtime adapter. */
7
+ export type RunStore = {
8
+ ensureSchema?: () => Promise<void>;
9
+ createRunId: () => Promise<string>;
10
+ writeRunSummary: (input: {
11
+ runId: string;
12
+ summary: RunSummary;
13
+ input?: unknown;
14
+ }) => Promise<void>;
15
+ readRunSummary: (input: {
16
+ runId: string;
17
+ }) => Promise<RunSummary | undefined>;
18
+ listRunSummaries: () => Promise<{
19
+ summary: RunSummary;
20
+ input: unknown;
21
+ }[]>;
22
+ readInput: (input: {
23
+ runId: string;
24
+ }) => Promise<unknown>;
25
+ writeStructure: (input: {
26
+ runId: string;
27
+ number: number;
28
+ structure: DeclaredStructure;
29
+ }) => Promise<string>;
30
+ readStructure: (input: {
31
+ runId: string;
32
+ name: string;
33
+ }) => Promise<DeclaredStructure | undefined>;
34
+ appendEvent: (input: {
35
+ runId: string;
36
+ event: RunEvent;
37
+ }) => Promise<void>;
38
+ readEvents: (input: {
39
+ runId: string;
40
+ afterSeq?: number;
41
+ }) => Promise<RunEvent[]>;
42
+ writeCheckpoint: (input: {
43
+ runId: string;
44
+ checkpoint: Checkpoint;
45
+ }) => Promise<string>;
46
+ readCheckpoint: (input: {
47
+ runId: string;
48
+ name: string;
49
+ }) => Promise<Checkpoint | undefined>;
50
+ listCheckpoints: (input: {
51
+ runId: string;
52
+ }) => Promise<string[]>;
53
+ writeCall: (input: {
54
+ runId: string;
55
+ call: CallFile;
56
+ }) => Promise<void>;
57
+ readCall: (input: {
58
+ runId: string;
59
+ callId: string;
60
+ }) => Promise<CallFile | undefined>;
61
+ writeArtifact: (input: {
62
+ runId: string;
63
+ id: string;
64
+ artifact: Artifact;
65
+ }) => Promise<SavedArtifact>;
66
+ readArtifact: (input: {
67
+ runId: string;
68
+ saved: SavedArtifact;
69
+ }) => Promise<{
70
+ name: string;
71
+ mediaType: string;
72
+ bytes: Uint8Array;
73
+ }>;
74
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { RunProgress } from './progress.js';
2
+ import type { RunSummary } from './run-types.js';
3
+ /** What the Runs table shows for a run, worked out from where the run stands. */
4
+ export declare function summaryOfProgress({ runId, blueprintName, progress, }: {
5
+ runId: string;
6
+ blueprintName: string;
7
+ progress: RunProgress;
8
+ }): RunSummary;
@@ -0,0 +1,19 @@
1
+ /** What the Runs table shows for a run, worked out from where the run stands. */
2
+ export function summaryOfProgress({ runId, blueprintName, progress, }) {
3
+ const { phasePosition } = progress;
4
+ return {
5
+ runId,
6
+ blueprint: blueprintName,
7
+ blueprintHash: progress.blueprintHash ?? '',
8
+ createdAt: progress.createdAt ?? new Date().toISOString(),
9
+ status: progress.status,
10
+ ...(progress.reason ? { reason: progress.reason } : {}),
11
+ callsAnsweredBy: progress.callsAnsweredBy ?? 'scripted',
12
+ questionsAnsweredBy: progress.questionsAnsweredBy ?? 'person',
13
+ ...(progress.startedFrom ? { startedFrom: progress.startedFrom } : {}),
14
+ ...(progress.stopAfter ? { stopAfter: progress.stopAfter } : {}),
15
+ ...(phasePosition ? { phaseReached: phasePosition.phase } : {}),
16
+ seq: progress.seq,
17
+ totals: progress.totals,
18
+ };
19
+ }
@@ -0,0 +1,95 @@
1
+ import type { PromptRange } from '../../blueprint/prompt-file.js';
2
+ import type { CallsAnsweredBy, QuestionsAnsweredBy } from '../../blueprint/run-settings.js';
3
+ import type { Tokens } from './events.js';
4
+ import type { RunProgress, RunStatus } from './progress.js';
5
+ /** What the Runs table shows for one run: a copy of what its events say. */
6
+ export type RunSummary = {
7
+ runId: string;
8
+ blueprint: string;
9
+ blueprintHash: string;
10
+ createdAt: string;
11
+ status: RunStatus;
12
+ reason?: string;
13
+ callsAnsweredBy: CallsAnsweredBy;
14
+ questionsAnsweredBy: QuestionsAnsweredBy;
15
+ startedFrom?: {
16
+ runId: string;
17
+ checkpoint: string;
18
+ };
19
+ stopAfter?: string;
20
+ phaseReached?: string;
21
+ /** The last events line these numbers include. */
22
+ seq: number;
23
+ totals: RunProgress['totals'];
24
+ };
25
+ /** One tool call of a call, recorded where its handler ran. */
26
+ export type SavedToolCall = {
27
+ tool: string;
28
+ arguments: unknown;
29
+ result?: unknown;
30
+ error?: string;
31
+ durationMs: number;
32
+ status: 'returned' | 'failed' | 'asked';
33
+ };
34
+ /** A reasoning summary the provider returned, and how many of the call's tool calls came before. */
35
+ export type ReasoningSummary = {
36
+ text: string;
37
+ afterToolCalls: number;
38
+ };
39
+ /** One call's record: what the model was shown and what it answered. Written when the call starts,
40
+ * again after each tool call, and completed when it ends. Outcome, tokens and duration are in the
41
+ * call's events lines. */
42
+ export type CallFile = {
43
+ callId: string;
44
+ assignmentId: string;
45
+ phase: string;
46
+ lane: string;
47
+ subjectKey: string;
48
+ repeat: number;
49
+ agent: string;
50
+ placeInChain: number;
51
+ attempt: number;
52
+ answeredBy: CallsAnsweredBy;
53
+ model?: string;
54
+ effort?: string;
55
+ promptFile: {
56
+ path: string;
57
+ text: string;
58
+ templates: string[];
59
+ };
60
+ /** The complete prompt, once. */
61
+ prompt: string;
62
+ inputs: {
63
+ placeholder: string;
64
+ description: string;
65
+ serializer: string;
66
+ sizeInBytes: number;
67
+ ranges: PromptRange[];
68
+ }[];
69
+ /** Where each placed template's text sits in the prompt. */
70
+ templates: {
71
+ template: string;
72
+ ranges: PromptRange[];
73
+ }[];
74
+ attachedImages: {
75
+ name: string;
76
+ artifactId: string;
77
+ }[];
78
+ tools: {
79
+ name: string;
80
+ description: string;
81
+ inputSchema: unknown;
82
+ annotations?: unknown;
83
+ }[];
84
+ startedAt: string;
85
+ /** The instruction text the launcher sent beside the prompt, when one answered. */
86
+ launcherInstruction?: string;
87
+ toolCalls: SavedToolCall[];
88
+ reasoning: ReasoningSummary[];
89
+ replyText?: string;
90
+ replyParsed?: unknown;
91
+ /** The correction sent back with this reply. */
92
+ correction?: string;
93
+ failure?: string;
94
+ tokens?: Tokens;
95
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,42 @@
1
+ import type { z } from 'zod';
2
+ import type { Change } from '../../blueprint/outcomes.js';
3
+ import type { ChangeEntry } from './events.js';
4
+ /** Freezes a value and everything inside it that is not frozen yet, so a change that edits the
5
+ * state in place throws instead of silently changing saved history. */
6
+ export declare function deepFreeze<Value>(value: Value): Value;
7
+ /** Each place where `after` differs from `before`. A list that only grew or shrank at its end is
8
+ * recorded item by item; a list changed any other way is recorded whole. */
9
+ export declare function changedPlaces({ before, after }: {
10
+ before: unknown;
11
+ after: unknown;
12
+ }): ChangeEntry[];
13
+ /** The state with saved change entries applied, copying only the containers on each path. */
14
+ export declare function withChangeEntries({ state, entries }: {
15
+ state: unknown;
16
+ entries: ChangeEntry[];
17
+ }): unknown;
18
+ /** Checks a state against the blueprint's schema and returns it as the schema parsed it, with
19
+ * the schema's defaults filled in. A failure, or a field the schema does not have, is a mistake
20
+ * in the blueprint. */
21
+ export declare function stateFittedToSchema<State>({ state, schema, madeBy, }: {
22
+ state: unknown;
23
+ schema: z.ZodType<State, z.ZodTypeDef, unknown>;
24
+ /** What produced the state, for the message. */
25
+ madeBy: string;
26
+ }): State;
27
+ /** Runs a change against the state as it stands and fits the result to the blueprint's schema. */
28
+ export declare function fittedNextState<State>({ state, change, schema, madeBy, }: {
29
+ state: State;
30
+ change: Change<State>;
31
+ schema: z.ZodType<State, z.ZodTypeDef, unknown>;
32
+ madeBy: string;
33
+ }): State;
34
+ /** Runs a change against the state as it stands, checks the result against the schema, and
35
+ * returns each place it touched. Nothing is applied: the events line that carries the entries
36
+ * makes them count. */
37
+ export declare function checkedChangeEntries<State>({ state, change, schema, madeBy, }: {
38
+ state: State;
39
+ change: Change<State>;
40
+ schema: z.ZodType<State, z.ZodTypeDef, unknown>;
41
+ madeBy: string;
42
+ }): ChangeEntry[];
@@ -0,0 +1,157 @@
1
+ import { BlueprintMistake } from '../blueprint-mistake.js';
2
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ /** Sets a key as an ordinary one, so that a key named `__proto__` is data like any other. */
4
+ const setKey = ({ record, key, value }) => Object.defineProperty(record, key, {
5
+ value,
6
+ enumerable: true,
7
+ writable: true,
8
+ configurable: true,
9
+ });
10
+ /** Freezes a value and everything inside it that is not frozen yet, so a change that edits the
11
+ * state in place throws instead of silently changing saved history. */
12
+ export function deepFreeze(value) {
13
+ if (typeof value !== 'object' || value === null || Object.isFrozen(value))
14
+ return value;
15
+ Object.freeze(value);
16
+ for (const inner of Object.values(value))
17
+ deepFreeze(inner);
18
+ return value;
19
+ }
20
+ /** Each place where `after` differs from `before`. A list that only grew or shrank at its end is
21
+ * recorded item by item; a list changed any other way is recorded whole. */
22
+ export function changedPlaces({ before, after }) {
23
+ const entries = [];
24
+ const compare = ({ path, was, now }) => {
25
+ if (was === now)
26
+ return;
27
+ if (isRecord(was) && isRecord(now)) {
28
+ for (const key of Object.keys(was))
29
+ if (Object.hasOwn(now, key))
30
+ compare({ path: [...path, key], was: was[key], now: now[key] });
31
+ else
32
+ entries.push({ path: [...path, key], kind: 'removed', before: was[key] });
33
+ for (const key of Object.keys(now))
34
+ if (!Object.hasOwn(was, key))
35
+ entries.push({ path: [...path, key], kind: 'added', after: now[key] });
36
+ return;
37
+ }
38
+ if (Array.isArray(was) && Array.isArray(now)) {
39
+ const shared = Math.min(was.length, now.length);
40
+ const firstOfList = entries.length;
41
+ for (let index = 0; index < shared; index++)
42
+ compare({ path: [...path, index], was: was[index], now: now[index] });
43
+ // Items that moved make every later index differ; one whole-list entry reads better.
44
+ if (was.length !== now.length && entries.length > firstOfList) {
45
+ entries.splice(firstOfList);
46
+ entries.push({ path, kind: 'changed', before: was, after: now });
47
+ return;
48
+ }
49
+ for (let index = shared; index < now.length; index++)
50
+ entries.push({ path: [...path, index], kind: 'added', after: now[index] });
51
+ // Highest index first, so applying the removals in order never shifts a later one.
52
+ for (let index = was.length - 1; index >= shared; index--)
53
+ entries.push({ path: [...path, index], kind: 'removed', before: was[index] });
54
+ return;
55
+ }
56
+ if (JSON.stringify(was) !== JSON.stringify(now))
57
+ entries.push({ path, kind: 'changed', before: was, after: now });
58
+ };
59
+ compare({ path: [], was: before, now: after });
60
+ return entries;
61
+ }
62
+ /** The state with saved change entries applied, copying only the containers on each path. */
63
+ export function withChangeEntries({ state, entries }) {
64
+ const applyAt = ({ value, path, entry, }) => {
65
+ if (!path.length)
66
+ return entry.after;
67
+ const [head, ...rest] = path;
68
+ if (Array.isArray(value)) {
69
+ const copy = [...value];
70
+ const index = head;
71
+ if (rest.length)
72
+ copy[index] = applyAt({ value: copy[index], path: rest, entry });
73
+ else if (entry.kind === 'removed')
74
+ copy.splice(index, 1);
75
+ else
76
+ copy[index] = entry.after;
77
+ return copy;
78
+ }
79
+ const copy = { ...value };
80
+ const key = head;
81
+ if (rest.length)
82
+ setKey({ record: copy, key, value: applyAt({ value: copy[key], path: rest, entry }) });
83
+ else if (entry.kind === 'removed')
84
+ delete copy[key];
85
+ else
86
+ setKey({ record: copy, key, value: entry.after });
87
+ return copy;
88
+ };
89
+ let next = state;
90
+ for (const entry of entries)
91
+ next = applyAt({ value: next, path: entry.path, entry });
92
+ return deepFreeze(next);
93
+ }
94
+ /** The path of the first field in `value` that `parsed` lacks: a field the schema does not have,
95
+ * which Zod drops without failing. */
96
+ function droppedFieldPath({ value, parsed, path = [], }) {
97
+ if (Array.isArray(value) && Array.isArray(parsed))
98
+ for (let index = 0; index < value.length; index++) {
99
+ const dropped = droppedFieldPath({
100
+ value: value[index],
101
+ parsed: parsed[index],
102
+ path: [...path, index],
103
+ });
104
+ if (dropped)
105
+ return dropped;
106
+ }
107
+ if (isRecord(value) && isRecord(parsed))
108
+ for (const key of Object.keys(value)) {
109
+ if (value[key] !== undefined && !Object.hasOwn(parsed, key))
110
+ return [...path, key];
111
+ const dropped = droppedFieldPath({
112
+ value: value[key],
113
+ parsed: parsed[key],
114
+ path: [...path, key],
115
+ });
116
+ if (dropped)
117
+ return dropped;
118
+ }
119
+ return undefined;
120
+ }
121
+ /** Checks a state against the blueprint's schema and returns it as the schema parsed it, with
122
+ * the schema's defaults filled in. A failure, or a field the schema does not have, is a mistake
123
+ * in the blueprint. */
124
+ export function stateFittedToSchema({ state, schema, madeBy, }) {
125
+ const parsed = schema.safeParse(state);
126
+ if (!parsed.success)
127
+ throw new BlueprintMistake(`${madeBy} left the run state in a shape its schema refuses: ${parsed.error.issues
128
+ .map((issue) => `${issue.path.join('.') || 'state'}: ${issue.message}`)
129
+ .join('; ')}`);
130
+ const dropped = droppedFieldPath({ value: state, parsed: parsed.data });
131
+ if (dropped?.at(-1) === '__proto__')
132
+ throw new BlueprintMistake(`${madeBy} wrote ${dropped.join('.')}; the run state cannot hold a key named __proto__.`);
133
+ if (dropped)
134
+ throw new BlueprintMistake(`${madeBy} wrote ${dropped.join('.')}, a field the run state's schema does not have.`);
135
+ return parsed.data;
136
+ }
137
+ /** Runs a change against the state as it stands and fits the result to the blueprint's schema. */
138
+ export function fittedNextState({ state, change, schema, madeBy, }) {
139
+ let plain;
140
+ try {
141
+ // A change must return plain JSON data; this drops anything else before it is compared.
142
+ plain = JSON.parse(JSON.stringify(change(state)));
143
+ }
144
+ catch (error) {
145
+ throw new BlueprintMistake(`${madeBy}'s change threw or did not return plain JSON data: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
146
+ }
147
+ return stateFittedToSchema({ state: plain, schema, madeBy });
148
+ }
149
+ /** Runs a change against the state as it stands, checks the result against the schema, and
150
+ * returns each place it touched. Nothing is applied: the events line that carries the entries
151
+ * makes them count. */
152
+ export function checkedChangeEntries({ state, change, schema, madeBy, }) {
153
+ return changedPlaces({
154
+ before: state,
155
+ after: fittedNextState({ state, change, schema, madeBy }),
156
+ });
157
+ }
@@ -0,0 +1,25 @@
1
+ import { type LoadedBlueprint } from '../blueprint/load-blueprint.js';
2
+ import type { Blueprint } from '../blueprint/phase.js';
3
+ import type { Infer } from '../inference/inference.js';
4
+ import type { ModelOverride } from './record/events.js';
5
+ import type { RunStore } from './record/run-store.js';
6
+ import { RunSession, type RunEventObserver } from './run-session.js';
7
+ /** Opens a stopped, failed or waiting run in `store` to continue it, and records any answers
8
+ * given with it. Concurrency locking is owned by the host. */
9
+ export declare function resumeRun<State = unknown, Input = unknown, Services = unknown>({ blueprint: blueprintInput, store, runId, answers, overrides, infer, services, promptFolder, readPrompt, retryWaitsMs, onEvent, }: {
10
+ blueprint: Blueprint<State, Input, Services> | LoadedBlueprint;
11
+ store: RunStore;
12
+ runId: string;
13
+ answers?: {
14
+ questionId: string;
15
+ answer: string;
16
+ }[];
17
+ /** New overrides for every call made after this resume; the run's own stay when left out. */
18
+ overrides?: ModelOverride[];
19
+ infer: Infer;
20
+ services?: Services;
21
+ promptFolder?: string;
22
+ readPrompt?: (path: string) => string;
23
+ retryWaitsMs?: number[];
24
+ onEvent?: RunEventObserver;
25
+ }): Promise<RunSession<State, Services>>;
@@ -0,0 +1,99 @@
1
+ import { isLoadedBlueprint, prepareBlueprint, } from '../blueprint/load-blueprint.js';
2
+ import { phaseAtPlace } from '../blueprint/places.js';
3
+ import { modelSettingsProblems } from './create-run.js';
4
+ import { START_CHECKPOINT_NAME } from './record/progress.js';
5
+ import { changedPlaces, stateFittedToSchema } from './record/state-changes.js';
6
+ import { RunSession } from './run-session.js';
7
+ /** Opens a stopped, failed or waiting run in `store` to continue it, and records any answers
8
+ * given with it. Concurrency locking is owned by the host. */
9
+ export async function resumeRun({ blueprint: blueprintInput, store, runId, answers = [], overrides, infer, services, promptFolder, readPrompt, retryWaitsMs, onEvent, }) {
10
+ const loaded = isLoadedBlueprint(blueprintInput)
11
+ ? blueprintInput
12
+ : prepareBlueprint({ blueprint: blueprintInput, promptFolder, readPrompt });
13
+ const blueprint = loaded.blueprint;
14
+ const events = await store.readEvents({ runId });
15
+ if (!events.some((event) => event.kind === 'run-started'))
16
+ throw new Error('The run was never started; there is nothing to resume.');
17
+ const start = await store.readCheckpoint({ runId, name: START_CHECKPOINT_NAME });
18
+ if (!start)
19
+ throw new Error(`Run ${runId} is missing its starting checkpoint.`);
20
+ const session = new RunSession({
21
+ runId,
22
+ store,
23
+ blueprint,
24
+ promptFiles: loaded.promptFiles,
25
+ infer,
26
+ services,
27
+ retryWaitsMs,
28
+ start,
29
+ events,
30
+ onEvent,
31
+ });
32
+ const { progress } = session;
33
+ const { phasePosition } = progress;
34
+ const isDeclared = (name) => !!phaseAtPlace({ blueprint, name });
35
+ if (progress.status === 'finished')
36
+ throw new Error('The run has finished; there is nothing to resume.');
37
+ if (phasePosition && !isDeclared(phasePosition.phase))
38
+ throw new Error(`The run stands on ${phasePosition.phase}, which is no longer in the blueprint.`);
39
+ for (const assignment of Object.values(progress.assignments)) {
40
+ const partFinished = assignment.status === 'running' || assignment.status === 'waiting-for-person';
41
+ const phase = phaseAtPlace({ blueprint, name: assignment.phase });
42
+ if (!partFinished || phase?.kind !== 'agents')
43
+ continue;
44
+ const lane = phase.lanes.find((candidate) => candidate.name === assignment.lane);
45
+ const agentsNow = lane?.chain.map((agent) => agent.name);
46
+ if (agentsNow?.join('\n') !== assignment.agents.join('\n'))
47
+ throw new Error(`The chain of ${assignment.label} in ${assignment.phase} has changed since it started (${assignment.agents.join(', ')}).`);
48
+ }
49
+ const answered = [];
50
+ for (const { questionId } of answers) {
51
+ const problem = answered.includes(questionId)
52
+ ? `Question ${questionId} is answered twice.`
53
+ : session.answerProblem({ questionId });
54
+ if (problem)
55
+ throw new Error(problem);
56
+ answered.push(questionId);
57
+ }
58
+ const problems = modelSettingsProblems({
59
+ loaded,
60
+ callsAnsweredBy: progress.callsAnsweredBy ?? 'custom',
61
+ overrides: overrides ?? progress.overrides,
62
+ });
63
+ if (problems.length)
64
+ throw new Error(`The run cannot resume:\n- ${problems.join('\n- ')}`);
65
+ // The schema as it is now may add defaults to the saved state; they are saved as a change.
66
+ const change = changedPlaces({
67
+ before: progress.state,
68
+ after: stateFittedToSchema({
69
+ state: progress.state,
70
+ schema: blueprint.runStateSchema,
71
+ madeBy: 'The saved run',
72
+ }),
73
+ });
74
+ const resumes = events.filter((event) => event.kind === 'run-resumed').length;
75
+ const structureFile = await store.writeStructure({
76
+ runId,
77
+ number: resumes + 2,
78
+ structure: loaded.structure,
79
+ });
80
+ await session.record({
81
+ kind: 'run-resumed',
82
+ blueprintHash: loaded.hash,
83
+ structureFile,
84
+ ...(overrides ? { overrides } : {}),
85
+ ...(change.length ? { change } : {}),
86
+ });
87
+ for (const answer of answers)
88
+ await session.recordAnswer({ ...answer, answeredBy: 'person' });
89
+ // A question asked just before a crash may not have had the run's own answer recorded.
90
+ const waitingGroups = [
91
+ ...Object.values(progress.assignments).map((assignment) => assignment.pendingAsk?.questionIds),
92
+ ...Object.values(progress.codePhases).map((codePhase) => codePhase.questionIds),
93
+ ];
94
+ for (const questionIds of waitingGroups)
95
+ await session.answerByRecommendation({
96
+ questions: (questionIds ?? []).map((id) => progress.questions[id]),
97
+ });
98
+ return session;
99
+ }
@@ -0,0 +1,20 @@
1
+ /** Stop was asked for. Work in progress ends and the run is left stopped. */
2
+ export declare class RunStopped extends Error {
3
+ /** Set when the run stopped because it was told to stop after this phase. */
4
+ readonly afterPhase?: string;
5
+ constructor({ message, afterPhase }: {
6
+ message: string;
7
+ afterPhase?: string;
8
+ });
9
+ }
10
+ /** Nothing can go on until the person answers a question. The run's process ends. */
11
+ export declare class RunWaitsForPerson extends Error {
12
+ }
13
+ /** The run cannot go on: a model call failed for good, or an agent used up its corrections. */
14
+ export declare class RunFailed extends Error {
15
+ readonly assignmentId?: string;
16
+ constructor({ message, assignmentId }: {
17
+ message: string;
18
+ assignmentId?: string;
19
+ });
20
+ }
@@ -0,0 +1,20 @@
1
+ /** Stop was asked for. Work in progress ends and the run is left stopped. */
2
+ export class RunStopped extends Error {
3
+ /** Set when the run stopped because it was told to stop after this phase. */
4
+ afterPhase;
5
+ constructor({ message, afterPhase }) {
6
+ super(message);
7
+ this.afterPhase = afterPhase;
8
+ }
9
+ }
10
+ /** Nothing can go on until the person answers a question. The run's process ends. */
11
+ export class RunWaitsForPerson extends Error {
12
+ }
13
+ /** The run cannot go on: a model call failed for good, or an agent used up its corrections. */
14
+ export class RunFailed extends Error {
15
+ assignmentId;
16
+ constructor({ message, assignmentId }) {
17
+ super(message);
18
+ this.assignmentId = assignmentId;
19
+ }
20
+ }