codehere 0.2.2 → 0.3.0-rc.10

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 (238) hide show
  1. package/README.md +88 -68
  2. package/dist/domain/entities/task.js +4 -4
  3. package/dist/error-handler.js +4 -9
  4. package/dist/index.js +261 -1224
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +348 -72
  7. package/dist/infrastructure/observability/execution-tracer.js +11 -6
  8. package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
  9. package/dist/infrastructure/orchestration/agent-installer.js +101 -0
  10. package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
  11. package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
  12. package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
  13. package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
  14. package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
  15. package/dist/infrastructure/orchestration/conductor-adapter.js +340 -0
  16. package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
  17. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  18. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  19. package/dist/infrastructure/orchestration/readiness.js +106 -0
  20. package/dist/infrastructure/orchestration/session-manager.js +278 -0
  21. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  22. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  23. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  24. package/dist/infrastructure/protocols/probe-port.js +36 -0
  25. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  26. package/dist/infrastructure/security/file-collection.js +115 -0
  27. package/dist/infrastructure/security/trust-scorer.js +301 -56
  28. package/dist/infrastructure/storage/task-repository.js +8 -7
  29. package/dist/monitoring.js +9 -38
  30. package/dist/presentation/cli/commands/help-command.js +96 -139
  31. package/dist/presentation/cli/commands/hook-command.js +17 -24
  32. package/dist/presentation/cli/commands/report-command.js +59 -72
  33. package/dist/presentation/cli/commands/setup-command.js +4 -4
  34. package/dist/presentation/cli/commands/status-command.js +321 -30
  35. package/dist/presentation/cli/commands/trust-command.js +84 -72
  36. package/dist/presentation/cli/error-display.js +17 -21
  37. package/dist/presentation/cli/repl.js +474 -0
  38. package/dist/ui.js +11 -11
  39. package/package.json +24 -62
  40. package/dist/agents/base.js +0 -101
  41. package/dist/agents/orchestrator-model-driven.js +0 -141
  42. package/dist/agents/react-orchestrator-agent.js +0 -54
  43. package/dist/application/agents/execution-agent.js +0 -508
  44. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  45. package/dist/application/agents/planning-agent.js +0 -433
  46. package/dist/application/agents/validation-agent.js +0 -317
  47. package/dist/application/architectures/plan-and-act.js +0 -242
  48. package/dist/application/index.js +0 -12
  49. package/dist/application/services/agent-factory.js +0 -28
  50. package/dist/application/services/dependency-container.js +0 -596
  51. package/dist/application/services/git-context-service.js +0 -83
  52. package/dist/application/services/intelligent-router.js +0 -934
  53. package/dist/application/services/tool-executor-service.js +0 -94
  54. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  55. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  56. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  57. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  58. package/dist/application/use-cases/planning-use-case.js +0 -276
  59. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  60. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  61. package/dist/application/workflows/deterministic-workflows.js +0 -189
  62. package/dist/ast-parser.js +0 -331
  63. package/dist/cache.js +0 -180
  64. package/dist/chat.js +0 -251
  65. package/dist/code-analysis.js +0 -327
  66. package/dist/context.js +0 -187
  67. package/dist/docs.js +0 -146
  68. package/dist/domain/entities/code-chunk.js +0 -6
  69. package/dist/domain/entities/decision.js +0 -9
  70. package/dist/domain/entities/edit.js +0 -6
  71. package/dist/domain/entities/knowledge-node.js +0 -9
  72. package/dist/domain/entities/knowledge-preservation.js +0 -10
  73. package/dist/domain/entities/memory.js +0 -6
  74. package/dist/domain/entities/pattern.js +0 -7
  75. package/dist/domain/entities/plan.js +0 -6
  76. package/dist/domain/entities/query.js +0 -6
  77. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  78. package/dist/domain/index.js +0 -19
  79. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  80. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  81. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  82. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  84. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  85. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  86. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  87. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  88. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  89. package/dist/domain/services/decision-recorder.js +0 -223
  90. package/dist/domain/services/decision-retriever.js +0 -133
  91. package/dist/domain/services/environment-mode-manager.js +0 -22
  92. package/dist/domain/services/graded-memory-activation.js +0 -69
  93. package/dist/domain/services/knowledge-access.js +0 -132
  94. package/dist/domain/services/knowledge-extractor.js +0 -247
  95. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  96. package/dist/domain/services/knowledge-graph-query.js +0 -187
  97. package/dist/domain/services/memory-retriever.js +0 -82
  98. package/dist/domain/services/memory-synthesizer.js +0 -91
  99. package/dist/domain/services/pattern-extractor.js +0 -442
  100. package/dist/domain/services/query-intent-classifier.js +0 -140
  101. package/dist/domain/services/react-loop.js +0 -186
  102. package/dist/domain/services/risk-tier-detector.js +0 -78
  103. package/dist/edit.js +0 -319
  104. package/dist/embed.js +0 -459
  105. package/dist/formatter.js +0 -168
  106. package/dist/git.js +0 -198
  107. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  108. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  109. package/dist/infrastructure/ai/model-config.js +0 -84
  110. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  111. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  112. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  113. package/dist/infrastructure/cache/response-cache.js +0 -48
  114. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  115. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  116. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  117. package/dist/infrastructure/context/context-compressor.js +0 -329
  118. package/dist/infrastructure/context/conversation-context.js +0 -128
  119. package/dist/infrastructure/context/session-manager.js +0 -94
  120. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  121. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  122. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  123. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  124. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  125. package/dist/infrastructure/index.js +0 -7
  126. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  127. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  128. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  129. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  130. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  131. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  132. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  133. package/dist/infrastructure/providers/fake-provider.js +0 -130
  134. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  135. package/dist/infrastructure/providers/model-config.types.js +0 -9
  136. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  137. package/dist/infrastructure/providers/openai-provider.js +0 -413
  138. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  139. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  140. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  141. package/dist/infrastructure/providers/provider-registry.js +0 -88
  142. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  143. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  144. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  145. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  146. package/dist/infrastructure/security/license-scanner.js +0 -167
  147. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  148. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  149. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  150. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  151. package/dist/infrastructure/storage/plan-repository.js +0 -96
  152. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  153. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  154. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  155. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  156. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  157. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  158. package/dist/infrastructure/storage/task-helpers.js +0 -197
  159. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  160. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  161. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  162. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  163. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  164. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  165. package/dist/infrastructure/ux/expectation-management.js +0 -327
  166. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  167. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  168. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  169. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  170. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  171. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  172. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  173. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  174. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  175. package/dist/infrastructure/ux/team-standards.js +0 -196
  176. package/dist/infrastructure/ux/transparency.js +0 -71
  177. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  178. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  179. package/dist/infrastructure/validation/review-handler.js +0 -40
  180. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  181. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  182. package/dist/infrastructure/validation/trace-summary.js +0 -52
  183. package/dist/infrastructure/verification/verification-service.js +0 -47
  184. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  185. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  186. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  187. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  188. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  189. package/dist/intelligent-retrieval.js +0 -272
  190. package/dist/intent/classifier.js +0 -2
  191. package/dist/intent/context.js +0 -2
  192. package/dist/iterative-refinement.js +0 -189
  193. package/dist/learning.js +0 -232
  194. package/dist/log.js +0 -31
  195. package/dist/migrate.js +0 -133
  196. package/dist/parallel-processor.js +0 -534
  197. package/dist/planner.js +0 -198
  198. package/dist/policy.js +0 -26
  199. package/dist/presentation/cli/commands/ask-command.js +0 -314
  200. package/dist/presentation/cli/commands/cost-command.js +0 -191
  201. package/dist/presentation/cli/commands/decision-command.js +0 -207
  202. package/dist/presentation/cli/commands/docs-command.js +0 -25
  203. package/dist/presentation/cli/commands/fix-command.js +0 -53
  204. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  205. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  206. package/dist/presentation/cli/commands/models-command.js +0 -194
  207. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  208. package/dist/presentation/cli/commands/plan-command.js +0 -246
  209. package/dist/presentation/cli/commands/product-command.js +0 -199
  210. package/dist/presentation/cli/commands/react-command.js +0 -181
  211. package/dist/presentation/cli/commands/review-command.js +0 -154
  212. package/dist/presentation/cli/commands/run-command.js +0 -188
  213. package/dist/presentation/cli/commands/smart-command.js +0 -395
  214. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  215. package/dist/presentation/cli/commands/trace-command.js +0 -129
  216. package/dist/presentation/cli/commands/undo-command.js +0 -150
  217. package/dist/query-optimizer.js +0 -205
  218. package/dist/refactor.js +0 -116
  219. package/dist/review.js +0 -206
  220. package/dist/search.js +0 -163
  221. package/dist/session.js +0 -704
  222. package/dist/task-verification.js +0 -336
  223. package/dist/testgen.js +0 -166
  224. package/dist/token-optimizer.js +0 -277
  225. package/dist/tools/bash.js +0 -213
  226. package/dist/tools/edit.js +0 -235
  227. package/dist/tools/executor.js +0 -153
  228. package/dist/tools/git-tool.js +0 -292
  229. package/dist/tools/parser.js +0 -158
  230. package/dist/tools/registry.js +0 -302
  231. package/dist/tools/search.js +0 -100
  232. package/dist/types.js +0 -2
  233. package/dist/utils/check-api-status.js +0 -100
  234. package/dist/utils/diff-parser.js +0 -162
  235. package/dist/verification/backup.js +0 -259
  236. package/dist/verification/compiler.js +0 -264
  237. package/dist/verification/index.js +0 -273
  238. package/dist/verification/test-runner.js +0 -379
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Claude Code adapter — F1 foundation of the PM layer (v0.3).
3
+ *
4
+ * Wraps `claude -p "<task>" --output-format=stream-json …` as a subprocess
5
+ * and exposes a tight interface: spawn, subscribe to events, kill.
6
+ *
7
+ * Deep module: everything about process management, stream parsing, line
8
+ * buffering, SIGTERM→SIGKILL escalation, and late-joiner replay is hidden
9
+ * behind four exported names (TaskSession type, spawnClaudeCode, TaskEvent,
10
+ * TaskStatus). Callers never see a child_process handle.
11
+ *
12
+ * Safety note: spawned sessions inherit the user's global PreToolUse hook
13
+ * via ~/.claude/settings.json automatically — we do NOT re-wire it here.
14
+ * That's F0 doing its job for free.
15
+ */
16
+ import { spawn } from 'child_process';
17
+ import { execFileSync } from 'child_process';
18
+ import { EventEmitter } from 'events';
19
+ import { randomUUID } from 'crypto';
20
+ import { ProgressAggregator } from './progress-aggregator.js';
21
+ import { snapshotCwd, extractArtifacts } from './artifacts-extractor.js';
22
+ // Runtime-error fingerprints → structured codehere:error events with recovery hints.
23
+ // Matched against any stderr line or assistant-text content we see on the stream.
24
+ const ERROR_PATTERNS = [
25
+ {
26
+ code: 'credit_low',
27
+ regex: /credit balance is too low/i,
28
+ message: 'Your Claude API account has no credits.',
29
+ recovery: 'codehere tries to use your Claude Code subscription by default. If you are seeing this, ' +
30
+ 'ANTHROPIC_API_KEY is still being used somehow. Unset it in your shell (e.g. remove from ~/.zshrc), ' +
31
+ 'or top up at console.anthropic.com.',
32
+ },
33
+ {
34
+ code: 'auth_invalid',
35
+ regex: /invalid api key|authentication.*failed|not authenticated|401 unauth/i,
36
+ message: 'Claude Code auth was rejected.',
37
+ recovery: 'Run `claude` in a terminal, sign in, then retry the task.',
38
+ },
39
+ {
40
+ code: 'rate_limit',
41
+ regex: /rate.?limit(ed)?|429|too many requests/i,
42
+ message: 'Claude rate-limited the request.',
43
+ recovery: 'Wait a minute and retry. If this persists, check your Claude usage dashboard.',
44
+ },
45
+ ];
46
+ function scanForKnownError(text) {
47
+ for (const p of ERROR_PATTERNS) {
48
+ if (p.regex.test(text))
49
+ return { code: p.code, message: p.message, recovery: p.recovery };
50
+ }
51
+ return null;
52
+ }
53
+ const HEADLESS_FLAGS = [
54
+ '--output-format',
55
+ 'stream-json',
56
+ '--include-partial-messages',
57
+ '--include-hook-events',
58
+ '--verbose',
59
+ // Pre-grant common tools so -p mode doesn't dead-end at interactive permission
60
+ // prompts we cannot surface to the user. Safety is still enforced by codehere's
61
+ // PreToolUse hook (F0) on every tool call — that's the real gate.
62
+ '--allowedTools',
63
+ 'Bash',
64
+ 'Edit',
65
+ 'Write',
66
+ 'Read',
67
+ 'Grep',
68
+ 'Glob',
69
+ 'MultiEdit',
70
+ 'NotebookEdit',
71
+ ];
72
+ export function spawnClaudeCode(prompt, options = {}) {
73
+ const sessionId = randomUUID();
74
+ const startedAt = Date.now();
75
+ const emitter = new EventEmitter();
76
+ const buffer = [];
77
+ let statusValue = 'running';
78
+ let killRequested = false;
79
+ // PM UX Layer 2+3 state. Shared helper modules; per-session instances.
80
+ const cwd = options.cwd ?? process.cwd();
81
+ const snapshot = snapshotCwd(cwd);
82
+ const aggregator = new ProgressAggregator('claude-code');
83
+ let stepsSnapshot = [];
84
+ let artifactsSnapshot;
85
+ let textAccum = ''; // accumulates assistant text + result summary for test-count parsing
86
+ let usageSnapshot; // token accumulator (principle #7)
87
+ let errorEmitted = false;
88
+ const emit = (event) => {
89
+ buffer.push(event);
90
+ emitter.emit('event', event);
91
+ // Layer 2: feed aggregator; on step change, emit synthetic snapshot event.
92
+ if (aggregator.ingest(event)) {
93
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
94
+ const snapEvt = { type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } };
95
+ buffer.push(snapEvt);
96
+ emitter.emit('event', snapEvt);
97
+ }
98
+ // Accumulate text for test-summary parsing (Layer 3).
99
+ if (event.type === 'assistant') {
100
+ const msg = event.data?.message;
101
+ if (msg?.content) {
102
+ for (const b of msg.content) {
103
+ if (b.type === 'text' && b.text)
104
+ textAccum += b.text + '\n';
105
+ }
106
+ }
107
+ }
108
+ else if (event.type === 'result') {
109
+ const d = event.data;
110
+ if (d?.result)
111
+ textAccum += d.result + '\n';
112
+ // Claude Code's stream-json `result` event is the final summary — carries
113
+ // the full session's usage totals. One event per session; overwrite, don't sum.
114
+ if (d?.usage) {
115
+ usageSnapshot = {
116
+ inputTokens: Number(d.usage.input_tokens ?? 0),
117
+ outputTokens: Number(d.usage.output_tokens ?? 0),
118
+ cacheReadTokens: d.usage.cache_read_input_tokens ? Number(d.usage.cache_read_input_tokens) : undefined,
119
+ cacheCreationTokens: d.usage.cache_creation_input_tokens
120
+ ? Number(d.usage.cache_creation_input_tokens)
121
+ : undefined,
122
+ };
123
+ }
124
+ }
125
+ else if (event.type === 'user') {
126
+ const msg = event.data?.message;
127
+ if (msg?.content) {
128
+ for (const b of msg.content) {
129
+ if (b.type === 'tool_result') {
130
+ const raw = Array.isArray(b.content)
131
+ ? b.content.map((c) => c.text ?? '').join('')
132
+ : String(b.content ?? '');
133
+ textAccum += raw + '\n';
134
+ }
135
+ }
136
+ }
137
+ }
138
+ // F1b: scan for known failure patterns once per session
139
+ if (!errorEmitted) {
140
+ const data = event.data;
141
+ let text = '';
142
+ if (event.type === 'stderr' && data && typeof data.line === 'string') {
143
+ text = data.line;
144
+ }
145
+ else if (event.type === 'assistant' && data && typeof data === 'object') {
146
+ const msg = data.message;
147
+ if (msg?.content) {
148
+ text = msg.content.map((b) => (b.type === 'text' ? (b.text ?? '') : '')).join(' ');
149
+ }
150
+ }
151
+ else if (event.type === 'result' && data && typeof data.result === 'string') {
152
+ text = String(data.result ?? '');
153
+ }
154
+ if (text) {
155
+ const hit = scanForKnownError(text);
156
+ if (hit) {
157
+ errorEmitted = true;
158
+ const errEvent = {
159
+ type: 'codehere:error',
160
+ timestamp: Date.now(),
161
+ data: { code: hit.code, message: hit.message, recovery: hit.recovery },
162
+ };
163
+ buffer.push(errEvent);
164
+ emitter.emit('event', errEvent);
165
+ }
166
+ }
167
+ }
168
+ };
169
+ const preferSubscription = options.preferSubscription !== false;
170
+ const spawnEnv = { ...process.env, ...(options.env ?? {}) };
171
+ if (preferSubscription) {
172
+ // Force keychain/OAuth path — matches what the user's interactive `claude` uses.
173
+ delete spawnEnv.ANTHROPIC_API_KEY;
174
+ delete spawnEnv.ANTHROPIC_AUTH_TOKEN;
175
+ delete spawnEnv.CLAUDE_API_KEY;
176
+ }
177
+ let child;
178
+ try {
179
+ child = spawn('claude', ['-p', prompt, ...HEADLESS_FLAGS, ...(options.extraArgs ?? [])], {
180
+ cwd,
181
+ env: spawnEnv,
182
+ stdio: ['ignore', 'pipe', 'pipe'],
183
+ });
184
+ }
185
+ catch (err) {
186
+ statusValue = 'error';
187
+ const msg = err instanceof Error ? err.message : String(err);
188
+ // Emit synchronously so subscribers added immediately after see it
189
+ queueMicrotask(() => emit({ type: 'error', timestamp: Date.now(), data: { message: msg } }));
190
+ return {
191
+ sessionId,
192
+ startedAt,
193
+ prompt,
194
+ agent: 'claude-code',
195
+ get status() {
196
+ return statusValue;
197
+ },
198
+ get steps() {
199
+ return stepsSnapshot;
200
+ },
201
+ get artifacts() {
202
+ return artifactsSnapshot;
203
+ },
204
+ subscribe(handler) {
205
+ for (const e of buffer)
206
+ handler(e);
207
+ emitter.on('event', handler);
208
+ return () => emitter.off('event', handler);
209
+ },
210
+ kill() {
211
+ /* already not running */
212
+ },
213
+ };
214
+ }
215
+ // ── stdout: newline-delimited JSON from `--output-format stream-json` ────────
216
+ let stdoutBuf = '';
217
+ child.stdout?.on('data', (chunk) => {
218
+ stdoutBuf += chunk.toString('utf-8');
219
+ let idx;
220
+ while ((idx = stdoutBuf.indexOf('\n')) >= 0) {
221
+ const line = stdoutBuf.slice(0, idx).trim();
222
+ stdoutBuf = stdoutBuf.slice(idx + 1);
223
+ if (!line)
224
+ continue;
225
+ try {
226
+ const data = JSON.parse(line);
227
+ emit({ type: data.type ?? 'message', timestamp: Date.now(), data });
228
+ }
229
+ catch {
230
+ // Non-JSON stdout line — preserve so callers can see raw output
231
+ emit({ type: 'stdout', timestamp: Date.now(), data: { line } });
232
+ }
233
+ }
234
+ });
235
+ // ── stderr: Claude prints debug/errors here; forward raw ─────────────────────
236
+ child.stderr?.on('data', (chunk) => {
237
+ const text = chunk.toString('utf-8');
238
+ for (const line of text.split('\n')) {
239
+ if (line.trim())
240
+ emit({ type: 'stderr', timestamp: Date.now(), data: { line } });
241
+ }
242
+ });
243
+ child.on('exit', (code, signal) => {
244
+ statusValue =
245
+ killRequested || signal !== null ? 'killed' : errorEmitted ? 'error' : code === 0 ? 'completed' : 'error';
246
+ // Emit synthetic PM events BEFORE 'exit' so the client has time to render
247
+ // them before its onmessage handler closes the SSE stream in response to exit.
248
+ // (Client must close on exit to avoid leaking connections — but close() cancels
249
+ // pending messages, so order matters.)
250
+ // Layer 2: flip any still-active steps to done/failed so the UI stops spinning.
251
+ if (aggregator.finalize(statusValue === 'completed' ? 'completed' : statusValue === 'killed' ? 'killed' : 'error')) {
252
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
253
+ emit({ type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } });
254
+ }
255
+ // Layer 3: on clean completion, extract artifacts (git diff + trust + tests + tokens) and announce.
256
+ if (statusValue === 'completed') {
257
+ try {
258
+ artifactsSnapshot = { ...extractArtifacts(snapshot, textAccum), usage: usageSnapshot };
259
+ emit({ type: 'codehere:artifacts', timestamp: Date.now(), data: artifactsSnapshot });
260
+ }
261
+ catch {
262
+ /* best-effort; don't break exit path */
263
+ }
264
+ }
265
+ emit({
266
+ type: 'exit',
267
+ timestamp: Date.now(),
268
+ data: { code, signal, status: statusValue, durationMs: Date.now() - startedAt },
269
+ });
270
+ });
271
+ child.on('error', (err) => {
272
+ statusValue = 'error';
273
+ emit({ type: 'error', timestamp: Date.now(), data: { message: err.message } });
274
+ });
275
+ return {
276
+ sessionId,
277
+ startedAt,
278
+ prompt,
279
+ agent: 'claude-code',
280
+ get status() {
281
+ return statusValue;
282
+ },
283
+ get steps() {
284
+ return stepsSnapshot;
285
+ },
286
+ get artifacts() {
287
+ return artifactsSnapshot;
288
+ },
289
+ subscribe(handler) {
290
+ for (const e of buffer)
291
+ handler(e);
292
+ emitter.on('event', handler);
293
+ return () => emitter.off('event', handler);
294
+ },
295
+ kill() {
296
+ if (statusValue !== 'running')
297
+ return;
298
+ killRequested = true;
299
+ child.kill('SIGTERM');
300
+ // Escalate if it doesn't die in 3s
301
+ setTimeout(() => {
302
+ if (statusValue === 'running') {
303
+ try {
304
+ child.kill('SIGKILL');
305
+ }
306
+ catch {
307
+ /* already dead */
308
+ }
309
+ }
310
+ }, 3000);
311
+ },
312
+ };
313
+ }
314
+ // ── AgentAdapter implementation ─────────────────────────────────────────────
315
+ export const ClaudeCodeAdapter = {
316
+ id: 'claude-code',
317
+ label: 'Claude Code',
318
+ processPattern: /(?:^|\/)claude(?:\s|$)/,
319
+ isInstalled() {
320
+ try {
321
+ const out = execFileSync('which', ['claude'], { encoding: 'utf-8', timeout: 2000 });
322
+ return out.trim().length > 0;
323
+ }
324
+ catch {
325
+ return false;
326
+ }
327
+ },
328
+ spawn(prompt, options) {
329
+ return spawnClaudeCode(prompt, options);
330
+ },
331
+ checkReadiness() {
332
+ const installed = this.isInstalled();
333
+ if (!installed) {
334
+ return {
335
+ id: this.id,
336
+ label: this.label,
337
+ state: 'needs_install',
338
+ installed: false,
339
+ installHint: {
340
+ command: 'npm install -g @anthropic-ai/claude-code',
341
+ url: 'https://docs.claude.com/en/docs/claude-code/setup',
342
+ },
343
+ };
344
+ }
345
+ // Claude Code supports BOTH subscription (OAuth via keychain) and API key.
346
+ // "Ready" if either path works. We can't verify subscription without
347
+ // calling the API, so we treat any Claude Code install as ready by default —
348
+ // runtime F1b error-fingerprints catch real auth failures after spawn.
349
+ return { id: this.id, label: this.label, state: 'ready', installed: true };
350
+ },
351
+ };
352
+ //# sourceMappingURL=claude-code-adapter.js.map
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Codex adapter — F2 second concrete AgentAdapter (v0.4 → shipping in v0.3.0-alpha.4).
3
+ *
4
+ * Wraps `codex exec --json "<prompt>"` as a subprocess. Codex CLI's --json
5
+ * flag emits JSONL on stdout; we tokenize, parse, forward as TaskEvents.
6
+ *
7
+ * Event shapes are not fully documented — renderer handles unknowns by falling
8
+ * through (same pattern as ClaudeCodeAdapter: skip tokens we can't shape, fire
9
+ * raw stdout for anything else). First dogfood session will show what's real.
10
+ *
11
+ * Same structural pattern as ClaudeCodeAdapter: event buffer, late-joiner replay,
12
+ * SIGTERM→SIGKILL escalation, known-error fingerprints. Intentionally duplicates
13
+ * some structure — premature shared-base-class abstraction would couple adapters
14
+ * that may diverge substantially (each agent CLI has its own quirks).
15
+ */
16
+ import { spawn, execFileSync } from 'child_process';
17
+ import { EventEmitter } from 'events';
18
+ import { randomUUID } from 'crypto';
19
+ import { ProgressAggregator } from './progress-aggregator.js';
20
+ import { snapshotCwd, extractArtifacts } from './artifacts-extractor.js';
21
+ const HEADLESS_FLAGS = [
22
+ 'exec',
23
+ '--json',
24
+ // codehere is the external safety layer — every tool call goes through
25
+ // our PreToolUse hook (F0) which is where destructive-command scanning
26
+ // happens. codex's own gates in -p mode are redundant AND block tasks
27
+ // from actually running, so we bypass both:
28
+ //
29
+ // --skip-git-repo-check: run outside a git repo (like /tmp, home, etc)
30
+ // --dangerously-bypass-approvals-and-sandbox: skip codex's read-only
31
+ // sandbox (blocks writes) and its interactive approval prompts
32
+ // (impossible to answer in -p mode anyway).
33
+ //
34
+ // codex's own help text: "EXTREMELY DANGEROUS. Intended solely for
35
+ // running in environments that are externally sandboxed." — that's us.
36
+ '--skip-git-repo-check',
37
+ '--dangerously-bypass-approvals-and-sandbox',
38
+ ];
39
+ const ERROR_PATTERNS = [
40
+ {
41
+ code: 'auth_invalid',
42
+ regex: /not\s+logged\s+in|authentication\s+failed|401 unauth/i,
43
+ message: 'Codex auth missing or rejected.',
44
+ recovery: 'Run `codex login` in a terminal, then retry the task.',
45
+ },
46
+ {
47
+ code: 'rate_limit',
48
+ regex: /rate.?limit(ed)?|429|too many requests/i,
49
+ message: 'Codex rate-limited the request.',
50
+ recovery: 'Wait a minute and retry, or check your OpenAI usage dashboard.',
51
+ },
52
+ {
53
+ code: 'quota_exceeded',
54
+ regex: /quota|insufficient_quota|you exceeded your current quota/i,
55
+ message: 'OpenAI quota exhausted.',
56
+ recovery: 'Top up at platform.openai.com or switch to a different agent.',
57
+ },
58
+ ];
59
+ function scanForKnownError(text) {
60
+ for (const p of ERROR_PATTERNS) {
61
+ if (p.regex.test(text))
62
+ return { code: p.code, message: p.message, recovery: p.recovery };
63
+ }
64
+ return null;
65
+ }
66
+ export function spawnCodex(prompt, options = {}) {
67
+ const sessionId = randomUUID();
68
+ const startedAt = Date.now();
69
+ const emitter = new EventEmitter();
70
+ const buffer = [];
71
+ let statusValue = 'running';
72
+ let killRequested = false;
73
+ // PM UX Layer 2+3 state — same shape as claude-code-adapter. Kept in-file (not
74
+ // extracted to a base class) because the two CLIs diverge in more than they share.
75
+ const cwd = options.cwd ?? process.cwd();
76
+ const snapshot = snapshotCwd(cwd);
77
+ const aggregator = new ProgressAggregator('codex');
78
+ let stepsSnapshot = [];
79
+ let artifactsSnapshot;
80
+ let textAccum = '';
81
+ // Codex emits one turn.completed per turn; sum across turns for session total.
82
+ let usageSnapshot;
83
+ let errorEmitted = false;
84
+ const emit = (event) => {
85
+ buffer.push(event);
86
+ emitter.emit('event', event);
87
+ // Layer 2: aggregate + emit synthetic snapshot on change.
88
+ if (aggregator.ingest(event)) {
89
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
90
+ const snapEvt = { type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } };
91
+ buffer.push(snapEvt);
92
+ emitter.emit('event', snapEvt);
93
+ }
94
+ // Collect text for test-summary parsing (Layer 3). Codex surfaces command
95
+ // output via item.completed.aggregated_output and agent messages via item.text.
96
+ if (event.type === 'item.completed') {
97
+ const item = event.data?.item;
98
+ if (item?.type === 'command_execution' && item.aggregated_output)
99
+ textAccum += item.aggregated_output + '\n';
100
+ if (item?.type === 'agent_message' && item.text)
101
+ textAccum += item.text + '\n';
102
+ }
103
+ // Accumulate token usage across all turns (one turn.completed per turn).
104
+ if (event.type === 'turn.completed') {
105
+ const u = event.data?.usage;
106
+ if (u) {
107
+ const acc = usageSnapshot ?? { inputTokens: 0, outputTokens: 0 };
108
+ acc.inputTokens += Number(u.input_tokens ?? 0);
109
+ acc.outputTokens += Number(u.output_tokens ?? 0);
110
+ if (u.cached_input_tokens)
111
+ acc.cacheReadTokens = (acc.cacheReadTokens ?? 0) + Number(u.cached_input_tokens);
112
+ usageSnapshot = acc;
113
+ }
114
+ }
115
+ if (!errorEmitted) {
116
+ const data = event.data;
117
+ let text = '';
118
+ if (event.type === 'stderr' && data && typeof data.line === 'string') {
119
+ text = data.line;
120
+ }
121
+ else if (event.type === 'stdout' && data && typeof data.line === 'string') {
122
+ text = data.line;
123
+ }
124
+ else if (data && typeof data === 'object') {
125
+ // Catch-all: scan any string fields for known error patterns
126
+ text = JSON.stringify(data);
127
+ }
128
+ if (text) {
129
+ const hit = scanForKnownError(text);
130
+ if (hit) {
131
+ errorEmitted = true;
132
+ const errEvent = {
133
+ type: 'codehere:error',
134
+ timestamp: Date.now(),
135
+ data: { code: hit.code, message: hit.message, recovery: hit.recovery },
136
+ };
137
+ buffer.push(errEvent);
138
+ emitter.emit('event', errEvent);
139
+ }
140
+ }
141
+ }
142
+ };
143
+ const spawnEnv = { ...process.env, ...(options.env ?? {}) };
144
+ let child;
145
+ try {
146
+ // Codex expects the prompt via stdin when stdin is piped; passing as argv
147
+ // while stdin is 'ignore' causes codex to hang waiting for EOF → exit 0
148
+ // with no task run. Pipe stdin, write prompt, close.
149
+ child = spawn('codex', [...HEADLESS_FLAGS, ...(options.extraArgs ?? [])], {
150
+ cwd,
151
+ env: spawnEnv,
152
+ stdio: ['pipe', 'pipe', 'pipe'],
153
+ });
154
+ child.stdin?.write(prompt);
155
+ child.stdin?.end();
156
+ }
157
+ catch (err) {
158
+ statusValue = 'error';
159
+ const msg = err instanceof Error ? err.message : String(err);
160
+ queueMicrotask(() => emit({ type: 'error', timestamp: Date.now(), data: { message: msg } }));
161
+ return {
162
+ sessionId,
163
+ startedAt,
164
+ prompt,
165
+ agent: 'codex',
166
+ get status() {
167
+ return statusValue;
168
+ },
169
+ get steps() {
170
+ return stepsSnapshot;
171
+ },
172
+ get artifacts() {
173
+ return artifactsSnapshot;
174
+ },
175
+ subscribe(handler) {
176
+ for (const e of buffer)
177
+ handler(e);
178
+ emitter.on('event', handler);
179
+ return () => emitter.off('event', handler);
180
+ },
181
+ kill() {
182
+ /* already not running */
183
+ },
184
+ };
185
+ }
186
+ let stdoutBuf = '';
187
+ child.stdout?.on('data', (chunk) => {
188
+ stdoutBuf += chunk.toString('utf-8');
189
+ let idx;
190
+ while ((idx = stdoutBuf.indexOf('\n')) >= 0) {
191
+ const line = stdoutBuf.slice(0, idx).trim();
192
+ stdoutBuf = stdoutBuf.slice(idx + 1);
193
+ if (!line)
194
+ continue;
195
+ try {
196
+ const data = JSON.parse(line);
197
+ emit({ type: data.type ?? 'codex_event', timestamp: Date.now(), data });
198
+ }
199
+ catch {
200
+ emit({ type: 'stdout', timestamp: Date.now(), data: { line } });
201
+ }
202
+ }
203
+ });
204
+ child.stderr?.on('data', (chunk) => {
205
+ const text = chunk.toString('utf-8');
206
+ for (const line of text.split('\n')) {
207
+ if (line.trim())
208
+ emit({ type: 'stderr', timestamp: Date.now(), data: { line } });
209
+ }
210
+ });
211
+ child.on('exit', (code, signal) => {
212
+ statusValue =
213
+ killRequested || signal !== null ? 'killed' : errorEmitted ? 'error' : code === 0 ? 'completed' : 'error';
214
+ // PM events BEFORE 'exit' — see claude-code-adapter for rationale
215
+ // (client closes SSE on exit; close() cancels pending messages, so order matters).
216
+ if (aggregator.finalize(statusValue === 'completed' ? 'completed' : statusValue === 'killed' ? 'killed' : 'error')) {
217
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
218
+ emit({ type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } });
219
+ }
220
+ if (statusValue === 'completed') {
221
+ try {
222
+ artifactsSnapshot = { ...extractArtifacts(snapshot, textAccum), usage: usageSnapshot };
223
+ emit({ type: 'codehere:artifacts', timestamp: Date.now(), data: artifactsSnapshot });
224
+ }
225
+ catch {
226
+ /* best-effort */
227
+ }
228
+ }
229
+ emit({
230
+ type: 'exit',
231
+ timestamp: Date.now(),
232
+ data: { code, signal, status: statusValue, durationMs: Date.now() - startedAt },
233
+ });
234
+ });
235
+ child.on('error', (err) => {
236
+ statusValue = 'error';
237
+ emit({ type: 'error', timestamp: Date.now(), data: { message: err.message } });
238
+ });
239
+ return {
240
+ sessionId,
241
+ startedAt,
242
+ prompt,
243
+ agent: 'codex',
244
+ get status() {
245
+ return statusValue;
246
+ },
247
+ get steps() {
248
+ return stepsSnapshot;
249
+ },
250
+ get artifacts() {
251
+ return artifactsSnapshot;
252
+ },
253
+ subscribe(handler) {
254
+ for (const e of buffer)
255
+ handler(e);
256
+ emitter.on('event', handler);
257
+ return () => emitter.off('event', handler);
258
+ },
259
+ kill() {
260
+ if (statusValue !== 'running')
261
+ return;
262
+ killRequested = true;
263
+ child.kill('SIGTERM');
264
+ setTimeout(() => {
265
+ if (statusValue === 'running') {
266
+ try {
267
+ child.kill('SIGKILL');
268
+ }
269
+ catch {
270
+ /* already dead */
271
+ }
272
+ }
273
+ }, 3000);
274
+ },
275
+ };
276
+ }
277
+ export const CodexAdapter = {
278
+ id: 'codex',
279
+ label: 'Codex',
280
+ processPattern: /(?:^|\/)codex(?:\s|$)/,
281
+ isInstalled() {
282
+ try {
283
+ const out = execFileSync('which', ['codex'], { encoding: 'utf-8', timeout: 2000 });
284
+ return out.trim().length > 0;
285
+ }
286
+ catch {
287
+ return false;
288
+ }
289
+ },
290
+ spawn(prompt, options) {
291
+ return spawnCodex(prompt, options);
292
+ },
293
+ checkReadiness() {
294
+ const installed = this.isInstalled();
295
+ if (!installed) {
296
+ return {
297
+ id: this.id,
298
+ label: this.label,
299
+ state: 'needs_install',
300
+ installed: false,
301
+ installHint: { command: 'npm install -g @openai/codex', url: 'https://github.com/openai/codex-cli' },
302
+ };
303
+ }
304
+ // Codex supports ChatGPT account auth via `codex login` (similar to Claude
305
+ // Code's OAuth) OR OPENAI_API_KEY. Can't verify without calling out — let
306
+ // runtime catch real failures.
307
+ return { id: this.id, label: this.label, state: 'ready', installed: true };
308
+ },
309
+ };
310
+ //# sourceMappingURL=codex-adapter.js.map