@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,193 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ConverseStreamCommand, } from '@aws-sdk/client-bedrock-runtime';
3
+ import { ProviderConnectionError } from './inference.js';
4
+ const RETRYABLE_ERROR_NAMES = new Set([
5
+ 'ThrottlingException',
6
+ 'ServiceUnavailableException',
7
+ 'ModelTimeoutException',
8
+ 'InternalServerException',
9
+ 'ModelNotReadyException',
10
+ 'TimeoutError',
11
+ ]);
12
+ function isRetryableBedrockError(error) {
13
+ if (!error || typeof error !== 'object')
14
+ return false;
15
+ const err = error;
16
+ if (err.name && RETRYABLE_ERROR_NAMES.has(err.name))
17
+ return true;
18
+ const status = err.$metadata?.httpStatusCode;
19
+ if (typeof status === 'number' && (status === 429 || status >= 500))
20
+ return true;
21
+ if (err.code === 'ECONNRESET' ||
22
+ err.code === 'ETIMEDOUT' ||
23
+ err.code === 'ENOTFOUND' ||
24
+ err.code === 'EAI_AGAIN')
25
+ return true;
26
+ return false;
27
+ }
28
+ function finalizeBlock(block) {
29
+ if (block.kind === 'text')
30
+ return { text: block.text };
31
+ if (block.kind === 'reasoning') {
32
+ if (block.redactedContent)
33
+ return { reasoningContent: { redactedContent: block.redactedContent } };
34
+ return {
35
+ reasoningContent: {
36
+ reasoningText: {
37
+ text: block.text,
38
+ ...(block.signature ? { signature: block.signature } : {}),
39
+ },
40
+ },
41
+ };
42
+ }
43
+ let input = {};
44
+ if (block.inputJson.trim()) {
45
+ try {
46
+ input = JSON.parse(block.inputJson);
47
+ }
48
+ catch {
49
+ input = { raw: block.inputJson };
50
+ }
51
+ }
52
+ return {
53
+ toolUse: {
54
+ toolUseId: block.toolUseId,
55
+ name: block.name,
56
+ input: input,
57
+ },
58
+ };
59
+ }
60
+ /** Creates a `BedrockStreamSender` backed by an AWS SDK `BedrockRuntimeClient`. */
61
+ export function bedrockClientSender(client) {
62
+ return (input, { abortSignal }) => client.send(new ConverseStreamCommand(input), { abortSignal });
63
+ }
64
+ /**
65
+ * Sends one streaming ConverseStream request to AWS Bedrock and returns the assembled assistant
66
+ * content blocks. `onResponse` is called for every response that returned metadata/usage before
67
+ * any error is thrown, so every billable response is accounted for.
68
+ */
69
+ export async function completedBedrockConverse({ send, input, signal, onResponse, }) {
70
+ let output;
71
+ try {
72
+ output = await send(input, { abortSignal: signal });
73
+ }
74
+ catch (error) {
75
+ signal.throwIfAborted();
76
+ const detail = error instanceof Error ? error.message : String(error);
77
+ if (isRetryableBedrockError(error))
78
+ throw new ProviderConnectionError(`The AWS Bedrock API could not complete the request: ${detail}`);
79
+ throw new Error(`The AWS Bedrock API failed: ${detail}`);
80
+ }
81
+ const responseId = output.$metadata?.requestId ?? `bedrock-${randomUUID()}`;
82
+ const blocks = new Map();
83
+ let stopReason;
84
+ let usage;
85
+ let messageStopped = false;
86
+ let failure;
87
+ try {
88
+ if (!output.stream)
89
+ throw new ProviderConnectionError('The AWS Bedrock API returned an empty stream.');
90
+ for await (const event of output.stream) {
91
+ if (event.contentBlockStart && typeof event.contentBlockStart.contentBlockIndex === 'number') {
92
+ const index = event.contentBlockStart.contentBlockIndex;
93
+ const start = event.contentBlockStart.start;
94
+ if (start?.toolUse) {
95
+ blocks.set(index, {
96
+ kind: 'toolUse',
97
+ toolUseId: start.toolUse.toolUseId ?? '',
98
+ name: start.toolUse.name ?? '',
99
+ inputJson: '',
100
+ });
101
+ }
102
+ continue;
103
+ }
104
+ if (event.contentBlockDelta && typeof event.contentBlockDelta.contentBlockIndex === 'number') {
105
+ const index = event.contentBlockDelta.contentBlockIndex;
106
+ const delta = event.contentBlockDelta.delta;
107
+ if (delta?.text !== undefined) {
108
+ const existing = blocks.get(index);
109
+ if (existing?.kind === 'text')
110
+ existing.text += delta.text;
111
+ else
112
+ blocks.set(index, { kind: 'text', text: delta.text });
113
+ }
114
+ else if (delta?.toolUse?.input !== undefined) {
115
+ const existing = blocks.get(index);
116
+ if (existing?.kind === 'toolUse')
117
+ existing.inputJson += delta.toolUse.input;
118
+ }
119
+ else if (delta?.reasoningContent) {
120
+ const rc = delta.reasoningContent;
121
+ const existing = blocks.get(index);
122
+ const state = existing?.kind === 'reasoning'
123
+ ? existing
124
+ : { kind: 'reasoning', text: '', signature: '' };
125
+ if (rc.text)
126
+ state.text += rc.text;
127
+ if (rc.signature)
128
+ state.signature += rc.signature;
129
+ if (rc.redactedContent)
130
+ state.redactedContent = rc.redactedContent;
131
+ blocks.set(index, state);
132
+ }
133
+ continue;
134
+ }
135
+ if (event.messageStop) {
136
+ stopReason = event.messageStop.stopReason;
137
+ messageStopped = true;
138
+ continue;
139
+ }
140
+ if (event.metadata?.usage) {
141
+ usage = event.metadata.usage;
142
+ continue;
143
+ }
144
+ const streamError = event.internalServerException ??
145
+ event.modelStreamErrorException ??
146
+ event.throttlingException ??
147
+ event.serviceUnavailableException ??
148
+ event.validationException;
149
+ if (streamError) {
150
+ const detail = streamError.message ?? 'no reason given';
151
+ failure = event.validationException
152
+ ? new Error(`The AWS Bedrock API rejected the request: ${detail}`)
153
+ : new ProviderConnectionError(`The AWS Bedrock API failed mid-stream: ${detail}`);
154
+ }
155
+ }
156
+ }
157
+ catch (error) {
158
+ signal.throwIfAborted();
159
+ if (!failure && !messageStopped) {
160
+ const detail = error instanceof Error ? error.message : String(error);
161
+ throw new ProviderConnectionError(`The AWS Bedrock API's reply was cut off: ${detail}`);
162
+ }
163
+ }
164
+ const content = [...blocks.entries()]
165
+ .sort(([a], [b]) => a - b)
166
+ .map(([, block]) => finalizeBlock(block));
167
+ const assembled = {
168
+ responseId,
169
+ content,
170
+ ...(stopReason ? { stopReason } : {}),
171
+ ...(usage ? { usage } : {}),
172
+ };
173
+ if (failure) {
174
+ if (usage)
175
+ await onResponse({ response: assembled, status: 'failed' });
176
+ throw failure;
177
+ }
178
+ if (!messageStopped) {
179
+ if (usage)
180
+ await onResponse({ response: assembled, status: 'incomplete' });
181
+ throw new ProviderConnectionError('The AWS Bedrock API closed the reply before its end.');
182
+ }
183
+ if (stopReason === 'max_tokens') {
184
+ await onResponse({ response: assembled, status: 'incomplete' });
185
+ throw new Error('The AWS Bedrock API ended the reply early: max_tokens');
186
+ }
187
+ if (stopReason === 'content_filtered' || stopReason === 'guardrail_intervened') {
188
+ await onResponse({ response: assembled, status: 'failed' });
189
+ throw new Error(`The AWS Bedrock API refused the request: ${stopReason}`);
190
+ }
191
+ await onResponse({ response: assembled, status: 'completed' });
192
+ return assembled;
193
+ }
@@ -0,0 +1,273 @@
1
+ import { z } from 'zod';
2
+ export declare const TokensSchema: z.ZodObject<{
3
+ input: z.ZodOptional<z.ZodNumber>;
4
+ cached: z.ZodOptional<z.ZodNumber>;
5
+ output: z.ZodOptional<z.ZodNumber>;
6
+ reasoning: z.ZodOptional<z.ZodNumber>;
7
+ }, "strict", z.ZodTypeAny, {
8
+ input?: number | undefined;
9
+ cached?: number | undefined;
10
+ output?: number | undefined;
11
+ reasoning?: number | undefined;
12
+ }, {
13
+ input?: number | undefined;
14
+ cached?: number | undefined;
15
+ output?: number | undefined;
16
+ reasoning?: number | undefined;
17
+ }>;
18
+ /** The model program a worker answers a call with. */
19
+ export declare const WorkerProgramSchema: z.ZodEnum<["codex", "claude-code", "claude", "agy"]>;
20
+ export type WorkerProgram = z.infer<typeof WorkerProgramSchema>;
21
+ export declare const QueueConnectionStatusSchema: z.ZodEnum<["ready", "needs-attention", "disconnected"]>;
22
+ export type QueueConnectionStatus = z.infer<typeof QueueConnectionStatusSchema>;
23
+ export declare const WorkerStatusSchema: z.ZodObject<{
24
+ ready: z.ZodBoolean;
25
+ }, "strict", z.ZodTypeAny, {
26
+ ready: boolean;
27
+ }, {
28
+ ready: boolean;
29
+ }>;
30
+ export type WorkerStatus = z.infer<typeof WorkerStatusSchema>;
31
+ /** What the queue tells a worker: the calls waiting when it connects, then each new call and
32
+ * each call it must stop working on. */
33
+ export declare const QueueEventSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
34
+ type: z.ZodLiteral<"waiting">;
35
+ calls: z.ZodArray<z.ZodObject<{
36
+ id: z.ZodString;
37
+ taken: z.ZodBoolean;
38
+ }, "strict", z.ZodTypeAny, {
39
+ id: string;
40
+ taken: boolean;
41
+ }, {
42
+ id: string;
43
+ taken: boolean;
44
+ }>, "many">;
45
+ }, "strict", z.ZodTypeAny, {
46
+ type: "waiting";
47
+ calls: {
48
+ id: string;
49
+ taken: boolean;
50
+ }[];
51
+ }, {
52
+ type: "waiting";
53
+ calls: {
54
+ id: string;
55
+ taken: boolean;
56
+ }[];
57
+ }>, z.ZodObject<{
58
+ type: z.ZodLiteral<"call">;
59
+ id: z.ZodString;
60
+ }, "strict", z.ZodTypeAny, {
61
+ type: "call";
62
+ id: string;
63
+ }, {
64
+ type: "call";
65
+ id: string;
66
+ }>, z.ZodObject<{
67
+ type: z.ZodLiteral<"cancelled">;
68
+ id: z.ZodString;
69
+ }, "strict", z.ZodTypeAny, {
70
+ type: "cancelled";
71
+ id: string;
72
+ }, {
73
+ type: "cancelled";
74
+ id: string;
75
+ }>]>;
76
+ export type QueueEvent = z.infer<typeof QueueEventSchema>;
77
+ /** One call as a worker receives it when it takes the call. */
78
+ export declare const QueuedCallSchema: z.ZodObject<{
79
+ id: z.ZodString;
80
+ program: z.ZodOptional<z.ZodEnum<["codex", "claude-code", "claude", "agy"]>>;
81
+ worker: z.ZodOptional<z.ZodString>;
82
+ workerLabel: z.ZodOptional<z.ZodString>;
83
+ model: z.ZodOptional<z.ZodString>;
84
+ models: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
85
+ effort: z.ZodOptional<z.ZodEnum<["none", "low", "medium", "high"]>>;
86
+ activityLabel: z.ZodOptional<z.ZodString>;
87
+ subjectLabel: z.ZodOptional<z.ZodString>;
88
+ role: z.ZodOptional<z.ZodString>;
89
+ replyFormat: z.ZodOptional<z.ZodEnum<["text", "json"]>>;
90
+ maxOutputBytes: z.ZodOptional<z.ZodNumber>;
91
+ maxOutputTokens: z.ZodOptional<z.ZodNumber>;
92
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
93
+ prompt: z.ZodString;
94
+ images: z.ZodArray<z.ZodObject<{
95
+ mediaType: z.ZodString;
96
+ dataBase64: z.ZodString;
97
+ }, "strict", z.ZodTypeAny, {
98
+ mediaType: string;
99
+ dataBase64: string;
100
+ }, {
101
+ mediaType: string;
102
+ dataBase64: string;
103
+ }>, "many">;
104
+ tools: z.ZodArray<z.ZodObject<{
105
+ name: z.ZodString;
106
+ description: z.ZodString;
107
+ inputSchema: z.ZodUnknown;
108
+ annotations: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
109
+ }, "strict", z.ZodTypeAny, {
110
+ name: string;
111
+ description: string;
112
+ annotations?: Record<string, unknown> | undefined;
113
+ inputSchema?: unknown;
114
+ }, {
115
+ name: string;
116
+ description: string;
117
+ annotations?: Record<string, unknown> | undefined;
118
+ inputSchema?: unknown;
119
+ }>, "many">;
120
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
121
+ }, "strict", z.ZodTypeAny, {
122
+ id: string;
123
+ prompt: string;
124
+ tools: {
125
+ name: string;
126
+ description: string;
127
+ annotations?: Record<string, unknown> | undefined;
128
+ inputSchema?: unknown;
129
+ }[];
130
+ images: {
131
+ mediaType: string;
132
+ dataBase64: string;
133
+ }[];
134
+ worker?: string | undefined;
135
+ model?: string | undefined;
136
+ role?: string | undefined;
137
+ workerLabel?: string | undefined;
138
+ effort?: "none" | "low" | "medium" | "high" | undefined;
139
+ subjectLabel?: string | undefined;
140
+ models?: Record<string, string> | undefined;
141
+ program?: "codex" | "claude-code" | "claude" | "agy" | undefined;
142
+ activityLabel?: string | undefined;
143
+ replyFormat?: "text" | "json" | undefined;
144
+ maxOutputBytes?: number | undefined;
145
+ maxOutputTokens?: number | undefined;
146
+ timeoutMs?: number | undefined;
147
+ metadata?: Record<string, unknown> | undefined;
148
+ }, {
149
+ id: string;
150
+ prompt: string;
151
+ tools: {
152
+ name: string;
153
+ description: string;
154
+ annotations?: Record<string, unknown> | undefined;
155
+ inputSchema?: unknown;
156
+ }[];
157
+ images: {
158
+ mediaType: string;
159
+ dataBase64: string;
160
+ }[];
161
+ worker?: string | undefined;
162
+ model?: string | undefined;
163
+ role?: string | undefined;
164
+ workerLabel?: string | undefined;
165
+ effort?: "none" | "low" | "medium" | "high" | undefined;
166
+ subjectLabel?: string | undefined;
167
+ models?: Record<string, string> | undefined;
168
+ program?: "codex" | "claude-code" | "claude" | "agy" | undefined;
169
+ activityLabel?: string | undefined;
170
+ replyFormat?: "text" | "json" | undefined;
171
+ maxOutputBytes?: number | undefined;
172
+ maxOutputTokens?: number | undefined;
173
+ timeoutMs?: number | undefined;
174
+ metadata?: Record<string, unknown> | undefined;
175
+ }>;
176
+ export type QueuedCall = z.infer<typeof QueuedCallSchema>;
177
+ /** One tool call a worker forwards for the model, unchanged. */
178
+ export declare const ForwardedToolCallSchema: z.ZodObject<{
179
+ name: z.ZodString;
180
+ args: z.ZodUnknown;
181
+ }, "strict", z.ZodTypeAny, {
182
+ name: string;
183
+ args?: unknown;
184
+ }, {
185
+ name: string;
186
+ args?: unknown;
187
+ }>;
188
+ /** What the queue answers a forwarded tool call with: what goes back to the model. */
189
+ export declare const ToolCallAnswerSchema: z.ZodObject<{
190
+ result: z.ZodUnknown;
191
+ }, "strict", z.ZodTypeAny, {
192
+ result?: unknown;
193
+ }, {
194
+ result?: unknown;
195
+ }>;
196
+ /** What a worker returns for an answered call. */
197
+ export declare const WorkerReplySchema: z.ZodObject<{
198
+ replyText: z.ZodString;
199
+ tokens: z.ZodObject<{
200
+ input: z.ZodOptional<z.ZodNumber>;
201
+ cached: z.ZodOptional<z.ZodNumber>;
202
+ output: z.ZodOptional<z.ZodNumber>;
203
+ reasoning: z.ZodOptional<z.ZodNumber>;
204
+ }, "strict", z.ZodTypeAny, {
205
+ input?: number | undefined;
206
+ cached?: number | undefined;
207
+ output?: number | undefined;
208
+ reasoning?: number | undefined;
209
+ }, {
210
+ input?: number | undefined;
211
+ cached?: number | undefined;
212
+ output?: number | undefined;
213
+ reasoning?: number | undefined;
214
+ }>;
215
+ /** The cost the model program itself reported, as Claude Code does. */
216
+ programCostUsd: z.ZodOptional<z.ZodNumber>;
217
+ reasoning: z.ZodArray<z.ZodObject<{
218
+ text: z.ZodString;
219
+ afterToolCalls: z.ZodNumber;
220
+ }, "strict", z.ZodTypeAny, {
221
+ text: string;
222
+ afterToolCalls: number;
223
+ }, {
224
+ text: string;
225
+ afterToolCalls: number;
226
+ }>, "many">;
227
+ /** The instruction text the launcher sent beside the prompt. */
228
+ launcherInstruction: z.ZodOptional<z.ZodString>;
229
+ }, "strict", z.ZodTypeAny, {
230
+ replyText: string;
231
+ reasoning: {
232
+ text: string;
233
+ afterToolCalls: number;
234
+ }[];
235
+ tokens: {
236
+ input?: number | undefined;
237
+ cached?: number | undefined;
238
+ output?: number | undefined;
239
+ reasoning?: number | undefined;
240
+ };
241
+ programCostUsd?: number | undefined;
242
+ launcherInstruction?: string | undefined;
243
+ }, {
244
+ replyText: string;
245
+ reasoning: {
246
+ text: string;
247
+ afterToolCalls: number;
248
+ }[];
249
+ tokens: {
250
+ input?: number | undefined;
251
+ cached?: number | undefined;
252
+ output?: number | undefined;
253
+ reasoning?: number | undefined;
254
+ };
255
+ programCostUsd?: number | undefined;
256
+ launcherInstruction?: string | undefined;
257
+ }>;
258
+ export type WorkerReply = z.infer<typeof WorkerReplySchema>;
259
+ /** Why a worker could not answer a call.
260
+ * - `connection`: transient failure, retried up to 3 times.
261
+ * - `access` / `refusal`: resumable stop (`ProviderAccessError`) with zero retries.
262
+ * - `other`: unrecoverable call failure. */
263
+ export declare const WorkerFailureSchema: z.ZodObject<{
264
+ kind: z.ZodEnum<["connection", "access", "refusal", "other"]>;
265
+ message: z.ZodString;
266
+ }, "strict", z.ZodTypeAny, {
267
+ message: string;
268
+ kind: "connection" | "access" | "refusal" | "other";
269
+ }, {
270
+ message: string;
271
+ kind: "connection" | "access" | "refusal" | "other";
272
+ }>;
273
+ export type WorkerFailure = z.infer<typeof WorkerFailureSchema>;
@@ -0,0 +1,82 @@
1
+ import { z } from 'zod';
2
+ export const TokensSchema = z
3
+ .object({
4
+ input: z.number().optional(),
5
+ cached: z.number().optional(),
6
+ output: z.number().optional(),
7
+ reasoning: z.number().optional(),
8
+ })
9
+ .strict();
10
+ /** The model program a worker answers a call with. */
11
+ export const WorkerProgramSchema = z.enum(['codex', 'claude-code', 'claude', 'agy']);
12
+ export const QueueConnectionStatusSchema = z.enum(['ready', 'needs-attention', 'disconnected']);
13
+ export const WorkerStatusSchema = z.object({ ready: z.boolean() }).strict();
14
+ /** What the queue tells a worker: the calls waiting when it connects, then each new call and
15
+ * each call it must stop working on. */
16
+ export const QueueEventSchema = z.discriminatedUnion('type', [
17
+ z
18
+ .object({
19
+ type: z.literal('waiting'),
20
+ calls: z.object({ id: z.string(), taken: z.boolean() }).strict().array(),
21
+ })
22
+ .strict(),
23
+ z.object({ type: z.literal('call'), id: z.string() }).strict(),
24
+ z.object({ type: z.literal('cancelled'), id: z.string() }).strict(),
25
+ ]);
26
+ /** One call as a worker receives it when it takes the call. */
27
+ export const QueuedCallSchema = z
28
+ .object({
29
+ id: z.string(),
30
+ program: WorkerProgramSchema.optional(),
31
+ worker: z.string().optional(),
32
+ workerLabel: z.string().optional(),
33
+ model: z.string().optional(),
34
+ models: z.record(z.string()).optional(),
35
+ effort: z.enum(['none', 'low', 'medium', 'high']).optional(),
36
+ activityLabel: z.string().optional(),
37
+ subjectLabel: z.string().optional(),
38
+ role: z.string().optional(),
39
+ replyFormat: z.enum(['text', 'json']).optional(),
40
+ maxOutputBytes: z.number().int().positive().optional(),
41
+ maxOutputTokens: z.number().int().positive().optional(),
42
+ timeoutMs: z.number().int().positive().optional(),
43
+ prompt: z.string(),
44
+ images: z.object({ mediaType: z.string(), dataBase64: z.string() }).strict().array(),
45
+ tools: z
46
+ .object({
47
+ name: z.string(),
48
+ description: z.string(),
49
+ inputSchema: z.unknown(),
50
+ annotations: z.record(z.unknown()).optional(),
51
+ })
52
+ .strict()
53
+ .array(),
54
+ metadata: z.record(z.unknown()).optional(),
55
+ })
56
+ .strict();
57
+ /** One tool call a worker forwards for the model, unchanged. */
58
+ export const ForwardedToolCallSchema = z.object({ name: z.string(), args: z.unknown() }).strict();
59
+ /** What the queue answers a forwarded tool call with: what goes back to the model. */
60
+ export const ToolCallAnswerSchema = z.object({ result: z.unknown() }).strict();
61
+ /** What a worker returns for an answered call. */
62
+ export const WorkerReplySchema = z
63
+ .object({
64
+ replyText: z.string(),
65
+ tokens: TokensSchema,
66
+ /** The cost the model program itself reported, as Claude Code does. */
67
+ programCostUsd: z.number().optional(),
68
+ reasoning: z.object({ text: z.string(), afterToolCalls: z.number() }).strict().array(),
69
+ /** The instruction text the launcher sent beside the prompt. */
70
+ launcherInstruction: z.string().optional(),
71
+ })
72
+ .strict();
73
+ /** Why a worker could not answer a call.
74
+ * - `connection`: transient failure, retried up to 3 times.
75
+ * - `access` / `refusal`: resumable stop (`ProviderAccessError`) with zero retries.
76
+ * - `other`: unrecoverable call failure. */
77
+ export const WorkerFailureSchema = z
78
+ .object({
79
+ kind: z.enum(['connection', 'access', 'refusal', 'other']),
80
+ message: z.string().max(4000),
81
+ })
82
+ .strict();
@@ -0,0 +1,109 @@
1
+ import { type QueueConnectionStatus, type QueuedCall, type QueueEvent, type WorkerFailure, type WorkerProgram, type WorkerReply } from './call-queue-shapes.js';
2
+ import { type Infer, type InferenceCall, type InferenceReply } from './inference.js';
3
+ export declare class CallQueueError extends Error {
4
+ readonly status: 404 | 409;
5
+ constructor(status: 404 | 409, message: string);
6
+ }
7
+ /**
8
+ * Transport-agnostic, multi-tenant call queue coordinator.
9
+ * Partitions calls and workers by `partitionKey` (for example `accountId` in a server app, or
10
+ * `'local'` in Dagma CLI), tracks worker readiness (`ready` / `needs-attention` / `disconnected`),
11
+ * forwards tool calls, and enforces disconnect grace periods.
12
+ */
13
+ export declare class CallQueue {
14
+ private readonly calls;
15
+ private streams;
16
+ private readonly partitionLostReadyAt;
17
+ private readonly workerGoneAt;
18
+ private readonly startedAt;
19
+ private readonly noWorkerLimitMs;
20
+ private readonly disconnectedMessage;
21
+ private readonly needsAttentionMessage;
22
+ constructor({ noWorkerLimitMs, disconnectedMessage, needsAttentionMessage, }?: {
23
+ noWorkerLimitMs?: number;
24
+ disconnectedMessage?: string;
25
+ needsAttentionMessage?: string;
26
+ });
27
+ private workerKey;
28
+ private readyWorkerIds;
29
+ private publish;
30
+ private sendWaitingSnapshot;
31
+ /** Whether a partition has a ready worker, only non-ready workers, or none connected. */
32
+ connectionStatus({ partitionKey }: {
33
+ partitionKey: string;
34
+ }): QueueConnectionStatus;
35
+ /** Registers one worker SSE/push stream for `partitionKey`. Returns its disconnect cleanup. */
36
+ connectWorker({ partitionKey, workerId, ready, send, }: {
37
+ partitionKey: string;
38
+ workerId: string;
39
+ ready?: boolean;
40
+ send: (event: QueueEvent) => void;
41
+ }): () => void;
42
+ /** Updates readiness for a connected worker without dropping its stream. */
43
+ setWorkerReady({ partitionKey, workerId, ready, }: {
44
+ partitionKey: string;
45
+ workerId: string;
46
+ ready: boolean;
47
+ }): void;
48
+ private failUntakenCallsNeedingAttention;
49
+ private scheduleAbandonedCheck;
50
+ /** Enqueues one Dagma `InferenceCall` on `partitionKey` and resolves with its `InferenceReply`. */
51
+ infer({ partitionKey, call, callTool, signal, program, replyFormat, maxOutputBytes, maxOutputTokens, timeoutMs, metadata, onQueued, }: {
52
+ partitionKey: string;
53
+ call: InferenceCall;
54
+ callTool: (toolCall: {
55
+ name: string;
56
+ args: unknown;
57
+ }) => Promise<unknown>;
58
+ signal: AbortSignal;
59
+ program?: WorkerProgram;
60
+ replyFormat?: 'text' | 'json';
61
+ maxOutputBytes?: number;
62
+ maxOutputTokens?: number;
63
+ timeoutMs?: number;
64
+ metadata?: {
65
+ [key: string]: unknown;
66
+ };
67
+ onQueued?: (queuedCallId: string) => void;
68
+ }): Promise<InferenceReply>;
69
+ /** Claims a waiting call for `workerId` in `partitionKey`. Idempotent for the same worker. */
70
+ take({ partitionKey, workerId, callId, }: {
71
+ partitionKey: string;
72
+ workerId: string;
73
+ callId: string;
74
+ }): QueuedCall;
75
+ /** Forwards a tool call for an active queued call in `partitionKey`. */
76
+ answerToolCall({ partitionKey, callId, toolCall, }: {
77
+ partitionKey: string;
78
+ callId: string;
79
+ toolCall: {
80
+ name: string;
81
+ args: unknown;
82
+ };
83
+ }): Promise<unknown>;
84
+ /** Completes a queued call with the worker's reply. */
85
+ finish({ partitionKey, callId, reply, }: {
86
+ partitionKey: string;
87
+ callId: string;
88
+ reply: WorkerReply;
89
+ }): void;
90
+ /** Fails a queued call with a structured `WorkerFailure`. */
91
+ fail({ partitionKey, callId, failure, }: {
92
+ partitionKey: string;
93
+ callId: string;
94
+ failure: WorkerFailure;
95
+ }): void;
96
+ /** Fails all pending calls across every partition (used on server shutdown). */
97
+ close(): void;
98
+ }
99
+ /** Local `127.0.0.1` HTTP server mounting `CallQueue` on partition `'local'` for Dagma CLI runs. */
100
+ export declare function openCallQueue({ program, noWorkerLimitMs, }: {
101
+ program: WorkerProgram;
102
+ noWorkerLimitMs?: number;
103
+ }): Promise<{
104
+ address: string;
105
+ secret: string;
106
+ queue: CallQueue;
107
+ infer: Infer;
108
+ close(): Promise<void>;
109
+ }>;