codehere 0.2.2 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) 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 +253 -1219
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +335 -63
  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/generic-cli-adapter.js +553 -0
  16. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  17. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  18. package/dist/infrastructure/orchestration/readiness.js +106 -0
  19. package/dist/infrastructure/orchestration/session-manager.js +272 -0
  20. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  21. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  22. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  23. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  24. package/dist/infrastructure/security/file-collection.js +115 -0
  25. package/dist/infrastructure/security/trust-scorer.js +301 -56
  26. package/dist/infrastructure/storage/task-repository.js +8 -7
  27. package/dist/monitoring.js +9 -38
  28. package/dist/presentation/cli/commands/help-command.js +96 -139
  29. package/dist/presentation/cli/commands/hook-command.js +17 -24
  30. package/dist/presentation/cli/commands/report-command.js +59 -72
  31. package/dist/presentation/cli/commands/setup-command.js +4 -4
  32. package/dist/presentation/cli/commands/status-command.js +321 -30
  33. package/dist/presentation/cli/commands/trust-command.js +84 -72
  34. package/dist/presentation/cli/error-display.js +17 -21
  35. package/dist/ui.js +11 -11
  36. package/package.json +24 -62
  37. package/dist/agents/base.js +0 -101
  38. package/dist/agents/orchestrator-model-driven.js +0 -141
  39. package/dist/agents/react-orchestrator-agent.js +0 -54
  40. package/dist/application/agents/execution-agent.js +0 -508
  41. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  42. package/dist/application/agents/planning-agent.js +0 -433
  43. package/dist/application/agents/validation-agent.js +0 -317
  44. package/dist/application/architectures/plan-and-act.js +0 -242
  45. package/dist/application/index.js +0 -12
  46. package/dist/application/services/agent-factory.js +0 -28
  47. package/dist/application/services/dependency-container.js +0 -596
  48. package/dist/application/services/git-context-service.js +0 -83
  49. package/dist/application/services/intelligent-router.js +0 -934
  50. package/dist/application/services/tool-executor-service.js +0 -94
  51. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  52. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  53. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  54. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  55. package/dist/application/use-cases/planning-use-case.js +0 -276
  56. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  57. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  58. package/dist/application/workflows/deterministic-workflows.js +0 -189
  59. package/dist/ast-parser.js +0 -331
  60. package/dist/cache.js +0 -180
  61. package/dist/chat.js +0 -251
  62. package/dist/code-analysis.js +0 -327
  63. package/dist/context.js +0 -187
  64. package/dist/docs.js +0 -146
  65. package/dist/domain/entities/code-chunk.js +0 -6
  66. package/dist/domain/entities/decision.js +0 -9
  67. package/dist/domain/entities/edit.js +0 -6
  68. package/dist/domain/entities/knowledge-node.js +0 -9
  69. package/dist/domain/entities/knowledge-preservation.js +0 -10
  70. package/dist/domain/entities/memory.js +0 -6
  71. package/dist/domain/entities/pattern.js +0 -7
  72. package/dist/domain/entities/plan.js +0 -6
  73. package/dist/domain/entities/query.js +0 -6
  74. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  75. package/dist/domain/index.js +0 -19
  76. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  77. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  78. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  79. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  80. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  81. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  82. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  84. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  85. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  86. package/dist/domain/services/decision-recorder.js +0 -223
  87. package/dist/domain/services/decision-retriever.js +0 -133
  88. package/dist/domain/services/environment-mode-manager.js +0 -22
  89. package/dist/domain/services/graded-memory-activation.js +0 -69
  90. package/dist/domain/services/knowledge-access.js +0 -132
  91. package/dist/domain/services/knowledge-extractor.js +0 -247
  92. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  93. package/dist/domain/services/knowledge-graph-query.js +0 -187
  94. package/dist/domain/services/memory-retriever.js +0 -82
  95. package/dist/domain/services/memory-synthesizer.js +0 -91
  96. package/dist/domain/services/pattern-extractor.js +0 -442
  97. package/dist/domain/services/query-intent-classifier.js +0 -140
  98. package/dist/domain/services/react-loop.js +0 -186
  99. package/dist/domain/services/risk-tier-detector.js +0 -78
  100. package/dist/edit.js +0 -319
  101. package/dist/embed.js +0 -459
  102. package/dist/formatter.js +0 -168
  103. package/dist/git.js +0 -198
  104. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  105. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  106. package/dist/infrastructure/ai/model-config.js +0 -84
  107. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  108. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  109. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  110. package/dist/infrastructure/cache/response-cache.js +0 -48
  111. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  112. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  113. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  114. package/dist/infrastructure/context/context-compressor.js +0 -329
  115. package/dist/infrastructure/context/conversation-context.js +0 -128
  116. package/dist/infrastructure/context/session-manager.js +0 -94
  117. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  118. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  119. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  120. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  121. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  122. package/dist/infrastructure/index.js +0 -7
  123. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  124. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  125. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  126. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  127. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  128. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  129. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  130. package/dist/infrastructure/providers/fake-provider.js +0 -130
  131. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  132. package/dist/infrastructure/providers/model-config.types.js +0 -9
  133. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  134. package/dist/infrastructure/providers/openai-provider.js +0 -413
  135. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  136. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  137. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  138. package/dist/infrastructure/providers/provider-registry.js +0 -88
  139. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  140. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  141. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  142. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  143. package/dist/infrastructure/security/license-scanner.js +0 -167
  144. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  145. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  146. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  147. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  148. package/dist/infrastructure/storage/plan-repository.js +0 -96
  149. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  150. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  151. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  152. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  153. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  154. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  155. package/dist/infrastructure/storage/task-helpers.js +0 -197
  156. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  157. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  158. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  159. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  160. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  161. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  162. package/dist/infrastructure/ux/expectation-management.js +0 -327
  163. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  164. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  165. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  166. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  167. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  168. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  169. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  170. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  171. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  172. package/dist/infrastructure/ux/team-standards.js +0 -196
  173. package/dist/infrastructure/ux/transparency.js +0 -71
  174. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  175. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  176. package/dist/infrastructure/validation/review-handler.js +0 -40
  177. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  178. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  179. package/dist/infrastructure/validation/trace-summary.js +0 -52
  180. package/dist/infrastructure/verification/verification-service.js +0 -47
  181. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  182. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  183. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  184. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  185. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  186. package/dist/intelligent-retrieval.js +0 -272
  187. package/dist/intent/classifier.js +0 -2
  188. package/dist/intent/context.js +0 -2
  189. package/dist/iterative-refinement.js +0 -189
  190. package/dist/learning.js +0 -232
  191. package/dist/log.js +0 -31
  192. package/dist/migrate.js +0 -133
  193. package/dist/parallel-processor.js +0 -534
  194. package/dist/planner.js +0 -198
  195. package/dist/policy.js +0 -26
  196. package/dist/presentation/cli/commands/ask-command.js +0 -314
  197. package/dist/presentation/cli/commands/cost-command.js +0 -191
  198. package/dist/presentation/cli/commands/decision-command.js +0 -207
  199. package/dist/presentation/cli/commands/docs-command.js +0 -25
  200. package/dist/presentation/cli/commands/fix-command.js +0 -53
  201. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  202. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  203. package/dist/presentation/cli/commands/models-command.js +0 -194
  204. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  205. package/dist/presentation/cli/commands/plan-command.js +0 -246
  206. package/dist/presentation/cli/commands/product-command.js +0 -199
  207. package/dist/presentation/cli/commands/react-command.js +0 -181
  208. package/dist/presentation/cli/commands/review-command.js +0 -154
  209. package/dist/presentation/cli/commands/run-command.js +0 -188
  210. package/dist/presentation/cli/commands/smart-command.js +0 -395
  211. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  212. package/dist/presentation/cli/commands/trace-command.js +0 -129
  213. package/dist/presentation/cli/commands/undo-command.js +0 -150
  214. package/dist/query-optimizer.js +0 -205
  215. package/dist/refactor.js +0 -116
  216. package/dist/review.js +0 -206
  217. package/dist/search.js +0 -163
  218. package/dist/session.js +0 -704
  219. package/dist/task-verification.js +0 -336
  220. package/dist/testgen.js +0 -166
  221. package/dist/token-optimizer.js +0 -277
  222. package/dist/tools/bash.js +0 -213
  223. package/dist/tools/edit.js +0 -235
  224. package/dist/tools/executor.js +0 -153
  225. package/dist/tools/git-tool.js +0 -292
  226. package/dist/tools/parser.js +0 -158
  227. package/dist/tools/registry.js +0 -302
  228. package/dist/tools/search.js +0 -100
  229. package/dist/types.js +0 -2
  230. package/dist/utils/check-api-status.js +0 -100
  231. package/dist/utils/diff-parser.js +0 -162
  232. package/dist/verification/backup.js +0 -259
  233. package/dist/verification/compiler.js +0 -264
  234. package/dist/verification/index.js +0 -273
  235. package/dist/verification/test-runner.js +0 -379
