vibeman 0.0.3 → 0.0.6

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 (231) hide show
  1. package/dist/api.js +49 -0
  2. package/dist/cli.js +135 -0
  3. package/dist/ui/index-gnk6rhxs.js +9 -0
  4. package/dist/ui/index.html +10 -0
  5. package/dist/ui/index.js +2 -0
  6. package/package.json +10 -80
  7. package/README.md +0 -12
  8. package/dist/index.js +0 -114
  9. package/dist/runtime/api/.tsbuildinfo +0 -1
  10. package/dist/runtime/api/agent/agent-service.d.ts +0 -225
  11. package/dist/runtime/api/agent/agent-service.js +0 -904
  12. package/dist/runtime/api/agent/ai-providers/claude-code-adapter.d.ts +0 -61
  13. package/dist/runtime/api/agent/ai-providers/claude-code-adapter.js +0 -362
  14. package/dist/runtime/api/agent/ai-providers/codex-cli-provider.d.ts +0 -36
  15. package/dist/runtime/api/agent/ai-providers/codex-cli-provider.js +0 -347
  16. package/dist/runtime/api/agent/ai-providers/index.d.ts +0 -9
  17. package/dist/runtime/api/agent/ai-providers/index.js +0 -7
  18. package/dist/runtime/api/agent/ai-providers/types.d.ts +0 -182
  19. package/dist/runtime/api/agent/ai-providers/types.js +0 -5
  20. package/dist/runtime/api/agent/codex-cli-provider.test.d.ts +0 -1
  21. package/dist/runtime/api/agent/codex-cli-provider.test.js +0 -170
  22. package/dist/runtime/api/agent/core-agent-service.d.ts +0 -119
  23. package/dist/runtime/api/agent/core-agent-service.js +0 -267
  24. package/dist/runtime/api/agent/parsers.d.ts +0 -16
  25. package/dist/runtime/api/agent/parsers.js +0 -308
  26. package/dist/runtime/api/agent/prompt-service.d.ts +0 -30
  27. package/dist/runtime/api/agent/prompt-service.js +0 -449
  28. package/dist/runtime/api/agent/prompt-service.test.d.ts +0 -1
  29. package/dist/runtime/api/agent/prompt-service.test.js +0 -230
  30. package/dist/runtime/api/agent/routing-policy.d.ts +0 -171
  31. package/dist/runtime/api/agent/routing-policy.js +0 -196
  32. package/dist/runtime/api/agent/routing-policy.test.d.ts +0 -1
  33. package/dist/runtime/api/agent/routing-policy.test.js +0 -63
  34. package/dist/runtime/api/api/router-helpers.d.ts +0 -32
  35. package/dist/runtime/api/api/router-helpers.js +0 -31
  36. package/dist/runtime/api/api/routers/ai.d.ts +0 -200
  37. package/dist/runtime/api/api/routers/ai.js +0 -396
  38. package/dist/runtime/api/api/routers/executions.d.ts +0 -98
  39. package/dist/runtime/api/api/routers/executions.js +0 -94
  40. package/dist/runtime/api/api/routers/git.d.ts +0 -45
  41. package/dist/runtime/api/api/routers/git.js +0 -35
  42. package/dist/runtime/api/api/routers/provider-config.d.ts +0 -165
  43. package/dist/runtime/api/api/routers/provider-config.js +0 -252
  44. package/dist/runtime/api/api/routers/settings.d.ts +0 -139
  45. package/dist/runtime/api/api/routers/settings.js +0 -113
  46. package/dist/runtime/api/api/routers/tasks.d.ts +0 -141
  47. package/dist/runtime/api/api/routers/tasks.js +0 -238
  48. package/dist/runtime/api/api/routers/workflows.d.ts +0 -275
  49. package/dist/runtime/api/api/routers/workflows.js +0 -311
  50. package/dist/runtime/api/api/routers/worktrees.d.ts +0 -101
  51. package/dist/runtime/api/api/routers/worktrees.js +0 -80
  52. package/dist/runtime/api/api/trpc.d.ts +0 -118
  53. package/dist/runtime/api/api/trpc.js +0 -34
  54. package/dist/runtime/api/index.d.ts +0 -9
  55. package/dist/runtime/api/index.js +0 -117
  56. package/dist/runtime/api/lib/id-generator.d.ts +0 -70
  57. package/dist/runtime/api/lib/id-generator.js +0 -123
  58. package/dist/runtime/api/lib/local-config.d.ts +0 -245
  59. package/dist/runtime/api/lib/local-config.js +0 -288
  60. package/dist/runtime/api/lib/logger.d.ts +0 -11
  61. package/dist/runtime/api/lib/logger.js +0 -188
  62. package/dist/runtime/api/lib/provider-detection.d.ts +0 -59
  63. package/dist/runtime/api/lib/provider-detection.js +0 -244
  64. package/dist/runtime/api/lib/server/agent-service-singleton.d.ts +0 -6
  65. package/dist/runtime/api/lib/server/agent-service-singleton.js +0 -27
  66. package/dist/runtime/api/lib/server/bootstrap.d.ts +0 -38
  67. package/dist/runtime/api/lib/server/bootstrap.js +0 -197
  68. package/dist/runtime/api/lib/server/git-service-singleton.d.ts +0 -6
  69. package/dist/runtime/api/lib/server/git-service-singleton.js +0 -47
  70. package/dist/runtime/api/lib/server/project-root.d.ts +0 -2
  71. package/dist/runtime/api/lib/server/project-root.js +0 -61
  72. package/dist/runtime/api/lib/server/task-service-singleton.d.ts +0 -7
  73. package/dist/runtime/api/lib/server/task-service-singleton.js +0 -58
  74. package/dist/runtime/api/lib/server/vibing-orchestrator-singleton.d.ts +0 -7
  75. package/dist/runtime/api/lib/server/vibing-orchestrator-singleton.js +0 -57
  76. package/dist/runtime/api/lib/trpc/client.d.ts +0 -1
  77. package/dist/runtime/api/lib/trpc/client.js +0 -5
  78. package/dist/runtime/api/lib/trpc/server.d.ts +0 -935
  79. package/dist/runtime/api/lib/trpc/server.js +0 -11
  80. package/dist/runtime/api/lib/trpc/ws-server.d.ts +0 -8
  81. package/dist/runtime/api/lib/trpc/ws-server.js +0 -33
  82. package/dist/runtime/api/persistence/database-service.d.ts +0 -14
  83. package/dist/runtime/api/persistence/database-service.js +0 -74
  84. package/dist/runtime/api/persistence/execution-log-persistence.d.ts +0 -90
  85. package/dist/runtime/api/persistence/execution-log-persistence.js +0 -410
  86. package/dist/runtime/api/persistence/execution-log-persistence.test.d.ts +0 -1
  87. package/dist/runtime/api/persistence/execution-log-persistence.test.js +0 -170
  88. package/dist/runtime/api/router.d.ts +0 -938
  89. package/dist/runtime/api/router.js +0 -34
  90. package/dist/runtime/api/settings-service.d.ts +0 -110
  91. package/dist/runtime/api/settings-service.js +0 -661
  92. package/dist/runtime/api/tasks/file-watcher.d.ts +0 -23
  93. package/dist/runtime/api/tasks/file-watcher.js +0 -88
  94. package/dist/runtime/api/tasks/task-file-parser.d.ts +0 -13
  95. package/dist/runtime/api/tasks/task-file-parser.js +0 -161
  96. package/dist/runtime/api/tasks/task-service.d.ts +0 -36
  97. package/dist/runtime/api/tasks/task-service.js +0 -173
  98. package/dist/runtime/api/types/index.d.ts +0 -186
  99. package/dist/runtime/api/types/index.js +0 -1
  100. package/dist/runtime/api/types/settings.d.ts +0 -94
  101. package/dist/runtime/api/types/settings.js +0 -2
  102. package/dist/runtime/api/types.d.ts +0 -2
  103. package/dist/runtime/api/types.js +0 -1
  104. package/dist/runtime/api/utils/env.d.ts +0 -6
  105. package/dist/runtime/api/utils/env.js +0 -12
  106. package/dist/runtime/api/utils/stripNextEnv.d.ts +0 -7
  107. package/dist/runtime/api/utils/stripNextEnv.js +0 -22
  108. package/dist/runtime/api/utils/title-slug.d.ts +0 -6
  109. package/dist/runtime/api/utils/title-slug.js +0 -77
  110. package/dist/runtime/api/utils/url.d.ts +0 -2
  111. package/dist/runtime/api/utils/url.js +0 -19
  112. package/dist/runtime/api/vcs/git-history-service.d.ts +0 -57
  113. package/dist/runtime/api/vcs/git-history-service.js +0 -228
  114. package/dist/runtime/api/vcs/git-service.d.ts +0 -127
  115. package/dist/runtime/api/vcs/git-service.js +0 -284
  116. package/dist/runtime/api/vcs/worktree-service.d.ts +0 -93
  117. package/dist/runtime/api/vcs/worktree-service.js +0 -506
  118. package/dist/runtime/api/vcs/worktree-service.test.d.ts +0 -1
  119. package/dist/runtime/api/vcs/worktree-service.test.js +0 -20
  120. package/dist/runtime/api/workflows/quality-pipeline.d.ts +0 -58
  121. package/dist/runtime/api/workflows/quality-pipeline.js +0 -400
  122. package/dist/runtime/api/workflows/vibing-orchestrator.d.ts +0 -318
  123. package/dist/runtime/api/workflows/vibing-orchestrator.js +0 -1891
  124. package/dist/runtime/web/.next/BUILD_ID +0 -1
  125. package/dist/runtime/web/.next/app-build-manifest.json +0 -66
  126. package/dist/runtime/web/.next/app-path-routes-manifest.json +0 -8
  127. package/dist/runtime/web/.next/build-manifest.json +0 -33
  128. package/dist/runtime/web/.next/package.json +0 -1
  129. package/dist/runtime/web/.next/prerender-manifest.json +0 -61
  130. package/dist/runtime/web/.next/react-loadable-manifest.json +0 -39
  131. package/dist/runtime/web/.next/required-server-files.json +0 -334
  132. package/dist/runtime/web/.next/routes-manifest.json +0 -70
  133. package/dist/runtime/web/.next/server/app/.vibeman/assets/images/[...path]/route.js +0 -1
  134. package/dist/runtime/web/.next/server/app/.vibeman/assets/images/[...path]/route.js.nft.json +0 -1
  135. package/dist/runtime/web/.next/server/app/.vibeman/assets/images/[...path]/route_client-reference-manifest.js +0 -1
  136. package/dist/runtime/web/.next/server/app/_not-found/page.js +0 -2
  137. package/dist/runtime/web/.next/server/app/_not-found/page.js.nft.json +0 -1
  138. package/dist/runtime/web/.next/server/app/_not-found/page_client-reference-manifest.js +0 -1
  139. package/dist/runtime/web/.next/server/app/_not-found.html +0 -7
  140. package/dist/runtime/web/.next/server/app/_not-found.meta +0 -8
  141. package/dist/runtime/web/.next/server/app/_not-found.rsc +0 -22
  142. package/dist/runtime/web/.next/server/app/api/health/route.js +0 -1
  143. package/dist/runtime/web/.next/server/app/api/health/route.js.nft.json +0 -1
  144. package/dist/runtime/web/.next/server/app/api/health/route_client-reference-manifest.js +0 -1
  145. package/dist/runtime/web/.next/server/app/api/images/[...path]/route.js +0 -1
  146. package/dist/runtime/web/.next/server/app/api/images/[...path]/route.js.nft.json +0 -1
  147. package/dist/runtime/web/.next/server/app/api/images/[...path]/route_client-reference-manifest.js +0 -1
  148. package/dist/runtime/web/.next/server/app/api/upload/route.js +0 -1
  149. package/dist/runtime/web/.next/server/app/api/upload/route.js.nft.json +0 -1
  150. package/dist/runtime/web/.next/server/app/api/upload/route_client-reference-manifest.js +0 -1
  151. package/dist/runtime/web/.next/server/app/index.html +0 -7
  152. package/dist/runtime/web/.next/server/app/index.meta +0 -7
  153. package/dist/runtime/web/.next/server/app/index.rsc +0 -27
  154. package/dist/runtime/web/.next/server/app/page.js +0 -147
  155. package/dist/runtime/web/.next/server/app/page.js.nft.json +0 -1
  156. package/dist/runtime/web/.next/server/app/page_client-reference-manifest.js +0 -1
  157. package/dist/runtime/web/.next/server/app-paths-manifest.json +0 -8
  158. package/dist/runtime/web/.next/server/chunks/217.js +0 -1
  159. package/dist/runtime/web/.next/server/chunks/383.js +0 -6
  160. package/dist/runtime/web/.next/server/chunks/458.js +0 -1
  161. package/dist/runtime/web/.next/server/chunks/576.js +0 -18
  162. package/dist/runtime/web/.next/server/chunks/635.js +0 -22
  163. package/dist/runtime/web/.next/server/chunks/761.js +0 -1
  164. package/dist/runtime/web/.next/server/chunks/777.js +0 -3
  165. package/dist/runtime/web/.next/server/chunks/825.js +0 -1
  166. package/dist/runtime/web/.next/server/chunks/838.js +0 -1
  167. package/dist/runtime/web/.next/server/chunks/973.js +0 -15
  168. package/dist/runtime/web/.next/server/functions-config-manifest.json +0 -4
  169. package/dist/runtime/web/.next/server/middleware-build-manifest.js +0 -1
  170. package/dist/runtime/web/.next/server/middleware-manifest.json +0 -6
  171. package/dist/runtime/web/.next/server/middleware-react-loadable-manifest.js +0 -1
  172. package/dist/runtime/web/.next/server/next-font-manifest.js +0 -1
  173. package/dist/runtime/web/.next/server/next-font-manifest.json +0 -1
  174. package/dist/runtime/web/.next/server/pages/404.html +0 -7
  175. package/dist/runtime/web/.next/server/pages/500.html +0 -1
  176. package/dist/runtime/web/.next/server/pages/_app.js +0 -1
  177. package/dist/runtime/web/.next/server/pages/_app.js.nft.json +0 -1
  178. package/dist/runtime/web/.next/server/pages/_document.js +0 -1
  179. package/dist/runtime/web/.next/server/pages/_document.js.nft.json +0 -1
  180. package/dist/runtime/web/.next/server/pages/_error.js +0 -19
  181. package/dist/runtime/web/.next/server/pages/_error.js.nft.json +0 -1
  182. package/dist/runtime/web/.next/server/pages-manifest.json +0 -6
  183. package/dist/runtime/web/.next/server/server-reference-manifest.js +0 -1
  184. package/dist/runtime/web/.next/server/server-reference-manifest.json +0 -1
  185. package/dist/runtime/web/.next/server/webpack-runtime.js +0 -1
  186. package/dist/runtime/web/.next/static/5_15u1WQCxN1_eHZpldCv/_buildManifest.js +0 -1
  187. package/dist/runtime/web/.next/static/5_15u1WQCxN1_eHZpldCv/_ssgManifest.js +0 -1
  188. package/dist/runtime/web/.next/static/chunks/18-15c10d3288afef2e.js +0 -1
  189. package/dist/runtime/web/.next/static/chunks/1c0ca389.537bbe362e3ffbd9.js +0 -3
  190. package/dist/runtime/web/.next/static/chunks/22747d63-ad5da0c19f4cfe41.js +0 -71
  191. package/dist/runtime/web/.next/static/chunks/355.056c2645878a799a.js +0 -1
  192. package/dist/runtime/web/.next/static/chunks/420.a5ccf151c9e2b2f1.js +0 -1
  193. package/dist/runtime/web/.next/static/chunks/439.1be0c6242fd248d5.js +0 -15
  194. package/dist/runtime/web/.next/static/chunks/440.c52e7c0f797e22b2.js +0 -1
  195. package/dist/runtime/web/.next/static/chunks/575-e2478287c27da87b.js +0 -1
  196. package/dist/runtime/web/.next/static/chunks/691.920d88c115087314.js +0 -1
  197. package/dist/runtime/web/.next/static/chunks/765-e838910065b50c3d.js +0 -1
  198. package/dist/runtime/web/.next/static/chunks/823-6f371a6e829adbba.js +0 -63
  199. package/dist/runtime/web/.next/static/chunks/87c73c54-09e1ba5c70e60a51.js +0 -1
  200. package/dist/runtime/web/.next/static/chunks/891cff7f.0f71fc028f87e683.js +0 -1
  201. package/dist/runtime/web/.next/static/chunks/8bb4d8db-3e2aa02b0a2384b9.js +0 -1
  202. package/dist/runtime/web/.next/static/chunks/9af238c7-271a911d4e99ab18.js +0 -1
  203. package/dist/runtime/web/.next/static/chunks/app/.vibeman/assets/images/[...path]/route-751c9265a65409e5.js +0 -1
  204. package/dist/runtime/web/.next/static/chunks/app/_not-found/page-1cb74d1cba27d0ab.js +0 -1
  205. package/dist/runtime/web/.next/static/chunks/app/api/health/route-751c9265a65409e5.js +0 -1
  206. package/dist/runtime/web/.next/static/chunks/app/api/images/[...path]/route-751c9265a65409e5.js +0 -1
  207. package/dist/runtime/web/.next/static/chunks/app/api/upload/route-751c9265a65409e5.js +0 -1
  208. package/dist/runtime/web/.next/static/chunks/app/layout-8435322f09fd0975.js +0 -1
  209. package/dist/runtime/web/.next/static/chunks/app/page-9fe7d75095b4ccec.js +0 -1
  210. package/dist/runtime/web/.next/static/chunks/cac567b0-5b77dd12911823cd.js +0 -1
  211. package/dist/runtime/web/.next/static/chunks/framework-2518f1345b5b2806.js +0 -1
  212. package/dist/runtime/web/.next/static/chunks/main-17665e5e39de9a8a.js +0 -1
  213. package/dist/runtime/web/.next/static/chunks/main-app-c0b0f5ba4f7f9d75.js +0 -1
  214. package/dist/runtime/web/.next/static/chunks/pages/_app-d6f6b3bbc3d81ee1.js +0 -1
  215. package/dist/runtime/web/.next/static/chunks/pages/_error-75a96cf1997cc3b9.js +0 -1
  216. package/dist/runtime/web/.next/static/chunks/polyfills-42372ed130431b0a.js +0 -1
  217. package/dist/runtime/web/.next/static/chunks/webpack-c8de37305b4635cf.js +0 -1
  218. package/dist/runtime/web/.next/static/css/08c950681f1a9a92.css +0 -1
  219. package/dist/runtime/web/.next/static/css/2728291c68f99cb1.css +0 -3
  220. package/dist/runtime/web/.next/static/css/521bd69cc298cd1a.css +0 -1
  221. package/dist/runtime/web/.next/static/css/537e22821e101b87.css +0 -1
  222. package/dist/runtime/web/.next/static/media/19cfc7226ec3afaa-s.woff2 +0 -0
  223. package/dist/runtime/web/.next/static/media/21350d82a1f187e9-s.woff2 +0 -0
  224. package/dist/runtime/web/.next/static/media/8e9860b6e62d6359-s.woff2 +0 -0
  225. package/dist/runtime/web/.next/static/media/ba9851c3c22cd980-s.woff2 +0 -0
  226. package/dist/runtime/web/.next/static/media/c5fe6dc8356a8c31-s.woff2 +0 -0
  227. package/dist/runtime/web/.next/static/media/df0a9ae256c0569c-s.woff2 +0 -0
  228. package/dist/runtime/web/.next/static/media/e4af272ccee01ff0-s.p.woff2 +0 -0
  229. package/dist/runtime/web/package.json +0 -65
  230. package/dist/runtime/web/server.js +0 -44
  231. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -1,904 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- import { WorktreeService } from '../vcs/worktree-service.js';
