@flowdular/sdk 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/.ai/skills/test-hardening/SKILL.md +1 -1
  2. package/README.md +69 -12
  3. package/assets/flowdular-banner.png +0 -0
  4. package/modules/agents/package.json +1 -1
  5. package/modules/auth/package.json +1 -1
  6. package/modules/auth/src/client/AuthenticationCore.tsrx +3 -1
  7. package/modules/auth/src/server/endpoints.ts +3 -1
  8. package/modules/auth/src/server/runtime.ts +4 -0
  9. package/modules/automations/package.json +1 -1
  10. package/modules/automations-workflows-integration/package.json +1 -1
  11. package/modules/profile/package.json +1 -1
  12. package/modules/sandbox/package.json +1 -1
  13. package/modules/system/package.json +1 -1
  14. package/modules/users/package.json +1 -1
  15. package/modules/workflows/package.json +1 -1
  16. package/package.json +5 -13
  17. package/packages/ai-provider/package.json +1 -1
  18. package/packages/cli-protocol/package.json +1 -1
  19. package/packages/client/package.json +1 -1
  20. package/packages/client/src/routing.ts +39 -2
  21. package/packages/client/src/shell/BrandMark.tsrx +5 -1
  22. package/packages/client/src/shell/navigation.ts +3 -1
  23. package/packages/client/src/state.ts +6 -2
  24. package/packages/contracts/package.json +1 -1
  25. package/packages/contracts/schemas/project.schema.json +16 -42
  26. package/packages/database/package.json +1 -1
  27. package/packages/database-pglite/package.json +2 -2
  28. package/packages/database-pglite/src/driver.ts +21 -3
  29. package/packages/database-testing/package.json +1 -1
  30. package/packages/dev-console/package.json +1 -1
  31. package/packages/harness/package.json +1 -1
  32. package/packages/kernel/package.json +1 -1
  33. package/packages/server/package.json +1 -1
  34. package/packages/server/src/application-routes.ts +80 -8
  35. package/packages/server/src/index.ts +4 -1
  36. package/packages/server/src/web-html.ts +9 -5
  37. package/packages/server/src/web.ts +59 -7
  38. package/packages/ui/package.json +1 -1
  39. package/packages/coding-agent/package.json +0 -44
  40. package/packages/coding-agent/src/drivers/byok.ts +0 -322
  41. package/packages/coding-agent/src/drivers/claude-code.ts +0 -290
  42. package/packages/coding-agent/src/drivers/codex.ts +0 -281
  43. package/packages/coding-agent/src/index.ts +0 -56
  44. package/packages/coding-agent/src/registry.ts +0 -119
  45. package/packages/coding-agent/src/roles/contract.ts +0 -60
  46. package/packages/coding-agent/src/roles/defaults.ts +0 -134
  47. package/packages/coding-agent/src/roles/handoff.ts +0 -41
  48. package/packages/coding-agent/src/roles/registry.ts +0 -156
  49. package/packages/coding-agent/src/roles/skills.ts +0 -72
  50. package/packages/coding-agent/src/roles/sync.ts +0 -88
  51. package/packages/coding-agent/src/types.ts +0 -102
  52. package/packages/coding-agent/src/workspace.ts +0 -275
  53. package/packages/sandbox/README.md +0 -691
  54. package/packages/sandbox/bin/flowdular-sandbox.mjs +0 -393
  55. package/packages/sandbox/dist/client/assets/App-ClMOrpyg.js +0 -11
  56. package/packages/sandbox/dist/client/assets/PreviewHost-BHiHrfbQ.js +0 -1
  57. package/packages/sandbox/dist/client/assets/auto-buGEq6de.js +0 -3
  58. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  59. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  60. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  61. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  62. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  63. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  64. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  65. package/packages/sandbox/dist/client/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  66. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  67. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  68. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  69. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  70. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  71. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  72. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  73. package/packages/sandbox/dist/client/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  74. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  75. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  76. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  77. package/packages/sandbox/dist/client/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  78. package/packages/sandbox/dist/client/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  79. package/packages/sandbox/dist/client/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  80. package/packages/sandbox/dist/client/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  81. package/packages/sandbox/dist/client/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  82. package/packages/sandbox/dist/client/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  83. package/packages/sandbox/dist/client/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  84. package/packages/sandbox/dist/client/assets/index-CvwhlQ87.js +0 -4
  85. package/packages/sandbox/dist/client/assets/styles-BPWaGf55.js +0 -3
  86. package/packages/sandbox/dist/client/assets/styles-Dx1_KOag.css +0 -1
  87. package/packages/sandbox/dist/client/favicon.svg +0 -1
  88. package/packages/sandbox/dist/server/assets/auto-CVGNYyb3.js +0 -12785
  89. package/packages/sandbox/dist/server/assets/chunk-DDJLRBDX-3OUNo51g.js +0 -4125
  90. package/packages/sandbox/dist/server/assets/nodefs-DVSI7kG0.js +0 -24
  91. package/packages/sandbox/dist/server/assets/opfs-ahp-D56iokt1.js +0 -388
  92. package/packages/sandbox/dist/server/assets/token-Bvaq7Anz.js +0 -55
  93. package/packages/sandbox/dist/server/assets/token-util-BqSvdIPQ.js +0 -3
  94. package/packages/sandbox/dist/server/assets/token-util-CktFFT4z.js +0 -494
  95. package/packages/sandbox/dist/server/entry.js +0 -91671
  96. package/packages/sandbox/dist/server/favicon.svg +0 -1
  97. package/packages/sandbox/dist/server/index.html +0 -161
  98. package/packages/sandbox/index.html +0 -159
  99. package/packages/sandbox/octane.config.ts +0 -36
  100. package/packages/sandbox/package.json +0 -83
  101. package/packages/sandbox/public/favicon.svg +0 -1
  102. package/packages/sandbox/public/og.png +0 -0
  103. package/packages/sandbox/src/App.tsrx +0 -924
  104. package/packages/sandbox/src/client/ApprovalHandoff.tsrx +0 -39
  105. package/packages/sandbox/src/client/ChatPane.tsrx +0 -694
  106. package/packages/sandbox/src/client/ConnectView.tsrx +0 -86
  107. package/packages/sandbox/src/client/DiffPane.tsrx +0 -150
  108. package/packages/sandbox/src/client/EjectModal.tsrx +0 -571
  109. package/packages/sandbox/src/client/GateResults.tsrx +0 -60
  110. package/packages/sandbox/src/client/GitHubSettingsModal.tsrx +0 -219
  111. package/packages/sandbox/src/client/NewSessionForm.tsrx +0 -214
  112. package/packages/sandbox/src/client/SessionBar.tsrx +0 -151
  113. package/packages/sandbox/src/client/SessionPicker.tsrx +0 -472
  114. package/packages/sandbox/src/client/SpecEditor.tsrx +0 -109
  115. package/packages/sandbox/src/client/SpecReviewCard.tsrx +0 -321
  116. package/packages/sandbox/src/client/WorkCard.tsrx +0 -128
  117. package/packages/sandbox/src/client/WorkbenchModal.tsrx +0 -161
  118. package/packages/sandbox/src/client/WorkspaceMenu.tsrx +0 -100
  119. package/packages/sandbox/src/client/api.ts +0 -797
  120. package/packages/sandbox/src/client/attachments.ts +0 -73
  121. package/packages/sandbox/src/client/dashboard.ts +0 -46
  122. package/packages/sandbox/src/client/github-settings.ts +0 -48
  123. package/packages/sandbox/src/client/highlight.ts +0 -105
  124. package/packages/sandbox/src/client/i18n.ts +0 -32
  125. package/packages/sandbox/src/client/locales/en.json +0 -466
  126. package/packages/sandbox/src/client/locales/pl.json +0 -466
  127. package/packages/sandbox/src/client/session-labels.ts +0 -77
  128. package/packages/sandbox/src/client/state.ts +0 -108
  129. package/packages/sandbox/src/index.ts +0 -10
  130. package/packages/sandbox/src/preview/PreviewHost.tsrx +0 -373
  131. package/packages/sandbox/src/preview/load-module.ts +0 -16
  132. package/packages/sandbox/src/server/attachments.ts +0 -308
  133. package/packages/sandbox/src/server/auto-review.ts +0 -181
  134. package/packages/sandbox/src/server/checkpoints.ts +0 -90
  135. package/packages/sandbox/src/server/config.ts +0 -460
  136. package/packages/sandbox/src/server/dashboard.ts +0 -245
  137. package/packages/sandbox/src/server/delivery/configuration.ts +0 -193
  138. package/packages/sandbox/src/server/delivery/git-pr.ts +0 -1473
  139. package/packages/sandbox/src/server/delivery/index.ts +0 -83
  140. package/packages/sandbox/src/server/delivery/local.ts +0 -151
  141. package/packages/sandbox/src/server/delivery/official-modules.ts +0 -516
  142. package/packages/sandbox/src/server/delivery/plan.ts +0 -218
  143. package/packages/sandbox/src/server/delivery/policies.ts +0 -239
  144. package/packages/sandbox/src/server/delivery/record.ts +0 -41
  145. package/packages/sandbox/src/server/delivery/steps.ts +0 -464
  146. package/packages/sandbox/src/server/delivery/types.ts +0 -158
  147. package/packages/sandbox/src/server/dependencies.ts +0 -88
  148. package/packages/sandbox/src/server/diff.ts +0 -230
  149. package/packages/sandbox/src/server/gates.ts +0 -388
  150. package/packages/sandbox/src/server/index.ts +0 -139
  151. package/packages/sandbox/src/server/path-guard.ts +0 -282
  152. package/packages/sandbox/src/server/planning.ts +0 -749
  153. package/packages/sandbox/src/server/platform-client.ts +0 -189
  154. package/packages/sandbox/src/server/preview-database-host.ts +0 -340
  155. package/packages/sandbox/src/server/preview-database-protocol.ts +0 -163
  156. package/packages/sandbox/src/server/preview-database-proxy.ts +0 -356
  157. package/packages/sandbox/src/server/preview-database.ts +0 -109
  158. package/packages/sandbox/src/server/preview-ipc.ts +0 -15
  159. package/packages/sandbox/src/server/preview-modules.ts +0 -83
  160. package/packages/sandbox/src/server/preview-revision.ts +0 -44
  161. package/packages/sandbox/src/server/preview-runtime.ts +0 -467
  162. package/packages/sandbox/src/server/preview-worker-manager.ts +0 -436
  163. package/packages/sandbox/src/server/preview-worker.ts +0 -168
  164. package/packages/sandbox/src/server/reference.ts +0 -251
  165. package/packages/sandbox/src/server/routes.ts +0 -2258
  166. package/packages/sandbox/src/server/runtime.ts +0 -188
  167. package/packages/sandbox/src/server/session-owner.ts +0 -23
  168. package/packages/sandbox/src/server/sessions.ts +0 -849
  169. package/packages/sandbox/src/server/spec.ts +0 -471
  170. package/packages/sandbox/src/server/turn-lifecycle.ts +0 -56
  171. package/packages/sandbox/src/server/turns.ts +0 -993
  172. package/packages/sandbox/src/server/workspace-install.ts +0 -266
  173. package/packages/sandbox/src/server/workspace-root.ts +0 -73
  174. package/packages/sandbox/src/styles.css +0 -1573
  175. package/packages/sandbox/vite.config.ts +0 -133
