codehere 1.0.1 → 1.0.3

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 (163) hide show
  1. package/README.md +35 -193
  2. package/dist/application/use-cases/check-claimed-tests.js +81 -0
  3. package/dist/application/use-cases/detect-test-weakening.js +237 -0
  4. package/dist/application/use-cases/rerun-tests.js +110 -7
  5. package/dist/index.js +38 -1212
  6. package/dist/infrastructure/orchestration/artifacts-extractor.js +2 -323
  7. package/dist/presentation/cli/commands/check-command.js +178 -23
  8. package/dist/presentation/cli/commands/help-command.js +21 -285
  9. package/dist/ui.js +5 -236
  10. package/dist/utils/version.js +0 -6
  11. package/package.json +9 -38
  12. package/dist/application/services/verdict-service.js +0 -154
  13. package/dist/application/use-cases/assess-cross-vendor.js +0 -126
  14. package/dist/application/use-cases/build-cross-vendor-verdict.js +0 -118
  15. package/dist/application/use-cases/domain-trust.js +0 -110
  16. package/dist/application/use-cases/export-aat.js +0 -107
  17. package/dist/application/use-cases/generate-acceptance-criteria.js +0 -223
  18. package/dist/application/use-cases/generate-final-report.js +0 -259
  19. package/dist/application/use-cases/generate-narration.js +0 -130
  20. package/dist/application/use-cases/generate-thread-title.js +0 -181
  21. package/dist/application/use-cases/narrator-prompt-template.js +0 -158
  22. package/dist/application/use-cases/plan-auto-review.js +0 -57
  23. package/dist/application/use-cases/reconcile-audit.js +0 -100
  24. package/dist/application/use-cases/search-sessions.js +0 -70
  25. package/dist/application/use-cases/should-auto-review.js +0 -71
  26. package/dist/application/use-cases/thread-export.js +0 -245
  27. package/dist/application/use-cases/verify-claim.js +0 -456
  28. package/dist/application/use-cases/write-pass.js +0 -277
  29. package/dist/domain/audit.js +0 -11
  30. package/dist/domain/services/codebase-detector.js +0 -85
  31. package/dist/domain/task.js +0 -91
  32. package/dist/error-handler.js +0 -139
  33. package/dist/infrastructure/completion/bash-completion.js +0 -29
  34. package/dist/infrastructure/completion/fish-completion.js +0 -17
  35. package/dist/infrastructure/completion/zsh-completion.js +0 -25
  36. package/dist/infrastructure/config/config-manager.js +0 -174
  37. package/dist/infrastructure/config/product-context.js +0 -49
  38. package/dist/infrastructure/context/adapters/drawio-source.js +0 -157
  39. package/dist/infrastructure/context/adapters/figma-source.js +0 -198
  40. package/dist/infrastructure/context/adapters/github-issue-source.js +0 -160
  41. package/dist/infrastructure/context/adapters/linear-source.js +0 -190
  42. package/dist/infrastructure/context/context-resolver.js +0 -144
  43. package/dist/infrastructure/context/context-source.js +0 -114
  44. package/dist/infrastructure/context/github-api.js +0 -110
  45. package/dist/infrastructure/context/github-device-flow.js +0 -65
  46. package/dist/infrastructure/context/oauth-flow.js +0 -207
  47. package/dist/infrastructure/context/oauth-store.js +0 -122
  48. package/dist/infrastructure/context/registry-bootstrap.js +0 -95
  49. package/dist/infrastructure/context/write-pass-resolver.js +0 -106
  50. package/dist/infrastructure/cost/budget-config.js +0 -114
  51. package/dist/infrastructure/cost/cost-router.js +0 -97
  52. package/dist/infrastructure/cost/spend-aggregator.js +0 -222
  53. package/dist/infrastructure/cost/team-ledger.js +0 -355
  54. package/dist/infrastructure/discovery/discovery-log.js +0 -85
  55. package/dist/infrastructure/hooks/audit-tip-signature.js +0 -336
  56. package/dist/infrastructure/hooks/claude-sdk-hook.js +0 -1018
  57. package/dist/infrastructure/hooks/hook-mode.js +0 -87
  58. package/dist/infrastructure/hooks/mirror-tool-call-to-audit.js +0 -49
  59. package/dist/infrastructure/hooks/pre-prompt-scan.js +0 -122
  60. package/dist/infrastructure/hooks/session-analyzer.js +0 -177
  61. package/dist/infrastructure/observability/execution-tracer.js +0 -227
  62. package/dist/infrastructure/orchestration/agent-adapter.js +0 -13
  63. package/dist/infrastructure/orchestration/agent-installer.js +0 -101
  64. package/dist/infrastructure/orchestration/agents-config-seed.js +0 -68
  65. package/dist/infrastructure/orchestration/aider-adapter.js +0 -611
  66. package/dist/infrastructure/orchestration/cassette-recorder.js +0 -120
  67. package/dist/infrastructure/orchestration/claude-code-adapter.js +0 -592
  68. package/dist/infrastructure/orchestration/codex-adapter.js +0 -574
  69. package/dist/infrastructure/orchestration/conductor-adapter.js +0 -416
  70. package/dist/infrastructure/orchestration/context-handoff.js +0 -162
  71. package/dist/infrastructure/orchestration/control/codex-control-surface.js +0 -99
  72. package/dist/infrastructure/orchestration/control/control-surface.js +0 -15
  73. package/dist/infrastructure/orchestration/detect-ollama.js +0 -75
  74. package/dist/infrastructure/orchestration/failover-classifier.js +0 -151
  75. package/dist/infrastructure/orchestration/failover-config.js +0 -67
  76. package/dist/infrastructure/orchestration/failover-policy.js +0 -106
  77. package/dist/infrastructure/orchestration/gemini-adapter.js +0 -663
  78. package/dist/infrastructure/orchestration/generic-cli-adapter.js +0 -689
  79. package/dist/infrastructure/orchestration/graphify-context.js +0 -209
  80. package/dist/infrastructure/orchestration/memory-injector.js +0 -380
  81. package/dist/infrastructure/orchestration/mocks/mock-agent-repl.js +0 -388
  82. package/dist/infrastructure/orchestration/mocks/mock-codex-app-server.js +0 -73
  83. package/dist/infrastructure/orchestration/mocks/mock-synthesis.js +0 -83
  84. package/dist/infrastructure/orchestration/mocks/resolve-agent-spawn.js +0 -37
  85. package/dist/infrastructure/orchestration/opencode-adapter.js +0 -580
  86. package/dist/infrastructure/orchestration/progress-aggregator.js +0 -906
  87. package/dist/infrastructure/orchestration/readiness.js +0 -103
  88. package/dist/infrastructure/orchestration/session-manager.js +0 -1590
  89. package/dist/infrastructure/orchestration/session-persistence.js +0 -394
  90. package/dist/infrastructure/orchestration/thread-key-store.js +0 -127
  91. package/dist/infrastructure/orchestration/write-pass-store.js +0 -38
  92. package/dist/infrastructure/protocols/cloud-sync.js +0 -207
  93. package/dist/infrastructure/protocols/mcp-helpers.js +0 -25
  94. package/dist/infrastructure/protocols/mcp-server-impl.js +0 -3935
  95. package/dist/infrastructure/protocols/mcp-tools.js +0 -401
  96. package/dist/infrastructure/protocols/probe-port.js +0 -36
  97. package/dist/infrastructure/protocols/thread-phase.js +0 -105
  98. package/dist/infrastructure/protocols/ui/app-script-artifacts.js +0 -121
  99. package/dist/infrastructure/protocols/ui/app-script-audit-footer.js +0 -44
  100. package/dist/infrastructure/protocols/ui/app-script-audit-verify.js +0 -56
  101. package/dist/infrastructure/protocols/ui/app-script-composer-cost.js +0 -588
  102. package/dist/infrastructure/protocols/ui/app-script-context-sources.js +0 -168
  103. package/dist/infrastructure/protocols/ui/app-script-conversation.js +0 -67
  104. package/dist/infrastructure/protocols/ui/app-script-drawer.js +0 -115
  105. package/dist/infrastructure/protocols/ui/app-script-failover.js +0 -133
  106. package/dist/infrastructure/protocols/ui/app-script-github.js +0 -113
  107. package/dist/infrastructure/protocols/ui/app-script-observer.js +0 -104
  108. package/dist/infrastructure/protocols/ui/app-script-onboarding.js +0 -80
  109. package/dist/infrastructure/protocols/ui/app-script-overlay.js +0 -203
  110. package/dist/infrastructure/protocols/ui/app-script-recovery.js +0 -136
  111. package/dist/infrastructure/protocols/ui/app-script-render.js +0 -166
  112. package/dist/infrastructure/protocols/ui/app-script-share.js +0 -78
  113. package/dist/infrastructure/protocols/ui/app-script-sidebar.js +0 -194
  114. package/dist/infrastructure/protocols/ui/app-script-tour.js +0 -78
  115. package/dist/infrastructure/protocols/ui/app-script-wpass.js +0 -312
  116. package/dist/infrastructure/protocols/ui/app-script.js +0 -2998
  117. package/dist/infrastructure/protocols/ui/font-faces.js +0 -7
  118. package/dist/infrastructure/protocols/ui/styles.js +0 -2147
  119. package/dist/infrastructure/protocols/ui/tokens.js +0 -96
  120. package/dist/infrastructure/protocols/ui-page-v2.js +0 -320
  121. package/dist/infrastructure/protocols/verify-page.js +0 -1677
  122. package/dist/infrastructure/security/file-collection.js +0 -118
  123. package/dist/infrastructure/security/fix-code.js +0 -144
  124. package/dist/infrastructure/security/fix-secret.js +0 -89
  125. package/dist/infrastructure/security/permissions-config.js +0 -235
  126. package/dist/infrastructure/security/scan-types.js +0 -10
  127. package/dist/infrastructure/security/ship-scan.js +0 -195
  128. package/dist/infrastructure/security/trust-scorer.js +0 -724
  129. package/dist/infrastructure/security/vibe-checks.js +0 -99
  130. package/dist/infrastructure/storage/atomic-write.js +0 -86
  131. package/dist/infrastructure/storage/cross-tool-agents.js +0 -268
  132. package/dist/infrastructure/storage/project-thread-migration.js +0 -237
  133. package/dist/infrastructure/storage/project-thread-mirror.js +0 -671
  134. package/dist/infrastructure/storage/project-thread-reader.js +0 -409
  135. package/dist/infrastructure/storage/project-thread-title-backfill.js +0 -214
  136. package/dist/monitoring.js +0 -212
  137. package/dist/presentation/cli/commands/audit-command.js +0 -201
  138. package/dist/presentation/cli/commands/budget-command.js +0 -79
  139. package/dist/presentation/cli/commands/config-command.js +0 -125
  140. package/dist/presentation/cli/commands/context-source-command.js +0 -217
  141. package/dist/presentation/cli/commands/hook-command.js +0 -265
  142. package/dist/presentation/cli/commands/init-command.js +0 -590
  143. package/dist/presentation/cli/commands/memory-command.js +0 -1031
  144. package/dist/presentation/cli/commands/narrator-command.js +0 -101
  145. package/dist/presentation/cli/commands/permission-command.js +0 -105
  146. package/dist/presentation/cli/commands/protocols-builder.js +0 -254
  147. package/dist/presentation/cli/commands/protocols-command.js +0 -84
  148. package/dist/presentation/cli/commands/repo-map-builder.js +0 -247
  149. package/dist/presentation/cli/commands/report-command.js +0 -403
  150. package/dist/presentation/cli/commands/scan-command.js +0 -52
  151. package/dist/presentation/cli/commands/scan-tool-command.js +0 -110
  152. package/dist/presentation/cli/commands/search-command.js +0 -51
  153. package/dist/presentation/cli/commands/setup-command.js +0 -330
  154. package/dist/presentation/cli/commands/status-command.js +0 -614
  155. package/dist/presentation/cli/commands/team-command.js +0 -256
  156. package/dist/presentation/cli/commands/thread-command.js +0 -370
  157. package/dist/presentation/cli/commands/trust-command.js +0 -328
  158. package/dist/presentation/cli/commands/verify-command.js +0 -298
  159. package/dist/presentation/cli/error-display.js +0 -328
  160. package/dist/presentation/cli/repl.js +0 -805
  161. package/dist/presentation/cli/task-deliverable.js +0 -153
  162. package/dist/testing/cassette.js +0 -125
  163. package/dist/testing/replay-adapter.js +0 -147
