@open330/oac 2026.3.6 → 2026.4.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.

Potentially problematic release.


This version of @open330/oac might be problematic. Click here for more details.

Files changed (52) hide show
  1. package/dist/budget/index.d.ts +78 -0
  2. package/dist/budget/index.js +17 -0
  3. package/dist/chunk-LQC5DLT7.js +317 -0
  4. package/dist/chunk-LQC5DLT7.js.map +1 -0
  5. package/dist/chunk-NZEI4RPP.js +1499 -0
  6. package/dist/chunk-NZEI4RPP.js.map +1 -0
  7. package/dist/{chunk-Z7KEQPGV.js → chunk-SZUDHVBF.js} +65 -89
  8. package/dist/chunk-SZUDHVBF.js.map +1 -0
  9. package/dist/chunk-TGZ2TGDA.js +348 -0
  10. package/dist/chunk-TGZ2TGDA.js.map +1 -0
  11. package/dist/chunk-UL66HWYF.js +392 -0
  12. package/dist/chunk-UL66HWYF.js.map +1 -0
  13. package/dist/chunk-VLR2VYFW.js +475 -0
  14. package/dist/chunk-VLR2VYFW.js.map +1 -0
  15. package/dist/chunk-ZPI2VQ7U.js +1732 -0
  16. package/dist/chunk-ZPI2VQ7U.js.map +1 -0
  17. package/dist/cli/cli.js +15 -0
  18. package/dist/cli/cli.js.map +1 -0
  19. package/dist/cli/index.js +18 -0
  20. package/dist/cli/index.js.map +1 -0
  21. package/dist/completion/index.d.ts +91 -0
  22. package/dist/completion/index.js +590 -0
  23. package/dist/completion/index.js.map +1 -0
  24. package/dist/core/index.d.ts +1403 -0
  25. package/dist/core/index.js +75 -0
  26. package/dist/core/index.js.map +1 -0
  27. package/dist/dashboard/index.d.ts +14 -0
  28. package/dist/dashboard/index.js +1257 -0
  29. package/dist/dashboard/index.js.map +1 -0
  30. package/dist/discovery/index.d.ts +115 -0
  31. package/dist/discovery/index.js +19 -0
  32. package/dist/discovery/index.js.map +1 -0
  33. package/dist/event-bus-CRLkpNo0.d.ts +91 -0
  34. package/dist/execution/index.d.ts +162 -0
  35. package/dist/execution/index.js +18 -0
  36. package/dist/execution/index.js.map +1 -0
  37. package/dist/repo/index.d.ts +33 -0
  38. package/dist/repo/index.js +19 -0
  39. package/dist/repo/index.js.map +1 -0
  40. package/dist/tracking/index.d.ts +357 -0
  41. package/dist/tracking/index.js +15 -0
  42. package/dist/tracking/index.js.map +1 -0
  43. package/dist/types-CYCwgojB.d.ts +34 -0
  44. package/dist/types-cJZwCZZX.d.ts +172 -0
  45. package/package.json +42 -20
  46. package/dist/chunk-Z7KEQPGV.js.map +0 -1
  47. package/dist/cli.js +0 -9
  48. package/dist/index.js +0 -12
  49. package/dist/index.js.map +0 -1
  50. /package/dist/{cli.js.map → budget/index.js.map} +0 -0
  51. /package/dist/{cli.d.ts → cli/cli.d.ts} +0 -0
  52. /package/dist/{index.d.ts → cli/index.d.ts} +0 -0
