@praudent/dagma 0.0.0-stage → 0.1.1

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 +61 -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,189 @@
1
+ import { START_CHECKPOINT_NAME } from './progress.js';
2
+ const SCHEMA_STATEMENTS = [
3
+ `CREATE SCHEMA IF NOT EXISTS dagma`,
4
+ `CREATE SEQUENCE IF NOT EXISTS dagma.run_id_seq`,
5
+ `CREATE TABLE IF NOT EXISTS dagma.runs (
6
+ run_id text PRIMARY KEY,
7
+ blueprint text NOT NULL,
8
+ status text NOT NULL,
9
+ summary jsonb NOT NULL,
10
+ input jsonb,
11
+ structures jsonb NOT NULL DEFAULT '{}'::jsonb,
12
+ created_at timestamptz NOT NULL DEFAULT now(),
13
+ updated_at timestamptz NOT NULL DEFAULT now()
14
+ )`,
15
+ `CREATE TABLE IF NOT EXISTS dagma.events (
16
+ run_id text NOT NULL REFERENCES dagma.runs(run_id) ON DELETE CASCADE,
17
+ seq integer NOT NULL,
18
+ type text NOT NULL,
19
+ payload jsonb NOT NULL,
20
+ created_at timestamptz NOT NULL DEFAULT now(),
21
+ PRIMARY KEY (run_id, seq)
22
+ )`,
23
+ `CREATE TABLE IF NOT EXISTS dagma.checkpoints (
24
+ run_id text NOT NULL REFERENCES dagma.runs(run_id) ON DELETE CASCADE,
25
+ name text NOT NULL,
26
+ number integer NOT NULL,
27
+ payload jsonb NOT NULL,
28
+ created_at timestamptz NOT NULL DEFAULT now(),
29
+ PRIMARY KEY (run_id, name)
30
+ )`,
31
+ `CREATE TABLE IF NOT EXISTS dagma.calls (
32
+ run_id text NOT NULL REFERENCES dagma.runs(run_id) ON DELETE CASCADE,
33
+ call_id text NOT NULL,
34
+ payload jsonb NOT NULL,
35
+ updated_at timestamptz NOT NULL DEFAULT now(),
36
+ PRIMARY KEY (run_id, call_id)
37
+ )`,
38
+ `CREATE TABLE IF NOT EXISTS dagma.artifacts (
39
+ run_id text NOT NULL REFERENCES dagma.runs(run_id) ON DELETE CASCADE,
40
+ artifact_id text NOT NULL,
41
+ name text NOT NULL,
42
+ media_type text NOT NULL,
43
+ size_in_bytes integer NOT NULL,
44
+ bytes bytea NOT NULL,
45
+ created_at timestamptz NOT NULL DEFAULT now(),
46
+ PRIMARY KEY (run_id, artifact_id)
47
+ )`,
48
+ ];
49
+ const DAGMA_SCHEMA_LOCK_ID = 74616761;
50
+ /** Creates Dagma's self-managed `dagma` schema and tables idempotently. Never touches `public`.
51
+ * Uses a Postgres advisory lock so concurrent process startups never race on `CREATE SCHEMA`. */
52
+ export async function ensureDagmaSchema({ pool }) {
53
+ if ('connect' in pool && typeof pool.connect === 'function') {
54
+ const client = await pool.connect();
55
+ try {
56
+ await client.query('BEGIN');
57
+ await client.query('SELECT pg_advisory_xact_lock($1)', [DAGMA_SCHEMA_LOCK_ID]);
58
+ for (const statement of SCHEMA_STATEMENTS)
59
+ await client.query(statement);
60
+ await client.query('COMMIT');
61
+ }
62
+ catch (error) {
63
+ await client.query('ROLLBACK').catch(() => undefined);
64
+ throw error;
65
+ }
66
+ finally {
67
+ client.release();
68
+ }
69
+ return;
70
+ }
71
+ for (const statement of SCHEMA_STATEMENTS)
72
+ await pool.query(statement);
73
+ }
74
+ /** Postgres-backed `RunStore` operating exclusively in the `dagma` schema on the caller's pool. */
75
+ export function postgresRunStore({ pool }) {
76
+ return {
77
+ ensureSchema: () => ensureDagmaSchema({ pool }),
78
+ async createRunId() {
79
+ const { rows } = await pool.query(`SELECT nextval('dagma.run_id_seq')::text AS id`);
80
+ return rows[0].id;
81
+ },
82
+ async writeRunSummary({ runId, summary, input }) {
83
+ const hasInput = input !== undefined;
84
+ await pool.query(`INSERT INTO dagma.runs (run_id, blueprint, status, summary, input, created_at, updated_at)
85
+ VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::timestamptz, now())
86
+ ON CONFLICT (run_id) DO UPDATE SET
87
+ blueprint = EXCLUDED.blueprint,
88
+ status = EXCLUDED.status,
89
+ summary = EXCLUDED.summary,
90
+ input = CASE WHEN $7 THEN EXCLUDED.input ELSE dagma.runs.input END,
91
+ updated_at = now()`, [
92
+ runId,
93
+ summary.blueprint,
94
+ summary.status,
95
+ JSON.stringify(summary),
96
+ hasInput ? JSON.stringify(input) : null,
97
+ summary.createdAt,
98
+ hasInput,
99
+ ]);
100
+ },
101
+ async readRunSummary({ runId }) {
102
+ const { rows } = await pool.query(`SELECT summary FROM dagma.runs WHERE run_id = $1`, [runId]);
103
+ return rows[0]?.summary;
104
+ },
105
+ async listRunSummaries() {
106
+ const { rows } = await pool.query(`SELECT summary, input FROM dagma.runs ORDER BY created_at DESC, run_id DESC`);
107
+ return rows;
108
+ },
109
+ async readInput({ runId }) {
110
+ const { rows } = await pool.query(`SELECT input FROM dagma.runs WHERE run_id = $1`, [runId]);
111
+ return rows[0]?.input;
112
+ },
113
+ async writeStructure({ runId, number, structure }) {
114
+ const name = `blueprint-${number}.json`;
115
+ await pool.query(`UPDATE dagma.runs
116
+ SET structures = jsonb_set(structures, ARRAY[$2::text], $3::jsonb, true),
117
+ updated_at = now()
118
+ WHERE run_id = $1`, [runId, name, JSON.stringify(structure)]);
119
+ return name;
120
+ },
121
+ async readStructure({ runId, name }) {
122
+ const { rows } = await pool.query(`SELECT structures -> $2 AS structure FROM dagma.runs WHERE run_id = $1`, [runId, name]);
123
+ return rows[0]?.structure ?? undefined;
124
+ },
125
+ async appendEvent({ runId, event }) {
126
+ await pool.query(`INSERT INTO dagma.events (run_id, seq, type, payload, created_at)
127
+ VALUES ($1, $2, $3, $4::jsonb, $5::timestamptz)`, [runId, event.seq, event.kind, JSON.stringify(event), event.at]);
128
+ },
129
+ async readEvents({ runId, afterSeq = 0 }) {
130
+ const { rows } = await pool.query(`SELECT payload FROM dagma.events
131
+ WHERE run_id = $1 AND seq > $2
132
+ ORDER BY seq ASC`, [runId, afterSeq]);
133
+ return rows.map((row) => row.payload);
134
+ },
135
+ async writeCheckpoint({ runId, checkpoint }) {
136
+ const name = checkpoint.number === 0 ? START_CHECKPOINT_NAME : `${checkpoint.number}-${checkpoint.phase}`;
137
+ await pool.query(`INSERT INTO dagma.checkpoints (run_id, name, number, payload)
138
+ VALUES ($1, $2, $3, $4::jsonb)
139
+ ON CONFLICT (run_id, name) DO UPDATE SET
140
+ number = EXCLUDED.number,
141
+ payload = EXCLUDED.payload`, [runId, name, checkpoint.number, JSON.stringify(checkpoint)]);
142
+ return name;
143
+ },
144
+ async readCheckpoint({ runId, name }) {
145
+ const { rows } = await pool.query(`SELECT payload FROM dagma.checkpoints WHERE run_id = $1 AND name = $2`, [runId, name]);
146
+ return rows[0]?.payload;
147
+ },
148
+ async listCheckpoints({ runId }) {
149
+ const { rows } = await pool.query(`SELECT name FROM dagma.checkpoints WHERE run_id = $1 ORDER BY number ASC, name ASC`, [runId]);
150
+ return rows.map((row) => row.name);
151
+ },
152
+ async writeCall({ runId, call }) {
153
+ await pool.query(`INSERT INTO dagma.calls (run_id, call_id, payload, updated_at)
154
+ VALUES ($1, $2, $3::jsonb, now())
155
+ ON CONFLICT (run_id, call_id) DO UPDATE SET
156
+ payload = EXCLUDED.payload,
157
+ updated_at = now()`, [runId, call.callId, JSON.stringify(call)]);
158
+ },
159
+ async readCall({ runId, callId }) {
160
+ const { rows } = await pool.query(`SELECT payload FROM dagma.calls WHERE run_id = $1 AND call_id = $2`, [runId, callId]);
161
+ return rows[0]?.payload;
162
+ },
163
+ async writeArtifact({ runId, id, artifact }) {
164
+ const bytes = Buffer.from(artifact.bytes);
165
+ await pool.query(`INSERT INTO dagma.artifacts (run_id, artifact_id, name, media_type, size_in_bytes, bytes)
166
+ VALUES ($1, $2, $3, $4, $5, $6)
167
+ ON CONFLICT (run_id, artifact_id) DO NOTHING`, [runId, id, artifact.name, artifact.mediaType, bytes.byteLength, bytes]);
168
+ return {
169
+ id,
170
+ name: artifact.name,
171
+ mediaType: artifact.mediaType,
172
+ sizeInBytes: bytes.byteLength,
173
+ };
174
+ },
175
+ async readArtifact({ runId, saved }) {
176
+ const { rows } = await pool.query(`SELECT name, media_type, bytes
177
+ FROM dagma.artifacts
178
+ WHERE run_id = $1 AND artifact_id = $2`, [runId, saved.id]);
179
+ const row = rows[0];
180
+ if (!row)
181
+ throw new Error(`Artifact ${saved.name} (${saved.id}) was not found in run ${runId}.`);
182
+ return {
183
+ name: row.name,
184
+ mediaType: row.media_type,
185
+ bytes: new Uint8Array(row.bytes),
186
+ };
187
+ },
188
+ };
189
+ }
@@ -0,0 +1,83 @@
1
+ import type { Question } from '../../blueprint/outcomes.js';
2
+ import type { Blueprint } from '../../blueprint/phase.js';
3
+ import type { RunEvent, Tokens } from './events.js';
4
+ import type { AssignmentStatus, QuestionProgress, RunProgress, RunStatus } from './progress.js';
5
+ export type ProgressPhase = {
6
+ name: string;
7
+ label: string;
8
+ status: 'pending' | 'running' | 'finished';
9
+ };
10
+ export type ProgressAssignment = {
11
+ id: string;
12
+ phase: string;
13
+ phaseLabel: string;
14
+ lane: string;
15
+ key: string;
16
+ label: string;
17
+ agent?: string;
18
+ agentLabel?: string;
19
+ role?: string;
20
+ status: AssignmentStatus;
21
+ attempt: number;
22
+ corrections: number;
23
+ startedAt?: string;
24
+ durationMs?: number;
25
+ };
26
+ export type ProgressQuestion = {
27
+ id: string;
28
+ question: Question;
29
+ owner: QuestionProgress['owner'];
30
+ };
31
+ /** Serializable, UI-agnostic progress snapshot derived from `RunProgress` and optional `Blueprint`. */
32
+ export type ProgressSnapshot = {
33
+ seq: number;
34
+ status: RunStatus;
35
+ reason?: string;
36
+ currentPhase?: {
37
+ name: string;
38
+ label: string;
39
+ };
40
+ phases: ProgressPhase[];
41
+ assignments: ProgressAssignment[];
42
+ pendingQuestions: ProgressQuestion[];
43
+ tokens: Required<Tokens>;
44
+ costUsd: number;
45
+ };
46
+ /** Monotonic `seq`-ordered delta for streaming progress updates without drift on reconnect. */
47
+ export type ProgressDelta = {
48
+ seq: number;
49
+ at: string;
50
+ eventKind: RunEvent['kind'];
51
+ status?: RunStatus;
52
+ reason?: string | null;
53
+ currentPhase?: {
54
+ name: string;
55
+ label: string;
56
+ } | null;
57
+ phases?: ProgressPhase[];
58
+ upsertedAssignments?: ProgressAssignment[];
59
+ pendingQuestions?: ProgressQuestion[];
60
+ tokens?: Required<Tokens>;
61
+ costUsd?: number;
62
+ };
63
+ /** Pure projection from `RunProgress` (+ optional `Blueprint` labels) to `ProgressSnapshot`. */
64
+ export declare function progressSnapshot({ progress, blueprint, }: {
65
+ progress: RunProgress;
66
+ blueprint?: Blueprint<any, any, any>;
67
+ }): ProgressSnapshot;
68
+ /** Computes a minimal `ProgressDelta` between two consecutive `ProgressSnapshot`s. */
69
+ export declare function progressDeltaFromSnapshots({ previous, next, event, }: {
70
+ previous: ProgressSnapshot;
71
+ next: ProgressSnapshot;
72
+ event: RunEvent;
73
+ }): ProgressDelta;
74
+ /** Applies a `ProgressDelta` to a `ProgressSnapshot`. Ignores stale deltas (`delta.seq <= snapshot.seq`). */
75
+ export declare function applyProgressDelta({ snapshot, delta, }: {
76
+ snapshot: ProgressSnapshot;
77
+ delta: ProgressDelta;
78
+ }): ProgressSnapshot;
79
+ export declare function allDeclaredPhaseLabels({ blueprint }: {
80
+ blueprint: Blueprint<any, any, any>;
81
+ }): {
82
+ [name: string]: string;
83
+ };
@@ -0,0 +1,167 @@
1
+ import { declaredPhases, phaseAtPlace } from '../../blueprint/places.js';
2
+ function phaseLabelFor({ blueprint, place, }) {
3
+ if (!blueprint)
4
+ return place;
5
+ const phase = phaseAtPlace({ blueprint, name: place });
6
+ return phase?.label ?? phase?.name ?? place;
7
+ }
8
+ function agentInfoFor({ blueprint, place, agentName, }) {
9
+ if (!blueprint || !agentName)
10
+ return {};
11
+ const phase = phaseAtPlace({ blueprint, name: place });
12
+ if (phase?.kind !== 'agents')
13
+ return {};
14
+ for (const lane of phase.lanes) {
15
+ const agent = lane.chain.find((candidate) => candidate.name === agentName);
16
+ if (agent)
17
+ return { label: agent.label ?? agent.name, role: agent.role };
18
+ }
19
+ return {};
20
+ }
21
+ /** Pure projection from `RunProgress` (+ optional `Blueprint` labels) to `ProgressSnapshot`. */
22
+ export function progressSnapshot({ progress, blueprint, }) {
23
+ const activePhaseName = progress.openVisit?.position?.place ?? progress.phasePosition?.phase;
24
+ const currentPhase = activePhaseName
25
+ ? { name: activePhaseName, label: phaseLabelFor({ blueprint, place: activePhaseName }) }
26
+ : undefined;
27
+ const trunkNames = blueprint ? blueprint.trunk.map((phase) => phase.name) : [];
28
+ const reachedTrunkIndex = progress.phasePosition
29
+ ? trunkNames.indexOf(progress.phasePosition.phase)
30
+ : -1;
31
+ const phases = blueprint
32
+ ? blueprint.trunk.map((phase, index) => {
33
+ let status = 'pending';
34
+ if (progress.status === 'finished')
35
+ status = 'finished';
36
+ else if (reachedTrunkIndex > index)
37
+ status = 'finished';
38
+ else if (reachedTrunkIndex === index)
39
+ status = progress.phasePosition?.stage === 'finished' ? 'finished' : 'running';
40
+ return {
41
+ name: phase.name,
42
+ label: phase.label ?? phase.name,
43
+ status,
44
+ };
45
+ })
46
+ : currentPhase
47
+ ? [
48
+ {
49
+ name: currentPhase.name,
50
+ label: currentPhase.label,
51
+ status: progress.status === 'finished' || progress.phasePosition?.stage === 'finished'
52
+ ? 'finished'
53
+ : 'running',
54
+ },
55
+ ]
56
+ : [];
57
+ const assignments = progress.assignmentIds
58
+ .map((id) => progress.assignments[id])
59
+ .map((assignment) => {
60
+ const currentAgent = assignment.agents?.[assignment.placeInChain]
61
+ ?? assignment.finishedPlaces.at(-1)?.agent;
62
+ const agentInfo = agentInfoFor({
63
+ blueprint,
64
+ place: assignment.phase,
65
+ agentName: currentAgent,
66
+ });
67
+ const attempt = currentAgent ? (assignment.attempts[currentAgent] ?? 0) : 0;
68
+ return {
69
+ id: assignment.id,
70
+ phase: assignment.phase,
71
+ phaseLabel: phaseLabelFor({ blueprint, place: assignment.phase }),
72
+ lane: assignment.lane,
73
+ key: assignment.key,
74
+ label: assignment.label,
75
+ ...(currentAgent ? { agent: currentAgent } : {}),
76
+ ...(agentInfo.label ? { agentLabel: agentInfo.label } : {}),
77
+ ...(agentInfo.role ? { role: agentInfo.role } : {}),
78
+ status: assignment.status,
79
+ attempt,
80
+ corrections: assignment.correctionsInARow,
81
+ };
82
+ });
83
+ const pendingQuestions = progress.questionIds
84
+ .map((id) => progress.questions[id])
85
+ .filter((entry) => entry.answer === undefined)
86
+ .map((entry) => ({
87
+ id: entry.id,
88
+ question: entry.question,
89
+ owner: entry.owner,
90
+ }));
91
+ return {
92
+ seq: progress.seq,
93
+ status: progress.status,
94
+ ...(progress.reason ? { reason: progress.reason } : {}),
95
+ ...(currentPhase ? { currentPhase } : {}),
96
+ phases,
97
+ assignments,
98
+ pendingQuestions,
99
+ tokens: { ...progress.totals.tokens },
100
+ costUsd: progress.totals.costUsd,
101
+ };
102
+ }
103
+ /** Computes a minimal `ProgressDelta` between two consecutive `ProgressSnapshot`s. */
104
+ export function progressDeltaFromSnapshots({ previous, next, event, }) {
105
+ const delta = {
106
+ seq: next.seq,
107
+ at: event.at,
108
+ eventKind: event.kind,
109
+ };
110
+ if (previous.status !== next.status)
111
+ delta.status = next.status;
112
+ if (previous.reason !== next.reason)
113
+ delta.reason = next.reason ?? null;
114
+ if (JSON.stringify(previous.currentPhase) !== JSON.stringify(next.currentPhase))
115
+ delta.currentPhase = next.currentPhase ?? null;
116
+ if (JSON.stringify(previous.phases) !== JSON.stringify(next.phases))
117
+ delta.phases = next.phases;
118
+ const prevById = Object.create(null);
119
+ for (const item of previous.assignments)
120
+ prevById[item.id] = item;
121
+ const changedAssignments = next.assignments.filter((item) => JSON.stringify(prevById[item.id]) !== JSON.stringify(item));
122
+ if (changedAssignments.length)
123
+ delta.upsertedAssignments = changedAssignments;
124
+ if (JSON.stringify(previous.pendingQuestions) !== JSON.stringify(next.pendingQuestions))
125
+ delta.pendingQuestions = next.pendingQuestions;
126
+ if (JSON.stringify(previous.tokens) !== JSON.stringify(next.tokens))
127
+ delta.tokens = next.tokens;
128
+ if (previous.costUsd !== next.costUsd)
129
+ delta.costUsd = next.costUsd;
130
+ return delta;
131
+ }
132
+ /** Applies a `ProgressDelta` to a `ProgressSnapshot`. Ignores stale deltas (`delta.seq <= snapshot.seq`). */
133
+ export function applyProgressDelta({ snapshot, delta, }) {
134
+ if (delta.seq <= snapshot.seq)
135
+ return snapshot;
136
+ let assignments = snapshot.assignments;
137
+ if (delta.upsertedAssignments?.length) {
138
+ const next = [...snapshot.assignments];
139
+ for (const item of delta.upsertedAssignments) {
140
+ const index = next.findIndex((existing) => existing.id === item.id);
141
+ if (index >= 0)
142
+ next[index] = item;
143
+ else
144
+ next.push(item);
145
+ }
146
+ assignments = next;
147
+ }
148
+ const nextReason = delta.reason === undefined ? snapshot.reason : (delta.reason ?? undefined);
149
+ const nextPhase = delta.currentPhase === undefined ? snapshot.currentPhase : (delta.currentPhase ?? undefined);
150
+ return {
151
+ seq: delta.seq,
152
+ status: delta.status ?? snapshot.status,
153
+ ...(nextReason !== undefined ? { reason: nextReason } : {}),
154
+ ...(nextPhase !== undefined ? { currentPhase: nextPhase } : {}),
155
+ phases: delta.phases ?? snapshot.phases,
156
+ assignments,
157
+ pendingQuestions: delta.pendingQuestions ?? snapshot.pendingQuestions,
158
+ tokens: delta.tokens ?? snapshot.tokens,
159
+ costUsd: delta.costUsd ?? snapshot.costUsd,
160
+ };
161
+ }
162
+ export function allDeclaredPhaseLabels({ blueprint }) {
163
+ const labels = Object.create(null);
164
+ for (const phase of declaredPhases({ blueprint }))
165
+ labels[phase.name] = phase.label ?? phase.name;
166
+ return labels;
167
+ }
@@ -0,0 +1,207 @@
1
+ import type { Question } from '../../blueprint/outcomes.js';
2
+ import type { CallsAnsweredBy, QuestionsAnsweredBy } from '../../blueprint/run-settings.js';
3
+ import type { ModelOverride, SavedArtifact, Tokens } from './events.js';
4
+ /** The name of the checkpoint a run starts from. */
5
+ export declare const START_CHECKPOINT_NAME = "0-start";
6
+ export type RunStatus = 'running' | 'waiting' | 'stopped' | 'failed' | 'finished';
7
+ export type AssignmentStatus = 'waiting-to-start' | 'running' | 'waiting-for-person' | 'finished' | 'dropped';
8
+ /** An agent's place in an assignment's chain that is done: by an accepted reply, or by a failed
9
+ * call its `whenCallFails` accepted. The two numbers are the events lines whose states are
10
+ * "before its first change" and "after its last". */
11
+ export type FinishedPlace = {
12
+ agent: string;
13
+ callId: string;
14
+ callFailed: boolean;
15
+ stateBeforeSeq: number;
16
+ stateAfterSeq: number;
17
+ };
18
+ export type AssignmentProgress = {
19
+ id: string;
20
+ phase: string;
21
+ lane: string;
22
+ key: string;
23
+ label: string;
24
+ repeat: number;
25
+ status: AssignmentStatus;
26
+ /** Its start condition has held; it waits only for a free slot. */
27
+ mayStart: boolean;
28
+ subject?: unknown;
29
+ agents?: string[];
30
+ /** The place in the chain of the first agent that is not done. */
31
+ placeInChain: number;
32
+ finishedPlaces: FinishedPlace[];
33
+ /** How many calls each agent has made for this assignment. */
34
+ attempts: {
35
+ [agent: string]: number;
36
+ };
37
+ /** Replies sent back in a row to the agent at `placeInChain`. */
38
+ correctionsInARow: number;
39
+ /** The last reply sent back to the agent at `placeInChain`, and the correction sent with it. */
40
+ lastCorrection?: {
41
+ callId: string;
42
+ text: string;
43
+ };
44
+ /** Questions it waits on. `outcome`: the reply's outcome asked, and is judged again once they
45
+ * are answered. `tool`: a tool asked, and the agent is called again. */
46
+ pendingAsk?: {
47
+ by: 'outcome' | 'tool';
48
+ callId: string;
49
+ questionIds: string[];
50
+ };
51
+ /** Every question this assignment asked, in the order asked. */
52
+ questionIds: string[];
53
+ /** The events line before the first change made by the agent at `placeInChain`. */
54
+ firstChangeSeq?: number;
55
+ };
56
+ export type QuestionProgress = {
57
+ id: string;
58
+ question: Question;
59
+ owner: {
60
+ assignmentId: string;
61
+ } | {
62
+ phase: string;
63
+ };
64
+ answer?: string;
65
+ answeredBy?: 'person' | 'run';
66
+ };
67
+ export type CallProgress = {
68
+ assignmentId: string;
69
+ agent: string;
70
+ /** The last events line the call's prompt includes. */
71
+ stateSeq: number;
72
+ status: 'in-progress' | 'replied' | 'asked' | 'failed' | 'stopped';
73
+ /** What became of its reply, once judged. */
74
+ outcome?: 'accepted' | 'sent-back' | 'asked';
75
+ };
76
+ export type RunTotals = {
77
+ calls: number;
78
+ corrections: number;
79
+ /** The sum of each count over the calls that reported it. */
80
+ tokens: Required<Tokens>;
81
+ /** For each count, how many calls did not report it. */
82
+ callsNotReporting: Required<Tokens>;
83
+ /** Clock time the run was being executed, leaving out time stopped or waiting for the person. */
84
+ durationMs: number;
85
+ /** Priced from tokens. */
86
+ costUsd: number;
87
+ /** The sum of what the model program itself reported, as an estimate. */
88
+ programCostUsd: number;
89
+ };
90
+ /** Where a run stands, rebuilt from its starting checkpoint and its events. The live run keeps
91
+ * it current through the same function Resume uses, so the two cannot disagree. */
92
+ export type RunProgress = {
93
+ seq: number;
94
+ status: RunStatus;
95
+ reason?: string;
96
+ state: unknown;
97
+ blueprintHash?: string;
98
+ callsAnsweredBy?: CallsAnsweredBy;
99
+ questionsAnsweredBy?: QuestionsAnsweredBy;
100
+ overrides: ModelOverride[];
101
+ stopAfter?: string;
102
+ /** The run already stopped once after its stop-after phase. */
103
+ stoppedAfterPhase: boolean;
104
+ startedFrom?: {
105
+ runId: string;
106
+ checkpoint: string;
107
+ };
108
+ /** When the run-started line was written. */
109
+ createdAt?: string;
110
+ /** When the last events line was written. */
111
+ lastLineAt?: string;
112
+ /** How many times the run has gone onto each side line. */
113
+ sideLineVisits: {
114
+ [sideLine: string]: number;
115
+ };
116
+ /** The trunk phase the run is on. `fromCheckpoint`: the phase finished in the run this one
117
+ * started from, not in this run. */
118
+ phasePosition?: {
119
+ phase: string;
120
+ stage: 'running' | 'finished';
121
+ fromCheckpoint?: true;
122
+ };
123
+ /** The visit to a side line the run is on, while the trunk phase at `phasePosition` stays open.
124
+ * `position` is the place on the line the visit has reached; absent before its first. */
125
+ openVisit?: OpenVisit & {
126
+ position?: {
127
+ place: string;
128
+ stage: 'running' | 'finished';
129
+ fromCheckpoint?: true;
130
+ };
131
+ };
132
+ assignments: {
133
+ [id: string]: AssignmentProgress;
134
+ };
135
+ assignmentIds: string[];
136
+ /** The assignment identities (lane, key, repeat) that have finished, by phase. */
137
+ finishedAssignments: {
138
+ [phase: string]: {
139
+ [identity: string]: true;
140
+ };
141
+ };
142
+ questions: {
143
+ [id: string]: QuestionProgress;
144
+ };
145
+ questionIds: string[];
146
+ /** Each code phase the run has started, by place: the questions it asked, and whether it has
147
+ * saved its result. */
148
+ codePhases: {
149
+ [place: string]: {
150
+ questionIds: string[];
151
+ accepted: boolean;
152
+ };
153
+ };
154
+ /** The newest artifact of each name. `sourceRunId` is set when it belongs to the run this one
155
+ * started from. */
156
+ artifacts: {
157
+ [name: string]: SavedArtifact & {
158
+ sourceRunId?: string;
159
+ };
160
+ };
161
+ calls: {
162
+ [callId: string]: CallProgress;
163
+ };
164
+ checkpointsSaved: number;
165
+ totals: RunTotals;
166
+ };
167
+ /** A visit to a side line: which line, which of the run's visits to it, and the trunk phase the
168
+ * run left and comes back into. */
169
+ export type OpenVisit = {
170
+ sideLine: string;
171
+ visit: number;
172
+ during: string;
173
+ };
174
+ /** What a checkpoint file holds: enough to start a run after a phase. */
175
+ export type Checkpoint = {
176
+ number: number;
177
+ /** The place whose end this is; absent for the start of a run from an input. */
178
+ phase?: string;
179
+ state: unknown;
180
+ artifacts: RunProgress['artifacts'];
181
+ sideLineVisits: RunProgress['sideLineVisits'];
182
+ /** Set when the place is on a side line: the visit it belongs to. */
183
+ openVisit?: OpenVisit;
184
+ /** What has finished, so the trunk phase a visit comes back into does not start it again. */
185
+ finishedAssignments: RunProgress['finishedAssignments'];
186
+ };
187
+ /** How an assignment's lane, key and repeat are written in `finishedAssignments`. */
188
+ export declare const assignmentIdentity: ({ lane, key, repeat, }: {
189
+ lane: string;
190
+ key: string;
191
+ repeat: number;
192
+ }) => string;
193
+ /** The lane, key and repeat an identity was written from. */
194
+ export declare const partsOfAssignmentIdentity: (identity: string) => {
195
+ lane: string;
196
+ key: string;
197
+ repeat: number;
198
+ };
199
+ /** The progress of a run that has made no events yet, from its starting checkpoint. */
200
+ export declare function progressAtStart({ start }: {
201
+ start: Checkpoint;
202
+ }): RunProgress;
203
+ /** Whether every question in the list has an answer. */
204
+ export declare function allAnswered({ progress, questionIds, }: {
205
+ progress: RunProgress;
206
+ questionIds: string[];
207
+ }): boolean;