3
- import { ExecutionLogPersistence } from '../persistence/execution-log-persistence.js';
4
- import { log } from '../lib/logger.js';
5
- import { generateId } from '../lib/id-generator.js';
6
- import { getProjectRoot } from '../lib/server/project-root.js';
7
- import { CoreAgentService } from './core-agent-service.js';
8
- import { ClaudeCodeAdapter, CodexCliProvider } from './ai-providers/index.js';
9
- import { PromptService } from './prompt-service.js';
10
- import { RoutingPolicyManager, } from './routing-policy.js';
11
- import { isTestEnv } from '../utils/env.js';
12
- import { parseImprovementResult, parseReviewResult } from './parsers.js';
13
- import { getSettingsService } from '../settings-service.js';
14
- const fullTools = [
15
- 'Bash',
16
- 'Edit',
17
- 'Glob',
18
- 'Grep',
19
- 'MultiEdit',
20
- 'NotebookEdit',
21
- 'NotebookRead',
22
- 'Read',
23
- 'Task',
24
- 'TodoWrite',
25
- 'WebSearch',
26
- 'WebFetch',
27
- 'Write',
28
- ];
29
- export class AgentService extends EventEmitter {
30
- constructor(taskService, projectRoot = getProjectRoot(), worktreeService) {
31
- super();
32
- this.taskService = taskService;
33
- this.projectRoot = projectRoot;
34
- // Keep only minimal execution context locally; defer status/messages to CoreAgentService
35
- this.executionRegistry = new Map();
36
- this.initialized = false;
37
- // Track lightweight status for generic (non-core) executions
38
- this.genericStates = new Map();
39
- // Centralized default tool sets per operation
40
- // TODO: need to be more granular, based on the task type and the toolset available for the AI provider
41
- this.defaultTools = {
42
- execute_task: fullTools,
43
- quality_checks: fullTools,
44
- improve_task: fullTools,
45
- code_review: fullTools,
46
- ai_merge: fullTools,
47
- };
48
- // Centralized system prompts for all AI operations
49
- this.systemPrompts = {
50
- execute_task: {
51
- base: 'You are an expert software engineer. Follow best practices, write clean maintainable code, and ensure your implementation is robust and well-tested.',
52
- rerun: 'You are continuing a rerun of this task. Use prior context and focus on fixes.',
53
- },
54
- improve_task: 'You are an expert at improving task specifications. Respond with ONLY a valid JSON object containing type, priority, and content fields. No additional text or formatting.',
55
- ai_codereview: 'You are a senior developer performing thorough code review. Focus on quality, security, and best practices. Respond with ONLY a valid JSON object. Ultrathink.',
56
- ai_merge: 'You are an expert at resolving merge conflicts and integrating code changes. Ensure clean merges that maintain code consistency and functionality.',
57
- };
58
- this.worktreeService = worktreeService || new WorktreeService(projectRoot);
59
- this.logPersistence = new ExecutionLogPersistence();
60
- this.initialize();
61
- // Log streaming updates for verification in dev environments
62
- if (!isTestEnv()) {
63
- this.on('executionUpdated', (update) => {
64
- const exec = this.getExecutionStatus(update.executionId);
65
- const last = exec?.logs?.[exec.logs.length - 1];
66
- if (last) {
67
- log.info('Execution update', { executionId: update.executionId, message: last }, 'agent-service');
68
- }
69
- });
70
- }
71
- // Initialize worktree manager
72
- this.initializeWorktrees();
73
- }
74
- // ============ Generic (non-AI) execution helpers for local tasks (e.g., validation) ============
75
- /**
76
- * Start a generic execution that is not backed by an AI provider.
77
- * This enables persistent logs and status queries via existing APIs.
78
- */
79
- async startGenericExecution(taskId, options) {
80
- const executionId = generateId('exec');
81
- const startTime = new Date().toISOString();
82
- const workingDirectory = options?.workingDirectory || this.projectRoot;
83
- // Register minimal context so status queries work
84
- this.executionRegistry.set(executionId, { taskId, workingDirectory, startTime });
85
- const initial = {
86
- id: executionId,
87
- taskId,
88
- status: 'pending',
89
- startTime,
90
- logs: [],
91
- workingDirectory,
92
- };
93
- await this.logPersistence.startExecution(initial, options?.workflowId);
94
- this.genericStates.set(executionId, { status: 'running' });
95
- // Emit an update to notify subscribers
96
- this.emit('executionUpdated', { executionId, status: 'running', logs: [] });
97
- return executionId;
98
- }
99
- /** Append a log line to a generic execution and notify listeners (best-effort). */
100
- async logGenericExecution(executionId, message, level = 'info', data) {
101
- await this.logPersistence.logMessage(executionId, message, level, data);
102
- try {
103
- const logs = (await this.logPersistence.readExecutionLogs(executionId)).logs.map((e) => e.message);
104
- this.emit('executionUpdated', { executionId, status: 'running', logs });
105
- }
106
- catch {
107
- // ignore
108
- }
109
- }
110
- /** Mark a generic execution as completed/failed/cancelled and notify listeners. */
111
- async completeGenericExecution(executionId, status, error) {
112
- await this.logPersistence.completeExecution(executionId, status, error);
113
- this.genericStates.set(executionId, { status, endTime: new Date().toISOString(), error });
114
- try {
115
- const logs = (await this.logPersistence.readExecutionLogs(executionId)).logs.map((e) => e.message);
116
- this.emit('executionUpdated', { executionId, status, logs, error });
117
- }
118
- catch {
119
- this.emit('executionUpdated', { executionId, status, logs: [], error });
120
- }
121
- }
122
- getAgentConfig() {
123
- try {
124
- const settings = getSettingsService().getSettings();
125
- return {
126
- executionTimeout: 30 * 60 * 1000, // 30 minutes fixed
127
- defaultProvider: settings.agents.defaultProvider || 'claude-code',
128
- };
129
- }
130
- catch {
131
- return { executionTimeout: 30 * 60 * 1000, defaultProvider: 'claude-code' };
132
- }
133
- }
134
- initialize() {
135
- if (this.initialized)
136
- return;
137
- // Initialize core agent service with settings
138
- const agentConfig = this.getAgentConfig();
139
- this.coreAgentService = new CoreAgentService({
140
- defaultProvider: agentConfig.defaultProvider,
141
- executionTimeout: agentConfig.executionTimeout,
142
- });
143
- // Register Claude Code adapter
144
- const claudeAdapter = new ClaudeCodeAdapter({
145
- defaultWorkingDirectory: this.projectRoot,
146
- defaultModel: 'claude-sonnet-4-20250514',
147
- });
148
- this.coreAgentService.registerProvider('claude-code', claudeAdapter);
149
- // Register Codex CLI provider (not default)
150
- const codexProvider = new CodexCliProvider({
151
- defaultWorkingDirectory: this.projectRoot,
152
- });
153
- this.coreAgentService.registerProvider('codex', codexProvider);
154
- // Initialize prompt service
155
- this.promptService = new PromptService(this.projectRoot, this.taskService);
156
- // Initialize routing policy manager
157
- this.routingPolicyManager = new RoutingPolicyManager();
158
- // Set up event forwarding
159
- this.setupEventForwarding();
160
- this.initialized = true;
161
- }
162
- setupEventForwarding() {
163
- // Persist every message and enrich realtime UI for non-assistant types
164
- this.coreAgentService.on('executionMessage', (data) => {
165
- const state = this.coreAgentService.getExecutionStatus(data.executionId);
166
- const status = state?.status || 'running';
167
- const summary = this.summarizeMessage(data.message);
168
- void this.logPersistence.logMessage(data.executionId, summary, data.message.type === 'error' ? 'error' : 'info', { raw: data.message });
169
- const logs = this.coreAgentService
170
- .getExecutionMessages(data.executionId)
171
- .map((m) => this.summarizeMessage(m));
172
- this.emit('executionUpdated', {
173
- executionId: data.executionId,
174
- status,
175
- logs,
176
- });
177
- });
178
- this.coreAgentService.on('executionCompleted', (data) => {
179
- void this.logPersistence.completeExecution(data.executionId, 'completed');
180
- const logs = this.coreAgentService
181
- .getExecutionMessages(data.executionId)
182
- .map((m) => this.summarizeMessage(m));
183
- this.emit('executionUpdated', {
184
- executionId: data.executionId,
185
- status: 'completed',
186
- logs,
187
- });
188
- });
189
- this.coreAgentService.on('executionFailed', (data) => {
190
- void this.logPersistence.completeExecution(data.executionId, 'failed', data.error);
191
- const logs = this.coreAgentService
192
- .getExecutionMessages(data.executionId)
193
- .map((m) => this.summarizeMessage(m));
194
- this.emit('executionUpdated', {
195
- executionId: data.executionId,
196
- status: 'failed',
197
- logs,
198
- error: data.error,
199
- });
200
- });
201
- this.coreAgentService.on('executionCancelled', (data) => {
202
- void this.logPersistence.completeExecution(data.executionId, 'cancelled');
203
- const logs = this.coreAgentService
204
- .getExecutionMessages(data.executionId)
205
- .map((m) => this.summarizeMessage(m));
206
- this.emit('executionUpdated', {
207
- executionId: data.executionId,
208
- status: 'cancelled',
209
- logs,
210
- });
211
- });
212
- }
213
- /**
214
- * Create a concise, human-readable line from a structured execution message
215
- */
216
- summarizeMessage(msg) {
217
- const ts = new Date(msg.timestamp || Date.now()).toLocaleTimeString();
218
- switch (msg.type) {
219
- case 'init':
220
- return `[${ts}] Init: session started`;
221
- case 'assistant':
222
- return typeof msg.content === 'string' ? msg.content : '[assistant message]';
223
- case 'tool_use': {
224
- const tool = msg.tool || 'tool';
225
- const input = msg.input ? JSON.stringify(msg.input) : '';
226
- return `[${ts}] TOOL ${tool} ${input}`;
227
- }
228
- case 'result': {
229
- const success = msg.success;
230
- return `[${ts}] Result: ${success ? 'success' : 'error'}`;
231
- }
232
- case 'system':
233
- return `[${ts}] SYSTEM: ${typeof msg.content === 'string' ? msg.content : ''}`;
234
- case 'error':
235
- return `[${ts}] ERROR: ${String(msg.content || '')}`;
236
- default:
237
- // Ensure template-literal receives a string; avoid `never` type in lint
238
- return `[${ts}] ${String(msg.type)}`;
239
- }
240
- }
241
- /**
242
- * Initialize worktree manager
243
- */
244
- async initializeWorktrees() {
245
- try {
246
- await this.worktreeService.initialize();
247
- }
248
- catch (error) {
249
- log.warn('Failed to initialize WorktreeService', error, 'agent-service');
250
- }
251
- }
252
- /**
253
- * Execute a task using AI in an isolated worktree
254
- */
255
- async executeTask(taskId, workflowId, options) {
256
- const task = this.taskService.getTask(taskId);
257
- if (!task) {
258
- throw new Error(`Task ${taskId} not found`);
259
- }
260
- const executionId = generateId('exec');
261
- // Pre-register minimal context for this execution
262
- const initialStart = new Date().toISOString();
263
- this.executionRegistry.set(executionId, {
264
- taskId,
265
- workingDirectory: this.projectRoot,
266
- startTime: initialStart,
267
- });
268
- // Start persistent logging with workflow context
269
- const initialExecution = {
270
- id: executionId,
271
- taskId,
272
- status: 'pending',
273
- startTime: initialStart,
274
- logs: [],
275
- workingDirectory: this.projectRoot,
276
- };
277
- await this.logPersistence.startExecution(initialExecution, workflowId);
278
- // Update task status to in-progress
279
- await this.taskService.updateTask(taskId, { status: 'in-progress' });
280
- // Fire-and-forget creation event if needed by listeners
281
- // Include workflowId so orchestrators can associate execution to workflows
282
- this.emit('executionCreated', { executionId, taskId, workflowId });
283
- // Create worktree for isolated execution
284
- let worktree;
285
- let workingDirectory = this.projectRoot;
286
- try {
287
- worktree = await this.worktreeService.createWorktree(task);
288
- if (worktree?.path) {
289
- workingDirectory = worktree.path;
290
- log.info('Task executing in worktree', { taskId, workingDirectory }, 'agent-service');
291
- // Update registry with actual working directory
292
- this.executionRegistry.set(executionId, {
293
- taskId,
294
- workingDirectory,
295
- startTime: initialStart,
296
- });
297
- }
298
- }
299
- catch (error) {
300
- log.error('Failed to create worktree, using main directory', error, 'agent-service');
301
- }
302
- // Generate task prompt with workflow configuration for dynamic instructions
303
- const prompt = await this.promptService.generateTaskPrompt(task, options?.workflowConfig);
304
- // Build system prompt - use rerun context if available, otherwise base prompt
305
- let appendSystemPrompt;
306
- if (options?.rerunContext) {
307
- appendSystemPrompt = await this.buildRerunSystemPrompt(task, options.rerunContext, workingDirectory);
308
- }
309
- else {
310
- appendSystemPrompt = this.systemPrompts.execute_task.base;
311
- }
312
- // Persist prompt for auditing
313
- void this.logPersistence.logMessage(executionId, 'Prompt prepared', 'info', {
314
- prompt,
315
- appendSystemPrompt, // include system/rerun append
316
- options: { workingDirectory, tools: this.defaultTools.execute_task },
317
- taskId: task.id,
318
- workflowId,
319
- rerunContext: options?.rerunContext,
320
- });
321
- await this.executeWithRouting('execute_task', prompt, {
322
- workingDirectory,
323
- tools: this.defaultTools.execute_task,
324
- timeout: 30 * 60 * 1000,
325
- appendSystemPrompt,
326
- dangerouslyBypassApprovalsAndSandbox: true,
327
- executionId,
328
- metadata: {
329
- operation: 'execute_task',
330
- taskId,
331
- workflowId,
332
- worktree,
333
- rerun: !!options?.rerunContext,
334
- previousExecutionId: options?.rerunContext?.previousExecutionId,
335
- },
336
- }, options?.providerOverride);
337
- return executionId;
338
- }
339
- /**
340
- * Build an appended system prompt with rerun context (reason, logs, failed checks)
341
- */
342
- async buildRerunSystemPrompt(task, rerun, workingDirectory) {
343
- const parts = [];
344
- // Start with base system prompt, then add rerun context
345
- parts.push(this.systemPrompts.execute_task.base);
346
- parts.push('\n\n' + this.systemPrompts.execute_task.rerun);
347
- parts.push(`Rerun reason: ${rerun.reason}`);
348
- if (rerun.attempt)
349
- parts.push(`Attempt: ${String(rerun.attempt)}`);
350
- if (rerun.failurePhase)
351
- parts.push(`Previous failure phase: ${rerun.failurePhase}`);
352
- parts.push(`Working directory: ${workingDirectory}`);
353
- // Try to get persisted logs tail if not provided and we have an execution id
354
- let logs = rerun.lastLogs || [];
355
- if ((!logs || logs.length === 0) && rerun.previousExecutionId) {
356
- try {
357
- const persisted = await this.getPersistedExecutionLogs(rerun.previousExecutionId);
358
- const tail = persisted.logs.slice(-30).map((e) => e.message || JSON.stringify(e));
359
- logs = tail;
360
- }
361
- catch {
362
- const mem = this.getExecutionLogs(rerun.previousExecutionId);
363
- logs = mem.slice(-30);
364
- }
365
- }
366
- if (logs && logs.length) {
367
- parts.push('Recent logs (tail):');
368
- parts.push(logs.join('\n'));
369
- }
370
- const q = rerun.qualityResults;
371
- if (q) {
372
- const failed = Object.entries(q.details || {}).filter(([, ok]) => !ok);
373
- if (failed.length) {
374
- parts.push('Quality checks failed previously:');
375
- for (const [name] of failed) {
376
- const output = q.outputs?.[name];
377
- parts.push(`- ${name}: ${output ? String(output).slice(0, 2000) : 'failed'}`);
378
- }
379
- }
380
- }
381
- const review = rerun.aiReview;
382
- if (review) {
383
- parts.push('AI code review feedback from previous attempt:');
384
- if (typeof review.score === 'number') {
385
- parts.push(`- Quality score: ${review.score}`);
386
- }
387
- if (review.summary) {
388
- parts.push(`- Summary: ${review.summary}`);
389
- }
390
- const recs = Array.isArray(review.recommendations)
391
- ? review.recommendations.filter((r) => typeof r === 'string' && r.trim().length)
392
- : [];
393
- if (recs.length) {
394
- parts.push('Recommendations:');
395
- for (const item of recs.slice(0, 5)) {
396
- parts.push(` * ${item}`);
397
- }
398
- if (recs.length > 5) {
399
- parts.push(` * ...and ${recs.length - 5} more recommendations`);
400
- }
401
- }
402
- }
403
- parts.push('Instruction: Address the reasons above. Avoid repeating prior mistakes. Keep changes scoped and test thoroughly. ');
404
- return parts.join('\n');
405
- }
406
- /**
407
- * Stop a running execution and cleanup worktree
408
- */
409
- async stopExecution(executionId) {
410
- const registry = this.executionRegistry.get(executionId);
411
- if (!registry) {
412
- throw new Error(`Execution ${executionId} not found`);
413
- }
414
- try {
415
- await this.coreAgentService.stopExecution(executionId);
416
- }
417
- catch (error) {
418
- log.warn('Failed to stop execution', error, 'agent-service');
419
- }
420
- const logs = this.coreAgentService
421
- .getExecutionMessages(executionId)
422
- .map((m) => this.summarizeMessage(m));
423
- this.emit('executionUpdated', {
424
- executionId,
425
- status: 'cancelled',
426
- logs,
427
- });
428
- }
429
- /**
430
- * Get execution status
431
- */
432
- getExecutionStatus(executionId) {
433
- const registry = this.executionRegistry.get(executionId);
434
- const state = this.coreAgentService.getExecutionStatus(executionId);
435
- if (registry && state) {
436
- const logs = this.coreAgentService
437
- .getExecutionMessages(executionId)
438
- .map((m) => this.summarizeMessage(m));
439
- return {
440
- id: executionId,
441
- taskId: registry.taskId,
442
- status: state.status,
443
- startTime: registry.startTime || state.startTime,
444
- endTime: state.endTime,
445
- logs,
446
- error: state.error,
447
- provider: state.provider,
448
- usage: state.usage,
449
- workingDirectory: registry.workingDirectory,
450
- };
451
- }
452
- // Fallback for generic/local executions (non-core) using in-memory state
453
- if (registry && this.genericStates.has(executionId)) {
454
- const gs = this.genericStates.get(executionId);
455
- return {
456
- id: executionId,
457
- taskId: registry.taskId,
458
- status: gs.status,
459
- startTime: registry.startTime,
460
- endTime: gs.endTime,
461
- logs: [],
462
- error: gs.error,
463
- provider: 'local',
464
- workingDirectory: registry.workingDirectory,
465
- };
466
- }
467
- return null;
468
- }
469
- /**
470
- * Get execution logs
471
- */
472
- getExecutionLogs(executionId) {
473
- return this.coreAgentService
474
- .getExecutionMessages(executionId)
475
- .map((m) => this.summarizeMessage(m));
476
- }
477
- /**
478
- * Get all executions for a task
479
- */
480
- getTaskExecutions(taskId) {
481
- const results = [];
482
- for (const [id, meta] of this.executionRegistry.entries()) {
483
- if (meta.taskId !== taskId)
484
- continue;
485
- const state = this.coreAgentService.getExecutionStatus(id);
486
- if (!state)
487
- continue;
488
- results.push({
489
- id,
490
- taskId: meta.taskId,
491
- status: state.status,
492
- startTime: meta.startTime || state.startTime,
493
- endTime: state.endTime,
494
- logs: [],
495
- error: state.error,
496
- workingDirectory: meta.workingDirectory,
497
- });
498
- }
499
- return results.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
500
- }
501
- /**
502
- * Improve task content using AI
503
- */
504
- async improveTaskContent(task, taskData, executionId) {
505
- const finalExecutionId = executionId || generateId('improve');
506
- try {
507
- // Pre-register execution to enable streaming logs and persistence
508
- if (!this.executionRegistry.has(finalExecutionId)) {
509
- const startTime = new Date().toISOString();
510
- this.executionRegistry.set(finalExecutionId, {
511
- taskId: task.id,
512
- workingDirectory: this.projectRoot,
513
- startTime,
514
- });
515
- const execRec = {
516
- id: finalExecutionId,
517
- taskId: task.id,
518
- status: 'pending',
519
- startTime,
520
- logs: [],
521
- workingDirectory: this.projectRoot,
522
- };
523
- await this.logPersistence.startExecution(execRec);
524
- }
525
- // Generate improvement prompt
526
- const prompt = await this.promptService.generateImprovementPrompt(task, taskData);
527
- void this.logPersistence.logMessage(finalExecutionId, 'Improvement prompt prepared', 'info', {
528
- prompt,
529
- options: { workingDirectory: this.projectRoot, tools: this.defaultTools.improve_task },
530
- taskId: task.id,
531
- });
532
- // Execute improvement with AI
533
- const result = await this.executeWithRouting('improve_task', prompt, {
534
- workingDirectory: this.projectRoot,
535
- appendSystemPrompt: this.systemPrompts.improve_task,
536
- tools: this.defaultTools.improve_task,
537
- timeout: 5 * 60 * 1000,
538
- dangerouslyBypassApprovalsAndSandbox: false,
539
- executionId: finalExecutionId,
540
- metadata: {
541
- operation: 'improve_task',
542
- taskId: task.id,
543
- },
544
- });
545
- // Parse the result
546
- const improvement = this.parseImprovementResult(result, taskData);
547
- const payload = { ...improvement, executionId: finalExecutionId };
548
- // Ensure registry exists (already handled above) and mark completion in persistence
549
- await this.logPersistence.completeExecution(finalExecutionId, 'completed');
550
- return payload;
551
- }
552
- catch (error) {
553
- await this.logPersistence.completeExecution(finalExecutionId, 'failed', error instanceof Error ? error.message : String(error));
554
- throw new Error(`Failed to improve task content: ${error instanceof Error ? error.message : String(error)}`);
555
- }
556
- }
557
- /**
558
- * Perform AI code review of changes in a worktree
559
- */
560
- async aiReviewCode(taskId, reviewContext, options) {
561
- const task = this.taskService.getTask(taskId);
562
- if (!task) {
563
- throw new Error(`Task ${taskId} not found`);
564
- }
565
- const worktree = this.worktreeService.getWorktree(taskId);
566
- if (!worktree) {
567
- throw new Error(`No worktree found for task ${taskId}`);
568
- }
569
- const executionId = options?.executionId ?? generateId('review');
570
- try {
571
- // Pre-register execution for streaming/persistence
572
- if (!this.executionRegistry.has(executionId)) {
573
- const startTime = new Date().toISOString();
574
- this.executionRegistry.set(executionId, {
575
- taskId,
576
- workingDirectory: this.projectRoot,
577
- startTime,
578
- });
579
- const execRec = {
580
- id: executionId,
581
- taskId,
582
- status: 'pending',
583
- startTime,
584
- logs: [],
585
- workingDirectory: this.projectRoot,
586
- };
587
- await this.logPersistence.startExecution(execRec, options?.workflowId);
588
- }
589
- // Generate review prompt
590
- const reviewPrompt = await this.promptService.generateReviewPrompt(task, worktree, reviewContext);
591
- void this.logPersistence.logMessage(executionId, 'Review prompt prepared', 'info', {
592
- prompt: reviewPrompt,
593
- options: { workingDirectory: worktree.path, tools: this.defaultTools.code_review },
594
- taskId,
595
- });
596
- // Execute review with AI
597
- const result = await this.executeWithRouting('ai_codereview', reviewPrompt, {
598
- workingDirectory: worktree.path,
599
- appendSystemPrompt: this.systemPrompts.ai_codereview,
600
- tools: this.defaultTools.code_review,
601
- timeout: 10 * 60 * 1000,
602
- executionId,
603
- metadata: {
604
- operation: 'ai_codereview',
605
- taskId,
606
- },
607
- }, options?.overrides);
608
- // Parse review result
609
- const review = this.parseReviewResult(result);
610
- const payload = { executionId, ...review };
611
- // Ensure registry exists for lookups
612
- if (!this.executionRegistry.has(executionId)) {
613
- this.executionRegistry.set(executionId, {
614
- taskId,
615
- workingDirectory: this.projectRoot,
616
- startTime: new Date().toISOString(),
617
- });
618
- }
619
- return payload;
620
- }
621
- catch (error) {
622
- throw new Error(`Failed to review code: ${error instanceof Error ? error.message : String(error)}`);
623
- }
624
- }
625
- /**
626
- * Perform AI-assisted merge of a task's worktree into the base project
627
- */
628
- async aiMerge(taskId, options) {
629
- const task = this.taskService.getTask(taskId);
630
- if (!task) {
631
- throw new Error(`Task ${taskId} not found`);
632
- }
633
- const worktree = this.worktreeService.getWorktree(taskId);
634
- if (!worktree) {
635
- throw new Error(`No worktree found for task ${taskId}`);
636
- }
637
- const executionId = options?.executionId ?? generateId('merge');
638
- const workingDirectory = worktree.path || this.projectRoot;
639
- try {
640
- // Pre-register execution for streaming/persistence
641
- if (!this.executionRegistry.has(executionId)) {
642
- const startTime = new Date().toISOString();
643
- this.executionRegistry.set(executionId, {
644
- taskId,
645
- workingDirectory,
646
- startTime,
647
- });
648
- const execRec = {
649
- id: executionId,
650
- taskId,
651
- status: 'pending',
652
- startTime,
653
- logs: [],
654
- workingDirectory,
655
- };
656
- await this.logPersistence.startExecution(execRec, options?.workflowId);
657
- }
658
- // Generate merge prompt
659
- const mergePrompt = await this.promptService.generateAIMergePrompt(task, worktree, options?.baseBranch);
660
- void this.logPersistence.logMessage(executionId, 'Merge prompt prepared', 'info', {
661
- prompt: mergePrompt,
662
- options: { workingDirectory, tools: this.defaultTools.ai_merge },
663
- taskId,
664
- baseBranch: options?.baseBranch,
665
- });
666
- // Execute merge with AI
667
- await this.executeWithRouting('ai_merge', mergePrompt, {
668
- workingDirectory,
669
- appendSystemPrompt: this.systemPrompts.ai_merge,
670
- tools: this.defaultTools.ai_merge,
671
- timeout: 15 * 60 * 1000,
672
- executionId,
673
- metadata: {
674
- operation: 'ai_merge',
675
- taskId,
676
- baseBranch: options?.baseBranch,
677
- },
678
- }, options?.overrides);
679
- return { executionId };
680
- }
681
- catch (error) {
682
- throw new Error(`AI merge failed: ${error instanceof Error ? error.message : String(error)}`);
683
- }
684
- }
685
- /**
686
- * Get persistent execution logs
687
- */
688
- async getPersistedExecutionLogs(executionId) {
689
- return await this.logPersistence.readExecutionLogs(executionId);
690
- }
691
- /**
692
- * List all execution metadata from persistence
693
- */
694
- async listAllExecutions() {
695
- return await this.logPersistence.listExecutions();
696
- }
697
- /**
698
- * Clean up old execution logs
699
- */
700
- async cleanupOldExecutionLogs(maxAgeDays = 30) {
701
- return await this.logPersistence.cleanupOldLogs(maxAgeDays);
702
- }
703
- /**
704
- * Remove execution logs for a specific task
705
- */
706
- async removeExecutionLogsByTask(taskId) {
707
- return await this.logPersistence.removeExecutionsByTask(taskId);
708
- }
709
- /**
710
- * Get execution log statistics
711
- */
712
- async getExecutionLogStats() {
713
- return await this.logPersistence.getStats();
714
- }
715
- /**
716
- * Get statistics about executions
717
- */
718
- getExecutionStats() {
719
- const states = this.coreAgentService.getAllExecutions();
720
- const worktreeCounts = this.worktreeService.getWorktreeCounts();
721
- return {
722
- total: states.length,
723
- pending: states.filter((e) => e.status === 'pending').length,
724
- running: states.filter((e) => e.status === 'running').length,
725
- completed: states.filter((e) => e.status === 'completed').length,
726
- failed: states.filter((e) => e.status === 'failed').length,
727
- cancelled: states.filter((e) => e.status === 'cancelled').length,
728
- worktrees: {
729
- active: worktreeCounts.active,
730
- total: worktreeCounts.total,
731
- enabled: true,
732
- },
733
- };
734
- }
735
- /**
736
- * Get worktree service instance
737
- */
738
- getWorktreeService() {
739
- return this.worktreeService;
740
- }
741
- /**
742
- * Get worktree information for a task
743
- */
744
- getWorktreeInfo(taskId) {
745
- const wt = this.worktreeService.getWorktree(taskId);
746
- if (!wt)
747
- return null;
748
- const { git, ...rest } = wt;
749
- return rest;
750
- }
751
- /**
752
- * Get core agent service metrics
753
- */
754
- getCoreMetrics() {
755
- const states = this.coreAgentService.getAllExecutions();
756
- return {
757
- totalExecutions: states.length,
758
- activeExecutions: states.filter((e) => e.status === 'running').length,
759
- completedExecutions: states.filter((e) => e.status === 'completed').length,
760
- failedExecutions: states.filter((e) => e.status === 'failed').length,
761
- cancelledExecutions: states.filter((e) => e.status === 'cancelled').length,
762
- };
763
- }
764
- /**
765
- * Get available AI providers
766
- */
767
- getAvailableProviders() {
768
- return this.coreAgentService.getProviders();
769
- }
770
- /**
771
- * Validate provider setup
772
- */
773
- async validateProviders() {
774
- return await this.coreAgentService.validateProviders();
775
- }
776
- /**
777
- * Get available models from all providers
778
- */
779
- async getAvailableModels() {
780
- return await this.coreAgentService.getAvailableModels();
781
- }
782
- /**
783
- * Parse improvement result from AI response
784
- */
785
- parseImprovementResult(result, originalData) {
786
- return parseImprovementResult(result, originalData);
787
- }
788
- /**
789
- * Parse review result from AI response
790
- */
791
- parseReviewResult(result) {
792
- return parseReviewResult(result);
793
- }
794
- /**
795
- * Resolve provider for specific operation with failover support
796
- */
797
- async resolveProviderForOperation(operation, overrides) {
798
- return await this.routingPolicyManager.resolveProviderForOperation(operation, overrides);
799
- }
800
- async previewProviderForOperation(operation, overrides) {
801
- return await this.resolveProviderForOperation(operation, overrides);
802
- }
803
- /**
804
- * Execute with provider resolution and failover
805
- */
806
- async executeWithRouting(operation, prompt, options = {}, overrides) {
807
- const resolved = await this.resolveProviderForOperation(operation, overrides);
808
- // Merge resolved options with base options
809
- const executionOptions = {
810
- ...options,
811
- ...resolved.options,
812
- model: resolved.model || options.model,
813
- // Don't override workingDirectory or timeout from base options
814
- workingDirectory: options.workingDirectory,
815
- timeout: options.timeout,
816
- };
817
- // Persist a clear log line indicating chosen provider/model for this operation
818
- try {
819
- const execId = options?.executionId;
820
- if (execId) {
821
- await this.logPersistence.logMessage(execId, `Using provider: ${resolved.provider}${resolved.model ? ` (model: ${resolved.model})` : ''}`, 'info', { operation, resolved });
822
- }
823
- }
824
- catch {
825
- // best-effort logging; ignore
826
- }
827
- // Default maxTokens from settings when not provided (unlimited if omitted)
828
- try {
829
- if (executionOptions.maxTokens === undefined) {
830
- const s = getSettingsService().getSettings();
831
- const def = operation === 'ai_codereview'
832
- ? s.agents?.judgeAgent?.maxTokens
833
- : s.agents?.codingAgent?.maxTokens;
834
- if (typeof def === 'number') {
835
- executionOptions.maxTokens = def;
836
- }
837
- }
838
- }
839
- catch {
840
- // best effort; ignore if settings unavailable
841
- }
842
- const providersToTry = [resolved.provider, ...(resolved.fallbacks || [])];
843
- // Ensure Codex executes with write permissions when it is in the routing set.
844
- // Some overrides may omit the flag, so default it on for task execution.
845
- if (operation === 'execute_task' &&
846
- providersToTry.includes('codex') &&
847
- executionOptions.dangerouslyBypassApprovalsAndSandbox === undefined) {
848
- executionOptions.dangerouslyBypassApprovalsAndSandbox = true;
849
- }
850
- let lastError = null;
851
- for (let i = 0; i < providersToTry.length; i++) {
852
- const provider = providersToTry[i];
853
- const isLastProvider = i === providersToTry.length - 1;
854
- try {
855
- log.debug(`Attempting execution with provider: ${provider} (attempt ${i + 1}/${providersToTry.length})`, { operation, provider, isLastProvider }, 'agent-service');
856
- const result = await this.coreAgentService.execute({
857
- prompt,
858
- provider,
859
- options: executionOptions,
860
- metadata: {
861
- ...options.metadata,
862
- operation,
863
- provider,
864
- model: resolved.model,
865
- providerAttempt: i + 1,
866
- totalProviderAttempts: providersToTry.length,
867
- },
868
- executionId: options.executionId,
869
- });
870
- // Success - log provider usage
871
- log.info(`Successful execution with provider: ${provider}`, {
872
- operation,
873
- provider,
874
- model: resolved.model,
875
- attempt: i + 1,
876
- fallbackUsed: i > 0,
877
- }, 'agent-service');
878
- return result;
879
- }
880
- catch (error) {
881
- lastError = error instanceof Error ? error : new Error(String(error));
882
- log.warn(`Provider ${provider} failed for operation ${operation}`, {
883
- operation,
884
- provider,
885
- attempt: i + 1,
886
- error: lastError.message,
887
- willRetry: !isLastProvider,
888
- }, 'agent-service');
889
- // If this is not the last provider, continue to next
890
- if (!isLastProvider) {
891
- continue;
892
- }
893
- }
894
- }
895
- // All providers failed
896
- throw new Error(`All providers failed for operation ${operation}. Last error: ${lastError?.message}`);
897
- }
898
- /**
899
- * Get routing policy manager (for tRPC router access)
900
- */
901
- getRoutingPolicyManager() {
902
- return this.routingPolicyManager;
903
- }
904
- }