codehere 0.8.0 → 1.0.2

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