@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,100 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { launchClaudeCode } from './launchers/claude-code.js';
5
+ import { launchCodex } from './launchers/codex.js';
6
+ import { ProgramConnectionError } from './launchers/program-run.js';
7
+ import { startToolServer } from './launchers/tool-server.js';
8
+ /** What a model program's own output says about a call beyond its reply: reasoning summaries in
9
+ * their order among the tool calls, token counts, and the program's own cost figure. */
10
+ function providerFacts({ program }) {
11
+ const reasoning = [];
12
+ const tokens = {};
13
+ let toolCalls = 0;
14
+ let programCostUsd;
15
+ /** Each parsed line of the program's output. The shapes are the programs' own. */
16
+ const read = (event) => {
17
+ if (program === 'codex') {
18
+ if (event?.type === 'item.completed' && event.item?.type === 'mcp_tool_call')
19
+ toolCalls += 1;
20
+ if (event?.type === 'item.completed' && event.item?.type === 'reasoning' && event.item.text)
21
+ reasoning.push({ text: String(event.item.text), afterToolCalls: toolCalls });
22
+ if (event?.type === 'turn.completed' && event.usage) {
23
+ tokens.input = event.usage.input_tokens;
24
+ tokens.cached = event.usage.cached_input_tokens;
25
+ tokens.output = event.usage.output_tokens;
26
+ tokens.reasoning = event.usage.reasoning_output_tokens;
27
+ }
28
+ return;
29
+ }
30
+ if (event?.type === 'assistant' && !event.parent_tool_use_id)
31
+ for (const block of event.message?.content ?? []) {
32
+ if (block?.type === 'tool_use')
33
+ toolCalls += 1;
34
+ if (block?.type === 'thinking' && block.thinking)
35
+ reasoning.push({ text: String(block.thinking), afterToolCalls: toolCalls });
36
+ }
37
+ if (event?.type === 'result' && !event.parent_tool_use_id) {
38
+ const usage = event.usage ?? {};
39
+ const cached = usage.cache_read_input_tokens;
40
+ // Claude Code reports uncached, cache-written and cache-read input apart.
41
+ if (typeof usage.input_tokens === 'number')
42
+ tokens.input = usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (cached ?? 0);
43
+ tokens.cached = cached;
44
+ tokens.output = usage.output_tokens;
45
+ tokens.reasoning = usage.output_tokens_details?.thinking_tokens;
46
+ if (typeof event.total_cost_usd === 'number')
47
+ programCostUsd = event.total_cost_usd;
48
+ }
49
+ };
50
+ return { read, reasoning, tokens, programCost: () => programCostUsd };
51
+ }
52
+ /**
53
+ * Answers one queued call with Codex or Claude Code on this computer, in a temporary folder that is deleted
54
+ * afterwards. The call's pictures go to the program with the prompt, and the model's tool calls are forwarded
55
+ * through `callTool`.
56
+ */
57
+ export async function answerQueuedCall({ call, callTool, signal, }) {
58
+ const folder = await mkdtemp(join(tmpdir(), 'dagma-'));
59
+ const program = call.program ?? 'codex';
60
+ const model = call.model ?? '';
61
+ const facts = providerFacts({ program });
62
+ const tools = call.tools;
63
+ const toolServer = tools.length ? await startToolServer({ tools, callTool }) : undefined;
64
+ try {
65
+ const launch = program === 'codex' ? launchCodex : launchClaudeCode;
66
+ const launched = await launch({
67
+ folder,
68
+ model,
69
+ effort: call.effort,
70
+ prompt: call.prompt,
71
+ images: call.images,
72
+ tools,
73
+ toolServer,
74
+ onProviderEvent: facts.read,
75
+ signal,
76
+ });
77
+ const programCostUsd = facts.programCost();
78
+ return {
79
+ reply: {
80
+ replyText: launched.replyText,
81
+ tokens: facts.tokens,
82
+ ...(programCostUsd !== undefined ? { programCostUsd } : {}),
83
+ reasoning: facts.reasoning,
84
+ launcherInstruction: launched.instruction,
85
+ },
86
+ };
87
+ }
88
+ catch (error) {
89
+ return {
90
+ failure: {
91
+ kind: error instanceof ProgramConnectionError ? 'connection' : 'other',
92
+ message: (error instanceof Error ? error.message : String(error)).slice(0, 4000),
93
+ },
94
+ };
95
+ }
96
+ finally {
97
+ await toolServer?.close();
98
+ await rm(folder, { recursive: true, force: true });
99
+ }
100
+ }
@@ -0,0 +1,7 @@
1
+ import { type Launch, type Launched } from './launch.js';
2
+ /**
3
+ * Answers one call with `claude --print`: a new conversation with the person's settings, hooks, memory and
4
+ * Claude Code's own tools all off, the call's pictures sent in the message and its tools reached through the local
5
+ * tool server.
6
+ */
7
+ export declare function launchClaudeCode(launch: Launch): Promise<Launched>;
@@ -0,0 +1,156 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { launcherInstructionOf } from './launch.js';
4
+ import { MAX_REPLY_BYTES, ProgramConnectionError, isConnectionFailure, programEnvironment, runProgram } from './program-run.js';
5
+ import { TOOL_SERVER_NAME, TOOL_SERVER_TOKEN_VARIABLE } from './tool-server.js';
6
+ const AGENT_NAME = 'dagma';
7
+ /** The name Claude Code gives a tool of the call's tool server. */
8
+ function toolNameOf(name) {
9
+ return `mcp__${TOOL_SERVER_NAME}__${name}`;
10
+ }
11
+ /**
12
+ * Answers one call with `claude --print`: a new conversation with the person's settings, hooks, memory and
13
+ * Claude Code's own tools all off, the call's pictures sent in the message and its tools reached through the local
14
+ * tool server.
15
+ */
16
+ export async function launchClaudeCode(launch) {
17
+ const instruction = launcherInstructionOf({ hasTools: launch.tools.length > 0 });
18
+ const allowedTools = launch.tools.map((tool) => toolNameOf(tool.name));
19
+ const settingsFiles = await writeSettingsFiles({ launch, instruction, allowedTools });
20
+ let replyText;
21
+ let refusal = '';
22
+ let failure;
23
+ const ended = await runProgram({
24
+ program: 'claude',
25
+ args: claudeArguments({ launch, allowedTools, ...settingsFiles }),
26
+ folder: launch.folder,
27
+ env: {
28
+ ...programEnvironment(),
29
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
30
+ ENABLE_TOOL_SEARCH: 'false',
31
+ ...(launch.toolServer ? { [TOOL_SERVER_TOKEN_VARIABLE]: launch.toolServer.token } : {}),
32
+ },
33
+ input: `${JSON.stringify(userMessageOf(launch))}\n`,
34
+ signal: launch.signal,
35
+ onEvent: (line) => {
36
+ const event = line;
37
+ launch.onProviderEvent(event);
38
+ // Claude Code answers a refusal (a usage limit, an overload) with a message of its own, not the model's.
39
+ if (event.type === 'assistant' && event.message?.model === '<synthetic>')
40
+ refusal = textOf(event);
41
+ if (event.type === 'assistant' && usesToolOutsideTheCall({ event, allowedTools })) {
42
+ return 'Claude Code tried a tool that is not one of this call’s tools. Its reply was not accepted.';
43
+ }
44
+ if (event.type !== 'result' || event.parent_tool_use_id)
45
+ return undefined;
46
+ if (event.is_error || event.subtype !== 'success') {
47
+ const said = refusal || (typeof event.result === 'string' ? event.result : '');
48
+ failure = claudeFailure({ detail: JSON.stringify([event.error, event.errors, event.result, refusal]), said });
49
+ return failure.message;
50
+ }
51
+ replyText = typeof event.result === 'string' ? event.result : undefined;
52
+ return undefined;
53
+ },
54
+ });
55
+ if (failure)
56
+ throw failure;
57
+ if (ended.failure)
58
+ throw new Error(ended.failure);
59
+ if (ended.exitCode !== 0)
60
+ throw new Error('Claude Code stopped before its reply. Check the model, the subscription and the sign-in, then resume.');
61
+ if (replyText === undefined)
62
+ throw new Error('Claude Code ended without a reply.');
63
+ if (Buffer.byteLength(replyText) > MAX_REPLY_BYTES)
64
+ throw new Error('Claude Code returned a reply over 1 MB.');
65
+ return { replyText, instruction };
66
+ }
67
+ /** The one message of the conversation: the call's pictures in order, then the prompt. */
68
+ function userMessageOf({ prompt, images }) {
69
+ return {
70
+ type: 'user',
71
+ message: {
72
+ role: 'user',
73
+ content: [
74
+ ...images.map((image) => ({ type: 'image', source: { type: 'base64', media_type: image.mediaType, data: image.dataBase64 } })),
75
+ { type: 'text', text: prompt },
76
+ ],
77
+ },
78
+ };
79
+ }
80
+ /** The agent Claude Code runs as (its only instruction is the launcher's) and where it reaches the call's tools. */
81
+ async function writeSettingsFiles({ launch, instruction, allowedTools }) {
82
+ const agentsFile = join(launch.folder, 'claude-agents.json');
83
+ const toolServerFile = join(launch.folder, 'claude-mcp.json');
84
+ const agents = { [AGENT_NAME]: { description: 'Answers one call.', prompt: instruction, tools: allowedTools, omitClaudeMd: true } };
85
+ const servers = launch.toolServer
86
+ ? { [TOOL_SERVER_NAME]: { type: 'http', url: launch.toolServer.endpoint, headers: { Authorization: `Bearer \${${TOOL_SERVER_TOKEN_VARIABLE}}` } } }
87
+ : {};
88
+ await writeFile(agentsFile, JSON.stringify(agents), { mode: 0o600 });
89
+ await writeFile(toolServerFile, JSON.stringify({ mcpServers: servers }), { mode: 0o600 });
90
+ return { agentsFile, toolServerFile };
91
+ }
92
+ function claudeArguments({ launch, allowedTools, agentsFile, toolServerFile }) {
93
+ return [
94
+ '--print',
95
+ '--verbose',
96
+ '--input-format',
97
+ 'stream-json',
98
+ '--output-format',
99
+ 'stream-json',
100
+ '--restricted',
101
+ '--strict-mcp-config',
102
+ '--mcp-config',
103
+ toolServerFile,
104
+ '--agents',
105
+ agentsFile,
106
+ '--agent',
107
+ AGENT_NAME,
108
+ '--tools',
109
+ '',
110
+ '--allowedTools',
111
+ ...allowedTools,
112
+ '--permission-mode',
113
+ 'dontAsk',
114
+ '--permission-prompts',
115
+ 'none',
116
+ '--disable-slash-commands',
117
+ '--no-chrome',
118
+ '--no-session-persistence',
119
+ '--setting-sources',
120
+ '',
121
+ '--settings',
122
+ JSON.stringify({ disableAllHooks: true, autoMemoryEnabled: false }),
123
+ // Claude Code has no "none": a run answered by Claude Code refuses that effort before any call.
124
+ ...(launch.effort && launch.effort !== 'none' ? ['--effort', launch.effort] : []),
125
+ '--model',
126
+ launch.model,
127
+ '--thinking-display',
128
+ 'summarized',
129
+ ];
130
+ }
131
+ function textOf(event) {
132
+ return (event.message?.content ?? [])
133
+ .filter((block) => block.type === 'text')
134
+ .map((block) => String(block.text))
135
+ .join(' ');
136
+ }
137
+ function usesToolOutsideTheCall({ event, allowedTools }) {
138
+ if (event.parent_tool_use_id)
139
+ return true;
140
+ return (event.message?.content ?? []).some((block) => block.type === 'tool_use' && !allowedTools.includes(block.name ?? ''));
141
+ }
142
+ /** Claude's own words about a refusal (the time a limit resets, for example) are kept, shortened, in the message. */
143
+ function claudeFailure({ detail, said }) {
144
+ const words = said.replace(/\s+/g, ' ').trim().slice(0, 300);
145
+ const suffix = words ? `: ${words}` : '.';
146
+ if (/rate.?limit|usage.?limit|session limit|weekly limit|hit your [a-z ]*limit|limit reached|quota|429/i.test(detail)) {
147
+ return new Error(`Claude Code’s usage limit is reached${suffix}`);
148
+ }
149
+ if (isConnectionFailure(detail))
150
+ return new ProgramConnectionError(`Claude Code could not reach the model for the moment${suffix}`);
151
+ if (/auth|login|sign.?in|credential/i.test(detail))
152
+ return new Error(`Claude Code is not signed in${suffix}`);
153
+ if (/model|not.found/i.test(detail))
154
+ return new Error(`Claude Code does not have the requested model; check its name and the subscription${suffix}`);
155
+ return new Error(`Claude Code could not complete the call${suffix}`);
156
+ }
@@ -0,0 +1,6 @@
1
+ import { type Launch, type Launched } from './launch.js';
2
+ /**
3
+ * Answers one call with `codex exec`: a new conversation with the person's settings ignored, the sandbox read-only,
4
+ * Codex's own tools off, the call's pictures attached and its tools reached through the local tool server.
5
+ */
6
+ export declare function launchCodex(launch: Launch): Promise<Launched>;
@@ -0,0 +1,141 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { launcherInstructionOf } from './launch.js';
4
+ import { MAX_REPLY_BYTES, ProgramConnectionError, isConnectionFailure, programEnvironment, runProgram } from './program-run.js';
5
+ import { TOOL_SERVER_NAME, TOOL_SERVER_TOKEN_VARIABLE } from './tool-server.js';
6
+ /** Everything of Codex's own that a call must not use: a call sees its prompt, its pictures and its tools only. */
7
+ const DISABLED_FEATURES = [
8
+ 'code_mode',
9
+ 'view_image',
10
+ 'sleep_tool',
11
+ 'multi_agent',
12
+ 'multi_agent_v2',
13
+ 'apps',
14
+ 'browser_use',
15
+ 'browser_use_external',
16
+ 'computer_use',
17
+ 'hooks',
18
+ 'goals',
19
+ 'shell_tool',
20
+ 'unified_exec',
21
+ 'plugins',
22
+ 'remote_plugin',
23
+ 'image_generation',
24
+ 'skill_search',
25
+ ];
26
+ const FILE_EXTENSIONS = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' };
27
+ /**
28
+ * Answers one call with `codex exec`: a new conversation with the person's settings ignored, the sandbox read-only,
29
+ * Codex's own tools off, the call's pictures attached and its tools reached through the local tool server.
30
+ */
31
+ export async function launchCodex(launch) {
32
+ const instruction = launcherInstructionOf({ hasTools: launch.tools.length > 0 });
33
+ const instructionFile = join(launch.folder, 'response.instructions.md');
34
+ const imageFiles = await writeImageFiles(launch);
35
+ let replyText = '';
36
+ let providerErrors = '';
37
+ await writeFile(instructionFile, instruction, { mode: 0o600 });
38
+ const ended = await runProgram({
39
+ program: 'codex',
40
+ args: codexArguments({ launch, instructionFile, imageFiles }),
41
+ folder: launch.folder,
42
+ env: { ...programEnvironment(), ...(launch.toolServer ? { [TOOL_SERVER_TOKEN_VARIABLE]: launch.toolServer.token } : {}) },
43
+ input: launch.prompt,
44
+ signal: launch.signal,
45
+ onEvent: (line) => {
46
+ const event = line;
47
+ launch.onProviderEvent(event);
48
+ if (event.type === 'item.completed' && event.item?.type === 'agent_message')
49
+ replyText = event.item.text ?? '';
50
+ if (event.type === 'error' || event.type === 'turn.failed' || event.item?.type === 'error') {
51
+ providerErrors = (providerErrors + (event.message ?? event.error?.message ?? event.item?.message ?? '') + '\n').slice(-4000);
52
+ }
53
+ return isOutsideTheCall({ event, launch }) ? 'Codex tried a tool that is not one of this call’s tools. Its reply was not accepted.' : undefined;
54
+ },
55
+ });
56
+ if (ended.failure)
57
+ throw new Error(ended.failure);
58
+ if (ended.exitCode !== 0)
59
+ throw codexFailure(`${ended.diagnostic}\n${providerErrors}`);
60
+ if (!replyText)
61
+ throw new Error('Codex ended without a reply.');
62
+ if (Buffer.byteLength(replyText) > MAX_REPLY_BYTES)
63
+ throw new Error('Codex returned a reply over 1 MB.');
64
+ return { replyText, instruction };
65
+ }
66
+ /** A call's pictures as files in its folder, in order: Codex takes pictures by file. */
67
+ async function writeImageFiles({ folder, images }) {
68
+ const files = [];
69
+ for (const [index, image] of images.entries()) {
70
+ const file = join(folder, `image-${index + 1}.${FILE_EXTENSIONS[image.mediaType] ?? 'png'}`);
71
+ await writeFile(file, Buffer.from(image.dataBase64, 'base64'), { mode: 0o600 });
72
+ files.push(file);
73
+ }
74
+ return files;
75
+ }
76
+ function codexArguments({ launch, instructionFile, imageFiles }) {
77
+ const setting = (name, value) => ['-c', `${name}=${JSON.stringify(value)}`];
78
+ const server = `mcp_servers.${TOOL_SERVER_NAME}`;
79
+ const hasTools = Boolean(launch.toolServer);
80
+ return [
81
+ '--ask-for-approval',
82
+ 'never',
83
+ 'exec',
84
+ // Before the other options: an option after the pictures ends their list.
85
+ ...imageFiles.flatMap((file) => ['--image', file]),
86
+ '--ephemeral',
87
+ '--ignore-rules',
88
+ '--skip-git-repo-check',
89
+ '--ignore-user-config',
90
+ '--sandbox',
91
+ 'read-only',
92
+ '--json',
93
+ ...setting('web_search', 'disabled'),
94
+ '-c',
95
+ 'agents.enabled=false',
96
+ // Some models make their tool calls through this host even with code mode off.
97
+ hasTools ? '--enable' : '--disable',
98
+ 'code_mode_host',
99
+ ...DISABLED_FEATURES.flatMap((feature) => ['--disable', feature]),
100
+ '--enable',
101
+ 'skip_host_skill_discovery',
102
+ // Replaces Codex's own coding instructions, about 4,000 input tokens a call.
103
+ ...setting('model_instructions_file', instructionFile),
104
+ ...setting('model', launch.model),
105
+ ...setting('model_reasoning_summary', 'detailed'),
106
+ ...(launch.effort ? setting('model_reasoning_effort', launch.effort) : []),
107
+ ...(launch.toolServer
108
+ ? [
109
+ ...setting(`${server}.url`, launch.toolServer.endpoint),
110
+ ...setting(`${server}.bearer_token_env_var`, TOOL_SERVER_TOKEN_VARIABLE),
111
+ '-c',
112
+ `${server}.required=true`,
113
+ '-c',
114
+ `${server}.enabled_tools=${JSON.stringify(launch.tools.map((tool) => tool.name))}`,
115
+ // Codex runs with approvals off and refuses a tool not marked as only reading unless it is approved by name.
116
+ ...launch.tools.flatMap((tool) => setting(`${server}.tools.${tool.name}.approval_mode`, 'approve')),
117
+ ]
118
+ : []),
119
+ // The prompt is read from the input.
120
+ '-',
121
+ ];
122
+ }
123
+ /** A shell command, or a tool call that is not one of the call's own tools. */
124
+ function isOutsideTheCall({ event, launch }) {
125
+ if (event.item?.type === 'command_execution')
126
+ return true;
127
+ if (event.item?.type !== 'mcp_tool_call')
128
+ return false;
129
+ return event.item.server !== TOOL_SERVER_NAME || !launch.tools.some((tool) => tool.name === event.item?.tool);
130
+ }
131
+ function codexFailure(detail) {
132
+ const said = detail.replace(/\s+/g, ' ').trim().slice(-300);
133
+ if (/quota|exhaust|usage limit/i.test(detail))
134
+ return new Error('Your ChatGPT usage is used up. Wait for the limit to reset, then resume.');
135
+ if (/login|auth|401/i.test(detail))
136
+ return new Error('Codex is not signed in. Run codex login, then resume.');
137
+ if (isConnectionFailure(detail)) {
138
+ return new ProgramConnectionError(/capacity/i.test(detail) ? 'The Codex model is at capacity for the moment.' : 'Codex could not connect to the model service.');
139
+ }
140
+ return new Error(`Codex could not complete the call${said ? `: ${said}` : '.'}`);
141
+ }
@@ -0,0 +1,31 @@
1
+ import type { OfferedTool } from './tool-server.js';
2
+ /** One call as a launcher receives it: the complete prompt, its pictures, its tools and its model settings. */
3
+ export type Launch = {
4
+ /** A folder of the call's own; the launcher writes its settings files here. */
5
+ folder: string;
6
+ model: string;
7
+ effort?: 'none' | 'low' | 'medium' | 'high';
8
+ prompt: string;
9
+ images: {
10
+ mediaType: string;
11
+ dataBase64: string;
12
+ }[];
13
+ tools: OfferedTool[];
14
+ /** Where the program reaches the call's tools; absent for a call with none. */
15
+ toolServer?: {
16
+ endpoint: string;
17
+ token: string;
18
+ };
19
+ /** Receives each line of JSON the program prints, as the program wrote it. */
20
+ onProviderEvent: (event: unknown) => void;
21
+ signal: AbortSignal;
22
+ };
23
+ export type Launched = {
24
+ replyText: string;
25
+ /** The instruction the launcher sent beside the prompt. */
26
+ instruction: string;
27
+ };
28
+ /** What a launcher tells the model beside the prompt: the prompt is the whole task. */
29
+ export declare function launcherInstructionOf({ hasTools }: {
30
+ hasTools: boolean;
31
+ }): string;
@@ -0,0 +1,6 @@
1
+ /** What a launcher tells the model beside the prompt: the prompt is the whole task. */
2
+ export function launcherInstructionOf({ hasTools }) {
3
+ return hasTools
4
+ ? 'Follow the supplied task. Use only the tools it names. Return only the requested response.'
5
+ : 'Follow the supplied task. Return only the requested response; do not call tools.';
6
+ }
@@ -0,0 +1,30 @@
1
+ /** A failed connection, a provider outage or a model at capacity: the call is tried again. */
2
+ export declare class ProgramConnectionError extends Error {
3
+ }
4
+ /** A reply over this size fails its call. */
5
+ export declare const MAX_REPLY_BYTES = 1000000;
6
+ /** Model programs say a connection failed in their diagnostic text, not with a typed error. */
7
+ export declare function isConnectionFailure(detail: string): boolean;
8
+ /** Only what a model program needs to find itself and its sign-in; nothing else of this process's environment. */
9
+ export declare function programEnvironment(): NodeJS.ProcessEnv;
10
+ type ProgramRun = {
11
+ program: string;
12
+ args: string[];
13
+ folder: string;
14
+ env: NodeJS.ProcessEnv;
15
+ /** Written to the program's input, which is then closed. */
16
+ input: string;
17
+ /** Receives each line of JSON the program prints. Returning a message fails the call with it. */
18
+ onEvent: (event: unknown) => string | undefined;
19
+ signal: AbortSignal;
20
+ };
21
+ /**
22
+ * Runs a model program to its end in `folder`, handing each printed JSON line to `onEvent`. Stopping the call ends
23
+ * the program. Returns how it ended and the tail of what it wrote as diagnostics.
24
+ */
25
+ export declare function runProgram({ program, args, folder, env, input, onEvent, signal }: ProgramRun): Promise<{
26
+ exitCode: number | null;
27
+ diagnostic: string;
28
+ failure: string | undefined;
29
+ }>;
30
+ export {};
@@ -0,0 +1,92 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ /** A failed connection, a provider outage or a model at capacity: the call is tried again. */
5
+ export class ProgramConnectionError extends Error {
6
+ }
7
+ /** A reply over this size fails its call. */
8
+ export const MAX_REPLY_BYTES = 1_000_000;
9
+ const CONNECTION_FAILURE = /\b(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH)\b|network (?:error|failure)|connection (?:error|reset|refused|timed out)|request (?:timed out|timeout)|error (?:sending request|connecting)|stream disconnected|fetch failed|overloaded|capacity|\b(?:500|502|503|504|529)\b/i;
10
+ /** Model programs say a connection failed in their diagnostic text, not with a typed error. */
11
+ export function isConnectionFailure(detail) {
12
+ return CONNECTION_FAILURE.test(detail);
13
+ }
14
+ /** Only what a model program needs to find itself and its sign-in; nothing else of this process's environment. */
15
+ export function programEnvironment() {
16
+ const names = ['HOME', 'USER', 'CODEX_HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS'];
17
+ const kept = Object.fromEntries(names.flatMap((name) => (process.env[name] ? [[name, process.env[name]]] : [])));
18
+ const path = [process.env.PATH, join(homedir(), '.local/bin'), '/opt/homebrew/bin', '/usr/local/bin'].filter(Boolean).join(':');
19
+ return { ...kept, PATH: path };
20
+ }
21
+ const running = new Set();
22
+ process.once('exit', () => {
23
+ for (const child of running)
24
+ killGroup(child);
25
+ });
26
+ /** A model program starts helpers of its own; the whole group is ended with it. */
27
+ function killGroup(child) {
28
+ if (!child.pid)
29
+ return;
30
+ try {
31
+ process.kill(-child.pid, 'SIGKILL');
32
+ }
33
+ catch {
34
+ // The group has already ended.
35
+ }
36
+ }
37
+ /**
38
+ * Runs a model program to its end in `folder`, handing each printed JSON line to `onEvent`. Stopping the call ends
39
+ * the program. Returns how it ended and the tail of what it wrote as diagnostics.
40
+ */
41
+ export async function runProgram({ program, args, folder, env, input, onEvent, signal }) {
42
+ signal.throwIfAborted();
43
+ const child = spawn(program, args, { cwd: folder, env, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
44
+ let unfinishedLine = '';
45
+ let diagnostic = '';
46
+ let failure;
47
+ const fail = (message) => {
48
+ failure ??= message;
49
+ killGroup(child);
50
+ };
51
+ const readLine = (line) => {
52
+ if (!line.trim())
53
+ return;
54
+ try {
55
+ const problem = onEvent(JSON.parse(line));
56
+ if (problem)
57
+ fail(problem);
58
+ }
59
+ catch {
60
+ fail(`${program} printed a line that is not JSON.`);
61
+ }
62
+ };
63
+ const stop = () => killGroup(child);
64
+ running.add(child);
65
+ signal.addEventListener('abort', stop, { once: true });
66
+ child.stdout.on('data', (chunk) => {
67
+ const lines = (unfinishedLine + chunk.toString('utf8')).split('\n');
68
+ unfinishedLine = lines.pop() ?? '';
69
+ lines.forEach(readLine);
70
+ });
71
+ child.stderr.on('data', (chunk) => {
72
+ diagnostic = (diagnostic + chunk.toString('utf8')).slice(-16_000);
73
+ });
74
+ child.stdin.on('error', () => fail(`${program} could not receive the prompt.`));
75
+ try {
76
+ const ended = new Promise((resolve, reject) => {
77
+ child.once('error', reject);
78
+ child.once('close', resolve);
79
+ });
80
+ child.stdin.end(input);
81
+ const exitCode = await ended;
82
+ readLine(unfinishedLine);
83
+ if (signal.aborted)
84
+ throw signal.reason instanceof Error ? signal.reason : new DOMException('Call stopped', 'AbortError');
85
+ return { exitCode, diagnostic, failure };
86
+ }
87
+ finally {
88
+ signal.removeEventListener('abort', stop);
89
+ killGroup(child);
90
+ running.delete(child);
91
+ }
92
+ }
@@ -0,0 +1,26 @@
1
+ export type OfferedTool = {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: unknown;
5
+ annotations?: Record<string, unknown>;
6
+ };
7
+ /** The name a model program knows the call's tools by. */
8
+ export declare const TOOL_SERVER_NAME = "dagma";
9
+ /** The environment variable a model program reads the tool server's secret from. */
10
+ export declare const TOOL_SERVER_TOKEN_VARIABLE = "DAGMA_TOOL_TOKEN";
11
+ /**
12
+ * A call's tools, offered to the model program on this computer only: one local listener that speaks the MCP
13
+ * requests a program makes (initialize, ping, tools/list, tools/call) and hands each tool call to `callTool`.
14
+ * A request without the secret, from another address or naming another host is refused.
15
+ */
16
+ export declare function startToolServer({ tools, callTool, }: {
17
+ tools: OfferedTool[];
18
+ callTool: (toolCall: {
19
+ name: string;
20
+ args: unknown;
21
+ }) => Promise<unknown>;
22
+ }): Promise<{
23
+ endpoint: string;
24
+ token: string;
25
+ close(): Promise<void>;
26
+ }>;