@@ -0,0 +1,1499 @@
1
+ import {
2
+ OacError,
3
+ executionError
4
+ } from "./chunk-TGZ2TGDA.js";
5
+
6
+ // src/execution/agents/claude-code.adapter.ts
7
+ import { createInterface } from "readline";
8
+ import { execa } from "execa";
9
+ var AsyncEventQueue = class {
10
+ values = [];
11
+ resolvers = [];
12
+ done = false;
13
+ pendingError;
14
+ push(value) {
15
+ if (this.done) {
16
+ return;
17
+ }
18
+ const nextResolver = this.resolvers.shift();
19
+ if (nextResolver) {
20
+ nextResolver({ done: false, value });
21
+ return;
22
+ }
23
+ this.values.push(value);
24
+ }
25
+ close() {
26
+ if (this.done) {
27
+ return;
28
+ }
29
+ this.done = true;
30
+ this.flush();
31
+ }
32
+ fail(error) {
33
+ this.pendingError = error;
34
+ this.done = true;
35
+ this.flush();
36
+ }
37
+ [Symbol.asyncIterator]() {
38
+ return {
39
+ next: async () => {
40
+ if (this.values.length > 0) {
41
+ const value = this.values.shift();
42
+ if (value === void 0) {
43
+ return { done: true, value: void 0 };
44
+ }
45
+ return { done: false, value };
46
+ }
47
+ if (this.pendingError !== void 0) {
48
+ throw this.pendingError;
49
+ }
50
+ if (this.done) {
51
+ return { done: true, value: void 0 };
52
+ }
53
+ return new Promise((resolve2) => {
54
+ this.resolvers.push(resolve2);
55
+ });
56
+ }
57
+ };
58
+ }
59
+ flush() {
60
+ for (const resolve2 of this.resolvers.splice(0)) {
61
+ resolve2({ done: true, value: void 0 });
62
+ }
63
+ }
64
+ };
65
+ function isRecord(value) {
66
+ return typeof value === "object" && value !== null;
67
+ }
68
+ function readNumber(value) {
69
+ if (typeof value !== "number" || !Number.isFinite(value)) {
70
+ return void 0;
71
+ }
72
+ return Math.max(0, Math.floor(value));
73
+ }
74
+ function readString(value) {
75
+ if (typeof value !== "string") {
76
+ return void 0;
77
+ }
78
+ const trimmed = value.trim();
79
+ return trimmed.length > 0 ? trimmed : void 0;
80
+ }
81
+ function parseJsonPayload(line) {
82
+ const trimmed = line.trim();
83
+ if (trimmed.length === 0) {
84
+ return void 0;
85
+ }
86
+ const candidates = [trimmed];
87
+ const start = trimmed.indexOf("{");
88
+ const end = trimmed.lastIndexOf("}");
89
+ if (start >= 0 && end > start) {
90
+ const fragment = trimmed.slice(start, end + 1);
91
+ if (fragment !== trimmed) {
92
+ candidates.push(fragment);
93
+ }
94
+ }
95
+ for (const candidate of candidates) {
96
+ try {
97
+ const parsed = JSON.parse(candidate);
98
+ if (isRecord(parsed)) {
99
+ return parsed;
100
+ }
101
+ } catch {
102
+ }
103
+ }
104
+ return void 0;
105
+ }
106
+ function patchTokenState(state, patch) {
107
+ if (patch.inputTokens === void 0 && patch.outputTokens === void 0 && patch.cumulativeTokens === void 0) {
108
+ return void 0;
109
+ }
110
+ state.inputTokens = patch.inputTokens ?? state.inputTokens;
111
+ state.outputTokens = patch.outputTokens ?? state.outputTokens;
112
+ const computedTotal = state.inputTokens + state.outputTokens;
113
+ state.cumulativeTokens = Math.max(
114
+ state.cumulativeTokens,
115
+ patch.cumulativeTokens ?? computedTotal
116
+ );
117
+ return {
118
+ type: "tokens",
119
+ inputTokens: state.inputTokens,
120
+ outputTokens: state.outputTokens,
121
+ cumulativeTokens: state.cumulativeTokens
122
+ };
123
+ }
124
+ function parseTokenPatchFromPayload(payload) {
125
+ const usage = isRecord(payload.usage) ? payload.usage : void 0;
126
+ return {
127
+ inputTokens: readNumber(
128
+ payload.inputTokens ?? payload.input_tokens ?? payload.promptTokens ?? payload.prompt_tokens ?? usage?.inputTokens ?? usage?.input_tokens ?? usage?.promptTokens ?? usage?.prompt_tokens
129
+ ),
130
+ outputTokens: readNumber(
131
+ payload.outputTokens ?? payload.output_tokens ?? payload.completionTokens ?? payload.completion_tokens ?? usage?.outputTokens ?? usage?.output_tokens ?? usage?.completionTokens ?? usage?.completion_tokens
132
+ ),
133
+ cumulativeTokens: readNumber(
134
+ payload.cumulativeTokens ?? payload.cumulative_tokens ?? payload.totalTokens ?? payload.total_tokens ?? usage?.cumulativeTokens ?? usage?.cumulative_tokens ?? usage?.totalTokens ?? usage?.total_tokens
135
+ )
136
+ };
137
+ }
138
+ function parseTokenPatchFromLine(line) {
139
+ const inputMatch = line.match(/(?:input|prompt)\s*tokens?\s*[:=]\s*(\d+)/i);
140
+ const outputMatch = line.match(/(?:output|completion)\s*tokens?\s*[:=]\s*(\d+)/i);
141
+ const totalMatch = line.match(/(?:total|cumulative|used)\s*tokens?\s*[:=]\s*(\d+)/i);
142
+ return {
143
+ inputTokens: inputMatch ? Number.parseInt(inputMatch[1], 10) : void 0,
144
+ outputTokens: outputMatch ? Number.parseInt(outputMatch[1], 10) : void 0,
145
+ cumulativeTokens: totalMatch ? Number.parseInt(totalMatch[1], 10) : void 0
146
+ };
147
+ }
148
+ function parseTokenEvent(line, state) {
149
+ const payload = parseJsonPayload(line);
150
+ const patch = payload ? parseTokenPatchFromPayload(payload) : parseTokenPatchFromLine(line);
151
+ return patchTokenState(state, patch);
152
+ }
153
+ function normalizeFileAction(value) {
154
+ if (value !== "create" && value !== "modify" && value !== "delete") {
155
+ return void 0;
156
+ }
157
+ return value;
158
+ }
159
+ function parseFileEditFromPayload(payload) {
160
+ if (payload.type === "file_edit") {
161
+ const action = normalizeFileAction(payload.action);
162
+ const path = readString(payload.path);
163
+ if (action && path) {
164
+ return {
165
+ type: "file_edit",
166
+ action,
167
+ path
168
+ };
169
+ }
170
+ }
171
+ const tool = readString(payload.tool ?? payload.tool_name ?? payload.name);
172
+ const input = isRecord(payload.input) ? payload.input : void 0;
173
+ const inputPath = readString(input?.path ?? input?.file_path ?? input?.filePath);
174
+ if (!tool || !inputPath) {
175
+ return void 0;
176
+ }
177
+ if (tool === "create_file") {
178
+ return { type: "file_edit", action: "create", path: inputPath };
179
+ }
180
+ if (tool === "delete_file") {
181
+ return { type: "file_edit", action: "delete", path: inputPath };
182
+ }
183
+ if (tool === "write_file" || tool === "edit_file" || tool === "replace_file") {
184
+ return { type: "file_edit", action: "modify", path: inputPath };
185
+ }
186
+ return void 0;
187
+ }
188
+ function parseFileEditFromLine(line) {
189
+ const fileActionMatch = line.match(/\b(created|modified|deleted)\s+(?:file\s+)?([^\s"'`]+)/i);
190
+ if (!fileActionMatch) {
191
+ return void 0;
192
+ }
193
+ const actionMap = {
194
+ created: "create",
195
+ modified: "modify",
196
+ deleted: "delete"
197
+ };
198
+ const action = actionMap[fileActionMatch[1].toLowerCase()];
199
+ const path = fileActionMatch[2]?.trim();
200
+ if (!action || !path) {
201
+ return void 0;
202
+ }
203
+ return {
204
+ type: "file_edit",
205
+ action,
206
+ path
207
+ };
208
+ }
209
+ function parseFileEditEvent(line) {
210
+ const payload = parseJsonPayload(line);
211
+ return payload ? parseFileEditFromPayload(payload) : parseFileEditFromLine(line);
212
+ }
213
+ function parseToolUseEvent(line) {
214
+ const payload = parseJsonPayload(line);
215
+ if (!payload) {
216
+ return void 0;
217
+ }
218
+ const tool = readString(payload.tool ?? payload.tool_name ?? payload.name);
219
+ if (!tool) {
220
+ return void 0;
221
+ }
222
+ return {
223
+ type: "tool_use",
224
+ tool,
225
+ input: payload.input
226
+ };
227
+ }
228
+ function parseErrorEvent(line, stream) {
229
+ const payload = parseJsonPayload(line);
230
+ if (payload?.type === "error") {
231
+ const message = readString(payload.message) ?? "Unknown Claude CLI error";
232
+ const recoverable = payload.recoverable !== false;
233
+ return { type: "error", message, recoverable };
234
+ }
235
+ if (stream === "stderr" && /error|failed|exception/i.test(line)) {
236
+ return { type: "error", message: line.trim(), recoverable: true };
237
+ }
238
+ return void 0;
239
+ }
240
+ function estimateTokenCount(text) {
241
+ if (text.length === 0) {
242
+ return 0;
243
+ }
244
+ return Math.max(1, Math.ceil(text.length / 4));
245
+ }
246
+ function normalizeUnknownError(error, executionId) {
247
+ if (error instanceof OacError) {
248
+ return error;
249
+ }
250
+ const message = error instanceof Error ? error.message : String(error);
251
+ if (/timed out|timeout/i.test(message)) {
252
+ return executionError("AGENT_TIMEOUT", `Claude execution timed out for ${executionId}`, {
253
+ context: { executionId, message },
254
+ cause: error
255
+ });
256
+ }
257
+ if (/out of memory|ENOMEM|heap/i.test(message)) {
258
+ return executionError("AGENT_OOM", `Claude execution ran out of memory for ${executionId}`, {
259
+ context: { executionId, message },
260
+ cause: error
261
+ });
262
+ }
263
+ if (/network|ECONN|ENOTFOUND|EAI_AGAIN/i.test(message)) {
264
+ return new OacError(
265
+ "Claude execution failed due to network issues",
266
+ "NETWORK_ERROR",
267
+ "recoverable",
268
+ {
269
+ executionId,
270
+ message
271
+ },
272
+ error
273
+ );
274
+ }
275
+ return executionError("AGENT_EXECUTION_FAILED", `Claude execution failed for ${executionId}`, {
276
+ context: { executionId, message },
277
+ cause: error
278
+ });
279
+ }
280
+ function computeTotalTokens(state) {
281
+ return Math.max(state.cumulativeTokens, state.inputTokens + state.outputTokens);
282
+ }
283
+ function normalizeExitCode(value) {
284
+ if (typeof value === "number" && Number.isFinite(value)) {
285
+ return value;
286
+ }
287
+ return 1;
288
+ }
289
+ function hasBooleanFlag(value, key) {
290
+ if (!isRecord(value)) {
291
+ return false;
292
+ }
293
+ return value[key] === true;
294
+ }
295
+ function buildFailureMessage(stdout, stderr) {
296
+ const trimmedStderr = stderr.trim();
297
+ if (trimmedStderr.length > 0) {
298
+ return trimmedStderr;
299
+ }
300
+ const trimmedStdout = stdout.trim();
301
+ if (trimmedStdout.length > 0) {
302
+ return trimmedStdout;
303
+ }
304
+ return "Claude CLI process exited with a non-zero status.";
305
+ }
306
+ var ClaudeCodeAdapter = class {
307
+ id = "claude-code";
308
+ name = "Claude Code";
309
+ runningExecutions = /* @__PURE__ */ new Map();
310
+ async checkAvailability() {
311
+ try {
312
+ const result = await execa("claude", ["--version"], { reject: false });
313
+ const version = result.stdout.trim().split("\n")[0];
314
+ if (result.exitCode === 0) {
315
+ return {
316
+ available: true,
317
+ version: version.length > 0 ? version : void 0
318
+ };
319
+ }
320
+ return {
321
+ available: false,
322
+ error: result.stderr.trim() || `claude --version exited with code ${result.exitCode}`
323
+ };
324
+ } catch (error) {
325
+ const message = error instanceof Error ? error.message : String(error);
326
+ return {
327
+ available: false,
328
+ error: message
329
+ };
330
+ }
331
+ }
332
+ execute(params) {
333
+ const startedAt = Date.now();
334
+ const filesChanged = /* @__PURE__ */ new Set();
335
+ const tokenState = {
336
+ inputTokens: 0,
337
+ outputTokens: 0,
338
+ cumulativeTokens: 0
339
+ };
340
+ const eventQueue = new AsyncEventQueue();
341
+ const processEnv = {
342
+ ...Object.fromEntries(
343
+ Object.entries(process.env).filter(
344
+ (entry) => typeof entry[1] === "string" && // Strip Claude Code session markers to allow spawning a fresh Claude subprocess
345
+ entry[0] !== "CLAUDECODE" && entry[0] !== "CLAUDE_CODE_SESSION"
346
+ )
347
+ ),
348
+ ...params.env,
349
+ OAC_TOKEN_BUDGET: `${params.tokenBudget}`,
350
+ OAC_ALLOW_COMMITS: `${params.allowCommits}`
351
+ };
352
+ const subprocess = execa("claude", ["-p", params.prompt], {
353
+ cwd: params.workingDirectory,
354
+ env: processEnv,
355
+ extendEnv: false,
356
+ reject: false,
357
+ timeout: params.timeoutMs
358
+ });
359
+ this.runningExecutions.set(params.executionId, subprocess);
360
+ const consumeStream = async (stream, streamName) => {
361
+ if (!stream) {
362
+ return;
363
+ }
364
+ const lineReader = createInterface({
365
+ input: stream,
366
+ crlfDelay: Number.POSITIVE_INFINITY
367
+ });
368
+ for await (const line of lineReader) {
369
+ eventQueue.push({
370
+ type: "output",
371
+ content: line,
372
+ stream: streamName
373
+ });
374
+ const tokenEvent = parseTokenEvent(line, tokenState);
375
+ if (tokenEvent?.type === "tokens") {
376
+ eventQueue.push(tokenEvent);
377
+ }
378
+ const fileEvent = parseFileEditEvent(line);
379
+ if (fileEvent) {
380
+ filesChanged.add(fileEvent.path);
381
+ eventQueue.push(fileEvent);
382
+ }
383
+ const toolEvent = parseToolUseEvent(line);
384
+ if (toolEvent) {
385
+ eventQueue.push(toolEvent);
386
+ }
387
+ const errorEvent = parseErrorEvent(line, streamName);
388
+ if (errorEvent) {
389
+ eventQueue.push(errorEvent);
390
+ }
391
+ }
392
+ };
393
+ const stdoutDone = consumeStream(subprocess.stdout ?? void 0, "stdout");
394
+ const stderrDone = consumeStream(subprocess.stderr ?? void 0, "stderr");
395
+ const resultPromise = (async () => {
396
+ try {
397
+ const settled = await subprocess;
398
+ await Promise.all([stdoutDone, stderrDone]);
399
+ const timedOut = hasBooleanFlag(settled, "timedOut");
400
+ if (timedOut) {
401
+ const timeoutError = executionError(
402
+ "AGENT_TIMEOUT",
403
+ `Claude execution timed out for ${params.executionId}`,
404
+ {
405
+ context: {
406
+ executionId: params.executionId,
407
+ timeoutMs: params.timeoutMs
408
+ }
409
+ }
410
+ );
411
+ eventQueue.push({
412
+ type: "error",
413
+ message: timeoutError.message,
414
+ recoverable: true
415
+ });
416
+ throw timeoutError;
417
+ }
418
+ const canceled = hasBooleanFlag(settled, "isCanceled");
419
+ if (canceled) {
420
+ return {
421
+ success: false,
422
+ exitCode: normalizeExitCode(settled.exitCode),
423
+ totalTokensUsed: computeTotalTokens(tokenState),
424
+ filesChanged: [...filesChanged],
425
+ duration: Date.now() - startedAt,
426
+ error: "Claude execution was cancelled."
427
+ };
428
+ }
429
+ const exitCode = normalizeExitCode(settled.exitCode);
430
+ const success = exitCode === 0;
431
+ return {
432
+ success,
433
+ exitCode,
434
+ totalTokensUsed: computeTotalTokens(tokenState),
435
+ filesChanged: [...filesChanged],
436
+ duration: Date.now() - startedAt,
437
+ error: success ? void 0 : buildFailureMessage(settled.stdout, settled.stderr)
438
+ };
439
+ } catch (error) {
440
+ const normalized = normalizeUnknownError(error, params.executionId);
441
+ eventQueue.push({
442
+ type: "error",
443
+ message: normalized.message,
444
+ recoverable: normalized.severity !== "fatal"
445
+ });
446
+ eventQueue.fail(normalized);
447
+ throw normalized;
448
+ } finally {
449
+ this.runningExecutions.delete(params.executionId);
450
+ eventQueue.close();
451
+ }
452
+ })();
453
+ return {
454
+ executionId: params.executionId,
455
+ providerId: this.id,
456
+ events: eventQueue,
457
+ result: resultPromise,
458
+ pid: subprocess.pid
459
+ };
460
+ }
461
+ async estimateTokens(params) {
462
+ const contextTokens = params.contextTokens ?? params.targetFiles.length * 80 + params.targetFiles.join("\n").length;
463
+ const promptTokens = estimateTokenCount(params.prompt);
464
+ const expectedOutputTokens = params.expectedOutputTokens ?? Math.max(128, Math.ceil(promptTokens * 0.6));
465
+ const totalEstimatedTokens = contextTokens + promptTokens + expectedOutputTokens;
466
+ return {
467
+ taskId: params.taskId,
468
+ providerId: this.id,
469
+ contextTokens,
470
+ promptTokens,
471
+ expectedOutputTokens,
472
+ totalEstimatedTokens,
473
+ confidence: 0.6,
474
+ feasible: true
475
+ };
476
+ }
477
+ async abort(executionId) {
478
+ const running = this.runningExecutions.get(executionId);
479
+ if (!running) {
480
+ return;
481
+ }
482
+ running.kill("SIGTERM");
483
+ const forceKillTimer = setTimeout(() => {
484
+ running.kill("SIGKILL");
485
+ }, 5e3);
486
+ forceKillTimer.unref();
487
+ try {
488
+ await running;
489
+ } catch {
490
+ } finally {
491
+ clearTimeout(forceKillTimer);
492
+ }
493
+ }
494
+ };
495
+
496
+ // src/execution/agents/codex.adapter.ts
497
+ import { stat } from "fs/promises";
498
+ import { createInterface as createInterface2 } from "readline";
499
+ import { execa as execa2 } from "execa";
500
+ var AsyncEventQueue2 = class {
501
+ values = [];
502
+ resolvers = [];
503
+ done = false;
504
+ pendingError;
505
+ push(value) {
506
+ if (this.done) {
507
+ return;
508
+ }
509
+ const nextResolver = this.resolvers.shift();
510
+ if (nextResolver) {
511
+ nextResolver({ done: false, value });
512
+ return;
513
+ }
514
+ this.values.push(value);
515
+ }
516
+ close() {
517
+ if (this.done) {
518
+ return;
519
+ }
520
+ this.done = true;
521
+ this.flush();
522
+ }
523
+ fail(error) {
524
+ this.pendingError = error;
525
+ this.done = true;
526
+ this.flush();
527
+ }
528
+ [Symbol.asyncIterator]() {
529
+ return {
530
+ next: async () => {
531
+ if (this.values.length > 0) {
532
+ const value = this.values.shift();
533
+ if (value === void 0) {
534
+ return { done: true, value: void 0 };
535
+ }
536
+ return { done: false, value };
537
+ }
538
+ if (this.pendingError !== void 0) {
539
+ throw this.pendingError;
540
+ }
541
+ if (this.done) {
542
+ return { done: true, value: void 0 };
543
+ }
544
+ return new Promise((resolve2) => {
545
+ this.resolvers.push(resolve2);
546
+ });
547
+ }
548
+ };
549
+ }
550
+ flush() {
551
+ for (const resolve2 of this.resolvers.splice(0)) {
552
+ resolve2({ done: true, value: void 0 });
553
+ }
554
+ }
555
+ };
556
+ function isRecord2(value) {
557
+ return typeof value === "object" && value !== null;
558
+ }
559
+ function readString2(value) {
560
+ if (typeof value !== "string") {
561
+ return void 0;
562
+ }
563
+ const trimmed = value.trim();
564
+ return trimmed.length > 0 ? trimmed : void 0;
565
+ }
566
+ function readNumber2(value) {
567
+ if (typeof value !== "number" || !Number.isFinite(value)) {
568
+ return void 0;
569
+ }
570
+ return Math.max(0, Math.floor(value));
571
+ }
572
+ function parseJsonPayload2(line) {
573
+ const trimmed = line.trim();
574
+ if (trimmed.length === 0) {
575
+ return void 0;
576
+ }
577
+ try {
578
+ const parsed = JSON.parse(trimmed);
579
+ if (isRecord2(parsed)) {
580
+ return parsed;
581
+ }
582
+ } catch {
583
+ }
584
+ return void 0;
585
+ }
586
+ function parseTokenPatchFromPayload2(payload) {
587
+ const usage = isRecord2(payload.usage) ? payload.usage : void 0;
588
+ return {
589
+ inputTokens: readNumber2(
590
+ payload.inputTokens ?? payload.input_tokens ?? payload.promptTokens ?? payload.prompt_tokens ?? usage?.inputTokens ?? usage?.input_tokens ?? usage?.promptTokens ?? usage?.prompt_tokens
591
+ ),
592
+ outputTokens: readNumber2(
593
+ payload.outputTokens ?? payload.output_tokens ?? payload.completionTokens ?? payload.completion_tokens ?? usage?.outputTokens ?? usage?.output_tokens ?? usage?.completionTokens ?? usage?.completion_tokens
594
+ ),
595
+ cumulativeTokens: readNumber2(
596
+ payload.cumulativeTokens ?? payload.cumulative_tokens ?? payload.totalTokens ?? payload.total_tokens ?? usage?.cumulativeTokens ?? usage?.cumulative_tokens ?? usage?.totalTokens ?? usage?.total_tokens
597
+ )
598
+ };
599
+ }
600
+ function patchTokenState2(state, patch) {
601
+ if (patch.inputTokens === void 0 && patch.outputTokens === void 0 && patch.cumulativeTokens === void 0) {
602
+ return void 0;
603
+ }
604
+ state.inputTokens = patch.inputTokens ?? state.inputTokens;
605
+ state.outputTokens = patch.outputTokens ?? state.outputTokens;
606
+ const computedTotal = state.inputTokens + state.outputTokens;
607
+ state.cumulativeTokens = Math.max(
608
+ state.cumulativeTokens,
609
+ patch.cumulativeTokens ?? computedTotal
610
+ );
611
+ return {
612
+ type: "tokens",
613
+ inputTokens: state.inputTokens,
614
+ outputTokens: state.outputTokens,
615
+ cumulativeTokens: state.cumulativeTokens
616
+ };
617
+ }
618
+ function parseTokenEvent2(line, payload, state) {
619
+ if (payload) {
620
+ return patchTokenState2(state, parseTokenPatchFromPayload2(payload));
621
+ }
622
+ const inputMatch = line.match(/(?:input|prompt)\s*tokens?\s*[:=]\s*(\d+)/i);
623
+ const outputMatch = line.match(/(?:output|completion)\s*tokens?\s*[:=]\s*(\d+)/i);
624
+ const totalMatch = line.match(/(?:total|cumulative|used)\s*tokens?\s*[:=]\s*(\d+)/i);
625
+ return patchTokenState2(state, {
626
+ inputTokens: inputMatch ? Number.parseInt(inputMatch[1], 10) : void 0,
627
+ outputTokens: outputMatch ? Number.parseInt(outputMatch[1], 10) : void 0,
628
+ cumulativeTokens: totalMatch ? Number.parseInt(totalMatch[1], 10) : void 0
629
+ });
630
+ }
631
+ function normalizeFileAction2(value) {
632
+ if (value !== "create" && value !== "modify" && value !== "delete") {
633
+ return void 0;
634
+ }
635
+ return value;
636
+ }
637
+ function parseFileEditFromPayload2(payload) {
638
+ if (payload.type === "file_edit") {
639
+ const action = normalizeFileAction2(payload.action);
640
+ const path = readString2(payload.path);
641
+ if (action && path) {
642
+ return {
643
+ type: "file_edit",
644
+ action,
645
+ path
646
+ };
647
+ }
648
+ }
649
+ const tool = readString2(payload.tool ?? payload.tool_name ?? payload.name);
650
+ const input = isRecord2(payload.input) ? payload.input : void 0;
651
+ const inputPath = readString2(input?.path ?? input?.file_path ?? input?.filePath);
652
+ if (!tool || !inputPath) {
653
+ return void 0;
654
+ }
655
+ if (tool === "create_file") {
656
+ return { type: "file_edit", action: "create", path: inputPath };
657
+ }
658
+ if (tool === "delete_file") {
659
+ return { type: "file_edit", action: "delete", path: inputPath };
660
+ }
661
+ if (tool === "write_file" || tool === "edit_file" || tool === "replace_file") {
662
+ return { type: "file_edit", action: "modify", path: inputPath };
663
+ }
664
+ return void 0;
665
+ }
666
+ function parseToolUseFromPayload(payload) {
667
+ const tool = readString2(payload.tool ?? payload.tool_name ?? payload.name);
668
+ if (!tool) {
669
+ return void 0;
670
+ }
671
+ return {
672
+ type: "tool_use",
673
+ tool,
674
+ input: payload.input
675
+ };
676
+ }
677
+ function parseErrorFromPayload(payload) {
678
+ if (payload.type !== "error") {
679
+ return void 0;
680
+ }
681
+ return {
682
+ type: "error",
683
+ message: readString2(payload.message) ?? "Unknown Codex CLI error",
684
+ recoverable: payload.recoverable !== false
685
+ };
686
+ }
687
+ function estimateTokenCount2(text) {
688
+ if (text.length === 0) {
689
+ return 0;
690
+ }
691
+ return Math.max(1, Math.ceil(text.length / 4));
692
+ }
693
+ function normalizeUnknownError2(error, executionId) {
694
+ if (error instanceof OacError) {
695
+ return error;
696
+ }
697
+ const message = error instanceof Error ? error.message : String(error);
698
+ if (/timed out|timeout/i.test(message)) {
699
+ return executionError("AGENT_TIMEOUT", `Codex execution timed out for ${executionId}`, {
700
+ context: { executionId, message },
701
+ cause: error
702
+ });
703
+ }
704
+ if (/out of memory|ENOMEM|heap/i.test(message)) {
705
+ return executionError("AGENT_OOM", `Codex execution ran out of memory for ${executionId}`, {
706
+ context: { executionId, message },
707
+ cause: error
708
+ });
709
+ }
710
+ if (/rate.limit|429|too many requests|throttl/i.test(message)) {
711
+ return executionError("AGENT_RATE_LIMITED", `Codex execution rate-limited for ${executionId}`, {
712
+ context: { executionId, message },
713
+ cause: error
714
+ });
715
+ }
716
+ if (/network|ECONN|ENOTFOUND|EAI_AGAIN/i.test(message)) {
717
+ return new OacError(
718
+ "Codex execution failed due to network issues",
719
+ "NETWORK_ERROR",
720
+ "recoverable",
721
+ {
722
+ executionId,
723
+ message
724
+ },
725
+ error
726
+ );
727
+ }
728
+ return executionError("AGENT_EXECUTION_FAILED", `Codex execution failed for ${executionId}`, {
729
+ context: { executionId, message },
730
+ cause: error
731
+ });
732
+ }
733
+ function computeTotalTokens2(state) {
734
+ return Math.max(state.cumulativeTokens, state.inputTokens + state.outputTokens);
735
+ }
736
+ function normalizeExitCode2(value) {
737
+ if (typeof value === "number" && Number.isFinite(value)) {
738
+ return value;
739
+ }
740
+ return 1;
741
+ }
742
+ function hasBooleanFlag2(value, key) {
743
+ if (!isRecord2(value)) {
744
+ return false;
745
+ }
746
+ return value[key] === true;
747
+ }
748
+ function buildFailureMessage2(stdout, stderr) {
749
+ const trimmedStderr = stderr.trim();
750
+ if (trimmedStderr.length > 0) {
751
+ return trimmedStderr;
752
+ }
753
+ const trimmedStdout = stdout.trim();
754
+ if (trimmedStdout.length > 0) {
755
+ return trimmedStdout;
756
+ }
757
+ return "Codex CLI process exited with a non-zero status.";
758
+ }
759
+ function parseVersion(output) {
760
+ const match = output.match(/(\d+\.\d+\.\d+)/);
761
+ if (!match) {
762
+ return void 0;
763
+ }
764
+ return match[1];
765
+ }
766
+ async function estimateContextTokens(targetFiles) {
767
+ let totalBytes = 0;
768
+ for (const filePath of targetFiles) {
769
+ try {
770
+ const fileStat = await stat(filePath);
771
+ if (fileStat.isFile()) {
772
+ totalBytes += fileStat.size;
773
+ }
774
+ } catch {
775
+ }
776
+ }
777
+ return Math.ceil(totalBytes / 4);
778
+ }
779
+ var CodexAdapter = class {
780
+ id = "codex";
781
+ name = "Codex CLI";
782
+ runningExecutions = /* @__PURE__ */ new Map();
783
+ async checkAvailability() {
784
+ try {
785
+ const result = await execa2("codex", ["--version"], { reject: false });
786
+ if (result.exitCode === 0) {
787
+ const versionLine = result.stdout.trim().split("\n")[0] ?? "";
788
+ return {
789
+ available: true,
790
+ version: parseVersion(versionLine)
791
+ };
792
+ }
793
+ return {
794
+ available: false,
795
+ error: result.stderr.trim() || result.stdout.trim() || `codex --version exited with code ${result.exitCode}`
796
+ };
797
+ } catch (error) {
798
+ const message = error instanceof Error ? error.message : String(error);
799
+ return {
800
+ available: false,
801
+ error: message
802
+ };
803
+ }
804
+ }
805
+ execute(params) {
806
+ const startedAt = Date.now();
807
+ const filesChanged = /* @__PURE__ */ new Set();
808
+ const tokenState = {
809
+ inputTokens: 0,
810
+ outputTokens: 0,
811
+ cumulativeTokens: 0
812
+ };
813
+ const eventQueue = new AsyncEventQueue2();
814
+ const processEnv = {
815
+ ...Object.fromEntries(
816
+ Object.entries(process.env).filter(
817
+ (entry) => typeof entry[1] === "string"
818
+ )
819
+ ),
820
+ ...params.env,
821
+ OAC_TOKEN_BUDGET: `${params.tokenBudget}`,
822
+ OAC_ALLOW_COMMITS: `${params.allowCommits}`
823
+ };
824
+ const subprocess = execa2(
825
+ "codex",
826
+ ["exec", "--full-auto", "-C", params.workingDirectory, params.prompt],
827
+ {
828
+ cwd: params.workingDirectory,
829
+ env: processEnv,
830
+ reject: false,
831
+ timeout: params.timeoutMs
832
+ }
833
+ );
834
+ this.runningExecutions.set(params.executionId, subprocess);
835
+ const consumeStream = async (stream, streamName) => {
836
+ if (!stream) {
837
+ return;
838
+ }
839
+ const lineReader = createInterface2({
840
+ input: stream,
841
+ crlfDelay: Number.POSITIVE_INFINITY
842
+ });
843
+ for await (const line of lineReader) {
844
+ eventQueue.push({
845
+ type: "output",
846
+ content: line,
847
+ stream: streamName
848
+ });
849
+ if (streamName === "stdout") {
850
+ const payload = parseJsonPayload2(line);
851
+ const tokenEvent = parseTokenEvent2(line, payload, tokenState);
852
+ if (tokenEvent?.type === "tokens") {
853
+ eventQueue.push(tokenEvent);
854
+ }
855
+ if (payload) {
856
+ const fileEvent = parseFileEditFromPayload2(payload);
857
+ if (fileEvent) {
858
+ filesChanged.add(fileEvent.path);
859
+ eventQueue.push(fileEvent);
860
+ }
861
+ const toolEvent = parseToolUseFromPayload(payload);
862
+ if (toolEvent) {
863
+ eventQueue.push(toolEvent);
864
+ }
865
+ const errorEvent = parseErrorFromPayload(payload);
866
+ if (errorEvent) {
867
+ eventQueue.push(errorEvent);
868
+ }
869
+ }
870
+ } else if (/error|failed|exception/i.test(line)) {
871
+ eventQueue.push({
872
+ type: "error",
873
+ message: line.trim(),
874
+ recoverable: true
875
+ });
876
+ }
877
+ }
878
+ };
879
+ const stdoutDone = consumeStream(subprocess.stdout ?? void 0, "stdout");
880
+ const stderrDone = consumeStream(subprocess.stderr ?? void 0, "stderr");
881
+ const resultPromise = (async () => {
882
+ try {
883
+ const settled = await subprocess;
884
+ await Promise.all([stdoutDone, stderrDone]);
885
+ const timedOut = hasBooleanFlag2(settled, "timedOut");
886
+ if (timedOut) {
887
+ const timeoutError = executionError(
888
+ "AGENT_TIMEOUT",
889
+ `Codex execution timed out for ${params.executionId}`,
890
+ {
891
+ context: {
892
+ executionId: params.executionId,
893
+ timeoutMs: params.timeoutMs
894
+ }
895
+ }
896
+ );
897
+ eventQueue.push({
898
+ type: "error",
899
+ message: timeoutError.message,
900
+ recoverable: true
901
+ });
902
+ throw timeoutError;
903
+ }
904
+ const canceled = hasBooleanFlag2(settled, "isCanceled");
905
+ if (canceled) {
906
+ return {
907
+ success: false,
908
+ exitCode: normalizeExitCode2(settled.exitCode),
909
+ totalTokensUsed: computeTotalTokens2(tokenState),
910
+ filesChanged: [...filesChanged],
911
+ duration: Date.now() - startedAt,
912
+ error: "Codex execution was cancelled."
913
+ };
914
+ }
915
+ const exitCode = normalizeExitCode2(settled.exitCode);
916
+ const success = exitCode === 0;
917
+ return {
918
+ success,
919
+ exitCode,
920
+ totalTokensUsed: computeTotalTokens2(tokenState),
921
+ filesChanged: [...filesChanged],
922
+ duration: Date.now() - startedAt,
923
+ error: success ? void 0 : buildFailureMessage2(settled.stdout, settled.stderr)
924
+ };
925
+ } catch (error) {
926
+ const normalized = normalizeUnknownError2(error, params.executionId);
927
+ eventQueue.push({
928
+ type: "error",
929
+ message: normalized.message,
930
+ recoverable: normalized.severity !== "fatal"
931
+ });
932
+ eventQueue.fail(normalized);
933
+ throw normalized;
934
+ } finally {
935
+ this.runningExecutions.delete(params.executionId);
936
+ eventQueue.close();
937
+ }
938
+ })();
939
+ return {
940
+ executionId: params.executionId,
941
+ providerId: this.id,
942
+ events: eventQueue,
943
+ result: resultPromise,
944
+ pid: subprocess.pid
945
+ };
946
+ }
947
+ async estimateTokens(params) {
948
+ const baseTokens = params.targetFiles.length * 2e3;
949
+ const promptTokens = estimateTokenCount2(params.prompt);
950
+ const contextTokens = await estimateContextTokens(params.targetFiles);
951
+ const expectedOutputTokens = baseTokens;
952
+ const totalEstimatedTokens = contextTokens + promptTokens + expectedOutputTokens;
953
+ return {
954
+ taskId: params.taskId,
955
+ providerId: this.id,
956
+ contextTokens,
957
+ promptTokens,
958
+ expectedOutputTokens,
959
+ totalEstimatedTokens,
960
+ confidence: 0.6,
961
+ feasible: totalEstimatedTokens < 2e5
962
+ };
963
+ }
964
+ async abort(executionId) {
965
+ const running = this.runningExecutions.get(executionId);
966
+ if (!running) {
967
+ return;
968
+ }
969
+ running.kill("SIGTERM");
970
+ const forceKillTimer = setTimeout(() => {
971
+ running.kill("SIGKILL");
972
+ }, 2e3);
973
+ forceKillTimer.unref();
974
+ try {
975
+ await running;
976
+ } catch {
977
+ } finally {
978
+ clearTimeout(forceKillTimer);
979
+ }
980
+ }
981
+ };
982
+
983
+ // src/execution/sandbox.ts
984
+ import { mkdir } from "fs/promises";
985
+ import { join, resolve } from "path";
986
+ import { simpleGit } from "simple-git";
987
+ var worktreeLock = Promise.resolve();
988
+ function withWorktreeLock(fn) {
989
+ const next = worktreeLock.then(fn, fn);
990
+ worktreeLock = next.then(() => {
991
+ }, () => {
992
+ });
993
+ return next;
994
+ }
995
+ function getWorktreePath(repoPath, branchName) {
996
+ return resolve(join(repoPath, "..", ".oac-worktrees", branchName));
997
+ }
998
+ async function createSandbox(repoPath, branchName, baseBranch) {
999
+ const worktreePath = getWorktreePath(repoPath, branchName);
1000
+ const worktreeRoot = resolve(join(repoPath, "..", ".oac-worktrees"));
1001
+ const git = simpleGit(repoPath);
1002
+ await withWorktreeLock(async () => {
1003
+ await mkdir(worktreeRoot, { recursive: true });
1004
+ await git.raw(["worktree", "add", worktreePath, "-b", branchName, `origin/${baseBranch}`]);
1005
+ });
1006
+ let cleanedUp = false;
1007
+ return {
1008
+ path: worktreePath,
1009
+ branchName,
1010
+ cleanup: async () => {
1011
+ if (cleanedUp) {
1012
+ return;
1013
+ }
1014
+ cleanedUp = true;
1015
+ await withWorktreeLock(async () => {
1016
+ try {
1017
+ await git.raw(["worktree", "remove", worktreePath, "--force"]);
1018
+ } finally {
1019
+ try {
1020
+ await git.raw(["worktree", "prune"]);
1021
+ } catch {
1022
+ }
1023
+ }
1024
+ });
1025
+ }
1026
+ };
1027
+ }
1028
+
1029
+ // src/execution/worker.ts
1030
+ import { randomUUID } from "crypto";
1031
+ var DEFAULT_TOKEN_BUDGET = 5e4;
1032
+ var DEFAULT_TIMEOUT_MS = 3e5;
1033
+ function readPositiveNumber(value) {
1034
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
1035
+ return void 0;
1036
+ }
1037
+ return Math.floor(value);
1038
+ }
1039
+ function readMetadataNumber(task, key) {
1040
+ return readPositiveNumber(task.metadata[key]);
1041
+ }
1042
+ function buildTaskPrompt(task) {
1043
+ const fileList = task.targetFiles.length > 0 ? task.targetFiles.join("\n") : "(none provided)";
1044
+ const lines = [
1045
+ "You are implementing a scoped repository contribution task.",
1046
+ `Task ID: ${task.id}`,
1047
+ `Title: ${task.title}`,
1048
+ `Source: ${task.source}`,
1049
+ `Priority: ${task.priority}`,
1050
+ `Complexity: ${task.complexity}`,
1051
+ `Execution mode: ${task.executionMode}`
1052
+ ];
1053
+ if (task.linkedIssue) {
1054
+ lines.push(
1055
+ "",
1056
+ `GitHub Issue #${task.linkedIssue.number}: ${task.linkedIssue.url}`,
1057
+ task.linkedIssue.labels.length > 0 ? `Labels: ${task.linkedIssue.labels.join(", ")}` : "",
1058
+ "Resolve this issue completely. Read the issue description carefully and implement the fix."
1059
+ );
1060
+ }
1061
+ lines.push(
1062
+ "",
1063
+ "Description:",
1064
+ task.description,
1065
+ "",
1066
+ "Target files:",
1067
+ fileList,
1068
+ "",
1069
+ "Apply minimal, safe changes and ensure the repository remains buildable."
1070
+ );
1071
+ return lines.filter((l) => l !== void 0).join("\n");
1072
+ }
1073
+ function stageFromEvent(event) {
1074
+ switch (event.type) {
1075
+ case "output":
1076
+ return event.stream;
1077
+ case "tokens":
1078
+ return "tokens";
1079
+ case "file_edit":
1080
+ return `file:${event.action}`;
1081
+ case "tool_use":
1082
+ return `tool:${event.tool}`;
1083
+ case "error":
1084
+ return event.recoverable ? "agent-warning" : "agent-error";
1085
+ default:
1086
+ return "running";
1087
+ }
1088
+ }
1089
+ function mergeExecutionResult(result, observedTokens, observedFiles, startedAt) {
1090
+ for (const changedFile of result.filesChanged) {
1091
+ observedFiles.add(changedFile);
1092
+ }
1093
+ return {
1094
+ success: result.success,
1095
+ exitCode: result.exitCode,
1096
+ totalTokensUsed: Math.max(result.totalTokensUsed, observedTokens),
1097
+ filesChanged: [...observedFiles],
1098
+ duration: result.duration > 0 ? result.duration : Date.now() - startedAt,
1099
+ error: result.error
1100
+ };
1101
+ }
1102
+ function normalizeExecutionError(error, task, executionId) {
1103
+ if (error instanceof OacError) {
1104
+ return error;
1105
+ }
1106
+ const message = error instanceof Error ? error.message : String(error);
1107
+ if (/timed out|timeout/i.test(message)) {
1108
+ return executionError("AGENT_TIMEOUT", `Task ${task.id} timed out during execution.`, {
1109
+ context: {
1110
+ taskId: task.id,
1111
+ executionId,
1112
+ message
1113
+ },
1114
+ cause: error
1115
+ });
1116
+ }
1117
+ return executionError("AGENT_EXECUTION_FAILED", `Task ${task.id} failed during execution.`, {
1118
+ context: {
1119
+ taskId: task.id,
1120
+ executionId,
1121
+ message
1122
+ },
1123
+ cause: error
1124
+ });
1125
+ }
1126
+ async function executeTask(agent, task, sandbox, eventBus, options = {}) {
1127
+ const executionId = options.executionId ?? randomUUID();
1128
+ const tokenBudget = options.tokenBudget ?? readMetadataNumber(task, "tokenBudget") ?? DEFAULT_TOKEN_BUDGET;
1129
+ const timeoutMs = options.timeoutMs ?? readMetadataNumber(task, "timeoutMs") ?? DEFAULT_TIMEOUT_MS;
1130
+ const allowCommits = options.allowCommits ?? true;
1131
+ const startedAt = Date.now();
1132
+ let observedTokens = 0;
1133
+ const observedFiles = /* @__PURE__ */ new Set();
1134
+ const execution = agent.execute({
1135
+ executionId,
1136
+ workingDirectory: sandbox.path,
1137
+ prompt: buildTaskPrompt(task),
1138
+ targetFiles: task.targetFiles,
1139
+ tokenBudget,
1140
+ allowCommits,
1141
+ timeoutMs
1142
+ });
1143
+ const streamPromise = (async () => {
1144
+ for await (const event of execution.events) {
1145
+ if (event.type === "tokens") {
1146
+ observedTokens = Math.max(observedTokens, event.cumulativeTokens);
1147
+ }
1148
+ if (event.type === "file_edit") {
1149
+ observedFiles.add(event.path);
1150
+ }
1151
+ eventBus.emit("execution:progress", {
1152
+ jobId: executionId,
1153
+ tokensUsed: observedTokens,
1154
+ stage: stageFromEvent(event)
1155
+ });
1156
+ }
1157
+ })();
1158
+ try {
1159
+ const result = await execution.result;
1160
+ await streamPromise;
1161
+ return mergeExecutionResult(result, observedTokens, observedFiles, startedAt);
1162
+ } catch (error) {
1163
+ try {
1164
+ await streamPromise;
1165
+ } catch {
1166
+ }
1167
+ throw normalizeExecutionError(error, task, executionId);
1168
+ }
1169
+ }
1170
+
1171
+ // src/execution/engine.ts
1172
+ import { randomUUID as randomUUID2 } from "crypto";
1173
+ import { setTimeout as delay } from "timers/promises";
1174
+ import PQueue from "p-queue";
1175
+ var DEFAULT_CONCURRENCY = 2;
1176
+ var DEFAULT_MAX_ATTEMPTS = 2;
1177
+ var DEFAULT_TIMEOUT_MS2 = 3e5;
1178
+ var DEFAULT_TOKEN_BUDGET2 = 5e4;
1179
+ function isRecord3(value) {
1180
+ return typeof value === "object" && value !== null;
1181
+ }
1182
+ function toErrorMessage(error) {
1183
+ if (error instanceof Error) {
1184
+ return error.message;
1185
+ }
1186
+ return String(error);
1187
+ }
1188
+ function sanitizeBranchSegment(value) {
1189
+ const sanitized = value.toLowerCase().replace(/[^a-z0-9/_-]+/g, "-").replace(/-+/g, "-").replace(/^[-/]+|[-/]+$/g, "");
1190
+ return sanitized || "task";
1191
+ }
1192
+ function isTransientError(error) {
1193
+ return error.code === "AGENT_TIMEOUT" || error.code === "AGENT_OOM" || error.code === "AGENT_RATE_LIMITED" || error.code === "NETWORK_ERROR" || error.code === "GIT_LOCK_FAILED";
1194
+ }
1195
+ var ExecutionEngine = class {
1196
+ constructor(agents, eventBus, config = {}) {
1197
+ this.agents = agents;
1198
+ this.eventBus = eventBus;
1199
+ if (agents.length === 0) {
1200
+ throw executionError(
1201
+ "AGENT_NOT_AVAILABLE",
1202
+ "ExecutionEngine requires at least one agent provider"
1203
+ );
1204
+ }
1205
+ this.concurrency = Math.max(1, config.concurrency ?? DEFAULT_CONCURRENCY);
1206
+ this.maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
1207
+ this.repoPath = config.repoPath ?? process.cwd();
1208
+ this.baseBranch = config.baseBranch ?? "main";
1209
+ this.branchPrefix = config.branchPrefix ?? "oac";
1210
+ this.taskTimeoutMs = Math.max(1, config.taskTimeoutMs ?? DEFAULT_TIMEOUT_MS2);
1211
+ this.defaultTokenBudget = Math.max(1, config.defaultTokenBudget ?? DEFAULT_TOKEN_BUDGET2);
1212
+ this.queue = new PQueue({
1213
+ concurrency: this.concurrency,
1214
+ autoStart: false
1215
+ });
1216
+ }
1217
+ queue;
1218
+ jobs = /* @__PURE__ */ new Map();
1219
+ activeJobs = /* @__PURE__ */ new Map();
1220
+ concurrency;
1221
+ maxAttempts;
1222
+ repoPath;
1223
+ baseBranch;
1224
+ branchPrefix;
1225
+ taskTimeoutMs;
1226
+ defaultTokenBudget;
1227
+ aborted = false;
1228
+ nextAgentIndex = 0;
1229
+ enqueue(plan) {
1230
+ const enqueuedJobs = [];
1231
+ for (const { task, estimate } of plan.selectedTasks) {
1232
+ const job = {
1233
+ id: randomUUID2(),
1234
+ task,
1235
+ estimate,
1236
+ status: "queued",
1237
+ attempts: 0,
1238
+ maxAttempts: this.maxAttempts,
1239
+ createdAt: Date.now()
1240
+ };
1241
+ this.jobs.set(job.id, job);
1242
+ enqueuedJobs.push(job);
1243
+ this.schedule(job);
1244
+ }
1245
+ return enqueuedJobs;
1246
+ }
1247
+ async run() {
1248
+ this.aborted = false;
1249
+ this.queue.start();
1250
+ await this.queue.onIdle();
1251
+ return this.buildRunResult();
1252
+ }
1253
+ async abort() {
1254
+ this.aborted = true;
1255
+ this.queue.pause();
1256
+ this.queue.clear();
1257
+ const abortError = executionError("AGENT_EXECUTION_FAILED", "Execution aborted by user.");
1258
+ for (const job of this.jobs.values()) {
1259
+ if (job.status === "queued" || job.status === "retrying") {
1260
+ job.status = "aborted";
1261
+ job.completedAt = Date.now();
1262
+ job.error = abortError;
1263
+ }
1264
+ }
1265
+ await Promise.all(
1266
+ [...this.activeJobs.values()].map(async ({ job, agent }) => {
1267
+ job.status = "aborted";
1268
+ job.completedAt = Date.now();
1269
+ job.error = abortError;
1270
+ this.eventBus.emit("execution:failed", {
1271
+ jobId: job.id,
1272
+ error: abortError
1273
+ });
1274
+ try {
1275
+ await agent.abort(job.id);
1276
+ } catch {
1277
+ }
1278
+ })
1279
+ );
1280
+ }
1281
+ schedule(job, delayMs = 0) {
1282
+ void this.queue.add(
1283
+ async () => {
1284
+ if (delayMs > 0) {
1285
+ await delay(delayMs);
1286
+ }
1287
+ await this.runJob(job);
1288
+ },
1289
+ { priority: job.task.priority }
1290
+ ).catch((error) => {
1291
+ const normalized = this.normalizeError(error, job);
1292
+ job.status = "failed";
1293
+ job.completedAt = Date.now();
1294
+ job.error = normalized;
1295
+ this.eventBus.emit("execution:failed", {
1296
+ jobId: job.id,
1297
+ error: normalized
1298
+ });
1299
+ });
1300
+ }
1301
+ async runJob(job) {
1302
+ if (this.aborted || job.status === "aborted") {
1303
+ return;
1304
+ }
1305
+ job.attempts += 1;
1306
+ job.status = "running";
1307
+ job.startedAt ??= Date.now();
1308
+ const agent = this.selectAgent();
1309
+ job.workerId = agent.id;
1310
+ this.activeJobs.set(job.id, { job, agent });
1311
+ this.eventBus.emit("execution:started", {
1312
+ jobId: job.id,
1313
+ task: job.task,
1314
+ agent: agent.id
1315
+ });
1316
+ let sandboxCleanup;
1317
+ try {
1318
+ const branchName = this.createBranchName(job);
1319
+ const sandbox = await createSandbox(this.repoPath, branchName, this.baseBranch);
1320
+ sandboxCleanup = sandbox.cleanup;
1321
+ const result = await executeTask(agent, job.task, sandbox, this.eventBus, {
1322
+ executionId: job.id,
1323
+ tokenBudget: job.estimate.totalEstimatedTokens > 0 ? job.estimate.totalEstimatedTokens : this.defaultTokenBudget,
1324
+ timeoutMs: this.taskTimeoutMs,
1325
+ allowCommits: true
1326
+ });
1327
+ job.result = result;
1328
+ job.completedAt = Date.now();
1329
+ if (result.success) {
1330
+ job.status = "completed";
1331
+ this.eventBus.emit("execution:completed", {
1332
+ jobId: job.id,
1333
+ result
1334
+ });
1335
+ return;
1336
+ }
1337
+ const failure = executionError(
1338
+ "AGENT_EXECUTION_FAILED",
1339
+ result.error ?? `Task ${job.task.id} exited with code ${result.exitCode}.`,
1340
+ {
1341
+ context: {
1342
+ taskId: job.task.id,
1343
+ jobId: job.id,
1344
+ exitCode: result.exitCode,
1345
+ attempt: job.attempts
1346
+ }
1347
+ }
1348
+ );
1349
+ await this.handleFailure(job, failure);
1350
+ } catch (error) {
1351
+ const normalized = this.normalizeError(error, job);
1352
+ await this.handleFailure(job, normalized);
1353
+ } finally {
1354
+ this.activeJobs.delete(job.id);
1355
+ if (sandboxCleanup) {
1356
+ try {
1357
+ await sandboxCleanup();
1358
+ } catch (cleanupError) {
1359
+ const cleanupMessage = toErrorMessage(cleanupError);
1360
+ job.error ??= executionError(
1361
+ "AGENT_EXECUTION_FAILED",
1362
+ `Sandbox cleanup failed for job ${job.id}`,
1363
+ {
1364
+ context: {
1365
+ jobId: job.id,
1366
+ cleanupError: cleanupMessage
1367
+ },
1368
+ cause: cleanupError
1369
+ }
1370
+ );
1371
+ }
1372
+ }
1373
+ }
1374
+ }
1375
+ async handleFailure(job, error) {
1376
+ job.error = error;
1377
+ if (this.aborted || job.status === "aborted") {
1378
+ job.status = "aborted";
1379
+ job.completedAt = Date.now();
1380
+ return;
1381
+ }
1382
+ if (job.attempts < job.maxAttempts && isTransientError(error)) {
1383
+ job.status = "retrying";
1384
+ const retryDelay = error.code === "AGENT_RATE_LIMITED" ? Math.min(6e4, 1e4 * 2 ** (job.attempts - 1)) : Math.min(5e3, job.attempts * 1e3);
1385
+ this.schedule(job, retryDelay);
1386
+ return;
1387
+ }
1388
+ job.status = "failed";
1389
+ job.completedAt = Date.now();
1390
+ this.eventBus.emit("execution:failed", {
1391
+ jobId: job.id,
1392
+ error
1393
+ });
1394
+ }
1395
+ selectAgent() {
1396
+ const agent = this.agents[this.nextAgentIndex % this.agents.length];
1397
+ this.nextAgentIndex = (this.nextAgentIndex + 1) % this.agents.length;
1398
+ return agent;
1399
+ }
1400
+ createBranchName(job) {
1401
+ const dateSegment = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10).replaceAll("-", "");
1402
+ const taskSegment = sanitizeBranchSegment(job.task.id);
1403
+ return `${this.branchPrefix}/${dateSegment}/${taskSegment}-${job.id.slice(0, 8)}-a${job.attempts}`;
1404
+ }
1405
+ normalizeError(error, job) {
1406
+ if (error instanceof OacError) {
1407
+ return error;
1408
+ }
1409
+ const message = toErrorMessage(error);
1410
+ if (/timed out|timeout/i.test(message)) {
1411
+ return executionError("AGENT_TIMEOUT", `Job ${job.id} timed out.`, {
1412
+ context: {
1413
+ jobId: job.id,
1414
+ taskId: job.task.id,
1415
+ message,
1416
+ attempt: job.attempts
1417
+ },
1418
+ cause: error
1419
+ });
1420
+ }
1421
+ if (/out of memory|ENOMEM|heap/i.test(message)) {
1422
+ return executionError("AGENT_OOM", `Job ${job.id} ran out of memory.`, {
1423
+ context: {
1424
+ jobId: job.id,
1425
+ taskId: job.task.id,
1426
+ message,
1427
+ attempt: job.attempts
1428
+ },
1429
+ cause: error
1430
+ });
1431
+ }
1432
+ if (/network|ECONN|ENOTFOUND|EAI_AGAIN/i.test(message)) {
1433
+ return new OacError(
1434
+ `Job ${job.id} failed due to a network error.`,
1435
+ "NETWORK_ERROR",
1436
+ "recoverable",
1437
+ {
1438
+ jobId: job.id,
1439
+ taskId: job.task.id,
1440
+ message,
1441
+ attempt: job.attempts
1442
+ },
1443
+ error
1444
+ );
1445
+ }
1446
+ if (/index\.lock|cannot lock ref|Unable to create '.+?\.git\/index\.lock'/i.test(message)) {
1447
+ return new OacError(
1448
+ `Job ${job.id} failed due to a git lock conflict.`,
1449
+ "GIT_LOCK_FAILED",
1450
+ "recoverable",
1451
+ {
1452
+ jobId: job.id,
1453
+ taskId: job.task.id,
1454
+ message,
1455
+ attempt: job.attempts
1456
+ },
1457
+ error
1458
+ );
1459
+ }
1460
+ if (isRecord3(error) && error.name === "AbortError") {
1461
+ return executionError("AGENT_EXECUTION_FAILED", `Job ${job.id} was aborted.`, {
1462
+ context: {
1463
+ jobId: job.id,
1464
+ taskId: job.task.id,
1465
+ attempt: job.attempts
1466
+ },
1467
+ cause: error
1468
+ });
1469
+ }
1470
+ return executionError("AGENT_EXECUTION_FAILED", `Job ${job.id} failed unexpectedly.`, {
1471
+ context: {
1472
+ jobId: job.id,
1473
+ taskId: job.task.id,
1474
+ message,
1475
+ attempt: job.attempts
1476
+ },
1477
+ cause: error
1478
+ });
1479
+ }
1480
+ buildRunResult() {
1481
+ const jobs = [...this.jobs.values()];
1482
+ return {
1483
+ jobs,
1484
+ completed: jobs.filter((job) => job.status === "completed"),
1485
+ failed: jobs.filter((job) => job.status === "failed"),
1486
+ aborted: jobs.filter((job) => job.status === "aborted")
1487
+ };
1488
+ }
1489
+ };
1490
+
1491
+ export {
1492
+ ClaudeCodeAdapter,
1493
+ CodexAdapter,
1494
+ createSandbox,
1495
+ executeTask,
1496
+ isTransientError,
1497
+ ExecutionEngine
1498
+ };
1499
+ //# sourceMappingURL=chunk-NZEI4RPP.js.map