@praudent/dagma 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/admin-ui/assets/index-CHJ8lsZp.js +120 -0
  2. package/dist/admin-ui/assets/index-XyqtD-IA.css +1 -0
  3. package/dist/admin-ui/index.html +12 -0
  4. package/dist/blueprint/agent.d.ts +148 -0
  5. package/dist/blueprint/agent.js +1 -0
  6. package/dist/blueprint/declaration-site.d.ts +7 -0
  7. package/dist/blueprint/declaration-site.js +8 -0
  8. package/dist/blueprint/declared-structure.d.ts +145 -0
  9. package/dist/blueprint/declared-structure.js +213 -0
  10. package/dist/blueprint/define-run-state.d.ts +79 -0
  11. package/dist/blueprint/define-run-state.js +89 -0
  12. package/dist/blueprint/load-blueprint.d.ts +28 -0
  13. package/dist/blueprint/load-blueprint.js +85 -0
  14. package/dist/blueprint/outcomes.d.ts +76 -0
  15. package/dist/blueprint/outcomes.js +10 -0
  16. package/dist/blueprint/phase.d.ts +153 -0
  17. package/dist/blueprint/phase.js +1 -0
  18. package/dist/blueprint/places.d.ts +26 -0
  19. package/dist/blueprint/places.js +37 -0
  20. package/dist/blueprint/prompt-file.d.ts +81 -0
  21. package/dist/blueprint/prompt-file.js +131 -0
  22. package/dist/blueprint/reply-reader.d.ts +36 -0
  23. package/dist/blueprint/reply-reader.js +38 -0
  24. package/dist/blueprint/run-settings.d.ts +38 -0
  25. package/dist/blueprint/run-settings.js +1 -0
  26. package/dist/blueprint/serializer.d.ts +14 -0
  27. package/dist/blueprint/serializer.js +4 -0
  28. package/dist/blueprint/write-scope.d.ts +39 -0
  29. package/dist/blueprint/write-scope.js +106 -0
  30. package/dist/command.d.ts +2 -0
  31. package/dist/command.js +148 -0
  32. package/dist/commands/calls-answering.d.ts +16 -0
  33. package/dist/commands/calls-answering.js +63 -0
  34. package/dist/commands/json-file.d.ts +6 -0
  35. package/dist/commands/json-file.js +19 -0
  36. package/dist/commands/run-command.d.ts +23 -0
  37. package/dist/commands/run-command.js +172 -0
  38. package/dist/commands/typed-answers.d.ts +10 -0
  39. package/dist/commands/typed-answers.js +43 -0
  40. package/dist/config.d.ts +27 -0
  41. package/dist/config.js +20 -0
  42. package/dist/devtool-server/app-pages.d.ts +12 -0
  43. package/dist/devtool-server/app-pages.js +68 -0
  44. package/dist/devtool-server/blueprint-description.d.ts +21 -0
  45. package/dist/devtool-server/blueprint-description.js +27 -0
  46. package/dist/devtool-server/connected-runs.d.ts +36 -0
  47. package/dist/devtool-server/connected-runs.js +201 -0
  48. package/dist/devtool-server/devtool-server.d.ts +17 -0
  49. package/dist/devtool-server/devtool-server.js +294 -0
  50. package/dist/devtool-server/devtool-shapes.d.ts +312 -0
  51. package/dist/devtool-server/devtool-shapes.js +24 -0
  52. package/dist/devtool-server/listed-runs.d.ts +17 -0
  53. package/dist/devtool-server/listed-runs.js +42 -0
  54. package/dist/devtool-server/print-blueprint.d.ts +1 -0
  55. package/dist/devtool-server/print-blueprint.js +36 -0
  56. package/dist/example/added-species.d.ts +21 -0
  57. package/dist/example/added-species.js +19 -0
  58. package/dist/example/cover.d.ts +21 -0
  59. package/dist/example/cover.js +67 -0
  60. package/dist/example/cross-references.d.ts +21 -0
  61. package/dist/example/cross-references.js +77 -0
  62. package/dist/example/entry-drafts.d.ts +21 -0
  63. package/dist/example/entry-drafts.js +63 -0
  64. package/dist/example/entry-merge.d.ts +108 -0
  65. package/dist/example/entry-merge.js +284 -0
  66. package/dist/example/field-guide.d.ts +26 -0
  67. package/dist/example/field-guide.js +40 -0
  68. package/dist/example/guide-page.d.ts +21 -0
  69. package/dist/example/guide-page.js +15 -0
  70. package/dist/example/missing-species.d.ts +21 -0
  71. package/dist/example/missing-species.js +59 -0
  72. package/dist/example/run-state.d.ts +803 -0
  73. package/dist/example/run-state.js +58 -0
  74. package/dist/example/serializers.d.ts +32 -0
  75. package/dist/example/serializers.js +42 -0
  76. package/dist/example/species-list.d.ts +47 -0
  77. package/dist/example/species-list.js +93 -0
  78. package/dist/index.d.ts +35 -0
  79. package/dist/index.js +25 -0
  80. package/dist/inference/anthropic-api.d.ts +37 -0
  81. package/dist/inference/anthropic-api.js +197 -0
  82. package/dist/inference/anthropic-prices.d.ts +18 -0
  83. package/dist/inference/anthropic-prices.js +39 -0
  84. package/dist/inference/anthropic-request.d.ts +51 -0
  85. package/dist/inference/anthropic-request.js +208 -0
  86. package/dist/inference/bedrock-api.d.ts +45 -0
  87. package/dist/inference/bedrock-api.js +242 -0
  88. package/dist/inference/bedrock-prices.d.ts +22 -0
  89. package/dist/inference/bedrock-prices.js +79 -0
  90. package/dist/inference/bedrock-request.d.ts +27 -0
  91. package/dist/inference/bedrock-request.js +193 -0
  92. package/dist/inference/call-queue-shapes.d.ts +273 -0
  93. package/dist/inference/call-queue-shapes.js +82 -0
  94. package/dist/inference/call-queue.d.ts +109 -0
  95. package/dist/inference/call-queue.js +408 -0
  96. package/dist/inference/gemini-api.d.ts +44 -0
  97. package/dist/inference/gemini-api.js +191 -0
  98. package/dist/inference/gemini-prices.d.ts +19 -0
  99. package/dist/inference/gemini-prices.js +33 -0
  100. package/dist/inference/gemini-request.d.ts +25 -0
  101. package/dist/inference/gemini-request.js +126 -0
  102. package/dist/inference/inference.d.ts +84 -0
  103. package/dist/inference/inference.js +9 -0
  104. package/dist/inference/openai-api.d.ts +29 -0
  105. package/dist/inference/openai-api.js +138 -0
  106. package/dist/inference/openai-prices.d.ts +12 -0
  107. package/dist/inference/openai-prices.js +25 -0
  108. package/dist/inference/openai-request.d.ts +50 -0
  109. package/dist/inference/openai-request.js +100 -0
  110. package/dist/inference/own-worker.d.ts +6 -0
  111. package/dist/inference/own-worker.js +16 -0
  112. package/dist/inference/scripted.d.ts +146 -0
  113. package/dist/inference/scripted.js +67 -0
  114. package/dist/run/assignments/agent-call.d.ts +32 -0
  115. package/dist/run/assignments/agent-call.js +218 -0
  116. package/dist/run/assignments/agent-phase.d.ts +14 -0
  117. package/dist/run/assignments/agent-phase.js +243 -0
  118. package/dist/run/assignments/assignment-memory.d.ts +42 -0
  119. package/dist/run/assignments/assignment-memory.js +52 -0
  120. package/dist/run/assignments/assignment.d.ts +17 -0
  121. package/dist/run/assignments/assignment.js +252 -0
  122. package/dist/run/assignments/model-settings.d.ts +39 -0
  123. package/dist/run/assignments/model-settings.js +57 -0
  124. package/dist/run/assignments/prepared-call.d.ts +28 -0
  125. package/dist/run/assignments/prepared-call.js +115 -0
  126. package/dist/run/assignments/tool-call.d.ts +26 -0
  127. package/dist/run/assignments/tool-call.js +108 -0
  128. package/dist/run/blueprint-mistake.d.ts +8 -0
  129. package/dist/run/blueprint-mistake.js +14 -0
  130. package/dist/run/code-phase.d.ts +11 -0
  131. package/dist/run/code-phase.js +59 -0
  132. package/dist/run/create-run.d.ts +36 -0
  133. package/dist/run/create-run.js +119 -0
  134. package/dist/run/execute-run.d.ts +7 -0
  135. package/dist/run/execute-run.js +158 -0
  136. package/dist/run/record/apply-event.d.ts +13 -0
  137. package/dist/run/record/apply-event.js +256 -0
  138. package/dist/run/record/events.d.ts +187 -0
  139. package/dist/run/record/events.js +1 -0
  140. package/dist/run/record/postgres-run-store.d.ts +13 -0
  141. package/dist/run/record/postgres-run-store.js +189 -0
  142. package/dist/run/record/progress-projection.d.ts +83 -0
  143. package/dist/run/record/progress-projection.js +167 -0
  144. package/dist/run/record/progress.d.ts +207 -0
  145. package/dist/run/record/progress.js +63 -0
  146. package/dist/run/record/run-store.d.ts +74 -0
  147. package/dist/run/record/run-store.js +1 -0
  148. package/dist/run/record/run-summary.d.ts +8 -0
  149. package/dist/run/record/run-summary.js +19 -0
  150. package/dist/run/record/run-types.d.ts +95 -0
  151. package/dist/run/record/run-types.js +1 -0
  152. package/dist/run/record/state-changes.d.ts +42 -0
  153. package/dist/run/record/state-changes.js +157 -0
  154. package/dist/run/resume-run.d.ts +25 -0
  155. package/dist/run/resume-run.js +99 -0
  156. package/dist/run/run-endings.d.ts +20 -0
  157. package/dist/run/run-endings.js +20 -0
  158. package/dist/run/run-option-shapes.d.ts +176 -0
  159. package/dist/run/run-option-shapes.js +47 -0
  160. package/dist/run/run-session.d.ts +144 -0
  161. package/dist/run/run-session.js +278 -0
  162. package/dist/worker/answer-queued-call.d.ts +19 -0
  163. package/dist/worker/answer-queued-call.js +100 -0
  164. package/dist/worker/launchers/claude-code.d.ts +7 -0
  165. package/dist/worker/launchers/claude-code.js +156 -0
  166. package/dist/worker/launchers/codex.d.ts +6 -0
  167. package/dist/worker/launchers/codex.js +141 -0
  168. package/dist/worker/launchers/launch.d.ts +31 -0
  169. package/dist/worker/launchers/launch.js +6 -0
  170. package/dist/worker/launchers/program-run.d.ts +30 -0
  171. package/dist/worker/launchers/program-run.js +92 -0
  172. package/dist/worker/launchers/tool-server.d.ts +26 -0
  173. package/dist/worker/launchers/tool-server.js +90 -0
  174. package/dist/worker/worker.d.ts +13 -0
  175. package/dist/worker/worker.js +170 -0
  176. package/package.json +43 -4
  177. package/README.md +0 -3
