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,553 @@
1
+ /**
2
+ * Generic CLI adapter — user-configurable catch-all.
3
+ *
4
+ * Kills the "codehere only supports N agents" narrative. Users plug ANY CLI
5
+ * that takes a prompt and streams stdout, via a config file, without writing
6
+ * TypeScript. codehere still wraps every subprocess in the safety hook + audit
7
+ * trail; the per-agent concerns (auth flags, stdin-vs-argv prompt delivery,
8
+ * process-detection regex) move into config.
9
+ *
10
+ * Config file: ~/.codehere/agents.yaml (or .json — parser auto-detects).
11
+ *
12
+ * Shape:
13
+ * agents:
14
+ * - id: gemini
15
+ * label: Gemini CLI
16
+ * command: gemini
17
+ * args: [--prompt] # "<prompt>" slots in after these args
18
+ * prompt_via: argv # or "stdin"
19
+ * process_pattern: '(?:^|/)gemini(?:\\s|$)'
20
+ * format: text # or "jsonl" if the CLI streams JSON lines
21
+ *
22
+ * - id: my-internal-agent
23
+ * label: Internal Agent
24
+ * command: /opt/tools/my-agent
25
+ * args: [run, --json]
26
+ * prompt_via: stdin
27
+ * format: jsonl
28
+ *
29
+ * Each top-level entry becomes a first-class AgentAdapter registered alongside
30
+ * the built-in ones (Claude Code, Codex, Aider, OpenCode).
31
+ */
32
+ import { spawn, execFileSync } from 'child_process';
33
+ import { EventEmitter } from 'events';
34
+ import { readFileSync, existsSync } from 'fs';
35
+ import { homedir } from 'os';
36
+ import { join } from 'path';
37
+ import { randomUUID } from 'crypto';
38
+ import { ProgressAggregator } from './progress-aggregator.js';
39
+ import { snapshotCwd, extractArtifacts } from './artifacts-extractor.js';
40
+ const CONFIG_PATH = join(homedir(), '.codehere', 'agents.yaml');
41
+ const CONFIG_PATH_JSON = join(homedir(), '.codehere', 'agents.json');
42
+ /** Minimal YAML parser for the narrow shape above. Intentionally NOT a full YAML
43
+ * parser — avoids dragging in a dep. Handles: `key: value`, lists with `- key: val`,
44
+ * nested lists of simple strings via `[a, b]`, comments after `#`. Errors loud.
45
+ *
46
+ * @internal — exported for the T4-B fuzz suite; not part of the public API. */
47
+ export function parseSimpleYaml(text) {
48
+ const lines = text.split('\n').map((l) => l.replace(/#.*$/, '').replace(/\s+$/, ''));
49
+ const agents = [];
50
+ let current = null;
51
+ let inAgentsList = false;
52
+ for (const raw of lines) {
53
+ if (!raw.trim())
54
+ continue;
55
+ if (/^agents\s*:\s*$/.test(raw)) {
56
+ inAgentsList = true;
57
+ continue;
58
+ }
59
+ if (!inAgentsList)
60
+ continue;
61
+ const listItem = raw.match(/^\s*-\s+(\w+)\s*:\s*(.*)$/);
62
+ const field = raw.match(/^\s{4,}(\w+)\s*:\s*(.*)$/);
63
+ if (listItem) {
64
+ if (current)
65
+ agents.push(current);
66
+ current = {};
67
+ const [, k, v] = listItem;
68
+ applyField(current, k, v);
69
+ continue;
70
+ }
71
+ if (field && current) {
72
+ const [, k, v] = field;
73
+ applyField(current, k, v);
74
+ }
75
+ }
76
+ if (current)
77
+ agents.push(current);
78
+ return { agents: agents.filter((a) => a.id && a.command) };
79
+ }
80
+ function applyField(acc, k, v) {
81
+ const val = v.trim();
82
+ if (k === 'args') {
83
+ // Expect e.g. [a, b, --json]
84
+ const m = val.match(/^\[(.*)\]$/);
85
+ acc.args = m
86
+ ? m[1]
87
+ .split(',')
88
+ .map((s) => s.trim())
89
+ .filter(Boolean)
90
+ : [];
91
+ }
92
+ else if (k === 'env') {
93
+ // Inline JSON only for simplicity
94
+ try {
95
+ acc.env = JSON.parse(val);
96
+ }
97
+ catch {
98
+ acc.env = {};
99
+ }
100
+ }
101
+ else if (k === 'prompt_via') {
102
+ acc.prompt_via = val === 'stdin' ? 'stdin' : 'argv';
103
+ }
104
+ else if (k === 'format') {
105
+ acc.format = val === 'jsonl' ? 'jsonl' : 'text';
106
+ }
107
+ else if (k === 'install_command' || k === 'install_url') {
108
+ acc[k] = val.replace(/^['"]|['"]$/g, '');
109
+ }
110
+ else {
111
+ acc[k] = val.replace(/^['"]|['"]$/g, '');
112
+ }
113
+ }
114
+ export function loadAgentsConfig() {
115
+ try {
116
+ if (existsSync(CONFIG_PATH_JSON)) {
117
+ const raw = JSON.parse(readFileSync(CONFIG_PATH_JSON, 'utf-8'));
118
+ return raw.agents ?? [];
119
+ }
120
+ if (existsSync(CONFIG_PATH)) {
121
+ return parseSimpleYaml(readFileSync(CONFIG_PATH, 'utf-8')).agents;
122
+ }
123
+ }
124
+ catch {
125
+ // Config exists but unparseable — silently skip. A noisier mode can be added later.
126
+ }
127
+ return [];
128
+ }
129
+ function spawnGeneric(cfg, prompt, options = {}) {
130
+ const sessionId = randomUUID();
131
+ const startedAt = Date.now();
132
+ const emitter = new EventEmitter();
133
+ const buffer = [];
134
+ let statusValue = 'running';
135
+ let killRequested = false;
136
+ const cwd = options.cwd ?? process.cwd();
137
+ const snapshot = snapshotCwd(cwd);
138
+ const aggregator = new ProgressAggregator(cfg.id);
139
+ let stepsSnapshot = [];
140
+ let artifactsSnapshot;
141
+ let textAccum = '';
142
+ const emit = (event) => {
143
+ buffer.push(event);
144
+ emitter.emit('event', event);
145
+ if (aggregator.ingest(event)) {
146
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
147
+ const snapEvt = { type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } };
148
+ buffer.push(snapEvt);
149
+ emitter.emit('event', snapEvt);
150
+ }
151
+ if (event.type === 'stdout' && event.data?.line) {
152
+ textAccum += String(event.data.line) + '\n';
153
+ }
154
+ };
155
+ const spawnEnv = { ...process.env, ...(cfg.env ?? {}), ...(options.env ?? {}) };
156
+ const usesStdin = cfg.prompt_via === 'stdin';
157
+ const fixedArgs = cfg.args ?? [];
158
+ const argv = usesStdin ? [...fixedArgs] : [...fixedArgs, prompt];
159
+ let child;
160
+ try {
161
+ // SAFE · array form (not shell:true) means no shell interpretation.
162
+ // The prompt and args land as separate argv entries; shell metacharacters
163
+ // pass through to the spawned process verbatim. Per-arg arrays are the
164
+ // recommended safe form (Node docs, OWASP, CWE-78).
165
+ // The `cfg.command` path is from a user-edited YAML and is therefore
166
+ // user-controlled; the user choosing what binary to launch on their own
167
+ // machine is documented + accepted in CODEHERE.md threat-model section.
168
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process
169
+ child = spawn(cfg.command, [...argv, ...(options.extraArgs ?? [])], {
170
+ cwd,
171
+ env: spawnEnv,
172
+ stdio: [usesStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
173
+ });
174
+ if (usesStdin) {
175
+ child.stdin?.write(prompt);
176
+ child.stdin?.end();
177
+ }
178
+ }
179
+ catch (err) {
180
+ statusValue = 'error';
181
+ const msg = err instanceof Error ? err.message : String(err);
182
+ queueMicrotask(() => emit({ type: 'error', timestamp: Date.now(), data: { message: msg } }));
183
+ return {
184
+ sessionId,
185
+ startedAt,
186
+ prompt,
187
+ agent: cfg.id,
188
+ get status() {
189
+ return statusValue;
190
+ },
191
+ get steps() {
192
+ return stepsSnapshot;
193
+ },
194
+ get artifacts() {
195
+ return artifactsSnapshot;
196
+ },
197
+ subscribe(handler) {
198
+ for (const e of buffer)
199
+ handler(e);
200
+ emitter.on('event', handler);
201
+ return () => emitter.off('event', handler);
202
+ },
203
+ kill() {
204
+ /* already not running */
205
+ },
206
+ };
207
+ }
208
+ let stdoutBuf = '';
209
+ child.stdout?.on('data', (chunk) => {
210
+ stdoutBuf += chunk.toString('utf-8');
211
+ let idx;
212
+ while ((idx = stdoutBuf.indexOf('\n')) >= 0) {
213
+ const line = stdoutBuf.slice(0, idx).trim();
214
+ stdoutBuf = stdoutBuf.slice(idx + 1);
215
+ if (!line)
216
+ continue;
217
+ if (cfg.format === 'jsonl') {
218
+ try {
219
+ const data = JSON.parse(line);
220
+ emit({ type: data.type ?? `${cfg.id}_event`, timestamp: Date.now(), data });
221
+ continue;
222
+ }
223
+ catch {
224
+ /* not JSON — fall through to stdout */
225
+ }
226
+ }
227
+ emit({ type: 'stdout', timestamp: Date.now(), data: { line } });
228
+ }
229
+ });
230
+ child.stderr?.on('data', (chunk) => {
231
+ const text = chunk.toString('utf-8');
232
+ for (const line of text.split('\n')) {
233
+ if (line.trim())
234
+ emit({ type: 'stderr', timestamp: Date.now(), data: { line } });
235
+ }
236
+ });
237
+ child.on('exit', (code, signal) => {
238
+ statusValue = killRequested || signal !== null ? 'killed' : code === 0 ? 'completed' : 'error';
239
+ if (aggregator.finalize(statusValue === 'completed' ? 'completed' : statusValue === 'killed' ? 'killed' : 'error')) {
240
+ stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
241
+ emit({ type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } });
242
+ }
243
+ if (statusValue === 'completed') {
244
+ try {
245
+ artifactsSnapshot = extractArtifacts(snapshot, textAccum);
246
+ emit({ type: 'codehere:artifacts', timestamp: Date.now(), data: artifactsSnapshot });
247
+ }
248
+ catch {
249
+ /* best-effort */
250
+ }
251
+ }
252
+ emit({
253
+ type: 'exit',
254
+ timestamp: Date.now(),
255
+ data: { code, signal, status: statusValue, durationMs: Date.now() - startedAt },
256
+ });
257
+ });
258
+ child.on('error', (err) => {
259
+ statusValue = 'error';
260
+ emit({ type: 'error', timestamp: Date.now(), data: { message: err.message } });
261
+ });
262
+ return {
263
+ sessionId,
264
+ startedAt,
265
+ prompt,
266
+ agent: cfg.id,
267
+ get status() {
268
+ return statusValue;
269
+ },
270
+ get steps() {
271
+ return stepsSnapshot;
272
+ },
273
+ get artifacts() {
274
+ return artifactsSnapshot;
275
+ },
276
+ subscribe(handler) {
277
+ for (const e of buffer)
278
+ handler(e);
279
+ emitter.on('event', handler);
280
+ return () => emitter.off('event', handler);
281
+ },
282
+ kill() {
283
+ if (statusValue !== 'running')
284
+ return;
285
+ killRequested = true;
286
+ child.kill('SIGTERM');
287
+ setTimeout(() => {
288
+ if (statusValue === 'running') {
289
+ try {
290
+ child.kill('SIGKILL');
291
+ }
292
+ catch {
293
+ /* already dead */
294
+ }
295
+ }
296
+ }, 3000);
297
+ },
298
+ };
299
+ }
300
+ /**
301
+ * Detect regex shapes that are statically known to enable catastrophic
302
+ * backtracking. The check is conservative — it errs toward false positives,
303
+ * because any pattern flagged here can only ever match process names (a
304
+ * narrow domain that the fallback already handles fine).
305
+ *
306
+ * Strategy: simple substring checks instead of trying to parse paren balance.
307
+ * The tell of every classic ReDoS shape is a quantifier *followed by* another
308
+ * quantifier — possibly with `)`, `}`, or whitespace between. We catch the
309
+ * combinations directly.
310
+ *
311
+ * Shapes covered:
312
+ * 1. Quantifier-after-quantifier separated by `)` — `(a+)+`, `(a*)*`,
313
+ * `(([a-z])+.)+`, `(a+)*`, `(a+){0,5}`, etc. The first quantifier sits
314
+ * inside the inner group; the second sits outside the outer group.
315
+ * 2. Quantifier-after-`}` — `a{1,3}+`, `(a{1,3}){0,5}` — bounded
316
+ * repetitions stacked under another quantifier.
317
+ * 3. Overlapping alternation under a quantifier — `(a|a)+`, `(a|aa)*`,
318
+ * where one branch is a prefix of another.
319
+ *
320
+ * Returns the first reason the source is rejected, or null if it looks safe.
321
+ */
322
+ function detectRedosShape(source) {
323
+ // A user-supplied process_pattern over 4KB is suspicious on its face —
324
+ // legitimate process patterns are rarely longer than 100 chars. Reject
325
+ // outright so we never walk a hostile-sized input.
326
+ if (source.length > 4096) {
327
+ return 'oversized-pattern';
328
+ }
329
+ // Paren-depth walk · O(n), no regex, cannot ReDoS itself.
330
+ // For each parenthesised group we track whether its body contains an
331
+ // unbounded quantifier (`+`, `*`, or `{m,}` with no upper bound, or `{m,n}`
332
+ // with n large). If such a group is itself followed by `+`, `*`, `?`, or
333
+ // `{...}`, we have the canonical nested-quantifier shape that causes
334
+ // catastrophic backtracking on inputs that almost-match.
335
+ const stack = [];
336
+ let inCharClass = false;
337
+ for (let i = 0; i < source.length; i++) {
338
+ const c = source[i];
339
+ if (c === '\\') {
340
+ i++;
341
+ continue;
342
+ }
343
+ if (inCharClass) {
344
+ if (c === ']')
345
+ inCharClass = false;
346
+ continue;
347
+ }
348
+ if (c === '[') {
349
+ inCharClass = true;
350
+ continue;
351
+ }
352
+ if (c === '(') {
353
+ stack.push({ hasQuantifier: false, hasOverlapAlt: false, altChecked: false });
354
+ continue;
355
+ }
356
+ if (c === ')') {
357
+ const frame = stack.pop();
358
+ if (!frame)
359
+ continue;
360
+ // Peek next non-whitespace char for an outer quantifier.
361
+ let j = i + 1;
362
+ while (j < source.length && /\s/.test(source[j]))
363
+ j++;
364
+ const next = source[j];
365
+ const outerQuantified = next === '+' || next === '*' || next === '?' || next === '{';
366
+ if (outerQuantified && frame.hasQuantifier) {
367
+ return 'nested-quantifier';
368
+ }
369
+ if (outerQuantified && frame.hasOverlapAlt) {
370
+ return 'overlapping-alternation';
371
+ }
372
+ // Propagate "contains quantifier" up — the outer quantifier on this
373
+ // group counts as a quantifier inside any further-outer group.
374
+ if (outerQuantified && stack.length > 0) {
375
+ stack[stack.length - 1].hasQuantifier = true;
376
+ }
377
+ continue;
378
+ }
379
+ if (stack.length > 0 && (c === '+' || c === '*')) {
380
+ stack[stack.length - 1].hasQuantifier = true;
381
+ continue;
382
+ }
383
+ if (stack.length > 0 && c === '{') {
384
+ // `{m,n}` — flag as quantifier when n is missing or large enough to
385
+ // multiply meaningfully.
386
+ const close = source.indexOf('}', i);
387
+ if (close > i && close - i < 16) {
388
+ const body = source.slice(i + 1, close);
389
+ const m = body.match(/^(\d+)\s*,?\s*(\d*)$/);
390
+ if (m) {
391
+ const upper = m[2] ? parseInt(m[2], 10) : Infinity;
392
+ if (upper >= 3)
393
+ stack[stack.length - 1].hasQuantifier = true;
394
+ }
395
+ i = close;
396
+ }
397
+ continue;
398
+ }
399
+ if (stack.length > 0 && c === '|') {
400
+ const frame = stack[stack.length - 1];
401
+ // Run the body-scan at most once per group · keeps total work O(n).
402
+ if (frame.altChecked)
403
+ continue;
404
+ frame.altChecked = true;
405
+ const groupStart = findGroupStart(source, i);
406
+ const groupEnd = findGroupEnd(source, i);
407
+ if (groupStart >= 0 && groupEnd > groupStart) {
408
+ const body = source.slice(groupStart + 1, groupEnd);
409
+ const branches = body.split('|');
410
+ for (let k = 0; k < branches.length - 1; k++) {
411
+ const a = branches[k];
412
+ const b = branches[k + 1];
413
+ if (a && b && (a === b || a.startsWith(b) || b.startsWith(a))) {
414
+ frame.hasOverlapAlt = true;
415
+ break;
416
+ }
417
+ }
418
+ }
419
+ }
420
+ }
421
+ return null;
422
+ }
423
+ function findGroupStart(s, from) {
424
+ let depth = 1;
425
+ for (let i = from - 1; i >= 0; i--) {
426
+ if (s[i] === '\\') {
427
+ i--;
428
+ continue;
429
+ }
430
+ if (s[i] === ')')
431
+ depth++;
432
+ else if (s[i] === '(') {
433
+ depth--;
434
+ if (depth === 0)
435
+ return i;
436
+ }
437
+ }
438
+ return -1;
439
+ }
440
+ function findGroupEnd(s, from) {
441
+ let depth = 1;
442
+ for (let i = from + 1; i < s.length; i++) {
443
+ if (s[i] === '\\') {
444
+ i++;
445
+ continue;
446
+ }
447
+ if (s[i] === '(')
448
+ depth++;
449
+ else if (s[i] === ')') {
450
+ depth--;
451
+ if (depth === 0)
452
+ return i;
453
+ }
454
+ }
455
+ return -1;
456
+ }
457
+ /**
458
+ * Compile a regex from user-supplied YAML, with a static + dynamic ReDoS guard.
459
+ *
460
+ * CRIT-4 fix · `cfg.process_pattern` is user-controlled (anyone editing
461
+ * ~/.codehere/agents.yaml). A pattern like `(a+)+b` causes catastrophic
462
+ * backtracking that hangs the daemon every time it enumerates processes.
463
+ *
464
+ * Two-layer guard:
465
+ * 1. STATIC · `detectRedosShape` rejects known-dangerous shapes *before*
466
+ * handing the source to the regex engine. This is the only fully
467
+ * reliable defense, because Node's regex engine is not interruptible
468
+ * mid-evaluation — once a pathological pattern reaches it, the process
469
+ * can hang for minutes.
470
+ * 2. DYNAMIC · 100ms smoke test against a benign 1000-char string catches
471
+ * patterns the static heuristic missed. Best-effort only; included as
472
+ * defense-in-depth.
473
+ *
474
+ * On any failure we fall back to a safe pattern derived from the command name.
475
+ */
476
+ /** @internal — exported for the T4-B fuzz suite; not part of the public API. */
477
+ export function compileSafePattern(source, fallback, agentId) {
478
+ // Layer 1 · static shape check — this is the only fully reliable defense.
479
+ const danger = detectRedosShape(source);
480
+ if (danger) {
481
+ // eslint-disable-next-line no-console
482
+ console.warn(`[codehere] Regex for "${agentId}" rejected (${danger}) — using fallback`);
483
+ return fallback;
484
+ }
485
+ let candidate;
486
+ try {
487
+ candidate = new RegExp(source);
488
+ }
489
+ catch {
490
+ // eslint-disable-next-line no-console
491
+ console.warn(`[codehere] Invalid regex in agents.yaml for "${agentId}" — using fallback`);
492
+ return fallback;
493
+ }
494
+ // Layer 2 · dynamic smoke test — catches anything the static heuristic missed.
495
+ try {
496
+ const start = Date.now();
497
+ candidate.test('a'.repeat(1000));
498
+ if (Date.now() - start > 100) {
499
+ // eslint-disable-next-line no-console
500
+ console.warn(`[codehere] Regex for "${agentId}" too slow (likely ReDoS) — using fallback`);
501
+ return fallback;
502
+ }
503
+ }
504
+ catch {
505
+ return fallback;
506
+ }
507
+ return candidate;
508
+ }
509
+ /** Build an AgentAdapter from a user config entry. */
510
+ export function buildGenericAdapter(cfg) {
511
+ const fallbackPattern = new RegExp(`(?:^|/)${cfg.command.split('/').pop()}(?:\\s|$)`);
512
+ const pattern = cfg.process_pattern
513
+ ? compileSafePattern(cfg.process_pattern, fallbackPattern, cfg.id)
514
+ : fallbackPattern;
515
+ const adapter = {
516
+ id: cfg.id,
517
+ label: cfg.label || cfg.id,
518
+ processPattern: pattern,
519
+ isInstalled() {
520
+ try {
521
+ if (cfg.command.startsWith('/'))
522
+ return existsSync(cfg.command);
523
+ const out = execFileSync('which', [cfg.command], { encoding: 'utf-8', timeout: 2000 });
524
+ return out.trim().length > 0;
525
+ }
526
+ catch {
527
+ return false;
528
+ }
529
+ },
530
+ spawn(prompt, options) {
531
+ return spawnGeneric(cfg, prompt, options);
532
+ },
533
+ checkReadiness() {
534
+ const installed = adapter.isInstalled();
535
+ if (!installed) {
536
+ return {
537
+ id: cfg.id,
538
+ label: cfg.label || cfg.id,
539
+ state: 'needs_install',
540
+ installed: false,
541
+ // Fall back gracefully: if no install_command is configured, keep the
542
+ // button disabled (UI checks for a real command before enabling).
543
+ installHint: cfg.install_command ? { command: cfg.install_command, url: cfg.install_url } : undefined,
544
+ };
545
+ }
546
+ // Generic adapters can't introspect auth — treat install as ready, let
547
+ // runtime error detection surface real auth failures to the user.
548
+ return { id: cfg.id, label: cfg.label || cfg.id, state: 'ready', installed: true };
549
+ },
550
+ };
551
+ return adapter;
552
+ }
553
+ //# sourceMappingURL=generic-cli-adapter.js.map