@@ -0,0 +1,275 @@
1
+ /**
2
+ * OpenCode adapter — fourth concrete AgentAdapter.
3
+ *
4
+ * `opencode run --format json "<prompt>"`
5
+ *
6
+ * OpenCode's --format json emits newline-delimited JSON (same general shape as
7
+ * Claude Code and Codex). Event types observed: step_start, text, step_finish
8
+ * (carries token counts + cost). Tool-call events likely fire in larger tasks
9
+ * (unconfirmed on probe) — renderer falls through gracefully for unknowns.
10
+ *
11
+ * Same spawn-pattern pattern as Codex.
12
+ */
13
+ import { spawn, execFileSync } from 'child_process';
14
+ import { EventEmitter } from 'events';
15
+ import { randomUUID } from 'crypto';
16
+ import { ProgressAggregator } from './progress-aggregator.js';
17
+ import { snapshotCwd, extractArtifacts } from './artifacts-extractor.js';
18
+ const HEADLESS_FLAGS = ['run', '--format', 'json'];
19
+ const ERROR_PATTERNS = [
20
+ {
21
+ code: 'auth_invalid',
22
+ regex: /not\s+logged\s+in|authentication\s+failed|401 unauth|no credentials/i,
23
+ message: 'OpenCode auth missing or rejected.',
24
+ recovery: 'Run `opencode providers` (alias `opencode auth`) to configure a provider, then retry.',
25
+ },
26
+ {
27
+ code: 'rate_limit',
28
+ regex: /rate.?limit(ed)?|429|too many requests/i,
29
+ message: 'OpenCode rate-limited the request.',
30
+ recovery: 'Wait a minute and retry, or swap provider via --model.',
31
+ },
32
+ ];
33
+ function scanForKnownError(text) {
34
+ for (const p of ERROR_PATTERNS) {
35
+ if (p.regex.test(text))
36
+ return { code: p.code, message: p.message, recovery: p.recovery };
37
+ }
38
+ return null;
39
+ }
40
+ export function spawnOpenCode(prompt, options = {}) {
41
+ const sessionId = randomUUID();
42
+ const startedAt = Date.now();
43
+ const emitter = new EventEmitter();
44
+ const buffer = [];
45
+ let statusValue = 'running';
46
+ let killRequested = false;
47
+ const cwd = options.cwd ?? process.cwd();
48
+ const snapshot = snapshotCwd(cwd);
49
+ const aggregator = new ProgressAggregator('opencode');
50
+ let stepsSnapshot = [];
51
+ let artifactsSnapshot;
52
+ let textAccum = '';
53
+ let usageSnapshot;
54
+ let errorEmitted = false;
55
+ const emit = (event) => {
56
+ buffer.push(event);
57
+ emitter.emit('event', event);
58
+ if (aggregator.ingest(event)) {
59
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
60
+ const snapEvt = { type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } };
61
+ buffer.push(snapEvt);
62
+ emitter.emit('event', snapEvt);
63
+ }
64
+ // OpenCode token accounting: step_finish events carry .part.tokens.{input,output,cache.{read,write}}.
65
+ // Sum across all steps for session total.
66
+ if (event.type === 'step_finish') {
67
+ const part = event.data?.part;
68
+ const t = part?.tokens;
69
+ if (t) {
70
+ const input = Number(t.input ?? 0);
71
+ const output = Number(t.output ?? 0);
72
+ const cache = t.cache ?? {};
73
+ const acc = usageSnapshot ?? { inputTokens: 0, outputTokens: 0 };
74
+ acc.inputTokens += input;
75
+ // OpenCode's output_tokens is sometimes negative on error/cancellation; floor at 0
76
+ acc.outputTokens += Math.max(0, output);
77
+ if (cache.read)
78
+ acc.cacheReadTokens = (acc.cacheReadTokens ?? 0) + Number(cache.read);
79
+ if (cache.write)
80
+ acc.cacheCreationTokens = (acc.cacheCreationTokens ?? 0) + Number(cache.write);
81
+ usageSnapshot = acc;
82
+ }
83
+ }
84
+ // Text for test-summary parsing: pull from `text` events' part.text
85
+ if (event.type === 'text') {
86
+ const txt = event.data?.part?.text;
87
+ if (txt)
88
+ textAccum += txt + '\n';
89
+ }
90
+ if (!errorEmitted) {
91
+ const data = event.data;
92
+ let text = '';
93
+ if (event.type === 'stderr' && typeof data?.line === 'string')
94
+ text = data.line;
95
+ else if (event.type === 'stdout' && typeof data?.line === 'string')
96
+ text = data.line;
97
+ else if (data && typeof data === 'object')
98
+ text = JSON.stringify(data);
99
+ if (text) {
100
+ const hit = scanForKnownError(text);
101
+ if (hit) {
102
+ errorEmitted = true;
103
+ const errEvent = {
104
+ type: 'codehere:error',
105
+ timestamp: Date.now(),
106
+ data: { code: hit.code, message: hit.message, recovery: hit.recovery },
107
+ };
108
+ buffer.push(errEvent);
109
+ emitter.emit('event', errEvent);
110
+ }
111
+ }
112
+ }
113
+ };
114
+ const spawnEnv = { ...process.env, ...(options.env ?? {}) };
115
+ let child;
116
+ try {
117
+ // OpenCode's `run` expects the message as positional args, not stdin.
118
+ child = spawn('opencode', [...HEADLESS_FLAGS, prompt, ...(options.extraArgs ?? [])], {
119
+ cwd,
120
+ env: spawnEnv,
121
+ stdio: ['ignore', 'pipe', 'pipe'],
122
+ });
123
+ }
124
+ catch (err) {
125
+ statusValue = 'error';
126
+ const msg = err instanceof Error ? err.message : String(err);
127
+ queueMicrotask(() => emit({ type: 'error', timestamp: Date.now(), data: { message: msg } }));
128
+ return {
129
+ sessionId,
130
+ startedAt,
131
+ prompt,
132
+ agent: 'opencode',
133
+ get status() {
134
+ return statusValue;
135
+ },
136
+ get steps() {
137
+ return stepsSnapshot;
138
+ },
139
+ get artifacts() {
140
+ return artifactsSnapshot;
141
+ },
142
+ subscribe(handler) {
143
+ for (const e of buffer)
144
+ handler(e);
145
+ emitter.on('event', handler);
146
+ return () => emitter.off('event', handler);
147
+ },
148
+ kill() {
149
+ /* already not running */
150
+ },
151
+ };
152
+ }
153
+ let stdoutBuf = '';
154
+ child.stdout?.on('data', (chunk) => {
155
+ stdoutBuf += chunk.toString('utf-8');
156
+ let idx;
157
+ while ((idx = stdoutBuf.indexOf('\n')) >= 0) {
158
+ const line = stdoutBuf.slice(0, idx).trim();
159
+ stdoutBuf = stdoutBuf.slice(idx + 1);
160
+ if (!line)
161
+ continue;
162
+ try {
163
+ const data = JSON.parse(line);
164
+ emit({ type: data.type ?? 'opencode_event', timestamp: Date.now(), data });
165
+ }
166
+ catch {
167
+ emit({ type: 'stdout', timestamp: Date.now(), data: { line } });
168
+ }
169
+ }
170
+ });
171
+ child.stderr?.on('data', (chunk) => {
172
+ const text = chunk.toString('utf-8');
173
+ for (const line of text.split('\n')) {
174
+ if (line.trim())
175
+ emit({ type: 'stderr', timestamp: Date.now(), data: { line } });
176
+ }
177
+ });
178
+ child.on('exit', (code, signal) => {
179
+ statusValue =
180
+ killRequested || signal !== null ? 'killed' : errorEmitted ? 'error' : code === 0 ? 'completed' : 'error';
181
+ if (aggregator.finalize(statusValue === 'completed' ? 'completed' : statusValue === 'killed' ? 'killed' : 'error')) {
182
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
183
+ emit({ type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } });
184
+ }
185
+ if (statusValue === 'completed') {
186
+ try {
187
+ artifactsSnapshot = { ...extractArtifacts(snapshot, textAccum), usage: usageSnapshot };
188
+ emit({ type: 'codehere:artifacts', timestamp: Date.now(), data: artifactsSnapshot });
189
+ }
190
+ catch {
191
+ /* best-effort */
192
+ }
193
+ }
194
+ emit({
195
+ type: 'exit',
196
+ timestamp: Date.now(),
197
+ data: { code, signal, status: statusValue, durationMs: Date.now() - startedAt },
198
+ });
199
+ });
200
+ child.on('error', (err) => {
201
+ statusValue = 'error';
202
+ emit({ type: 'error', timestamp: Date.now(), data: { message: err.message } });
203
+ });
204
+ return {
205
+ sessionId,
206
+ startedAt,
207
+ prompt,
208
+ agent: 'opencode',
209
+ get status() {
210
+ return statusValue;
211
+ },
212
+ get steps() {
213
+ return stepsSnapshot;
214
+ },
215
+ get artifacts() {
216
+ return artifactsSnapshot;
217
+ },
218
+ subscribe(handler) {
219
+ for (const e of buffer)
220
+ handler(e);
221
+ emitter.on('event', handler);
222
+ return () => emitter.off('event', handler);
223
+ },
224
+ kill() {
225
+ if (statusValue !== 'running')
226
+ return;
227
+ killRequested = true;
228
+ child.kill('SIGTERM');
229
+ setTimeout(() => {
230
+ if (statusValue === 'running') {
231
+ try {
232
+ child.kill('SIGKILL');
233
+ }
234
+ catch {
235
+ /* already dead */
236
+ }
237
+ }
238
+ }, 3000);
239
+ },
240
+ };
241
+ }
242
+ export const OpenCodeAdapter = {
243
+ id: 'opencode',
244
+ label: 'OpenCode',
245
+ processPattern: /(?:^|\/)opencode(?:\s|$)/,
246
+ isInstalled() {
247
+ try {
248
+ const out = execFileSync('which', ['opencode'], { encoding: 'utf-8', timeout: 2000 });
249
+ return out.trim().length > 0;
250
+ }
251
+ catch {
252
+ return false;
253
+ }
254
+ },
255
+ spawn(prompt, options) {
256
+ return spawnOpenCode(prompt, options);
257
+ },
258
+ checkReadiness() {
259
+ const installed = this.isInstalled();
260
+ if (!installed) {
261
+ return {
262
+ id: this.id,
263
+ label: this.label,
264
+ state: 'needs_install',
265
+ installed: false,
266
+ installHint: { command: 'curl -fsSL https://opencode.ai/install | bash', url: 'https://opencode.ai' },
267
+ };
268
+ }
269
+ // OpenCode manages its own provider credentials via `opencode providers`.
270
+ // Can't statically probe the config without reading its data dir — treat
271
+ // install as ready, let runtime codehere:error catch auth failures.
272
+ return { id: this.id, label: this.label, state: 'ready', installed: true };
273
+ },
274
+ };
275
+ //# sourceMappingURL=opencode-adapter.js.map
@@ -0,0 +1,189 @@
1
+ /**
2
+ * ProgressAggregator — PM UX Layer 2 (principles #1 "web is not a terminal", #2 "info density").
3
+ *
4
+ * Ingests the raw TaskEvent stream and produces semantic ProgressStep[] that a
5
+ * product manager would actually read ("Read src/session.ts", "Run npm test",
6
+ * "Writing reply…") rather than the underlying token-level chatter.
7
+ *
8
+ * Agent-aware by design: Claude's stream-json tool_use blocks and Codex's
9
+ * item.completed entries label differently, so we dispatch on the agent id.
10
+ * Keeps the per-adapter files free of PM-layer concerns.
11
+ */
12
+ const MAX_LABEL = 60;
13
+ function shortPath(p) {
14
+ const parts = String(p).split('/');
15
+ return parts.length <= 2 ? p : '…/' + parts.slice(-2).join('/');
16
+ }
17
+ function truncate(s, max = MAX_LABEL) {
18
+ return s.length > max ? s.slice(0, max - 1) + '…' : s;
19
+ }
20
+ function labelForClaudeToolUse(name, input) {
21
+ const i = (input && typeof input === 'object' ? input : {});
22
+ switch (name) {
23
+ case 'Read':
24
+ return 'Read ' + shortPath(String(i.file_path ?? 'file'));
25
+ case 'Write':
26
+ return 'Write ' + shortPath(String(i.file_path ?? 'file'));
27
+ case 'Edit':
28
+ return 'Edit ' + shortPath(String(i.file_path ?? 'file'));
29
+ case 'MultiEdit': {
30
+ const edits = Array.isArray(i.edits) ? i.edits : [];
31
+ const first = edits[0];
32
+ return `Edit ${shortPath(String(first?.file_path ?? 'file'))} (${edits.length})`;
33
+ }
34
+ case 'NotebookEdit':
35
+ return 'Edit notebook ' + shortPath(String(i.notebook_path ?? 'notebook'));
36
+ case 'Bash': {
37
+ const cmd = String(i.command ?? '')
38
+ .replace(/\n/g, ' ')
39
+ .trim();
40
+ return truncate('Run ' + cmd);
41
+ }
42
+ case 'Grep':
43
+ return 'Grep ' + truncate(String(i.pattern ?? ''), 40);
44
+ case 'Glob':
45
+ return 'List ' + truncate(String(i.pattern ?? ''), 40);
46
+ case 'WebFetch':
47
+ return 'Fetch ' + truncate(String(i.url ?? ''), 50);
48
+ case 'WebSearch':
49
+ return 'Search ' + truncate(String(i.query ?? ''), 50);
50
+ case 'TodoWrite':
51
+ return 'Plan ' + (Array.isArray(i.todos) ? `${i.todos.length} items` : 'tasks');
52
+ case 'Task':
53
+ return 'Delegate to subagent';
54
+ default:
55
+ return truncate(String(name || 'tool'));
56
+ }
57
+ }
58
+ function unwrapShellWrapper(command) {
59
+ // Codex wraps its shell calls in `/bin/zsh -lc "…"` or `sh -c "…"`. Strip that
60
+ // so the step label reads as the actual command instead of the wrapper.
61
+ const m = command.match(/^(?:\/bin\/(?:zsh|bash|sh)|sh|bash|zsh)\s+-l?c\s+["'](.+)["']\s*$/);
62
+ return m ? m[1].trim() : command.trim();
63
+ }
64
+ function labelForCodexCommand(command) {
65
+ const raw = unwrapShellWrapper(String(command).replace(/\n/g, ' ').trim());
66
+ // Heuristic friendly prefix for common operations
67
+ if (/^cat\s+/.test(raw))
68
+ return truncate('Read ' + raw.replace(/^cat\s+/, '').split(/\s+/)[0]);
69
+ if (/^sed\s+-n\s+/.test(raw)) {
70
+ // e.g. `sed -n '1,260p' README.md` → "Read README.md"
71
+ const tail = raw.split(/\s+/).slice(-1)[0];
72
+ return truncate('Read ' + tail);
73
+ }
74
+ if (/^(?:ls|find)\b/.test(raw))
75
+ return truncate('List ' + raw.replace(/^(?:ls|find)\s*/, ''));
76
+ if (/^(?:mkdir|cp|mv|rm|touch)\b/.test(raw) || /\becho\s+.+>/.test(raw))
77
+ return truncate('File op: ' + raw);
78
+ if (/^git\s+/.test(raw))
79
+ return truncate(raw);
80
+ if (/^npm\s+test\b/.test(raw) || /^pytest\b/.test(raw) || /^vitest\b/.test(raw))
81
+ return truncate('Run tests');
82
+ return truncate('Run ' + raw);
83
+ }
84
+ export class ProgressAggregator {
85
+ agentId;
86
+ _steps = [];
87
+ toolUseIndex = new Map(); // tool_use_id → step idx (Claude)
88
+ constructor(agentId) {
89
+ this.agentId = agentId;
90
+ }
91
+ get steps() {
92
+ return this._steps;
93
+ }
94
+ /** @returns true if the step list changed (caller emits synthetic event). */
95
+ ingest(event) {
96
+ const type = String(event.type || '');
97
+ const data = (event.data ?? {});
98
+ if (this.agentId === 'claude-code')
99
+ return this.ingestClaude(type, data);
100
+ if (this.agentId === 'codex')
101
+ return this.ingestCodex(type, data);
102
+ return false;
103
+ }
104
+ /** Flush: mark every still-active step as failed (called on abnormal exit). */
105
+ finalize(status) {
106
+ let changed = false;
107
+ for (const s of this._steps) {
108
+ if (s.state === 'active' || s.state === 'pending') {
109
+ s.state = status === 'completed' ? 'done' : 'failed';
110
+ s.completedAt = Date.now();
111
+ changed = true;
112
+ }
113
+ }
114
+ return changed;
115
+ }
116
+ addStep(label, state = 'active') {
117
+ const idx = this._steps.push({ label, state, startedAt: Date.now() }) - 1;
118
+ return idx;
119
+ }
120
+ ingestClaude(type, data) {
121
+ if (type === 'assistant') {
122
+ const msg = (data.message ?? {});
123
+ const content = Array.isArray(msg.content) ? msg.content : [];
124
+ let changed = false;
125
+ for (const blk of content) {
126
+ const b = (blk && typeof blk === 'object' ? blk : {});
127
+ if (b.type === 'tool_use') {
128
+ const id = String(b.id ?? '');
129
+ const label = labelForClaudeToolUse(String(b.name ?? ''), b.input);
130
+ const idx = this.addStep(label, 'active');
131
+ if (id)
132
+ this.toolUseIndex.set(id, idx);
133
+ changed = true;
134
+ }
135
+ }
136
+ return changed;
137
+ }
138
+ if (type === 'user') {
139
+ // Match tool_result blocks back to their tool_use step.
140
+ const msg = (data.message ?? {});
141
+ const content = Array.isArray(msg.content) ? msg.content : [];
142
+ let changed = false;
143
+ for (const blk of content) {
144
+ const b = (blk && typeof blk === 'object' ? blk : {});
145
+ if (b.type === 'tool_result') {
146
+ const id = String(b.tool_use_id ?? '');
147
+ const idx = id ? this.toolUseIndex.get(id) : undefined;
148
+ if (idx !== undefined) {
149
+ const step = this._steps[idx];
150
+ step.state = b.is_error ? 'failed' : 'done';
151
+ step.completedAt = Date.now();
152
+ changed = true;
153
+ }
154
+ }
155
+ }
156
+ return changed;
157
+ }
158
+ return false;
159
+ }
160
+ ingestCodex(type, data) {
161
+ if (type !== 'item.completed')
162
+ return false;
163
+ const item = (data.item ?? {});
164
+ const itemType = String(item.type ?? '');
165
+ if (itemType === 'command_execution') {
166
+ const label = labelForCodexCommand(String(item.command ?? ''));
167
+ const ok = item.exit_code === 0 || item.status === 'completed';
168
+ this._steps.push({
169
+ label,
170
+ state: ok ? 'done' : 'failed',
171
+ startedAt: Date.now(),
172
+ completedAt: Date.now(),
173
+ });
174
+ return true;
175
+ }
176
+ if (itemType === 'tool_call' || itemType === 'local_shell_call') {
177
+ const name = String(item.tool_name ?? item.name ?? 'tool');
178
+ this._steps.push({
179
+ label: truncate(name),
180
+ state: 'done',
181
+ startedAt: Date.now(),
182
+ completedAt: Date.now(),
183
+ });
184
+ return true;
185
+ }
186
+ return false;
187
+ }
188
+ }
189
+ //# sourceMappingURL=progress-aggregator.js.map
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Readiness detection — F1a foundation.
3
+ *
4
+ * Tells the UI whether a user can actually spawn Claude Code right now.
5
+ * Detects the observable pre-conditions and reports a single state plus a
6
+ * recovery hint. Never blocks the intake — the user can always try; F1b
7
+ * catches runtime failures. But the UI uses this to warn before a spawn
8
+ * wastes the user's time (or their API credits).
9
+ *
10
+ * Detection is file-system/env only. We do NOT invoke `claude` just to
11
+ * probe auth — that costs money / OAuth round-trips and is slow. Runtime
12
+ * error handling (F1b) covers the cases we can't pre-detect.
13
+ *
14
+ * States:
15
+ * - not_installed — `claude` binary missing on PATH (blocker)
16
+ * - api_key_shadow — ANTHROPIC_API_KEY is set in env; will shadow OAuth
17
+ * subscription on every spawn unless we strip it
18
+ * - ready — no detectable issues (doesn't prove OAuth works;
19
+ * runtime F1b detects expired/invalid auth)
20
+ */
21
+ import { existsSync } from 'fs';
22
+ import { execFileSync } from 'child_process';
23
+ function which(binary) {
24
+ try {
25
+ const out = execFileSync('which', [binary], { encoding: 'utf-8', timeout: 2000 });
26
+ const p = out.trim();
27
+ return p && existsSync(p) ? p : null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function claudeVersion(binPath) {
34
+ try {
35
+ const out = execFileSync(binPath, ['--version'], { encoding: 'utf-8', timeout: 3000 });
36
+ return out.trim().split('\n')[0] || null;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ /**
43
+ * Mask an API key for UI display. We intentionally reveal ZERO characters of
44
+ * the secret — not even a tail fingerprint. Rationale: users post codehere
45
+ * screenshots when reporting bugs, and even 6 trailing chars give an attacker
46
+ * enough signal to confirm a stolen key matches a known screenshot. Showing
47
+ * "set" without value is enough; the user already knows they set it.
48
+ */
49
+ function maskKey(_key) {
50
+ return '••••';
51
+ }
52
+ export function detectReadiness(env = process.env) {
53
+ const claudeBinary = which('claude');
54
+ const apiKey = env.ANTHROPIC_API_KEY ?? '';
55
+ const apiKeyPresent = apiKey.length > 0;
56
+ const detected = {
57
+ claudeBinary,
58
+ claudeVersion: claudeBinary ? claudeVersion(claudeBinary) : null,
59
+ apiKeyPresent,
60
+ apiKeyMasked: apiKeyPresent ? maskKey(apiKey) : null,
61
+ daemonCwd: process.cwd(),
62
+ };
63
+ if (!claudeBinary) {
64
+ return {
65
+ state: 'not_installed',
66
+ severity: 'blocker',
67
+ title: 'Claude Code is not installed',
68
+ detail: 'codehere delegates tasks to Claude Code. Install it first, then refresh this page.',
69
+ action: {
70
+ label: 'Open install docs',
71
+ url: 'https://docs.claude.com/en/docs/claude-code/setup',
72
+ },
73
+ canAttemptSpawn: false,
74
+ preferSubscription: false,
75
+ detected,
76
+ };
77
+ }
78
+ if (apiKeyPresent) {
79
+ return {
80
+ state: 'api_key_shadow',
81
+ severity: 'warn',
82
+ title: 'Using your Claude Code subscription',
83
+ detail: `ANTHROPIC_API_KEY is set in your environment. ` +
84
+ `codehere unsets it for spawned tasks so they use your Claude subscription — ` +
85
+ `the same auth your interactive \`claude\` uses. Remove the key from your shell ` +
86
+ `config to dismiss this warning.`,
87
+ action: {
88
+ label: 'Where is it set?',
89
+ command: 'grep -l ANTHROPIC_API_KEY ~/.zshrc ~/.bashrc ~/.zprofile 2>/dev/null',
90
+ },
91
+ canAttemptSpawn: true,
92
+ preferSubscription: true,
93
+ detected,
94
+ };
95
+ }
96
+ return {
97
+ state: 'ready',
98
+ severity: 'ok',
99
+ title: 'Ready',
100
+ detail: 'Claude Code is installed and no API-key conflict detected. Subscription path will be used.',
101
+ canAttemptSpawn: true,
102
+ preferSubscription: true,
103
+ detected,
104
+ };
105
+ }
106
+ //# sourceMappingURL=readiness.js.map