@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,12 @@
1
+ import type { IncomingMessage, Server, ServerResponse } from 'node:http';
2
+ /** Serves the pre-built static admin UI (`dist/admin-ui/`) when available, falling back to Vite
3
+ * middleware only during local development of Dagma itself. */
4
+ export declare function appPages({ server }: {
5
+ server: Server;
6
+ }): Promise<{
7
+ handle: (request: IncomingMessage, response: ServerResponse) => void;
8
+ close: () => Promise<undefined>;
9
+ } | {
10
+ handle: import("vite").Connect.Server;
11
+ close: () => Promise<void>;
12
+ }>;
@@ -0,0 +1,68 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { extname, join, normalize, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ const CONTENT_TYPES = {
6
+ '.html': 'text/html; charset=utf-8',
7
+ '.js': 'text/javascript; charset=utf-8',
8
+ '.css': 'text/css; charset=utf-8',
9
+ '.svg': 'image/svg+xml',
10
+ '.png': 'image/png',
11
+ '.json': 'application/json; charset=utf-8',
12
+ '.woff2': 'font/woff2',
13
+ };
14
+ function staticAdminDir() {
15
+ // When running from compiled `dist/devtool-server/app-pages.js`, static UI is `dist/admin-ui/`.
16
+ const built = resolve(fileURLToPath(new URL('../admin-ui', import.meta.url)));
17
+ if (existsSync(join(built, 'index.html')))
18
+ return built;
19
+ // When running from `src/devtool-server/app-pages.ts`, check `<repo>/dist/admin-ui/`.
20
+ const fromRoot = resolve(fileURLToPath(new URL('../../dist/admin-ui', import.meta.url)));
21
+ if (existsSync(join(fromRoot, 'index.html')))
22
+ return fromRoot;
23
+ return undefined;
24
+ }
25
+ function serveStaticDirectory({ root }) {
26
+ const indexPath = join(root, 'index.html');
27
+ const handle = (request, response) => {
28
+ const rawPath = (request.url ?? '/').split('?')[0] ?? '/';
29
+ const cleanPath = normalize(decodeURIComponent(rawPath)).replace(/^(\.\.(\/|\\|$))+/, '');
30
+ const candidate = join(root, cleanPath === '/' ? 'index.html' : cleanPath);
31
+ const target = candidate.startsWith(root) && existsSync(candidate) ? candidate : indexPath;
32
+ const contentType = CONTENT_TYPES[extname(target)] ?? 'application/octet-stream';
33
+ readFile(target)
34
+ .then((content) => {
35
+ response.writeHead(200, {
36
+ 'content-type': contentType,
37
+ 'content-length': content.byteLength,
38
+ 'cache-control': target === indexPath ? 'no-store' : 'public, max-age=31536000, immutable',
39
+ });
40
+ response.end(content);
41
+ })
42
+ .catch(() => {
43
+ response.writeHead(404).end('Not found');
44
+ });
45
+ };
46
+ return { handle, close: async () => undefined };
47
+ }
48
+ /** Serves the pre-built static admin UI (`dist/admin-ui/`) when available, falling back to Vite
49
+ * middleware only during local development of Dagma itself. */
50
+ export async function appPages({ server }) {
51
+ const staticDir = staticAdminDir();
52
+ if (staticDir)
53
+ return serveStaticDirectory({ root: staticDir });
54
+ const [{ default: react }, { createServer }] = await Promise.all([
55
+ import('@vitejs/plugin-react'),
56
+ import('vite'),
57
+ ]);
58
+ const vite = await createServer({
59
+ configFile: false,
60
+ root: fileURLToPath(new URL('../devtool-app', import.meta.url)),
61
+ plugins: [react()],
62
+ appType: 'spa',
63
+ clearScreen: false,
64
+ logLevel: 'warn',
65
+ server: { middlewareMode: true, hmr: { server } },
66
+ });
67
+ return { handle: vite.middlewares, close: () => vite.close() };
68
+ }
@@ -0,0 +1,21 @@
1
+ import type { DeclaredStructure } from '../blueprint/declared-structure.js';
2
+ /** What the devtool shows of a blueprint as its files are now. */
3
+ export type BlueprintDescription = {
4
+ structure: DeclaredStructure;
5
+ /** A short code that changes whenever the declared structure or a prompt changes. */
6
+ hash: string;
7
+ /** The shape of a run's input, as JSON Schema. */
8
+ inputSchema: unknown;
9
+ loadedAt: string;
10
+ /** When an input was given to check: what keeps it from fitting the input shape, or nothing. */
11
+ inputProblems?: string[];
12
+ };
13
+ /** What begins the one line of the short process's output that holds the description. */
14
+ export declare const BLUEPRINT_LINE_MARK = "dagma-blueprint:";
15
+ /** Reads the blueprint through a short process of its own, so files edited since the devtool
16
+ * started take effect. Rejects with what keeps the blueprint from being used. */
17
+ export declare function readBlueprintDescription({ blueprintFile, inputFile, }: {
18
+ blueprintFile: string;
19
+ /** A file holding a run input as JSON, to check against the blueprint's input shape. */
20
+ inputFile?: string;
21
+ }): Promise<BlueprintDescription>;
@@ -0,0 +1,27 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ /** What begins the one line of the short process's output that holds the description. */
4
+ export const BLUEPRINT_LINE_MARK = 'dagma-blueprint:';
5
+ /** Reads the blueprint through a short process of its own, so files edited since the devtool
6
+ * started take effect. Rejects with what keeps the blueprint from being used. */
7
+ export function readBlueprintDescription({ blueprintFile, inputFile, }) {
8
+ const entry = fileURLToPath(new URL('./print-blueprint.ts', import.meta.url));
9
+ return new Promise((resolve, reject) => {
10
+ // The child runs as this process does (through tsx).
11
+ const child = spawn(process.execPath, [...process.execArgv, entry, blueprintFile, ...(inputFile ? [inputFile] : [])], { stdio: ['ignore', 'pipe', 'pipe'] });
12
+ let printed = '';
13
+ let complaint = '';
14
+ child.stdout.setEncoding('utf8').on('data', (text) => (printed += text));
15
+ child.stderr.setEncoding('utf8').on('data', (text) => (complaint += text));
16
+ child.on('error', reject);
17
+ child.on('close', (code) => {
18
+ const line = printed
19
+ .split('\n')
20
+ .reverse()
21
+ .find((each) => each.startsWith(BLUEPRINT_LINE_MARK));
22
+ if (code !== 0 || !line)
23
+ return reject(new Error(complaint.trim() || 'The blueprint could not be read.'));
24
+ resolve(JSON.parse(line.slice(BLUEPRINT_LINE_MARK.length)));
25
+ });
26
+ });
27
+ }
@@ -0,0 +1,36 @@
1
+ import type { RunEvent } from '../run/record/events.js';
2
+ import type { RunStore } from '../run/record/run-store.js';
3
+ import type { GivenAnswer, ListedRun, NewRunRequest, ResumeRequest } from './devtool-shapes.js';
4
+ /** Starts runs as `dagma run … --print-events` processes and stays connected to each: reads its
5
+ * events from the process's output and writes Stop and answers to its input. */
6
+ export declare function connectedRuns({ blueprintFile, store, databaseUrl, onRunEvent, onRowChanged, }: {
7
+ blueprintFile?: string;
8
+ store: RunStore;
9
+ databaseUrl?: string;
10
+ onRunEvent: (happened: {
11
+ runId: string;
12
+ event: RunEvent;
13
+ }) => void;
14
+ onRowChanged: (row: ListedRun) => void;
15
+ }): {
16
+ start: ({ request }: {
17
+ request: NewRunRequest;
18
+ }) => Promise<{
19
+ runId: string;
20
+ }>;
21
+ resume: ({ runId, request }: {
22
+ runId: string;
23
+ request: ResumeRequest;
24
+ }) => Promise<{
25
+ runId: string;
26
+ }>;
27
+ rows: () => ListedRun[];
28
+ stop({ runId }: {
29
+ runId: string;
30
+ }): void;
31
+ answer({ runId, given }: {
32
+ runId: string;
33
+ given: GivenAnswer;
34
+ }): Promise<undefined>;
35
+ stopAll(): Promise<void>;
36
+ };
@@ -0,0 +1,201 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { createInterface } from 'node:readline';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { applyEvent, progressFromEvents } from '../run/record/apply-event.js';
8
+ import { START_CHECKPOINT_NAME } from '../run/record/progress.js';
9
+ import { summaryOfProgress } from '../run/record/run-summary.js';
10
+ import { RunNamedLineSchema } from '../run/run-option-shapes.js';
11
+ import { inputInOneLine, listedRun } from './listed-runs.js';
12
+ const STOP_LIMIT_MS = 10_000;
13
+ const KEPT_COMPLAINT_LENGTH = 4000;
14
+ /** The events lines that change what a run's row in the Runs table shows. */
15
+ const ROW_CHANGING_KINDS = [
16
+ 'run-started',
17
+ 'run-resumed',
18
+ 'phase-started',
19
+ 'phase-finished',
20
+ 'call-ended',
21
+ 'run-waiting',
22
+ 'run-stopped',
23
+ 'run-failed',
24
+ 'run-finished',
25
+ ];
26
+ /** Starts runs as `dagma run … --print-events` processes and stays connected to each: reads its
27
+ * events from the process's output and writes Stop and answers to its input. */
28
+ export function connectedRuns({ blueprintFile, store, databaseUrl, onRunEvent, onRowChanged, }) {
29
+ const command = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../command.ts' : '../command.js', import.meta.url));
30
+ const connected = Object.create(null);
31
+ const rowOf = (run) => ({
32
+ summary: summaryOfProgress({
33
+ runId: run.runId,
34
+ blueprintName: run.blueprintName,
35
+ progress: run.progress,
36
+ }),
37
+ inputText: run.inputText,
38
+ connected: true,
39
+ });
40
+ /** Starts the command and resolves with the run it names on its first line. Rejects with what
41
+ * the command said when it ends without naming one. */
42
+ const connect = ({ commandArguments }) => {
43
+ if (!blueprintFile)
44
+ return Promise.reject(new Error('Starting or resuming runs from the admin UI requires a configured blueprint file.'));
45
+ return new Promise((resolveStarted, rejectStarted) => {
46
+ const child = spawn(process.execPath, [
47
+ ...process.execArgv,
48
+ command,
49
+ 'run',
50
+ blueprintFile,
51
+ ...(databaseUrl ? ['--database-url', databaseUrl] : []),
52
+ ...commandArguments,
53
+ ], { stdio: ['pipe', 'pipe', 'pipe'] });
54
+ let run;
55
+ let complaint = '';
56
+ /** Lines are handled one at a time, in the order printed. */
57
+ let handled = Promise.resolve();
58
+ const nameRun = async ({ runId }) => {
59
+ const startCheckpoint = await store.readCheckpoint({ runId, name: START_CHECKPOINT_NAME });
60
+ const events = await store.readEvents({ runId });
61
+ if (!startCheckpoint)
62
+ throw new Error(`Run ${runId} is missing its starting checkpoint.`);
63
+ const progress = progressFromEvents({ start: startCheckpoint, events });
64
+ const started = events.find((event) => event.kind === 'run-started');
65
+ run = connected[runId] = {
66
+ runId,
67
+ process: child,
68
+ blueprintName: started?.kind === 'run-started' ? started.blueprint : '',
69
+ progress,
70
+ inputText: inputInOneLine({ input: await store.readInput({ runId }).catch(() => undefined) }),
71
+ unconfirmedAnswers: [],
72
+ };
73
+ onRowChanged(rowOf(run));
74
+ resolveStarted({ runId });
75
+ };
76
+ const addEvent = (event) => {
77
+ if (!run)
78
+ return;
79
+ if (event.seq > run.progress.seq)
80
+ applyEvent({ progress: run.progress, event });
81
+ if (event.kind === 'question-answered')
82
+ run.unconfirmedAnswers = run.unconfirmedAnswers.filter((given) => given.questionId !== event.questionId);
83
+ onRunEvent({ runId: run.runId, event });
84
+ if (ROW_CHANGING_KINDS.includes(event.kind))
85
+ onRowChanged(rowOf(run));
86
+ };
87
+ createInterface({ input: child.stdout }).on('line', (line) => {
88
+ handled = handled
89
+ .then(() => {
90
+ const printed = JSON.parse(line);
91
+ const named = RunNamedLineSchema.safeParse(printed);
92
+ return named.success ? nameRun(named.data) : addEvent(printed);
93
+ })
94
+ .catch((error) => {
95
+ console.error(`A line of a run's output could not be read: ${String(error)}`);
96
+ });
97
+ });
98
+ child.stderr.setEncoding('utf8').on('data', (text) => {
99
+ complaint = (complaint + text).slice(-KEPT_COMPLAINT_LENGTH);
100
+ process.stderr.write(text);
101
+ });
102
+ child.on('error', rejectStarted);
103
+ child.on('close', () => {
104
+ void handled.then(async () => {
105
+ if (!run)
106
+ return rejectStarted(new Error(complaint.trim() || 'The run could not be started.'));
107
+ delete connected[run.runId];
108
+ const row = await listedRun({ store, runId: run.runId });
109
+ if (row)
110
+ onRowChanged(row);
111
+ if (run.unconfirmedAnswers.length && run.progress.status === 'waiting')
112
+ await resume({ runId: run.runId, request: { answers: run.unconfirmedAnswers } }).catch((error) => console.error(error instanceof Error ? error.message : error));
113
+ });
114
+ });
115
+ });
116
+ };
117
+ /** Writes what the command reads from files into a temporary folder, runs the work, and removes
118
+ * the folder once the command has read them. */
119
+ const runUsingOptionFiles = async ({ files, work, }) => {
120
+ const folder = await mkdtemp(join(tmpdir(), 'dagma-devtool-'));
121
+ const paths = Object.create(null);
122
+ try {
123
+ for (const [name, content] of Object.entries(files)) {
124
+ paths[name] = join(folder, `${name}.json`);
125
+ await writeFile(paths[name], JSON.stringify(content));
126
+ }
127
+ return await work(paths);
128
+ }
129
+ finally {
130
+ await rm(folder, { recursive: true, force: true });
131
+ }
132
+ };
133
+ const start = ({ request }) => {
134
+ const { from, overrides } = request;
135
+ return runUsingOptionFiles({
136
+ files: { ...(from ? {} : { input: request.input }), ...(overrides ? { overrides } : {}) },
137
+ work: (paths) => connect({
138
+ commandArguments: [
139
+ '--print-events',
140
+ ...(from
141
+ ? ['--from-run', from.runId, '--checkpoint', from.checkpoint]
142
+ : ['--input', paths.input]),
143
+ ...(request.stopAfter ? ['--stop-after', request.stopAfter] : []),
144
+ '--calls-answered-by',
145
+ request.callsAnsweredBy,
146
+ ...(request.scriptedRepliesFile
147
+ ? ['--scripted-replies', resolve(request.scriptedRepliesFile)]
148
+ : []),
149
+ '--questions-answered-by',
150
+ request.questionsAnsweredBy,
151
+ ...(overrides ? ['--overrides', paths.overrides] : []),
152
+ ],
153
+ }),
154
+ });
155
+ };
156
+ const resume = ({ runId, request }) => {
157
+ const { overrides } = request;
158
+ return runUsingOptionFiles({
159
+ files: overrides ? { overrides } : {},
160
+ work: (paths) => connect({
161
+ commandArguments: [
162
+ '--print-events',
163
+ '--resume',
164
+ runId,
165
+ ...(request.answers ?? []).flatMap(({ questionId, answer }) => [
166
+ '--answer',
167
+ `${questionId}=${answer}`,
168
+ ]),
169
+ ...(overrides ? ['--overrides', paths.overrides] : []),
170
+ ],
171
+ }),
172
+ });
173
+ };
174
+ const writeToRun = ({ run, line }) => run.process.stdin.write(`${JSON.stringify(line)}\n`);
175
+ return {
176
+ start,
177
+ resume,
178
+ rows: () => Object.values(connected).map(rowOf),
179
+ stop({ runId }) {
180
+ const run = connected[runId];
181
+ if (!run)
182
+ throw new Error(`Run ${runId} was not started from this page, so it cannot be stopped here.`);
183
+ writeToRun({ run, line: { stop: true } });
184
+ },
185
+ async answer({ runId, given }) {
186
+ const run = connected[runId];
187
+ if (!run)
188
+ return void (await resume({ runId, request: { answers: [given] } }));
189
+ run.unconfirmedAnswers.push(given);
190
+ writeToRun({ run, line: { answer: given } });
191
+ },
192
+ async stopAll() {
193
+ const ended = Object.values(connected).map((run) => new Promise((resolveEnded) => {
194
+ run.process.once('close', () => resolveEnded());
195
+ writeToRun({ run, line: { stop: true } });
196
+ setTimeout(() => run.process.kill('SIGKILL'), STOP_LIMIT_MS).unref();
197
+ }));
198
+ await Promise.all(ended);
199
+ },
200
+ };
201
+ }
@@ -0,0 +1,17 @@
1
+ import type { Blueprint } from '../blueprint/phase.js';
2
+ import type { RunStore } from '../run/record/run-store.js';
3
+ /** Starts the Dagma admin UI server backed by `store` (Postgres). Inspecting runs only requires
4
+ * `store`; starting or resuming runs uses `blueprintFile` (or a configured blueprint). */
5
+ export declare function startDevtool({ store, databaseUrl, blueprintFile, blueprint, port, scriptedRepliesFile, }: {
6
+ store: RunStore;
7
+ databaseUrl?: string;
8
+ blueprintFile?: string;
9
+ blueprint?: Blueprint<any, any, any>;
10
+ port: number;
11
+ /** The replies file New run offers for a scripted run. */
12
+ scriptedRepliesFile?: string;
13
+ }): Promise<{
14
+ address: string;
15
+ /** Stops the runs the devtool started, then stops answering. */
16
+ close(): Promise<void>;
17
+ }>;