@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,33 @@
1
+ /**
2
+ * Dollars per million tokens for supported Google Gemini models on global endpoints.
3
+ * Regional Vertex AI endpoints (non-`global` location) carry a 1.1x multiplier.
4
+ * Output rate applies to both response tokens (`candidatesTokenCount`) and thinking tokens
5
+ * (`thoughtsTokenCount`).
6
+ */
7
+ const PRICES = {
8
+ 'gemini-4-neon': {
9
+ input: 3,
10
+ cachedInput: 0.15,
11
+ output: 15,
12
+ },
13
+ };
14
+ /** Whether the Gemini / Vertex AI route can price a model. A run on the API is refused before any
15
+ * call when an agent names a model that has no price. */
16
+ export function hasGeminiPrice({ model }) {
17
+ return Object.hasOwn(PRICES, model);
18
+ }
19
+ /**
20
+ * The cost in dollars of one request to Gemini / Vertex AI, priced by its own token counts.
21
+ * Note: Gemini's `promptTokenCount` includes cached tokens; pass `uncachedInputTokens` as
22
+ * `Math.max(0, totalInput - cachedInputTokens)` and `outputTokens` as
23
+ * `candidatesTokenCount + thoughtsTokenCount`.
24
+ */
25
+ export function geminiRequestCostUsd({ model, uncachedInputTokens, cachedInputTokens = 0, outputTokens, regional = false, }) {
26
+ const rates = PRICES[model];
27
+ const multiplier = regional ? 1.1 : 1;
28
+ return (((uncachedInputTokens * rates.input +
29
+ cachedInputTokens * rates.cachedInput +
30
+ outputTokens * rates.output) *
31
+ multiplier) /
32
+ 1_000_000);
33
+ }
@@ -0,0 +1,25 @@
1
+ import type { FinishReason, GenerateContentParameters, GenerateContentResponse, GenerateContentResponseUsageMetadata, GoogleGenAI, Part } from '@google/genai';
2
+ export type GeminiResponseStatus = 'completed' | 'failed' | 'incomplete';
3
+ export type GeminiGenerateResult = {
4
+ responseId: string;
5
+ parts: Part[];
6
+ finishReason?: FinishReason;
7
+ usage?: GenerateContentResponseUsageMetadata;
8
+ };
9
+ export type GeminiStreamSender = (params: GenerateContentParameters) => Promise<AsyncGenerator<GenerateContentResponse>>;
10
+ /** Creates a `GeminiStreamSender` backed by a `@google/genai` `GoogleGenAI` client. */
11
+ export declare function geminiClientSender(client: GoogleGenAI): GeminiStreamSender;
12
+ /**
13
+ * Sends one streaming `generateContentStream` request to Gemini / Vertex AI and returns the
14
+ * assembled assistant `parts`. `onResponse` is called for every response that produced usage
15
+ * before any error is thrown, so every billable response is accounted for.
16
+ */
17
+ export declare function completedGeminiGenerateContent({ stream: sendStream, params, signal, onResponse, }: {
18
+ stream: GeminiStreamSender;
19
+ params: GenerateContentParameters;
20
+ signal: AbortSignal;
21
+ onResponse: (result: {
22
+ response: GeminiGenerateResult;
23
+ status: GeminiResponseStatus;
24
+ }) => void | Promise<void>;
25
+ }): Promise<GeminiGenerateResult>;
@@ -0,0 +1,126 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ProviderConnectionError } from './inference.js';
3
+ const REFUSAL_FINISH_REASONS = new Set([
4
+ 'SAFETY',
5
+ 'RECITATION',
6
+ 'PROHIBITED_CONTENT',
7
+ 'BLOCKLIST',
8
+ 'SPII',
9
+ 'MALFORMED_FUNCTION_CALL',
10
+ ]);
11
+ function isRetryableGeminiError(error) {
12
+ if (!error || typeof error !== 'object')
13
+ return false;
14
+ const err = error;
15
+ if (typeof err.status === 'number' && (err.status === 429 || err.status >= 500))
16
+ return true;
17
+ if (typeof err.code === 'number' && (err.code === 429 || err.code >= 500))
18
+ return true;
19
+ if (err.code === 'ECONNRESET' ||
20
+ err.code === 'ETIMEDOUT' ||
21
+ err.code === 'ENOTFOUND' ||
22
+ err.code === 'EAI_AGAIN' ||
23
+ err.code === 'RESOURCE_EXHAUSTED' ||
24
+ err.code === 'UNAVAILABLE' ||
25
+ err.code === 'INTERNAL' ||
26
+ err.code === 'DEADLINE_EXCEEDED')
27
+ return true;
28
+ if (typeof err.message === 'string' &&
29
+ /\b(429|500|502|503|504|RESOURCE_EXHAUSTED|UNAVAILABLE|DEADLINE_EXCEEDED)\b/.test(err.message))
30
+ return true;
31
+ return false;
32
+ }
33
+ /** Appends a streamed part, coalescing consecutive plain text/thought chunks while keeping every
34
+ * part that carries a `thoughtSignature` or `functionCall` intact for multi-turn replay. */
35
+ function appendStreamPart(parts, incoming) {
36
+ const prev = parts.at(-1);
37
+ const isPlainText = typeof incoming.text === 'string' &&
38
+ !incoming.functionCall &&
39
+ !incoming.thoughtSignature &&
40
+ !incoming.inlineData;
41
+ if (isPlainText &&
42
+ prev &&
43
+ typeof prev.text === 'string' &&
44
+ !prev.functionCall &&
45
+ !prev.thoughtSignature &&
46
+ !prev.inlineData &&
47
+ Boolean(prev.thought) === Boolean(incoming.thought)) {
48
+ prev.text += incoming.text;
49
+ return;
50
+ }
51
+ parts.push({ ...incoming });
52
+ }
53
+ /** Creates a `GeminiStreamSender` backed by a `@google/genai` `GoogleGenAI` client. */
54
+ export function geminiClientSender(client) {
55
+ return (params) => client.models.generateContentStream(params);
56
+ }
57
+ /**
58
+ * Sends one streaming `generateContentStream` request to Gemini / Vertex AI and returns the
59
+ * assembled assistant `parts`. `onResponse` is called for every response that produced usage
60
+ * before any error is thrown, so every billable response is accounted for.
61
+ */
62
+ export async function completedGeminiGenerateContent({ stream: sendStream, params, signal, onResponse, }) {
63
+ let stream;
64
+ try {
65
+ stream = await sendStream(params);
66
+ }
67
+ catch (error) {
68
+ signal.throwIfAborted();
69
+ const detail = error instanceof Error ? error.message : String(error);
70
+ if (isRetryableGeminiError(error))
71
+ throw new ProviderConnectionError(`The Gemini API could not complete the request: ${detail}`);
72
+ throw new Error(`The Gemini API failed: ${detail}`);
73
+ }
74
+ let responseId;
75
+ let finishReason;
76
+ let usage;
77
+ const parts = [];
78
+ let receivedChunk = false;
79
+ let failure;
80
+ try {
81
+ for await (const chunk of stream) {
82
+ signal.throwIfAborted();
83
+ receivedChunk = true;
84
+ if (chunk.responseId)
85
+ responseId = chunk.responseId;
86
+ if (chunk.usageMetadata)
87
+ usage = chunk.usageMetadata;
88
+ const candidate = chunk.candidates?.[0];
89
+ if (candidate?.finishReason)
90
+ finishReason = candidate.finishReason;
91
+ for (const part of candidate?.content?.parts ?? [])
92
+ appendStreamPart(parts, part);
93
+ }
94
+ }
95
+ catch (error) {
96
+ signal.throwIfAborted();
97
+ const detail = error instanceof Error ? error.message : String(error);
98
+ failure = isRetryableGeminiError(error)
99
+ ? new ProviderConnectionError(`The Gemini API's reply was cut off: ${detail}`)
100
+ : new Error(`The Gemini API failed mid-stream: ${detail}`);
101
+ }
102
+ const assembled = {
103
+ responseId: responseId ?? `gemini-${randomUUID()}`,
104
+ parts,
105
+ ...(finishReason ? { finishReason } : {}),
106
+ ...(usage ? { usage } : {}),
107
+ };
108
+ if (failure) {
109
+ if (usage)
110
+ await onResponse({ response: assembled, status: 'failed' });
111
+ throw failure;
112
+ }
113
+ if (!receivedChunk) {
114
+ throw new ProviderConnectionError('The Gemini API closed the reply before sending any data.');
115
+ }
116
+ if (finishReason === 'MAX_TOKENS') {
117
+ await onResponse({ response: assembled, status: 'incomplete' });
118
+ throw new Error('The Gemini API ended the reply early: MAX_TOKENS');
119
+ }
120
+ if (finishReason && REFUSAL_FINISH_REASONS.has(finishReason)) {
121
+ await onResponse({ response: assembled, status: 'failed' });
122
+ throw new Error(`The Gemini API refused the request: ${finishReason}`);
123
+ }
124
+ await onResponse({ response: assembled, status: 'completed' });
125
+ return assembled;
126
+ }
@@ -0,0 +1,84 @@
1
+ import type { PromptBlock, PromptCacheTtl } from '../blueprint/prompt-file.js';
2
+ import type { Effort, ModelSettings } from '../blueprint/run-settings.js';
3
+ import type { Tokens } from '../run/record/events.js';
4
+ import type { ReasoningSummary } from '../run/record/run-types.js';
5
+ export type { PromptBlock, PromptCacheTtl };
6
+ /** A tool as it is offered to the model. */
7
+ export type OfferedTool = {
8
+ name: string;
9
+ description: string;
10
+ inputSchema: unknown;
11
+ annotations?: {
12
+ [hint: string]: unknown;
13
+ };
14
+ };
15
+ /** One model call as whatever answers it receives it. */
16
+ export type InferenceCall = {
17
+ callId: string;
18
+ /** Which agent's call this is and for what, for whatever answers to tell calls apart. */
19
+ agent: string;
20
+ phase: string;
21
+ lane: string;
22
+ subjectKey: string;
23
+ /** Human-readable phase/activity label from blueprint metadata, for worker UIs and logs. */
24
+ activityLabel?: string;
25
+ /** Human-readable subject label (omitted for `'once'` lanes). */
26
+ subjectLabel?: string;
27
+ /** Agent role (for example `'author'` or `'reviewer'`) from blueprint metadata. */
28
+ role?: string;
29
+ /** Blueprint worker type name (defaults to `'default'`). */
30
+ worker?: string;
31
+ /** Optional human-readable label for the worker type. */
32
+ workerLabel?: string;
33
+ repeat: number;
34
+ attempt: number;
35
+ /** Which answered call this is by this agent for this lane, subject and repeat in the whole run,
36
+ * from 1. A call counts once it failed, asked, or its reply was judged, so the number stays the
37
+ * same when a stopped call is made again after Resume. */
38
+ callNumber: number;
39
+ prompt: string;
40
+ /** Optional cache-delimited prompt blocks, emitted when the prompt file marks cache breakpoints. */
41
+ promptBlocks?: PromptBlock[];
42
+ images: {
43
+ mediaType: string;
44
+ bytes: Uint8Array;
45
+ }[];
46
+ tools: OfferedTool[];
47
+ model?: string;
48
+ /** Resolved per-plugin default models from the blueprint, forwarded even when `callsAnsweredBy === 'custom'`. */
49
+ models?: ModelSettings['model'];
50
+ effort?: Effort;
51
+ };
52
+ export type InferenceReply = {
53
+ replyText: string;
54
+ tokens: Tokens;
55
+ /** Priced per provider request and added up. Absent when a worker or a script answered. */
56
+ costUsd?: number;
57
+ /** The cost the model program itself reported for the call, as Claude Code does. */
58
+ programCostUsd?: number;
59
+ reasoning: ReasoningSummary[];
60
+ /** The instruction text a launcher sent beside the prompt. */
61
+ launcherInstruction?: string;
62
+ };
63
+ /** Answers one model call. `callTool` runs one of the call's tools and returns what goes back to
64
+ * the model: the tool's result, or `{ error }`. Cancelling `signal` ends the call. */
65
+ export type Infer = (request: {
66
+ call: InferenceCall;
67
+ callTool: (toolCall: {
68
+ name: string;
69
+ args: unknown;
70
+ }) => Promise<unknown>;
71
+ signal: AbortSignal;
72
+ /** Told, after each provider request of the call, what the requests so far add up to, so a
73
+ * call that fails or is stopped after one of them still saves what it used. */
74
+ onRequestCounted?: (soFar: Pick<InferenceReply, 'tokens' | 'costUsd' | 'reasoning'>) => void;
75
+ }) => Promise<InferenceReply>;
76
+ /** A connection failure, a provider outage or a model at capacity. The same call is made again,
77
+ * three attempts in all. */
78
+ export declare class ProviderConnectionError extends Error {
79
+ }
80
+ /** A resumable refusal such as out-of-credits, a disconnected local worker, or a local CLI that
81
+ * needs attention. Stops the run cleanly (`status: 'stopped'`) with zero retries, preserving state
82
+ * and the user-facing reason so the person can resolve it and Resume. */
83
+ export declare class ProviderAccessError extends Error {
84
+ }
@@ -0,0 +1,9 @@
1
+ /** A connection failure, a provider outage or a model at capacity. The same call is made again,
2
+ * three attempts in all. */
3
+ export class ProviderConnectionError extends Error {
4
+ }
5
+ /** A resumable refusal such as out-of-credits, a disconnected local worker, or a local CLI that
6
+ * needs attention. Stops the run cleanly (`status: 'stopped'`) with zero retries, preserving state
7
+ * and the user-facing reason so the person can resolve it and Resume. */
8
+ export class ProviderAccessError extends Error {
9
+ }
@@ -0,0 +1,29 @@
1
+ import type { Tokens } from '../run/record/events.js';
2
+ import type { Infer, InferenceCall } from './inference.js';
3
+ import { type ApiResponseStatus } from './openai-request.js';
4
+ export type OpenAiBeforeRequest = (input: {
5
+ call: InferenceCall;
6
+ requestIndex: number;
7
+ model: string;
8
+ }) => void | Promise<void>;
9
+ export type OpenAiProviderResponse = (input: {
10
+ call: InferenceCall;
11
+ responseId: string;
12
+ model: string;
13
+ tokens: Tokens;
14
+ costUsd?: number;
15
+ status: ApiResponseStatus;
16
+ }) => void | Promise<void>;
17
+ /** Answers calls with the OpenAI API. A call with tool calls makes several requests; token
18
+ * counts are summed over them and each is priced on its own. Hosts may supply `beforeRequest`
19
+ * (e.g. credit checks) and `onProviderResponse` (e.g. exact per-response billing by `responseId`). */
20
+ export declare function openAiApiInference({ apiKey, defaultModel, baseUrl, textFormat, maxOutputTokens, initialPreviousResponseId, beforeRequest, onProviderResponse, }: {
21
+ apiKey: string;
22
+ defaultModel?: string;
23
+ baseUrl?: string;
24
+ textFormat?: unknown;
25
+ maxOutputTokens?: number;
26
+ initialPreviousResponseId?: string;
27
+ beforeRequest?: OpenAiBeforeRequest;
28
+ onProviderResponse?: OpenAiProviderResponse;
29
+ }): Infer;
@@ -0,0 +1,138 @@
1
+ import { hasOpenAiPrice, requestCostUsd } from './openai-prices.js';
2
+ import { completedResponse, } from './openai-request.js';
3
+ const firstInput = ({ call }) => [
4
+ {
5
+ role: 'user',
6
+ content: [
7
+ { type: 'input_text', text: call.prompt },
8
+ ...call.images.map(({ mediaType, bytes }) => ({
9
+ type: 'input_image',
10
+ image_url: `data:${mediaType};base64,${Buffer.from(bytes).toString('base64')}`,
11
+ })),
12
+ ],
13
+ },
14
+ ];
15
+ /** Answers calls with the OpenAI API. A call with tool calls makes several requests; token
16
+ * counts are summed over them and each is priced on its own. Hosts may supply `beforeRequest`
17
+ * (e.g. credit checks) and `onProviderResponse` (e.g. exact per-response billing by `responseId`). */
18
+ export function openAiApiInference({ apiKey, defaultModel, baseUrl, textFormat, maxOutputTokens, initialPreviousResponseId, beforeRequest, onProviderResponse, }) {
19
+ return async ({ call, callTool, signal, onRequestCounted }) => {
20
+ const model = call.model ?? defaultModel;
21
+ if (!model || !hasOpenAiPrice({ model }))
22
+ throw new Error(`${call.agent} names ${model ?? 'no model'}, which has no price on the OpenAI API.`);
23
+ const tokens = {};
24
+ const reasoning = [];
25
+ let costUsd;
26
+ let toolCallsAnswered = 0;
27
+ let input = firstInput({ call });
28
+ let previousResponseId = initialPreviousResponseId;
29
+ /** Adds one ended request to the call's counts and notifies per-response listeners. */
30
+ const countRequest = async ({ response, status, }) => {
31
+ const { usage } = response;
32
+ const reported = {};
33
+ if (typeof usage?.input_tokens === 'number')
34
+ reported.input = usage.input_tokens;
35
+ if (typeof usage?.input_tokens_details?.cached_tokens === 'number')
36
+ reported.cached = usage.input_tokens_details.cached_tokens;
37
+ if (typeof usage?.output_tokens === 'number')
38
+ reported.output = usage.output_tokens;
39
+ if (typeof usage?.output_tokens_details?.reasoning_tokens === 'number')
40
+ reported.reasoning = usage.output_tokens_details.reasoning_tokens;
41
+ for (const name of ['input', 'cached', 'output', 'reasoning'])
42
+ if (typeof reported[name] === 'number')
43
+ tokens[name] = (tokens[name] ?? 0) + reported[name];
44
+ let responseCostUsd;
45
+ if (typeof reported.input === 'number' && typeof reported.output === 'number') {
46
+ responseCostUsd = requestCostUsd({
47
+ model,
48
+ inputTokens: reported.input,
49
+ cachedInputTokens: reported.cached ?? 0,
50
+ outputTokens: reported.output,
51
+ });
52
+ costUsd = (costUsd ?? 0) + responseCostUsd;
53
+ }
54
+ let toolCallsBefore = toolCallsAnswered;
55
+ for (const item of response.output ?? []) {
56
+ const text = (item.summary ?? []).map((part) => part.text ?? '').join('\n\n');
57
+ if (item.type === 'function_call')
58
+ toolCallsBefore += 1;
59
+ else if (item.type === 'reasoning' && text)
60
+ reasoning.push({ text, afterToolCalls: toolCallsBefore });
61
+ }
62
+ onRequestCounted?.({
63
+ tokens: { ...tokens },
64
+ ...(costUsd !== undefined ? { costUsd } : {}),
65
+ reasoning: [...reasoning],
66
+ });
67
+ await onProviderResponse?.({
68
+ call,
69
+ responseId: response.id,
70
+ model,
71
+ tokens: reported,
72
+ ...(responseCostUsd !== undefined ? { costUsd: responseCostUsd } : {}),
73
+ status,
74
+ });
75
+ };
76
+ for (let requestIndex = 1;; requestIndex += 1) {
77
+ await beforeRequest?.({ call, requestIndex, model });
78
+ const response = await completedResponse({
79
+ apiKey,
80
+ baseUrl,
81
+ signal,
82
+ onResponse: countRequest,
83
+ body: {
84
+ model,
85
+ input,
86
+ ...(previousResponseId ? { previous_response_id: previousResponseId } : {}),
87
+ ...(call.tools.length
88
+ ? {
89
+ tools: call.tools.map((tool) => ({
90
+ type: 'function',
91
+ name: tool.name,
92
+ description: tool.description,
93
+ parameters: tool.inputSchema,
94
+ strict: false,
95
+ })),
96
+ }
97
+ : {}),
98
+ ...(textFormat ? { text: { format: textFormat } } : {}),
99
+ ...(maxOutputTokens ? { max_output_tokens: maxOutputTokens } : {}),
100
+ reasoning: { ...(call.effort ? { effort: call.effort } : {}), summary: 'auto' },
101
+ store: true,
102
+ stream: true,
103
+ },
104
+ });
105
+ const output = response.output ?? [];
106
+ const toolCalls = output.filter((item) => item.type === 'function_call');
107
+ if (!toolCalls.length) {
108
+ const replyText = output
109
+ .filter((item) => item.type === 'message')
110
+ .flatMap((item) => item.content ?? [])
111
+ .filter((part) => part.type === 'output_text')
112
+ .map((part) => part.text ?? '')
113
+ .join('');
114
+ return { replyText, tokens, ...(costUsd !== undefined ? { costUsd } : {}), reasoning };
115
+ }
116
+ const results = [];
117
+ for (const toolCall of toolCalls) {
118
+ signal.throwIfAborted();
119
+ let args;
120
+ try {
121
+ args = JSON.parse(toolCall.arguments || '{}');
122
+ }
123
+ catch {
124
+ args = toolCall.arguments;
125
+ }
126
+ const result = await callTool({ name: toolCall.name ?? '', args });
127
+ toolCallsAnswered += 1;
128
+ results.push({
129
+ type: 'function_call_output',
130
+ call_id: toolCall.call_id,
131
+ output: typeof result === 'string' ? result : JSON.stringify(result ?? null),
132
+ });
133
+ }
134
+ input = results;
135
+ previousResponseId = response.id;
136
+ }
137
+ };
138
+ }
@@ -0,0 +1,12 @@
1
+ /** Whether the OpenAI API route can price a model. A run on the API is refused before any call
2
+ * when an agent names a model that has no price. */
3
+ export declare function hasOpenAiPrice({ model }: {
4
+ model: string;
5
+ }): boolean;
6
+ /** The cost in dollars of one request to the API, priced by that request's own token counts. */
7
+ export declare function requestCostUsd({ model, inputTokens, cachedInputTokens, outputTokens, }: {
8
+ model: string;
9
+ inputTokens: number;
10
+ cachedInputTokens: number;
11
+ outputTokens: number;
12
+ }): number;
@@ -0,0 +1,25 @@
1
+ /** A request whose prompt is longer than this is priced at the long-context rates. */
2
+ const LONG_CONTEXT_INPUT_TOKENS = 272_000;
3
+ /** Dollars per million tokens, from OpenAI's public price pages as copied in
4
+ * packages/api/src/modeling/openai-prices.ts (checked there on 2026-11-02). Dagma keeps its own
5
+ * copy: nothing in this package imports the API package. */
6
+ const PRICES = {
7
+ 'gpt-6.1-terra': {
8
+ standard: { input: 1, cachedInput: 0.05, output: 5 },
9
+ longContext: { input: 2, cachedInput: 0.1, output: 7.5 },
10
+ },
11
+ };
12
+ /** Whether the OpenAI API route can price a model. A run on the API is refused before any call
13
+ * when an agent names a model that has no price. */
14
+ export function hasOpenAiPrice({ model }) {
15
+ return Object.hasOwn(PRICES, model);
16
+ }
17
+ /** The cost in dollars of one request to the API, priced by that request's own token counts. */
18
+ export function requestCostUsd({ model, inputTokens, cachedInputTokens, outputTokens, }) {
19
+ const prices = PRICES[model];
20
+ const rates = inputTokens > LONG_CONTEXT_INPUT_TOKENS ? prices.longContext : prices.standard;
21
+ return (((inputTokens - cachedInputTokens) * rates.input +
22
+ cachedInputTokens * rates.cachedInput +
23
+ outputTokens * rates.output) /
24
+ 1_000_000);
25
+ }
@@ -0,0 +1,50 @@
1
+ export declare const DEFAULT_OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
2
+ export type ResponseItem = {
3
+ type?: string;
4
+ call_id?: string;
5
+ name?: string;
6
+ arguments?: string;
7
+ summary?: {
8
+ text?: string;
9
+ }[];
10
+ content?: {
11
+ type?: string;
12
+ text?: string;
13
+ }[];
14
+ };
15
+ export type ApiResponse = {
16
+ id: string;
17
+ output?: ResponseItem[];
18
+ usage?: {
19
+ input_tokens?: number;
20
+ input_tokens_details?: {
21
+ cached_tokens?: number;
22
+ };
23
+ output_tokens?: number;
24
+ output_tokens_details?: {
25
+ reasoning_tokens?: number;
26
+ };
27
+ };
28
+ error?: {
29
+ code?: string;
30
+ message?: string;
31
+ };
32
+ incomplete_details?: {
33
+ reason?: string;
34
+ };
35
+ };
36
+ export type ApiResponseStatus = 'completed' | 'failed' | 'incomplete';
37
+ /** Sends one request to the Responses API and returns the response its stream completes with.
38
+ * The stream is only how a long request keeps its connection open. `onResponse` is handed every
39
+ * response that ends the request, also one that failed or was cut short, before the failure is
40
+ * thrown: the provider counts its tokens either way. */
41
+ export declare function completedResponse({ apiKey, baseUrl, body, signal, onResponse, }: {
42
+ apiKey: string;
43
+ baseUrl?: string;
44
+ body: unknown;
45
+ signal: AbortSignal;
46
+ onResponse: (result: {
47
+ response: ApiResponse;
48
+ status: ApiResponseStatus;
49
+ }) => void | Promise<void>;
50
+ }): Promise<ApiResponse>;
@@ -0,0 +1,100 @@
1
+ import { ProviderConnectionError } from './inference.js';
2
+ export const DEFAULT_OPENAI_RESPONSES_URL = 'https://api.openai.com/v1/responses';
3
+ /** The failure codes of a refused request that waiting will not cure: the account is out of
4
+ * credit or over a limit its owner set. Every other "too many requests" is tried again. */
5
+ const ACCOUNT_LIMIT_CODES = [
6
+ 'insufficient_quota',
7
+ 'credit_balance_exhausted',
8
+ 'organization_spend_limit_exceeded',
9
+ 'project_spend_limit_exceeded',
10
+ 'organization_usage_limit_exceeded',
11
+ ];
12
+ /** The failure codes with which the provider reports its own outage or a model at capacity. */
13
+ const TRIED_AGAIN_CODES = ['server_error', 'rate_limit_exceeded'];
14
+ /** Sends one request to the Responses API and returns the response its stream completes with.
15
+ * The stream is only how a long request keeps its connection open. `onResponse` is handed every
16
+ * response that ends the request, also one that failed or was cut short, before the failure is
17
+ * thrown: the provider counts its tokens either way. */
18
+ export async function completedResponse({ apiKey, baseUrl = DEFAULT_OPENAI_RESPONSES_URL, body, signal, onResponse, }) {
19
+ let response;
20
+ try {
21
+ response = await fetch(baseUrl, {
22
+ method: 'POST',
23
+ headers: { authorization: `Bearer ${apiKey}`, 'content-type': 'application/json' },
24
+ body: JSON.stringify(body),
25
+ signal,
26
+ });
27
+ }
28
+ catch (error) {
29
+ signal.throwIfAborted();
30
+ throw new ProviderConnectionError(`The OpenAI API could not be reached: ${error instanceof Error ? error.message : String(error)}`);
31
+ }
32
+ if (!response.ok) {
33
+ const detail = await response.text().catch(() => '');
34
+ const message = `The OpenAI API answered ${response.status}: ${detail.slice(0, 500)}`;
35
+ let code;
36
+ try {
37
+ code = JSON.parse(detail)?.error?.code;
38
+ }
39
+ catch {
40
+ // An answer that is not JSON names no code.
41
+ }
42
+ const accountLimit = response.status === 429 && ACCOUNT_LIMIT_CODES.includes(code);
43
+ if ((response.status === 429 && !accountLimit) || response.status >= 500)
44
+ throw new ProviderConnectionError(message);
45
+ throw new Error(message);
46
+ }
47
+ const decoder = new TextDecoder();
48
+ let buffered = '';
49
+ let completed;
50
+ let failure;
51
+ try {
52
+ for await (const chunk of response.body) {
53
+ buffered += decoder.decode(chunk, { stream: true }).replaceAll('\r\n', '\n');
54
+ for (;;) {
55
+ const end = buffered.indexOf('\n\n');
56
+ if (end < 0)
57
+ break;
58
+ const data = buffered
59
+ .slice(0, end)
60
+ .split('\n')
61
+ .filter((line) => line.startsWith('data:'))
62
+ .map((line) => line.slice('data:'.length).trim())
63
+ .join('');
64
+ buffered = buffered.slice(end + 2);
65
+ if (!data || data === '[DONE]')
66
+ continue;
67
+ const event = JSON.parse(data);
68
+ let responseStatus;
69
+ if (event.type === 'response.completed') {
70
+ completed = event.response;
71
+ responseStatus = 'completed';
72
+ }
73
+ if (event.type === 'response.failed' || event.type === 'error') {
74
+ const code = event.response?.error?.code ?? event.code;
75
+ const message = `The OpenAI API failed the request: ${event.response?.error?.message ?? event.message ?? 'no reason given'}`;
76
+ failure = TRIED_AGAIN_CODES.includes(code ?? '')
77
+ ? new ProviderConnectionError(message)
78
+ : new Error(message);
79
+ responseStatus = 'failed';
80
+ }
81
+ if (event.type === 'response.incomplete') {
82
+ failure = new Error(`The OpenAI API ended the reply early: ${event.response?.incomplete_details?.reason ?? 'no reason given'}`);
83
+ responseStatus = 'incomplete';
84
+ }
85
+ if (event.response && responseStatus)
86
+ await onResponse({ response: event.response, status: responseStatus });
87
+ }
88
+ }
89
+ }
90
+ catch (error) {
91
+ signal.throwIfAborted();
92
+ if (!failure && !completed)
93
+ throw new ProviderConnectionError(`The OpenAI API's reply was cut off: ${error instanceof Error ? error.message : String(error)}`);
94
+ }
95
+ if (failure)
96
+ throw failure;
97
+ if (!completed)
98
+ throw new ProviderConnectionError('The OpenAI API closed the reply before its end.');
99
+ return completed;
100
+ }
@@ -0,0 +1,6 @@
1
+ /** Starts the worker a run answered by Codex or Claude Code brings with it, as a child program
2
+ * given the queue's address and secret. Returns the function that stops it. */
3
+ export declare function startOwnWorker({ address, secret }: {
4
+ address: string;
5
+ secret: string;
6
+ }): () => void;
@@ -0,0 +1,16 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ /** Starts the worker a run answered by Codex or Claude Code brings with it, as a child program
4
+ * given the queue's address and secret. Returns the function that stops it. */
5
+ export function startOwnWorker({ address, secret }) {
6
+ const command = fileURLToPath(new URL('../command.ts', import.meta.url));
7
+ // The child runs as this process does (through tsx), and its output goes to the error output so
8
+ // the run's own output stays one events line per line.
9
+ const child = spawn(process.execPath, [...process.execArgv, command, 'worker', '--url', address], {
10
+ env: { ...process.env, DAGMA_QUEUE_SECRET: secret },
11
+ stdio: ['ignore', process.stderr, process.stderr],
12
+ });
13
+ return () => {
14
+ child.kill('SIGTERM');
15
+ };
16
+ }