@@ -1,689 +0,0 @@
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 { resolveAgentSpawn } from './mocks/resolve-agent-spawn.js';
40
- import { snapshotCwd, extractArtifacts } from './artifacts-extractor.js';
41
- import { applyMemoryPrefix } from './memory-injector.js';
42
- import { mirrorToolCallToAudit } from '../hooks/mirror-tool-call-to-audit.js';
43
- const CONFIG_PATH = join(process.env.CODEHERE_HOME || homedir(), '.codehere', 'agents.yaml');
44
- const CONFIG_PATH_JSON = join(process.env.CODEHERE_HOME || homedir(), '.codehere', 'agents.json');
45
- /** Minimal YAML parser for the narrow shape above. Intentionally NOT a full YAML
46
- * parser — avoids dragging in a dep. Handles: `key: value`, lists with `- key: val`,
47
- * nested lists of simple strings via `[a, b]`, comments after `#`. Errors loud.
48
- *
49
- * @internal — exported for the T4-B fuzz suite; not part of the public API. */
50
- export function parseSimpleYaml(text) {
51
- const lines = text.split('\n').map((l) => l.replace(/#.*$/, '').replace(/\s+$/, ''));
52
- const agents = [];
53
- let current = null;
54
- let inAgentsList = false;
55
- for (const raw of lines) {
56
- if (!raw.trim())
57
- continue;
58
- if (/^agents\s*:\s*$/.test(raw)) {
59
- inAgentsList = true;
60
- continue;
61
- }
62
- if (!inAgentsList)
63
- continue;
64
- const listItem = raw.match(/^\s*-\s+(\w+)\s*:\s*(.*)$/);
65
- const field = raw.match(/^\s{4,}(\w+)\s*:\s*(.*)$/);
66
- if (listItem) {
67
- if (current)
68
- agents.push(current);
69
- current = {};
70
- const [, k, v] = listItem;
71
- applyField(current, k, v);
72
- continue;
73
- }
74
- if (field && current) {
75
- const [, k, v] = field;
76
- applyField(current, k, v);
77
- }
78
- }
79
- if (current)
80
- agents.push(current);
81
- return { agents: agents.filter((a) => a.id && a.command) };
82
- }
83
- function applyField(acc, k, v) {
84
- const val = v.trim();
85
- if (k === 'args') {
86
- // Expect e.g. [a, b, --json]
87
- const m = val.match(/^\[(.*)\]$/);
88
- acc.args = m
89
- ? m[1]
90
- .split(',')
91
- .map((s) => s.trim())
92
- .filter(Boolean)
93
- : [];
94
- }
95
- else if (k === 'env') {
96
- // Inline JSON only for simplicity
97
- try {
98
- acc.env = JSON.parse(val);
99
- }
100
- catch {
101
- acc.env = {};
102
- }
103
- }
104
- else if (k === 'prompt_via') {
105
- acc.prompt_via = val === 'stdin' ? 'stdin' : 'argv';
106
- }
107
- else if (k === 'format') {
108
- acc.format = val === 'jsonl' ? 'jsonl' : 'text';
109
- }
110
- else if (k === 'install_command' || k === 'install_url') {
111
- acc[k] = val.replace(/^['"]|['"]$/g, '');
112
- }
113
- else {
114
- acc[k] = val.replace(/^['"]|['"]$/g, '');
115
- }
116
- }
117
- export function loadAgentsConfig() {
118
- try {
119
- if (existsSync(CONFIG_PATH_JSON)) {
120
- const raw = JSON.parse(readFileSync(CONFIG_PATH_JSON, 'utf-8'));
121
- return raw.agents ?? [];
122
- }
123
- if (existsSync(CONFIG_PATH)) {
124
- return parseSimpleYaml(readFileSync(CONFIG_PATH, 'utf-8')).agents;
125
- }
126
- }
127
- catch {
128
- // Config exists but unparseable — silently skip. A noisier mode can be added later.
129
- }
130
- return [];
131
- }
132
- // Minimal generic failover fingerprints. Config-driven CLIs have no
133
- // per-provider error bank (we don't know the vendor), so detect only the two
134
- // signals every provider phrases recognizably: rate-limit and auth. Emits the
135
- // same `codehere:error` { code, message, recovery } shape the built-in adapters
136
- // emit — the session-manager's failover classifier consumes that shape and
137
- // treats 'rate_limit' as failover-eligible ('auth_invalid' is surfaced only).
138
- const ERROR_PATTERNS = [
139
- {
140
- code: 'rate_limit',
141
- regex: /rate.?limit|429|quota/i,
142
- message: 'The agent was rate-limited by its provider.',
143
- recovery: 'Wait a minute and retry, or switch the task to a different agent.',
144
- },
145
- {
146
- code: 'auth_invalid',
147
- regex: /auth|401|403|api.?key|login/i,
148
- message: "The agent's auth was rejected or missing.",
149
- recovery: 'Check the API key / login for this CLI, re-authenticate, and retry.',
150
- },
151
- ];
152
- /** @internal — exported for tests; not part of the public API. */
153
- export function scanForKnownError(text) {
154
- for (const p of ERROR_PATTERNS) {
155
- if (p.regex.test(text))
156
- return { code: p.code, message: p.message, recovery: p.recovery };
157
- }
158
- return null;
159
- }
160
- /**
161
- * Normalize a Claude-Code-style stream-json event (cursor-agent et al.) into the
162
- * flat event shapes the spawn handler already understands. Returns null for
163
- * events that need no translation (the caller emits them verbatim).
164
- *
165
- * - `{ type:'tool_call', subtype:'started', tool_call:{ <kind>ToolCall:{ args } } }`
166
- * → `{ type:'tool_use', data:{ name:<kind>, input:args } }` so the existing
167
- * mirror lands the call in the audit chain (only 'started', so a call is
168
- * counted once, not twice with 'completed').
169
- * - `{ type:'assistant', message:{ content:[{type:'text',text}] } }`
170
- * → `{ type:'stdout', data:{ line:<text> } }` so the agent's findings feed
171
- * textAccum + the Final Report (else a read-only review records no findings).
172
- *
173
- * @internal — exported for tests; not part of the public API.
174
- */
175
- export function normalizeStreamJson(data) {
176
- if (data.type === 'tool_call' && data.subtype === 'started' && data.tool_call) {
177
- const tc = data.tool_call;
178
- const kind = Object.keys(tc).find((k) => k.endsWith('ToolCall'));
179
- if (kind) {
180
- const call = tc[kind];
181
- return {
182
- type: 'tool_use',
183
- timestamp: Date.now(),
184
- data: { name: kind.replace(/ToolCall$/, ''), input: call?.args ?? {} },
185
- };
186
- }
187
- }
188
- if (data.type === 'assistant') {
189
- const content = data.message?.content ?? [];
190
- const text = content
191
- .filter((c) => c.type === 'text' && typeof c.text === 'string')
192
- .map((c) => c.text)
193
- .join('\n')
194
- .trim();
195
- if (text)
196
- return { type: 'stdout', timestamp: Date.now(), data: { line: text } };
197
- }
198
- return null;
199
- }
200
- function spawnGeneric(cfg, prompt, options = {}) {
201
- const sessionId = randomUUID();
202
- const startedAt = Date.now();
203
- const emitter = new EventEmitter();
204
- const buffer = [];
205
- let statusValue = 'running';
206
- let killRequested = false;
207
- const cwd = options.cwd ?? process.cwd();
208
- // F3 Task 8 — memory injection (same shape as every other adapter).
209
- // Apr 29: caught via the adapter-injection-wiring trip-wire — generic
210
- // adapters were silently exempt from F3 even though Task 8 said
211
- // "every spawned agent." Now consistent.
212
- const injected = applyMemoryPrefix(prompt, cwd, options);
213
- const finalPrompt = injected.prompt;
214
- const snapshot = snapshotCwd(cwd);
215
- const aggregator = new ProgressAggregator(cfg.id);
216
- let stepsSnapshot = [];
217
- let artifactsSnapshot;
218
- let textAccum = '';
219
- // Bounded recent-stdout tail for error scanning (same posture as aider):
220
- // scanning the whole accumulated buffer lets distant benign prose combine
221
- // into false matches; a single line misses wrapped error bodies.
222
- let scanTail = '';
223
- const SCAN_TAIL_CHARS = 600;
224
- let errorEmitted = false;
225
- const emit = (event) => {
226
- buffer.push(event);
227
- emitter.emit('event', event);
228
- if (aggregator.ingest(event)) {
229
- stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
230
- const snapEvt = { type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } };
231
- buffer.push(snapEvt);
232
- emitter.emit('event', snapEvt);
233
- }
234
- if (event.type === 'stdout' && event.data?.line) {
235
- textAccum += String(event.data.line) + '\n';
236
- }
237
- // Audit-trail parity: generic CLIs that stream jsonl tool_use events
238
- // (gemini-style { tool_name, parameters } or claude-style { name, input })
239
- // get the same post-hoc mirror the built-in adapters fire — their tool
240
- // calls land in the hash-chained audit instead of vanishing.
241
- if (event.type === 'tool_use') {
242
- const data = event.data;
243
- const toolName = String(data?.tool_name ?? data?.name ?? 'tool');
244
- const params = data?.parameters ?? data?.input ?? {};
245
- const input = (typeof params.command === 'string' && params.command) ||
246
- (typeof params.file_path === 'string' && params.file_path) ||
247
- (typeof params.path === 'string' && params.path) ||
248
- (typeof params.query === 'string' && params.query) ||
249
- JSON.stringify(params).slice(0, 500);
250
- mirrorToolCallToAudit({ sessionId, agent: cfg.id, toolName, toolInput: String(input), cwd });
251
- }
252
- if (!errorEmitted) {
253
- const data = event.data;
254
- let text = '';
255
- if (event.type === 'stderr' && typeof data?.line === 'string') {
256
- text = data.line;
257
- }
258
- else if (event.type === 'stdout' && typeof data?.line === 'string') {
259
- scanTail = (scanTail + '\n' + data.line).slice(-SCAN_TAIL_CHARS);
260
- text = scanTail;
261
- }
262
- if (text) {
263
- const hit = scanForKnownError(text);
264
- if (hit) {
265
- errorEmitted = true;
266
- const errEvent = {
267
- type: 'codehere:error',
268
- timestamp: Date.now(),
269
- data: { code: hit.code, message: hit.message, recovery: hit.recovery },
270
- };
271
- buffer.push(errEvent);
272
- emitter.emit('event', errEvent);
273
- }
274
- }
275
- }
276
- };
277
- const spawnEnv = { ...process.env, ...(cfg.env ?? {}), ...(options.env ?? {}) };
278
- const usesStdin = cfg.prompt_via === 'stdin';
279
- const fixedArgs = cfg.args ?? [];
280
- const argv = usesStdin ? [...fixedArgs] : [...fixedArgs, finalPrompt];
281
- let child;
282
- try {
283
- // SAFE · array form (not shell:true) means no shell interpretation.
284
- // The prompt and args land as separate argv entries; shell metacharacters
285
- // pass through to the spawned process verbatim. Per-arg arrays are the
286
- // recommended safe form (Node docs, OWASP, CWE-78).
287
- // The `cfg.command` path is from a user-edited YAML and is therefore
288
- // user-controlled; the user choosing what binary to launch on their own
289
- // machine is documented + accepted in CODEHERE.md threat-model section.
290
- //
291
- // Routed through the mock seam like every built-in adapter — under
292
- // CODEHERE_MOCK=1 spawning the configured binary directly would execute
293
- // the real CLI (the real-spend leak class).
294
- const sp = resolveAgentSpawn(cfg.id, cfg.command, [...argv, ...(options.extraArgs ?? [])], finalPrompt);
295
- // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process
296
- child = spawn(sp.command, sp.args, {
297
- cwd,
298
- env: spawnEnv,
299
- stdio: [usesStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
300
- });
301
- if (usesStdin) {
302
- child.stdin?.write(finalPrompt);
303
- child.stdin?.end();
304
- }
305
- }
306
- catch (err) {
307
- statusValue = 'error';
308
- const msg = err instanceof Error ? err.message : String(err);
309
- queueMicrotask(() => emit({ type: 'error', timestamp: Date.now(), data: { message: msg } }));
310
- return {
311
- sessionId,
312
- startedAt,
313
- prompt,
314
- agent: cfg.id,
315
- get status() {
316
- return statusValue;
317
- },
318
- get steps() {
319
- return stepsSnapshot;
320
- },
321
- get artifacts() {
322
- return artifactsSnapshot;
323
- },
324
- subscribe(handler) {
325
- for (const e of buffer)
326
- handler(e);
327
- emitter.on('event', handler);
328
- return () => emitter.off('event', handler);
329
- },
330
- kill() {
331
- /* already not running */
332
- },
333
- };
334
- }
335
- let stdoutBuf = '';
336
- child.stdout?.on('data', (chunk) => {
337
- stdoutBuf += chunk.toString('utf-8');
338
- let idx;
339
- while ((idx = stdoutBuf.indexOf('\n')) >= 0) {
340
- const line = stdoutBuf.slice(0, idx).trim();
341
- stdoutBuf = stdoutBuf.slice(idx + 1);
342
- if (!line)
343
- continue;
344
- if (cfg.format === 'jsonl') {
345
- try {
346
- const data = JSON.parse(line);
347
- // Claude-Code-style stream-json (cursor-agent, etc.) nests tool calls
348
- // and findings differently from the flat { tool_use } shape. Normalize
349
- // them into the events the handlers already understand, so a CLI agent's
350
- // reads land in the audit chain (attribution) and its findings feed the
351
- // Final Report — without that, a cross-vendor review reads "couldn't
352
- // attribute" and never earns the seal.
353
- const norm = normalizeStreamJson(data);
354
- if (norm) {
355
- emit(norm);
356
- continue;
357
- }
358
- emit({ type: data.type ?? `${cfg.id}_event`, timestamp: Date.now(), data });
359
- continue;
360
- }
361
- catch {
362
- /* not JSON — fall through to stdout */
363
- }
364
- }
365
- emit({ type: 'stdout', timestamp: Date.now(), data: { line } });
366
- }
367
- });
368
- child.stderr?.on('data', (chunk) => {
369
- const text = chunk.toString('utf-8');
370
- for (const line of text.split('\n')) {
371
- if (line.trim())
372
- emit({ type: 'stderr', timestamp: Date.now(), data: { line } });
373
- }
374
- });
375
- child.on('exit', (code, signal) => {
376
- statusValue = killRequested || signal !== null ? 'killed' : code === 0 ? 'completed' : 'error';
377
- if (aggregator.finalize(statusValue === 'completed' ? 'completed' : statusValue === 'killed' ? 'killed' : 'error')) {
378
- stepsSnapshot = aggregator.steps.map((s) => ({ ...s }));
379
- emit({ type: 'codehere:steps', timestamp: Date.now(), data: { steps: stepsSnapshot } });
380
- }
381
- if (statusValue === 'completed') {
382
- try {
383
- artifactsSnapshot = extractArtifacts(snapshot, textAccum);
384
- emit({ type: 'codehere:artifacts', timestamp: Date.now(), data: artifactsSnapshot });
385
- }
386
- catch {
387
- /* best-effort */
388
- }
389
- }
390
- emit({
391
- type: 'exit',
392
- timestamp: Date.now(),
393
- data: { code, signal, status: statusValue, durationMs: Date.now() - startedAt },
394
- });
395
- });
396
- child.on('error', (err) => {
397
- statusValue = 'error';
398
- emit({ type: 'error', timestamp: Date.now(), data: { message: err.message } });
399
- });
400
- return {
401
- sessionId,
402
- startedAt,
403
- prompt,
404
- agent: cfg.id,
405
- memoryInjection: injected.record,
406
- get status() {
407
- return statusValue;
408
- },
409
- get steps() {
410
- return stepsSnapshot;
411
- },
412
- get artifacts() {
413
- return artifactsSnapshot;
414
- },
415
- subscribe(handler) {
416
- for (const e of buffer)
417
- handler(e);
418
- emitter.on('event', handler);
419
- return () => emitter.off('event', handler);
420
- },
421
- kill() {
422
- if (statusValue !== 'running')
423
- return;
424
- killRequested = true;
425
- child.kill('SIGTERM');
426
- setTimeout(() => {
427
- if (statusValue === 'running') {
428
- try {
429
- child.kill('SIGKILL');
430
- }
431
- catch {
432
- /* already dead */
433
- }
434
- }
435
- }, 3000);
436
- },
437
- };
438
- }
439
- /**
440
- * Detect regex shapes that are statically known to enable catastrophic
441
- * backtracking. The check is conservative — it errs toward false positives,
442
- * because any pattern flagged here can only ever match process names (a
443
- * narrow domain that the fallback already handles fine).
444
- *
445
- * Strategy: simple substring checks instead of trying to parse paren balance.
446
- * The tell of every classic ReDoS shape is a quantifier *followed by* another
447
- * quantifier — possibly with `)`, `}`, or whitespace between. We catch the
448
- * combinations directly.
449
- *
450
- * Shapes covered:
451
- * 1. Quantifier-after-quantifier separated by `)` — `(a+)+`, `(a*)*`,
452
- * `(([a-z])+.)+`, `(a+)*`, `(a+){0,5}`, etc. The first quantifier sits
453
- * inside the inner group; the second sits outside the outer group.
454
- * 2. Quantifier-after-`}` — `a{1,3}+`, `(a{1,3}){0,5}` — bounded
455
- * repetitions stacked under another quantifier.
456
- * 3. Overlapping alternation under a quantifier — `(a|a)+`, `(a|aa)*`,
457
- * where one branch is a prefix of another.
458
- *
459
- * Returns the first reason the source is rejected, or null if it looks safe.
460
- */
461
- function detectRedosShape(source) {
462
- // A user-supplied process_pattern over 4KB is suspicious on its face —
463
- // legitimate process patterns are rarely longer than 100 chars. Reject
464
- // outright so we never walk a hostile-sized input.
465
- if (source.length > 4096) {
466
- return 'oversized-pattern';
467
- }
468
- // Paren-depth walk · O(n), no regex, cannot ReDoS itself.
469
- // For each parenthesised group we track whether its body contains an
470
- // unbounded quantifier (`+`, `*`, or `{m,}` with no upper bound, or `{m,n}`
471
- // with n large). If such a group is itself followed by `+`, `*`, `?`, or
472
- // `{...}`, we have the canonical nested-quantifier shape that causes
473
- // catastrophic backtracking on inputs that almost-match.
474
- const stack = [];
475
- let inCharClass = false;
476
- for (let i = 0; i < source.length; i++) {
477
- const c = source[i];
478
- if (c === '\\') {
479
- i++;
480
- continue;
481
- }
482
- if (inCharClass) {
483
- if (c === ']')
484
- inCharClass = false;
485
- continue;
486
- }
487
- if (c === '[') {
488
- inCharClass = true;
489
- continue;
490
- }
491
- if (c === '(') {
492
- stack.push({ hasQuantifier: false, hasOverlapAlt: false, altChecked: false });
493
- continue;
494
- }
495
- if (c === ')') {
496
- const frame = stack.pop();
497
- if (!frame)
498
- continue;
499
- // Peek next non-whitespace char for an outer quantifier.
500
- let j = i + 1;
501
- while (j < source.length && /\s/.test(source[j]))
502
- j++;
503
- const next = source[j];
504
- const outerQuantified = next === '+' || next === '*' || next === '?' || next === '{';
505
- if (outerQuantified && frame.hasQuantifier) {
506
- return 'nested-quantifier';
507
- }
508
- if (outerQuantified && frame.hasOverlapAlt) {
509
- return 'overlapping-alternation';
510
- }
511
- // Propagate "contains quantifier" up — the outer quantifier on this
512
- // group counts as a quantifier inside any further-outer group.
513
- if (outerQuantified && stack.length > 0) {
514
- stack[stack.length - 1].hasQuantifier = true;
515
- }
516
- continue;
517
- }
518
- if (stack.length > 0 && (c === '+' || c === '*')) {
519
- stack[stack.length - 1].hasQuantifier = true;
520
- continue;
521
- }
522
- if (stack.length > 0 && c === '{') {
523
- // `{m,n}` — flag as quantifier when n is missing or large enough to
524
- // multiply meaningfully.
525
- const close = source.indexOf('}', i);
526
- if (close > i && close - i < 16) {
527
- const body = source.slice(i + 1, close);
528
- const m = body.match(/^(\d+)\s*,?\s*(\d*)$/);
529
- if (m) {
530
- const upper = m[2] ? parseInt(m[2], 10) : Infinity;
531
- if (upper >= 3)
532
- stack[stack.length - 1].hasQuantifier = true;
533
- }
534
- i = close;
535
- }
536
- continue;
537
- }
538
- if (stack.length > 0 && c === '|') {
539
- const frame = stack[stack.length - 1];
540
- // Run the body-scan at most once per group · keeps total work O(n).
541
- if (frame.altChecked)
542
- continue;
543
- frame.altChecked = true;
544
- const groupStart = findGroupStart(source, i);
545
- const groupEnd = findGroupEnd(source, i);
546
- if (groupStart >= 0 && groupEnd > groupStart) {
547
- const body = source.slice(groupStart + 1, groupEnd);
548
- const branches = body.split('|');
549
- for (let k = 0; k < branches.length - 1; k++) {
550
- const a = branches[k];
551
- const b = branches[k + 1];
552
- if (a && b && (a === b || a.startsWith(b) || b.startsWith(a))) {
553
- frame.hasOverlapAlt = true;
554
- break;
555
- }
556
- }
557
- }
558
- }
559
- }
560
- return null;
561
- }
562
- function findGroupStart(s, from) {
563
- let depth = 1;
564
- for (let i = from - 1; i >= 0; i--) {
565
- if (s[i] === '\\') {
566
- i--;
567
- continue;
568
- }
569
- if (s[i] === ')')
570
- depth++;
571
- else if (s[i] === '(') {
572
- depth--;
573
- if (depth === 0)
574
- return i;
575
- }
576
- }
577
- return -1;
578
- }
579
- function findGroupEnd(s, from) {
580
- let depth = 1;
581
- for (let i = from + 1; i < s.length; i++) {
582
- if (s[i] === '\\') {
583
- i++;
584
- continue;
585
- }
586
- if (s[i] === '(')
587
- depth++;
588
- else if (s[i] === ')') {
589
- depth--;
590
- if (depth === 0)
591
- return i;
592
- }
593
- }
594
- return -1;
595
- }
596
- /**
597
- * Compile a regex from user-supplied YAML, with a static + dynamic ReDoS guard.
598
- *
599
- * CRIT-4 fix · `cfg.process_pattern` is user-controlled (anyone editing
600
- * ~/.codehere/agents.yaml). A pattern like `(a+)+b` causes catastrophic
601
- * backtracking that hangs the daemon every time it enumerates processes.
602
- *
603
- * Two-layer guard:
604
- * 1. STATIC · `detectRedosShape` rejects known-dangerous shapes *before*
605
- * handing the source to the regex engine. This is the only fully
606
- * reliable defense, because Node's regex engine is not interruptible
607
- * mid-evaluation — once a pathological pattern reaches it, the process
608
- * can hang for minutes.
609
- * 2. DYNAMIC · 100ms smoke test against a benign 1000-char string catches
610
- * patterns the static heuristic missed. Best-effort only; included as
611
- * defense-in-depth.
612
- *
613
- * On any failure we fall back to a safe pattern derived from the command name.
614
- */
615
- /** @internal — exported for the T4-B fuzz suite; not part of the public API. */
616
- export function compileSafePattern(source, fallback, agentId) {
617
- // Layer 1 · static shape check — this is the only fully reliable defense.
618
- const danger = detectRedosShape(source);
619
- if (danger) {
620
- console.warn(`[codehere] Regex for "${agentId}" rejected (${danger}) — using fallback`);
621
- return fallback;
622
- }
623
- let candidate;
624
- try {
625
- candidate = new RegExp(source);
626
- }
627
- catch {
628
- console.warn(`[codehere] Invalid regex in agents.yaml for "${agentId}" — using fallback`);
629
- return fallback;
630
- }
631
- // Layer 2 · dynamic smoke test — catches anything the static heuristic missed.
632
- try {
633
- const start = Date.now();
634
- candidate.test('a'.repeat(1000));
635
- if (Date.now() - start > 100) {
636
- console.warn(`[codehere] Regex for "${agentId}" too slow (likely ReDoS) — using fallback`);
637
- return fallback;
638
- }
639
- }
640
- catch {
641
- return fallback;
642
- }
643
- return candidate;
644
- }
645
- /** Build an AgentAdapter from a user config entry. */
646
- export function buildGenericAdapter(cfg) {
647
- const fallbackPattern = new RegExp(`(?:^|/)${cfg.command.split('/').pop()}(?:\\s|$)`);
648
- const pattern = cfg.process_pattern
649
- ? compileSafePattern(cfg.process_pattern, fallbackPattern, cfg.id)
650
- : fallbackPattern;
651
- const adapter = {
652
- id: cfg.id,
653
- label: cfg.label || cfg.id,
654
- processPattern: pattern,
655
- isInstalled() {
656
- try {
657
- if (cfg.command.startsWith('/'))
658
- return existsSync(cfg.command);
659
- const out = execFileSync('which', [cfg.command], { encoding: 'utf-8', timeout: 2000 });
660
- return out.trim().length > 0;
661
- }
662
- catch {
663
- return false;
664
- }
665
- },
666
- spawn(prompt, options) {
667
- return spawnGeneric(cfg, prompt, options);
668
- },
669
- checkReadiness() {
670
- const installed = adapter.isInstalled();
671
- if (!installed) {
672
- return {
673
- id: cfg.id,
674
- label: cfg.label || cfg.id,
675
- state: 'needs_install',
676
- installed: false,
677
- // Fall back gracefully: if no install_command is configured, keep the
678
- // button disabled (UI checks for a real command before enabling).
679
- installHint: cfg.install_command ? { command: cfg.install_command, url: cfg.install_url } : undefined,
680
- };
681
- }
682
- // Generic adapters can't introspect auth — treat install as ready, let
683
- // runtime error detection surface real auth failures to the user.
684
- return { id: cfg.id, label: cfg.label || cfg.id, state: 'ready', installed: true };
685
- },
686
- };
687
- return adapter;
688
- }
689
- //# sourceMappingURL=generic-cli-adapter.js.map