@@ -1,290 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import type { AiUsage } from '@flowdular/sdk/ai-provider';
3
- import {
4
- CodingAgentError,
5
- type CodingAgentAvailability,
6
- type CodingAgentDriver,
7
- type CodingAgentEvent,
8
- type CodingAgentTurnRequest,
9
- type FileChangeKind,
10
- } from '../types.ts';
11
- import {
12
- parseJsonLine,
13
- probeCommand,
14
- spawnLineStream,
15
- workspaceRelative,
16
- } from '../workspace.ts';
17
-
18
- export interface ClaudeCodeDriverOptions {
19
- readonly command?: string;
20
- /* Built-in tools the session may use. Command execution stays out: gates are
21
- run by the sandbox orchestrator, never by the model. */
22
- readonly tools?: readonly string[];
23
- readonly defaultModel?: string | null;
24
- readonly timeoutMs?: number;
25
- }
26
-
27
- const DEFAULT_TOOLS = ['Read', 'Write', 'Edit', 'Glob', 'Grep'] as const;
28
- const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
29
-
30
- interface ContentBlock {
31
- readonly type?: string;
32
- readonly text?: string;
33
- readonly name?: string;
34
- readonly input?: Record<string, unknown>;
35
- readonly content?: unknown;
36
- readonly is_error?: boolean;
37
- }
38
-
39
- function toolDetail(input: Record<string, unknown> | undefined): string {
40
- if (!input) return '';
41
- for (const key of ['file_path', 'path', 'pattern', 'query', 'command']) {
42
- const value = input[key];
43
- if (typeof value === 'string') return value.slice(0, 200);
44
- }
45
- return '';
46
- }
47
-
48
- function usageOf(value: unknown): AiUsage {
49
- const usage = (value ?? {}) as Record<string, unknown>;
50
- const inputTokens = Number(usage.input_tokens ?? 0);
51
- const outputTokens = Number(usage.output_tokens ?? 0);
52
- return {
53
- inputTokens: Number.isFinite(inputTokens) ? inputTokens : 0,
54
- outputTokens: Number.isFinite(outputTokens) ? outputTokens : 0,
55
- totalTokens:
56
- (Number.isFinite(inputTokens) ? inputTokens : 0) +
57
- (Number.isFinite(outputTokens) ? outputTokens : 0),
58
- };
59
- }
60
-
61
- /* A resumed session whose file is still held by the previous process, or was
62
- never flushed, fails before the init message. The turn then continues on a
63
- fresh session with the conversation replayed, as the codex driver does. */
64
- function isResumeFailure(error: unknown): boolean {
65
- return (
66
- error instanceof CodingAgentError && error.code === 'DRIVER_START_FAILED'
67
- );
68
- }
69
-
70
- function replayedPrompt(request: CodingAgentTurnRequest): string {
71
- const history = request.history ?? [];
72
- if (history.length === 0) return request.prompt;
73
- return [
74
- '<conversation-so-far>',
75
- ...history.map((message) => `${message.role}: ${message.text.trim()}`),
76
- '</conversation-so-far>',
77
- '',
78
- request.prompt,
79
- ].join('\n');
80
- }
81
-
82
- function changeKind(value: unknown): FileChangeKind | null {
83
- if (value === 'create') return 'created';
84
- if (value === 'update') return 'modified';
85
- if (value === 'delete') return 'deleted';
86
- return null;
87
- }
88
-
89
- export function createClaudeCodeDriver(
90
- options: ClaudeCodeDriverOptions = {},
91
- ): CodingAgentDriver {
92
- const command = options.command ?? 'claude';
93
- const tools = (options.tools ?? DEFAULT_TOOLS).join(',');
94
-
95
- return {
96
- id: 'claude-code',
97
- label: 'Claude Code',
98
- kind: 'local-cli',
99
- requiresLoopback: true,
100
- description:
101
- 'Local claude binary in print mode with restricted tools and the session workspace as its only writable directory.',
102
-
103
- async probe(): Promise<CodingAgentAvailability> {
104
- const result = await probeCommand(command, ['--version']);
105
- return {
106
- available: result.available,
107
- detail: result.available
108
- ? `Uses the operator login of ${command}.`
109
- : result.detail,
110
- version: result.version,
111
- };
112
- },
113
-
114
- async *run(
115
- request: CodingAgentTurnRequest,
116
- ): AsyncIterable<CodingAgentEvent> {
117
- const resumeId = request.resumeId ?? null;
118
- if (!resumeId) {
119
- yield* runSession(request, null);
120
- return;
121
- }
122
- try {
123
- yield* runSession(request, resumeId);
124
- } catch (error) {
125
- if (!isResumeFailure(error)) throw error;
126
- yield {
127
- type: 'error',
128
- code: 'DRIVER_SESSION_LOCKED',
129
- message:
130
- 'The previous claude session could not be resumed, so this turn continues on a new session with the conversation replayed.',
131
- };
132
- yield* runSession(request, null, true);
133
- }
134
- },
135
- };
136
-
137
- async function* runSession(
138
- request: CodingAgentTurnRequest,
139
- resumeId: string | null,
140
- replayHistory = false,
141
- ): AsyncIterable<CodingAgentEvent> {
142
- const sessionId = resumeId ?? randomUUID();
143
- const args = [
144
- '--print',
145
- '--output-format',
146
- 'stream-json',
147
- '--verbose',
148
- '--permission-mode',
149
- 'acceptEdits',
150
- '--restricted',
151
- '--strict-mcp-config',
152
- '--tools',
153
- tools,
154
- '--add-dir',
155
- request.workspacePath,
156
- '--append-system-prompt',
157
- request.systemInstruction,
158
- ...(resumeId ? ['--resume', resumeId] : ['--session-id', sessionId]),
159
- ...((request.model ?? options.defaultModel)
160
- ? ['--model', (request.model ?? options.defaultModel)!]
161
- : []),
162
- replayHistory ? replayedPrompt(request) : request.prompt,
163
- ];
164
-
165
- const stream = spawnLineStream({
166
- command,
167
- args,
168
- cwd: request.workspacePath,
169
- signal: request.signal,
170
- timeoutMs: request.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
171
- });
172
-
173
- let started = false;
174
- let completed = false;
175
- let currentResumeId = resumeId;
176
- for await (const line of stream.lines) {
177
- const message = parseJsonLine(line);
178
- if (!message) continue;
179
- const type = message.type;
180
-
181
- if (type === 'system' && message.subtype === 'init') {
182
- currentResumeId =
183
- typeof message.session_id === 'string'
184
- ? message.session_id
185
- : currentResumeId;
186
- started = true;
187
- yield {
188
- type: 'turn.started',
189
- driver: 'claude-code',
190
- role: request.role,
191
- resumeId: currentResumeId,
192
- };
193
- continue;
194
- }
195
-
196
- if (type === 'assistant') {
197
- const content = ((message.message ?? {}) as Record<string, unknown>)
198
- .content;
199
- for (const block of (content ?? []) as ContentBlock[]) {
200
- if (block.type === 'text' && block.text?.trim()) {
201
- yield { type: 'assistant.message', text: block.text };
202
- }
203
- if (block.type === 'thinking' && typeof block.text === 'string') {
204
- yield { type: 'reasoning', text: block.text };
205
- }
206
- if (block.type === 'tool_use' && block.name) {
207
- yield {
208
- type: 'tool.started',
209
- tool: block.name,
210
- detail: toolDetail(block.input),
211
- };
212
- }
213
- }
214
- continue;
215
- }
216
-
217
- if (type === 'user') {
218
- const content = ((message.message ?? {}) as Record<string, unknown>)
219
- .content;
220
- const result = (message.tool_use_result ?? {}) as Record<
221
- string,
222
- unknown
223
- >;
224
- for (const block of (content ?? []) as ContentBlock[]) {
225
- if (block.type !== 'tool_result') continue;
226
- yield {
227
- type: 'tool.completed',
228
- tool: typeof result.type === 'string' ? result.type : 'tool',
229
- detail: typeof result.filePath === 'string' ? result.filePath : '',
230
- ok: block.is_error !== true,
231
- };
232
- }
233
- const change = changeKind(result.type);
234
- if (change && typeof result.filePath === 'string') {
235
- yield {
236
- type: 'file.changed',
237
- path: workspaceRelative(request.workspacePath, result.filePath),
238
- change,
239
- };
240
- }
241
- continue;
242
- }
243
-
244
- if (type === 'result') {
245
- completed = true;
246
- const failed = message.is_error === true;
247
- if (failed && typeof message.result === 'string') {
248
- yield {
249
- type: 'error',
250
- code: 'DRIVER_TURN_FAILED',
251
- message: message.result.slice(0, 500),
252
- };
253
- } else if (typeof message.result === 'string' && message.result) {
254
- yield { type: 'assistant.message', text: message.result };
255
- }
256
- yield {
257
- type: 'turn.completed',
258
- resumeId:
259
- typeof message.session_id === 'string'
260
- ? message.session_id
261
- : currentResumeId,
262
- usage: usageOf(message.usage),
263
- costUsd:
264
- typeof message.total_cost_usd === 'number'
265
- ? message.total_cost_usd
266
- : null,
267
- finishReason: failed ? 'error' : 'stop',
268
- };
269
- }
270
- }
271
-
272
- const exit = await stream.finished;
273
- if (completed) return;
274
- if (exit.aborted) {
275
- yield {
276
- type: 'turn.completed',
277
- resumeId: currentResumeId,
278
- usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
279
- costUsd: null,
280
- finishReason: 'aborted',
281
- };
282
- return;
283
- }
284
- throw new CodingAgentError(
285
- started ? 'DRIVER_STREAM_INCOMPLETE' : 'DRIVER_START_FAILED',
286
- exit.stderr.trim().slice(0, 300) ||
287
- `The ${command} process exited with code ${exit.code} before completing the turn.`,
288
- );
289
- }
290
- }
@@ -1,281 +0,0 @@
1
- import type { AiUsage } from '@flowdular/sdk/ai-provider';
2
- import {
3
- CodingAgentError,
4
- type CodingAgentAvailability,
5
- type CodingAgentDriver,
6
- type CodingAgentEvent,
7
- type CodingAgentTurnRequest,
8
- type FileChangeKind,
9
- } from '../types.ts';
10
- import {
11
- parseJsonLine,
12
- probeCommand,
13
- spawnLineStream,
14
- workspaceRelative,
15
- } from '../workspace.ts';
16
-
17
- export interface CodexDriverOptions {
18
- readonly command?: string;
19
- readonly defaultModel?: string | null;
20
- readonly timeoutMs?: number;
21
- }
22
-
23
- const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
24
-
25
- interface CodexItem {
26
- readonly id?: string;
27
- readonly type?: string;
28
- readonly text?: string;
29
- readonly command?: string;
30
- readonly status?: string;
31
- readonly exit_code?: number | null;
32
- readonly changes?: readonly { path?: string; kind?: string }[];
33
- }
34
-
35
- function usageOf(value: unknown): AiUsage {
36
- const usage = (value ?? {}) as Record<string, unknown>;
37
- const inputTokens = Number(usage.input_tokens ?? 0);
38
- const outputTokens = Number(usage.output_tokens ?? 0);
39
- return {
40
- inputTokens: Number.isFinite(inputTokens) ? inputTokens : 0,
41
- outputTokens: Number.isFinite(outputTokens) ? outputTokens : 0,
42
- totalTokens:
43
- (Number.isFinite(inputTokens) ? inputTokens : 0) +
44
- (Number.isFinite(outputTokens) ? outputTokens : 0),
45
- };
46
- }
47
-
48
- function changeKind(value: string | undefined): FileChangeKind {
49
- if (value === 'add') return 'created';
50
- if (value === 'delete') return 'deleted';
51
- return 'modified';
52
- }
53
-
54
- /* Codex has no system prompt flag, so the role contract is prepended as a
55
- delimited preamble the model reads before the request. A turn that could not
56
- resume its thread also replays the conversation, because a fresh thread
57
- starts with no memory of it. */
58
- function composePrompt(
59
- request: CodingAgentTurnRequest,
60
- replayHistory: boolean,
61
- ): string {
62
- const history = replayHistory ? (request.history ?? []) : [];
63
- return [
64
- '<role-contract>',
65
- request.systemInstruction.trim(),
66
- '</role-contract>',
67
- ...(history.length > 0
68
- ? [
69
- '',
70
- '<conversation-so-far>',
71
- ...history.map(
72
- (message) => `${message.role}: ${message.text.trim()}`,
73
- ),
74
- '</conversation-so-far>',
75
- ]
76
- : []),
77
- '',
78
- '<request>',
79
- request.prompt.trim(),
80
- '</request>',
81
- ].join('\n');
82
- }
83
-
84
- /* Codex keeps one writer per thread. A previous turn that has not released it
85
- yet, or was killed before it could, makes every resume of that thread fail. */
86
- function isThreadLocked(error: unknown): boolean {
87
- return (
88
- error instanceof CodingAgentError &&
89
- /thread-store conflict|active writer/i.test(error.message)
90
- );
91
- }
92
-
93
- export function createCodexDriver(
94
- options: CodexDriverOptions = {},
95
- ): CodingAgentDriver {
96
- const command = options.command ?? 'codex';
97
-
98
- return {
99
- id: 'codex',
100
- label: 'Codex CLI',
101
- kind: 'local-cli',
102
- requiresLoopback: true,
103
- description:
104
- 'Local codex binary in exec mode with a workspace-write sandbox rooted at the session workspace.',
105
-
106
- async probe(): Promise<CodingAgentAvailability> {
107
- const result = await probeCommand(command, ['--version']);
108
- return {
109
- available: result.available,
110
- detail: result.available
111
- ? `Uses the operator login of ${command}.`
112
- : result.detail,
113
- version: result.version,
114
- };
115
- },
116
-
117
- async *run(
118
- request: CodingAgentTurnRequest,
119
- ): AsyncIterable<CodingAgentEvent> {
120
- const resumeId = request.resumeId ?? null;
121
- if (!resumeId) {
122
- yield* runThread(request, null);
123
- return;
124
- }
125
- try {
126
- yield* runThread(request, resumeId);
127
- } catch (error) {
128
- if (!isThreadLocked(error)) throw error;
129
- yield {
130
- type: 'error',
131
- code: 'DRIVER_THREAD_LOCKED',
132
- message:
133
- 'The previous codex thread was still open, so this turn continues on a new thread with the conversation replayed.',
134
- };
135
- yield* runThread(request, null);
136
- }
137
- },
138
- };
139
-
140
- async function* runThread(
141
- request: CodingAgentTurnRequest,
142
- resumeId: string | null,
143
- ): AsyncIterable<CodingAgentEvent> {
144
- const model = request.model ?? options.defaultModel ?? null;
145
- /* The resume subcommand takes a narrower option set than a fresh exec: it
146
- has no --cd or --sandbox, so the working directory comes from the child
147
- process and the sandbox policy from a config override. */
148
- const args = resumeId
149
- ? [
150
- 'exec',
151
- 'resume',
152
- resumeId,
153
- '--json',
154
- '--skip-git-repo-check',
155
- '-c',
156
- 'sandbox_mode="workspace-write"',
157
- ...(model ? ['--model', model] : []),
158
- composePrompt(request, resumeId === null),
159
- ]
160
- : [
161
- 'exec',
162
- '--json',
163
- '--cd',
164
- request.workspacePath,
165
- '--sandbox',
166
- 'workspace-write',
167
- '--skip-git-repo-check',
168
- ...(model ? ['--model', model] : []),
169
- composePrompt(request, resumeId === null),
170
- ];
171
-
172
- const stream = spawnLineStream({
173
- command,
174
- args,
175
- cwd: request.workspacePath,
176
- signal: request.signal,
177
- timeoutMs: request.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
178
- });
179
-
180
- let currentResumeId = resumeId;
181
- let started = false;
182
- let completed = false;
183
- for await (const line of stream.lines) {
184
- const message = parseJsonLine(line);
185
- if (!message) continue;
186
- const type = message.type;
187
-
188
- if (type === 'thread.started') {
189
- currentResumeId =
190
- typeof message.thread_id === 'string'
191
- ? message.thread_id
192
- : currentResumeId;
193
- continue;
194
- }
195
-
196
- if (type === 'turn.started') {
197
- started = true;
198
- yield {
199
- type: 'turn.started',
200
- driver: 'codex',
201
- role: request.role,
202
- resumeId: currentResumeId,
203
- };
204
- continue;
205
- }
206
-
207
- if (type === 'item.started' || type === 'item.completed') {
208
- const item = (message.item ?? {}) as CodexItem;
209
- const done = type === 'item.completed';
210
- if (item.type === 'agent_message' && done && item.text?.trim()) {
211
- yield { type: 'assistant.message', text: item.text };
212
- }
213
- if (item.type === 'reasoning' && done && item.text?.trim()) {
214
- yield { type: 'reasoning', text: item.text };
215
- }
216
- if (item.type === 'command_execution') {
217
- yield done
218
- ? {
219
- type: 'tool.completed',
220
- tool: 'command',
221
- detail: (item.command ?? '').slice(0, 200),
222
- ok: (item.exit_code ?? 0) === 0,
223
- }
224
- : {
225
- type: 'tool.started',
226
- tool: 'command',
227
- detail: (item.command ?? '').slice(0, 200),
228
- };
229
- }
230
- if (item.type === 'file_change' && done) {
231
- for (const change of item.changes ?? []) {
232
- if (!change.path) continue;
233
- yield {
234
- type: 'file.changed',
235
- path: workspaceRelative(request.workspacePath, change.path),
236
- change: changeKind(change.kind),
237
- };
238
- }
239
- }
240
- continue;
241
- }
242
-
243
- if (type === 'turn.completed' || type === 'turn.failed') {
244
- completed = true;
245
- if (type === 'turn.failed') {
246
- const error = (message.error ?? {}) as { message?: string };
247
- yield {
248
- type: 'error',
249
- code: 'DRIVER_TURN_FAILED',
250
- message: (error.message ?? 'The codex turn failed.').slice(0, 500),
251
- };
252
- }
253
- yield {
254
- type: 'turn.completed',
255
- resumeId: currentResumeId,
256
- usage: usageOf(message.usage),
257
- costUsd: null,
258
- finishReason: type === 'turn.failed' ? 'error' : 'stop',
259
- };
260
- }
261
- }
262
-
263
- const exit = await stream.finished;
264
- if (completed) return;
265
- if (exit.aborted) {
266
- yield {
267
- type: 'turn.completed',
268
- resumeId: currentResumeId,
269
- usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
270
- costUsd: null,
271
- finishReason: 'aborted',
272
- };
273
- return;
274
- }
275
- throw new CodingAgentError(
276
- started ? 'DRIVER_STREAM_INCOMPLETE' : 'DRIVER_START_FAILED',
277
- exit.stderr.trim().slice(0, 300) ||
278
- `The ${command} process exited with code ${exit.code} before completing the turn.`,
279
- );
280
- }
281
- }
@@ -1,56 +0,0 @@
1
- export {
2
- CodingAgentError,
3
- type CodingAgentAvailability,
4
- type CodingAgentDriver,
5
- type CodingAgentDriverInfo,
6
- type CodingAgentDriverKind,
7
- type CodingAgentEvent,
8
- type CodingAgentMessage,
9
- type CodingAgentTurnRequest,
10
- type FileChangeKind,
11
- type SandboxRuntimeMode,
12
- } from './types.ts';
13
- export {
14
- createCodingAgentRegistry,
15
- type CodingAgentRegistry,
16
- type CodingAgentRegistryOptions,
17
- type DriverStatus,
18
- } from './registry.ts';
19
- export { createClaudeCodeDriver } from './drivers/claude-code.ts';
20
- export type { ClaudeCodeDriverOptions } from './drivers/claude-code.ts';
21
- export { createCodexDriver } from './drivers/codex.ts';
22
- export type { CodexDriverOptions } from './drivers/codex.ts';
23
- export { createByokDriver } from './drivers/byok.ts';
24
- export type { ByokDriverOptions } from './drivers/byok.ts';
25
- export {
26
- SANDBOX_AGENT_CONTRACT,
27
- composeSessionFacts,
28
- type InstructionContext,
29
- } from './roles/contract.ts';
30
- export { parseHandoff, type HandoffDeclaration } from './roles/handoff.ts';
31
- export { selectTaskSkill, type TaskSkillContext } from './roles/skills.ts';
32
- export { DEFAULT_AGENT_ROLES } from './roles/defaults.ts';
33
- export type { AgentRoleDefinition } from './roles/defaults.ts';
34
- export {
35
- SANDBOX_ROLE_DIRECTORY,
36
- composeInstruction,
37
- findRole,
38
- loadAgentRoles,
39
- materializeAgentRoles,
40
- parseRoleDocument,
41
- renderRoleDocument,
42
- } from './roles/registry.ts';
43
- export {
44
- loadRoleDocuments,
45
- normalizeRoleDocument,
46
- renderDefaultsModule,
47
- } from './roles/sync.ts';
48
- export {
49
- parseJsonLine,
50
- probeCommand,
51
- resolveInsideWorkspace,
52
- resolveReadableInsideWorkspace,
53
- resolveWritableInsideWorkspace,
54
- spawnLineStream,
55
- workspaceRelative,
56
- } from './workspace.ts';