@@ -0,0 +1,408 @@
1
+ import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { ForwardedToolCallSchema, WorkerFailureSchema, WorkerReplySchema, } from './call-queue-shapes.js';
4
+ import { ProviderAccessError, ProviderConnectionError, } from './inference.js';
5
+ const KEEP_ALIVE_MS = 25_000;
6
+ const MAX_BODY_BYTES = 32 * 1024 * 1024;
7
+ const DEFAULT_NO_WORKER_LIMIT_MS = 30_000;
8
+ export class CallQueueError extends Error {
9
+ status;
10
+ constructor(status, message) {
11
+ super(message);
12
+ this.status = status;
13
+ }
14
+ }
15
+ /**
16
+ * Transport-agnostic, multi-tenant call queue coordinator.
17
+ * Partitions calls and workers by `partitionKey` (for example `accountId` in a server app, or
18
+ * `'local'` in Dagma CLI), tracks worker readiness (`ready` / `needs-attention` / `disconnected`),
19
+ * forwards tool calls, and enforces disconnect grace periods.
20
+ */
21
+ export class CallQueue {
22
+ calls = Object.create(null);
23
+ streams = [];
24
+ partitionLostReadyAt = Object.create(null);
25
+ workerGoneAt = Object.create(null);
26
+ startedAt = Date.now();
27
+ noWorkerLimitMs;
28
+ disconnectedMessage;
29
+ needsAttentionMessage;
30
+ constructor({ noWorkerLimitMs = DEFAULT_NO_WORKER_LIMIT_MS, disconnectedMessage, needsAttentionMessage, } = {}) {
31
+ this.noWorkerLimitMs = noWorkerLimitMs;
32
+ this.disconnectedMessage =
33
+ disconnectedMessage ??
34
+ `No worker has been connected for ${Math.round(noWorkerLimitMs / 1000)} seconds. Start one, then Resume.`;
35
+ this.needsAttentionMessage =
36
+ needsAttentionMessage ??
37
+ 'The connected worker needs attention before it can answer calls. Fix it, then Resume.';
38
+ }
39
+ workerKey({ partitionKey, workerId }) {
40
+ return `${partitionKey}\0${workerId}`;
41
+ }
42
+ readyWorkerIds({ partitionKey }) {
43
+ const ids = new Set();
44
+ for (const stream of this.streams)
45
+ if (stream.partitionKey === partitionKey && stream.ready)
46
+ ids.add(stream.workerId);
47
+ return [...ids];
48
+ }
49
+ publish({ partitionKey, event }) {
50
+ for (const stream of this.streams)
51
+ if (stream.partitionKey === partitionKey && stream.ready)
52
+ stream.send(event);
53
+ }
54
+ sendWaitingSnapshot({ stream }) {
55
+ const waiting = Object.values(this.calls)
56
+ .filter((entry) => entry.partitionKey === stream.partitionKey)
57
+ .map((entry) => ({
58
+ id: entry.call.id,
59
+ taken: entry.takenBy !== undefined && entry.takenBy !== stream.workerId,
60
+ }));
61
+ stream.send({ type: 'waiting', calls: waiting });
62
+ }
63
+ /** Whether a partition has a ready worker, only non-ready workers, or none connected. */
64
+ connectionStatus({ partitionKey }) {
65
+ let anyOpen = false;
66
+ for (const stream of this.streams) {
67
+ if (stream.partitionKey !== partitionKey)
68
+ continue;
69
+ if (stream.ready)
70
+ return 'ready';
71
+ anyOpen = true;
72
+ }
73
+ return anyOpen ? 'needs-attention' : 'disconnected';
74
+ }
75
+ /** Registers one worker SSE/push stream for `partitionKey`. Returns its disconnect cleanup. */
76
+ connectWorker({ partitionKey, workerId, ready = true, send, }) {
77
+ const stream = { partitionKey, workerId, ready, send };
78
+ this.streams.push(stream);
79
+ if (ready) {
80
+ delete this.partitionLostReadyAt[partitionKey];
81
+ delete this.workerGoneAt[this.workerKey({ partitionKey, workerId })];
82
+ this.sendWaitingSnapshot({ stream });
83
+ }
84
+ return () => {
85
+ const index = this.streams.indexOf(stream);
86
+ if (index >= 0)
87
+ this.streams.splice(index, 1);
88
+ const now = Date.now();
89
+ const readyWorkers = this.readyWorkerIds({ partitionKey });
90
+ if (!readyWorkers.includes(workerId))
91
+ this.workerGoneAt[this.workerKey({ partitionKey, workerId })] = now;
92
+ if (!readyWorkers.length) {
93
+ this.partitionLostReadyAt[partitionKey] = now;
94
+ if (this.connectionStatus({ partitionKey }) === 'needs-attention')
95
+ this.failUntakenCallsNeedingAttention({ partitionKey });
96
+ }
97
+ this.scheduleAbandonedCheck({ partitionKey });
98
+ };
99
+ }
100
+ /** Updates readiness for a connected worker without dropping its stream. */
101
+ setWorkerReady({ partitionKey, workerId, ready, }) {
102
+ let becameReady = false;
103
+ for (const stream of this.streams) {
104
+ if (stream.partitionKey !== partitionKey || stream.workerId !== workerId)
105
+ continue;
106
+ if (ready && !stream.ready)
107
+ becameReady = true;
108
+ stream.ready = ready;
109
+ if (becameReady)
110
+ this.sendWaitingSnapshot({ stream });
111
+ }
112
+ if (ready) {
113
+ delete this.partitionLostReadyAt[partitionKey];
114
+ delete this.workerGoneAt[this.workerKey({ partitionKey, workerId })];
115
+ }
116
+ else {
117
+ const now = Date.now();
118
+ const readyWorkers = this.readyWorkerIds({ partitionKey });
119
+ if (!readyWorkers.includes(workerId))
120
+ this.workerGoneAt[this.workerKey({ partitionKey, workerId })] = now;
121
+ if (!readyWorkers.length) {
122
+ this.partitionLostReadyAt[partitionKey] = now;
123
+ if (this.connectionStatus({ partitionKey }) === 'needs-attention')
124
+ this.failUntakenCallsNeedingAttention({ partitionKey });
125
+ }
126
+ this.scheduleAbandonedCheck({ partitionKey });
127
+ }
128
+ }
129
+ failUntakenCallsNeedingAttention({ partitionKey }) {
130
+ for (const waiting of Object.values(this.calls))
131
+ if (waiting.partitionKey === partitionKey && waiting.takenBy === undefined)
132
+ waiting.fail(new ProviderAccessError(this.needsAttentionMessage));
133
+ }
134
+ scheduleAbandonedCheck({ partitionKey }) {
135
+ const now = Date.now();
136
+ const status = this.connectionStatus({ partitionKey });
137
+ const readyWorkers = this.readyWorkerIds({ partitionKey });
138
+ let soonestDueInMs;
139
+ for (const waiting of Object.values(this.calls)) {
140
+ if (waiting.partitionKey !== partitionKey)
141
+ continue;
142
+ const { takenBy } = waiting;
143
+ const takerIsGone = takenBy !== undefined && !readyWorkers.includes(takenBy);
144
+ const abandonedAt = status !== 'ready'
145
+ ? (this.partitionLostReadyAt[partitionKey] ?? this.startedAt)
146
+ : takerIsGone
147
+ ? (this.workerGoneAt[this.workerKey({ partitionKey, workerId: takenBy })] ?? now)
148
+ : undefined;
149
+ if (abandonedAt === undefined)
150
+ continue;
151
+ const dueInMs = abandonedAt + this.noWorkerLimitMs - now;
152
+ if (dueInMs > 0) {
153
+ soonestDueInMs = Math.min(soonestDueInMs ?? dueInMs, dueInMs);
154
+ continue;
155
+ }
156
+ if (status === 'ready') {
157
+ waiting.fail(new ProviderConnectionError('The worker that took this call stopped.'));
158
+ }
159
+ else if (status === 'needs-attention') {
160
+ waiting.fail(new ProviderAccessError(this.needsAttentionMessage));
161
+ }
162
+ else {
163
+ waiting.fail(new ProviderAccessError(this.disconnectedMessage));
164
+ }
165
+ }
166
+ if (soonestDueInMs !== undefined)
167
+ setTimeout(() => this.scheduleAbandonedCheck({ partitionKey }), soonestDueInMs).unref();
168
+ }
169
+ /** Enqueues one Dagma `InferenceCall` on `partitionKey` and resolves with its `InferenceReply`. */
170
+ infer({ partitionKey, call, callTool, signal, program, replyFormat, maxOutputBytes, maxOutputTokens, timeoutMs, metadata, onQueued, }) {
171
+ const status = this.connectionStatus({ partitionKey });
172
+ if (status === 'needs-attention')
173
+ return Promise.reject(new ProviderAccessError(this.needsAttentionMessage));
174
+ const queuedId = randomUUID();
175
+ const queued = {
176
+ id: queuedId,
177
+ ...(program ? { program } : {}),
178
+ ...(call.worker ? { worker: call.worker } : {}),
179
+ ...(call.workerLabel ? { workerLabel: call.workerLabel } : {}),
180
+ ...(call.model ? { model: call.model } : {}),
181
+ ...(call.models ? { models: call.models } : {}),
182
+ ...(call.effort ? { effort: call.effort } : {}),
183
+ ...(call.activityLabel ? { activityLabel: call.activityLabel } : {}),
184
+ ...(call.subjectLabel ? { subjectLabel: call.subjectLabel } : {}),
185
+ ...(call.role ? { role: call.role } : {}),
186
+ ...(replyFormat ? { replyFormat } : {}),
187
+ ...(maxOutputBytes ? { maxOutputBytes } : {}),
188
+ ...(maxOutputTokens ? { maxOutputTokens } : {}),
189
+ ...(timeoutMs ? { timeoutMs } : {}),
190
+ prompt: call.prompt,
191
+ images: call.images.map(({ mediaType, bytes }) => ({
192
+ mediaType,
193
+ dataBase64: Buffer.from(bytes).toString('base64'),
194
+ })),
195
+ tools: call.tools,
196
+ ...(metadata ? { metadata } : {}),
197
+ };
198
+ return new Promise((resolveReply, rejectReply) => {
199
+ const done = (settle) => {
200
+ if (!this.calls[queuedId])
201
+ return;
202
+ delete this.calls[queuedId];
203
+ signal.removeEventListener('abort', cancelled);
204
+ settle();
205
+ };
206
+ const cancelled = () => done(() => {
207
+ this.publish({ partitionKey, event: { type: 'cancelled', id: queuedId } });
208
+ rejectReply(signal.reason);
209
+ });
210
+ if (signal.aborted)
211
+ return rejectReply(signal.reason);
212
+ signal.addEventListener('abort', cancelled, { once: true });
213
+ this.calls[queuedId] = {
214
+ partitionKey,
215
+ call: queued,
216
+ callTool,
217
+ finish: (reply) => done(() => resolveReply(reply)),
218
+ fail: (error) => done(() => rejectReply(error)),
219
+ };
220
+ onQueued?.(queuedId);
221
+ this.publish({ partitionKey, event: { type: 'call', id: queuedId } });
222
+ if (status !== 'ready') {
223
+ this.partitionLostReadyAt[partitionKey] ??= Date.now();
224
+ this.scheduleAbandonedCheck({ partitionKey });
225
+ }
226
+ });
227
+ }
228
+ /** Claims a waiting call for `workerId` in `partitionKey`. Idempotent for the same worker. */
229
+ take({ partitionKey, workerId, callId, }) {
230
+ const waiting = this.calls[callId];
231
+ if (!waiting || waiting.partitionKey !== partitionKey)
232
+ throw new CallQueueError(404, 'The call is no longer waiting.');
233
+ if (waiting.takenBy && waiting.takenBy !== workerId)
234
+ throw new CallQueueError(409, 'Another worker already took this call.');
235
+ waiting.takenBy = workerId;
236
+ return waiting.call;
237
+ }
238
+ /** Forwards a tool call for an active queued call in `partitionKey`. */
239
+ async answerToolCall({ partitionKey, callId, toolCall, }) {
240
+ const waiting = this.calls[callId];
241
+ if (!waiting || waiting.partitionKey !== partitionKey)
242
+ throw new CallQueueError(404, 'The call is no longer waiting.');
243
+ return waiting.callTool(toolCall);
244
+ }
245
+ /** Completes a queued call with the worker's reply. */
246
+ finish({ partitionKey, callId, reply, }) {
247
+ const waiting = this.calls[callId];
248
+ if (!waiting || waiting.partitionKey !== partitionKey)
249
+ throw new CallQueueError(404, 'The call is no longer waiting.');
250
+ waiting.finish(reply);
251
+ }
252
+ /** Fails a queued call with a structured `WorkerFailure`. */
253
+ fail({ partitionKey, callId, failure, }) {
254
+ const waiting = this.calls[callId];
255
+ if (!waiting || waiting.partitionKey !== partitionKey)
256
+ throw new CallQueueError(404, 'The call is no longer waiting.');
257
+ if (failure.kind === 'connection') {
258
+ waiting.fail(new ProviderConnectionError(failure.message));
259
+ }
260
+ else if (failure.kind === 'access' || failure.kind === 'refusal') {
261
+ waiting.fail(new ProviderAccessError(failure.message));
262
+ }
263
+ else {
264
+ waiting.fail(new Error(failure.message));
265
+ }
266
+ }
267
+ /** Fails all pending calls across every partition (used on server shutdown). */
268
+ close() {
269
+ for (const waiting of Object.values(this.calls))
270
+ waiting.fail(new ProviderAccessError('The call queue closed.'));
271
+ }
272
+ }
273
+ /** Local `127.0.0.1` HTTP server mounting `CallQueue` on partition `'local'` for Dagma CLI runs. */
274
+ export async function openCallQueue({ program, noWorkerLimitMs = DEFAULT_NO_WORKER_LIMIT_MS, }) {
275
+ const partitionKey = 'local';
276
+ const queue = new CallQueue({ noWorkerLimitMs });
277
+ const secret = randomBytes(32).toString('hex');
278
+ const openResponses = [];
279
+ const readBody = async (request) => {
280
+ const chunks = [];
281
+ let size = 0;
282
+ for await (const chunk of request) {
283
+ size += chunk.length;
284
+ if (size > MAX_BODY_BYTES)
285
+ throw new Error('The request is too large.');
286
+ chunks.push(chunk);
287
+ }
288
+ return chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
289
+ };
290
+ const send = ({ response, status, body, }) => {
291
+ response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
292
+ response.end(JSON.stringify(body));
293
+ };
294
+ const server = createServer((request, response) => {
295
+ const { port } = server.address();
296
+ const given = Buffer.from(request.headers.authorization?.replace(/^Bearer /, '') ?? '');
297
+ const expected = Buffer.from(secret);
298
+ if (request.socket.remoteAddress !== '127.0.0.1' ||
299
+ request.headers.host !== `127.0.0.1:${port}` ||
300
+ request.headers.origin ||
301
+ given.length !== expected.length ||
302
+ !timingSafeEqual(given, expected)) {
303
+ response.writeHead(403).end();
304
+ return;
305
+ }
306
+ let url;
307
+ try {
308
+ url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);
309
+ }
310
+ catch {
311
+ response.writeHead(404).end();
312
+ return;
313
+ }
314
+ const workerId = url.searchParams.get('worker') ?? '';
315
+ const [, root, callId, action] = url.pathname.split('/');
316
+ if (root !== 'calls' || !workerId) {
317
+ response.writeHead(404).end();
318
+ return;
319
+ }
320
+ if (request.method === 'GET' && !callId) {
321
+ response.writeHead(200, {
322
+ 'content-type': 'text/event-stream',
323
+ 'cache-control': 'no-store',
324
+ connection: 'keep-alive',
325
+ });
326
+ openResponses.push(response);
327
+ const disconnect = queue.connectWorker({
328
+ partitionKey,
329
+ workerId,
330
+ ready: true,
331
+ send: (event) => {
332
+ if (!response.writableEnded)
333
+ response.write(`data: ${JSON.stringify(event)}\n\n`);
334
+ },
335
+ });
336
+ const keepAlive = setInterval(() => {
337
+ if (!response.writableEnded)
338
+ response.write(': keep-alive\n\n');
339
+ }, KEEP_ALIVE_MS);
340
+ request.on('close', () => {
341
+ clearInterval(keepAlive);
342
+ const index = openResponses.indexOf(response);
343
+ if (index >= 0)
344
+ openResponses.splice(index, 1);
345
+ disconnect();
346
+ });
347
+ return;
348
+ }
349
+ if (request.method !== 'POST' || !callId) {
350
+ response.writeHead(404).end();
351
+ return;
352
+ }
353
+ void (async () => {
354
+ try {
355
+ if (action === 'take') {
356
+ const taken = queue.take({ partitionKey, workerId, callId });
357
+ return send({ response, status: 200, body: taken });
358
+ }
359
+ const body = await readBody(request);
360
+ if (action === 'tool') {
361
+ const parsed = ForwardedToolCallSchema.parse(body);
362
+ const result = await queue.answerToolCall({
363
+ partitionKey,
364
+ callId,
365
+ toolCall: { name: parsed.name, args: parsed.args },
366
+ });
367
+ return send({ response, status: 200, body: { result } });
368
+ }
369
+ if (action === 'reply') {
370
+ queue.finish({ partitionKey, callId, reply: WorkerReplySchema.parse(body) });
371
+ return send({ response, status: 200, body: { received: true } });
372
+ }
373
+ if (action === 'failure') {
374
+ queue.fail({ partitionKey, callId, failure: WorkerFailureSchema.parse(body) });
375
+ return send({ response, status: 200, body: { received: true } });
376
+ }
377
+ send({ response, status: 404, body: { error: 'Unknown action.' } });
378
+ }
379
+ catch (error) {
380
+ const status = error instanceof CallQueueError ? error.status : 400;
381
+ send({
382
+ response,
383
+ status,
384
+ body: { error: error instanceof Error ? error.message : String(error) },
385
+ });
386
+ }
387
+ })();
388
+ });
389
+ await new Promise((resolveListening, reject) => {
390
+ server.once('error', reject);
391
+ server.listen(0, '127.0.0.1', resolveListening);
392
+ });
393
+ const { port } = server.address();
394
+ const infer = ({ call, callTool, signal }) => queue.infer({ partitionKey, call, callTool, signal, program });
395
+ return {
396
+ address: `http://127.0.0.1:${port}`,
397
+ secret,
398
+ queue,
399
+ infer,
400
+ async close() {
401
+ queue.close();
402
+ for (const response of openResponses)
403
+ response.end();
404
+ server.closeAllConnections();
405
+ await new Promise((resolveClosed) => server.close(() => resolveClosed()));
406
+ },
407
+ };
408
+ }
@@ -0,0 +1,44 @@
1
+ import { GoogleGenAI } from '@google/genai';
2
+ import type { Tokens } from '../run/record/events.js';
3
+ import { type GeminiResponseStatus, type GeminiStreamSender } from './gemini-request.js';
4
+ import type { Infer, InferenceCall } from './inference.js';
5
+ export type GeminiCacheTokens = {
6
+ uncachedInput: number;
7
+ cachedInput: number;
8
+ thoughtsOutput: number;
9
+ };
10
+ export type GeminiBeforeRequest = (input: {
11
+ call: InferenceCall;
12
+ requestIndex: number;
13
+ model: string;
14
+ }) => void | Promise<void>;
15
+ export type GeminiProviderResponse = (input: {
16
+ call: InferenceCall;
17
+ responseId: string;
18
+ model: string;
19
+ tokens: Tokens;
20
+ cacheTokens: GeminiCacheTokens;
21
+ costUsd?: number;
22
+ status: GeminiResponseStatus;
23
+ }) => void | Promise<void>;
24
+ /**
25
+ * Answers calls with Google's Gemini API or Vertex AI (`@google/genai`). Supports both Vertex AI
26
+ * via GCP ADC (`vertexai: true`, `project`, `location: 'global'`) and API-key auth (`apiKey`),
27
+ * implicit prefix caching, thinking-level effort mapping, thought-signature preservation across
28
+ * multi-turn tool loops, structured JSON Schema output, and per-response billing hooks.
29
+ */
30
+ export declare function geminiApiInference({ apiKey, vertexai, project, location, client, stream: customStream, defaultModel, outputSchema, maxOutputTokens, beforeRequest, onProviderResponse, }?: {
31
+ apiKey?: string;
32
+ vertexai?: boolean;
33
+ project?: string;
34
+ location?: string;
35
+ client?: GoogleGenAI;
36
+ /** Injectable `generateContentStream` function for tests. */
37
+ stream?: GeminiStreamSender;
38
+ defaultModel?: string;
39
+ /** Optional JSON Schema (object) constraining the final text output. */
40
+ outputSchema?: unknown;
41
+ maxOutputTokens?: number;
42
+ beforeRequest?: GeminiBeforeRequest;
43
+ onProviderResponse?: GeminiProviderResponse;
44
+ }): Infer;
@@ -0,0 +1,191 @@
1
+ import { GoogleGenAI, ThinkingLevel, } from '@google/genai';
2
+ import { geminiRequestCostUsd, hasGeminiPrice } from './gemini-prices.js';
3
+ import { completedGeminiGenerateContent, geminiClientSender, } from './gemini-request.js';
4
+ const DEFAULT_MAX_OUTPUT_TOKENS = 16_384;
5
+ function thinkingLevelFor(effort) {
6
+ if (effort === 'none')
7
+ return ThinkingLevel.MINIMAL;
8
+ if (effort === 'low')
9
+ return ThinkingLevel.LOW;
10
+ if (effort === 'medium')
11
+ return ThinkingLevel.MEDIUM;
12
+ if (effort === 'high')
13
+ return ThinkingLevel.HIGH;
14
+ return undefined;
15
+ }
16
+ function initialUserParts({ call }) {
17
+ const parts = [{ text: call.prompt }];
18
+ for (const { mediaType, bytes } of call.images)
19
+ parts.push({
20
+ inlineData: {
21
+ mimeType: mediaType,
22
+ data: Buffer.from(bytes).toString('base64'),
23
+ },
24
+ });
25
+ return parts;
26
+ }
27
+ function toolResponseObject(result) {
28
+ if (result && typeof result === 'object' && !Array.isArray(result))
29
+ return result;
30
+ return { result: result ?? null };
31
+ }
32
+ /**
33
+ * Answers calls with Google's Gemini API or Vertex AI (`@google/genai`). Supports both Vertex AI
34
+ * via GCP ADC (`vertexai: true`, `project`, `location: 'global'`) and API-key auth (`apiKey`),
35
+ * implicit prefix caching, thinking-level effort mapping, thought-signature preservation across
36
+ * multi-turn tool loops, structured JSON Schema output, and per-response billing hooks.
37
+ */
38
+ export function geminiApiInference({ apiKey, vertexai, project, location, client, stream: customStream, defaultModel, outputSchema, maxOutputTokens, beforeRequest, onProviderResponse, } = {}) {
39
+ const effectiveLocation = vertexai ? (location ?? 'global') : undefined;
40
+ const regional = Boolean(vertexai && effectiveLocation && effectiveLocation !== 'global');
41
+ let resolvedStream = customStream;
42
+ const getStream = () => {
43
+ if (!resolvedStream) {
44
+ const sdkClient = client ??
45
+ new GoogleGenAI(vertexai
46
+ ? { vertexai: true, ...(project ? { project } : {}), location: effectiveLocation }
47
+ : { ...(apiKey ? { apiKey } : {}) });
48
+ resolvedStream = geminiClientSender(sdkClient);
49
+ }
50
+ return resolvedStream;
51
+ };
52
+ return async ({ call, callTool, signal, onRequestCounted }) => {
53
+ const model = call.model ?? defaultModel;
54
+ if (!model || !hasGeminiPrice({ model }))
55
+ throw new Error(`${call.agent} names ${model ?? 'no model'}, which has no price on the Gemini API.`);
56
+ const contents = [{ role: 'user', parts: initialUserParts({ call }) }];
57
+ const tokens = {};
58
+ const reasoning = [];
59
+ let costUsd;
60
+ let toolCallsAnswered = 0;
61
+ const countRequest = async ({ response, status, }) => {
62
+ const usage = response.usage;
63
+ const promptTokens = (typeof usage?.promptTokenCount === 'number' ? usage.promptTokenCount : 0) +
64
+ (typeof usage?.toolUsePromptTokenCount === 'number' ? usage.toolUsePromptTokenCount : 0);
65
+ const cachedInput = typeof usage?.cachedContentTokenCount === 'number' ? usage.cachedContentTokenCount : 0;
66
+ const uncachedInput = Math.max(0, promptTokens - cachedInput);
67
+ const candidatesOutput = typeof usage?.candidatesTokenCount === 'number' ? usage.candidatesTokenCount : 0;
68
+ const thoughtsOutput = typeof usage?.thoughtsTokenCount === 'number' ? usage.thoughtsTokenCount : 0;
69
+ const totalOutput = candidatesOutput + thoughtsOutput;
70
+ const cacheTokens = {
71
+ uncachedInput,
72
+ cachedInput,
73
+ thoughtsOutput,
74
+ };
75
+ const reported = {};
76
+ if (typeof usage?.promptTokenCount === 'number' ||
77
+ typeof usage?.toolUsePromptTokenCount === 'number')
78
+ reported.input = promptTokens;
79
+ if (cachedInput > 0 || typeof usage?.cachedContentTokenCount === 'number')
80
+ reported.cached = cachedInput;
81
+ if (typeof usage?.candidatesTokenCount === 'number' ||
82
+ typeof usage?.thoughtsTokenCount === 'number')
83
+ reported.output = totalOutput;
84
+ for (const name of ['input', 'cached', 'output'])
85
+ if (typeof reported[name] === 'number')
86
+ tokens[name] = (tokens[name] ?? 0) + reported[name];
87
+ let responseCostUsd;
88
+ if (typeof reported.input === 'number' && typeof reported.output === 'number') {
89
+ responseCostUsd = geminiRequestCostUsd({
90
+ model,
91
+ uncachedInputTokens: uncachedInput,
92
+ cachedInputTokens: cachedInput,
93
+ outputTokens: totalOutput,
94
+ regional,
95
+ });
96
+ costUsd = (costUsd ?? 0) + responseCostUsd;
97
+ }
98
+ let toolCallsBefore = toolCallsAnswered;
99
+ for (const part of response.parts) {
100
+ if (part.functionCall)
101
+ toolCallsBefore += 1;
102
+ else if (part.thought && part.text)
103
+ reasoning.push({ text: part.text, afterToolCalls: toolCallsBefore });
104
+ }
105
+ onRequestCounted?.({
106
+ tokens: { ...tokens },
107
+ ...(costUsd !== undefined ? { costUsd } : {}),
108
+ reasoning: [...reasoning],
109
+ });
110
+ await onProviderResponse?.({
111
+ call,
112
+ responseId: response.responseId,
113
+ model,
114
+ tokens: reported,
115
+ cacheTokens,
116
+ ...(responseCostUsd !== undefined ? { costUsd: responseCostUsd } : {}),
117
+ status,
118
+ });
119
+ };
120
+ const thinkingLevel = thinkingLevelFor(call.effort);
121
+ const config = {
122
+ abortSignal: signal,
123
+ maxOutputTokens: maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
124
+ ...(call.tools.length
125
+ ? {
126
+ tools: [
127
+ {
128
+ functionDeclarations: call.tools.map((tool) => ({
129
+ name: tool.name,
130
+ description: tool.description,
131
+ parametersJsonSchema: tool.inputSchema,
132
+ })),
133
+ },
134
+ ],
135
+ }
136
+ : {}),
137
+ ...(thinkingLevel
138
+ ? {
139
+ thinkingConfig: {
140
+ thinkingLevel,
141
+ ...(thinkingLevel !== ThinkingLevel.MINIMAL ? { includeThoughts: true } : {}),
142
+ },
143
+ }
144
+ : {}),
145
+ ...(outputSchema
146
+ ? {
147
+ responseMimeType: 'application/json',
148
+ responseJsonSchema: outputSchema,
149
+ }
150
+ : {}),
151
+ };
152
+ const stream = getStream();
153
+ for (let requestIndex = 1;; requestIndex += 1) {
154
+ await beforeRequest?.({ call, requestIndex, model });
155
+ const response = await completedGeminiGenerateContent({
156
+ stream,
157
+ signal,
158
+ onResponse: countRequest,
159
+ params: {
160
+ model,
161
+ contents,
162
+ config,
163
+ },
164
+ });
165
+ const functionCalls = response.parts.flatMap((part) => part.functionCall ? [part.functionCall] : []);
166
+ if (!functionCalls.length) {
167
+ const replyText = response.parts
168
+ .filter((part) => !part.thought && typeof part.text === 'string')
169
+ .map((part) => part.text)
170
+ .join('');
171
+ return { replyText, tokens, ...(costUsd !== undefined ? { costUsd } : {}), reasoning };
172
+ }
173
+ // Preserve exact assistant parts (including thought + thoughtSignature) for multi-turn replay.
174
+ contents.push({ role: 'model', parts: response.parts });
175
+ const responseParts = [];
176
+ for (const fnCall of functionCalls) {
177
+ signal.throwIfAborted();
178
+ const result = await callTool({ name: fnCall.name ?? '', args: fnCall.args ?? {} });
179
+ toolCallsAnswered += 1;
180
+ responseParts.push({
181
+ functionResponse: {
182
+ ...(fnCall.id ? { id: fnCall.id } : {}),
183
+ name: fnCall.name ?? '',
184
+ response: toolResponseObject(result),
185
+ },
186
+ });
187
+ }
188
+ contents.push({ role: 'user', parts: responseParts });
189
+ }
190
+ };
191
+ }
@@ -0,0 +1,19 @@
1
+ /** Whether the Gemini / Vertex AI route can price a model. A run on the API is refused before any
2
+ * call when an agent names a model that has no price. */
3
+ export declare function hasGeminiPrice({ model }: {
4
+ model: string;
5
+ }): boolean;
6
+ /**
7
+ * The cost in dollars of one request to Gemini / Vertex AI, priced by its own token counts.
8
+ * Note: Gemini's `promptTokenCount` includes cached tokens; pass `uncachedInputTokens` as
9
+ * `Math.max(0, totalInput - cachedInputTokens)` and `outputTokens` as
10
+ * `candidatesTokenCount + thoughtsTokenCount`.
11
+ */
12
+ export declare function geminiRequestCostUsd({ model, uncachedInputTokens, cachedInputTokens, outputTokens, regional, }: {
13
+ model: string;
14
+ uncachedInputTokens: number;
15
+ cachedInputTokens?: number;
16
+ outputTokens: number;
17
+ /** True for non-`global` Vertex AI regional endpoints (+10% over global pricing). */
18
+ regional?: boolean;
19
+ }): number;