codehere 0.3.0-rc.2 → 0.3.0-rc.27
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.
- package/dist/domain/services/codebase-detector.js +1 -1
- package/dist/index.js +96 -56
- package/dist/infrastructure/hooks/claude-sdk-hook.js +4 -4
- package/dist/infrastructure/hooks/session-analyzer.js +14 -5
- package/dist/infrastructure/orchestration/conductor-adapter.js +351 -0
- package/dist/infrastructure/orchestration/generic-cli-adapter.js +0 -3
- package/dist/infrastructure/orchestration/session-manager.js +6 -0
- package/dist/infrastructure/protocols/mcp-server-impl.js +33 -3
- package/dist/infrastructure/protocols/probe-port.js +36 -0
- package/dist/infrastructure/security/file-collection.js +3 -0
- package/dist/presentation/cli/commands/report-command.js +56 -11
- package/dist/presentation/cli/commands/status-command.js +32 -10
- package/dist/presentation/cli/repl.js +718 -0
- package/dist/ui.js +0 -3
- package/dist/utils/typo-guard.js +73 -0
- package/dist/utils/version.js +1 -1
- package/package.json +1 -1
|
@@ -9,7 +9,7 @@ import { join, dirname, resolve } from 'path';
|
|
|
9
9
|
*/
|
|
10
10
|
export function findCodebaseRoot(startPath = process.cwd()) {
|
|
11
11
|
const resolvedStart = resolve(startPath);
|
|
12
|
-
|
|
12
|
+
const currentDir = resolvedStart;
|
|
13
13
|
// Try to find git root first
|
|
14
14
|
const gitRoot = findGitRoot(currentDir);
|
|
15
15
|
if (gitRoot) {
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,6 @@ import { Command } from 'commander';
|
|
|
14
14
|
import { config } from 'dotenv';
|
|
15
15
|
import { join, dirname } from 'path';
|
|
16
16
|
import { fileURLToPath } from 'url';
|
|
17
|
-
import { existsSync, readFileSync } from 'fs';
|
|
18
17
|
import { executeSetupCommand } from './presentation/cli/commands/setup-command.js';
|
|
19
18
|
import { executeConfigCommand } from './presentation/cli/commands/config-command.js';
|
|
20
19
|
import { executeHelpCommand } from './presentation/cli/commands/help-command.js';
|
|
@@ -38,60 +37,53 @@ catch {
|
|
|
38
37
|
}
|
|
39
38
|
config();
|
|
40
39
|
import { getVersion } from './utils/version.js';
|
|
40
|
+
import { checkTypo } from './utils/typo-guard.js';
|
|
41
41
|
const program = new Command();
|
|
42
42
|
program
|
|
43
43
|
.name('codehere')
|
|
44
44
|
.description('A PM for your AI coding agents. Delegate a task, watch it run, get a plain-English report with a trust score on every file.')
|
|
45
45
|
.version(getVersion())
|
|
46
|
-
.configureHelp({ helpWidth: 80, sortSubcommands: true })
|
|
47
|
-
//
|
|
46
|
+
.configureHelp({ helpWidth: 80, sortSubcommands: true })
|
|
47
|
+
// rc.18: many users hit `codehere --help` first and get Commander's flat
|
|
48
|
+
// list. The grouped `codehere help` is more useful for discovery. Surface
|
|
49
|
+
// it inline so muscle-memory `--help` users find the better page.
|
|
50
|
+
// (Pin: no raw ANSI in --help output — existing commands.test.ts asserts
|
|
51
|
+
// this, see test/cli/commands.test.ts "no raw ANSI escape codes in --help".)
|
|
52
|
+
.addHelpText('after', '\nTip: `codehere help` shows commands grouped by use case (Delegate · Safety & Trust · Configuration).');
|
|
53
|
+
// Default action · show welcome, then drop into the interactive REPL on TTY.
|
|
54
|
+
// codehere offers TWO surfaces, both first-class: the CLI REPL (here) and the
|
|
55
|
+
// web UI (`codehere start`). Users pick whichever fits their workflow.
|
|
48
56
|
program
|
|
49
|
-
.argument('[query]', '
|
|
57
|
+
.argument('[query]', 'Optional initial task to delegate (otherwise enter interactive REPL)')
|
|
50
58
|
.action(async (query) => {
|
|
59
|
+
// One-shot delegate: `codehere "review src/auth.ts"` runs that task and exits.
|
|
60
|
+
// Useful for scripting or quick one-offs without entering the REPL.
|
|
51
61
|
if (query && query.trim()) {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
62
|
+
const trimmed = query.trim();
|
|
63
|
+
// Typo guard — see src/utils/typo-guard.ts for heuristics.
|
|
64
|
+
// Returns suggestions when input looks like a typo; null falls through.
|
|
65
|
+
const known = program.commands.map((c) => c.name());
|
|
66
|
+
const suggestions = checkTypo(trimmed, known);
|
|
67
|
+
if (suggestions) {
|
|
68
|
+
console.error(`codehere: unknown command '${trimmed}'.`);
|
|
69
|
+
console.error('');
|
|
70
|
+
console.error(' Did you mean:');
|
|
71
|
+
for (const s of suggestions)
|
|
72
|
+
console.error(` codehere ${s}`);
|
|
73
|
+
console.error('');
|
|
74
|
+
console.error(` If you meant to ask a question, quote it: codehere "${trimmed}"`);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
const { runOneShot } = await import('./presentation/cli/repl.js');
|
|
78
|
+
await runOneShot(trimmed);
|
|
79
|
+
return;
|
|
57
80
|
}
|
|
58
81
|
if (!process.stdin.isTTY) {
|
|
59
82
|
console.log(createWelcomeMessage());
|
|
60
83
|
return;
|
|
61
84
|
}
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
const hasHooks = existsSync(settingsPath) && readFileSync(settingsPath, 'utf-8').includes('codehere');
|
|
65
|
-
const hasAuditLog = existsSync(join(codehereDir, 'audit', 'hook-events.jsonl'));
|
|
66
|
-
console.log(createWelcomeMessage());
|
|
67
|
-
newline();
|
|
68
|
-
if (!hasHooks && !hasAuditLog) {
|
|
69
|
-
console.log(colors.bold("Welcome! Let's get you set up."));
|
|
70
|
-
newline();
|
|
71
|
-
console.log(' ' + colors.bold('Safety first — no API key, instant'));
|
|
72
|
-
console.log(colors.dim(' Every AI write gets scanned. Catches injections, hardcoded secrets,'));
|
|
73
|
-
console.log(colors.dim(' destructive ops, and more.'));
|
|
74
|
-
newline();
|
|
75
|
-
console.log(' → Run ' + colors.cyan('codehere hook install') + ' to activate safety');
|
|
76
|
-
console.log(' → Run ' + colors.cyan('codehere trust .') + ' to scan this project');
|
|
77
|
-
newline();
|
|
78
|
-
console.log(' ' + colors.bold('Delegate tasks — the PM for your AI coding agents'));
|
|
79
|
-
console.log(colors.dim(' Pick Claude Code, Codex, Aider, or OpenCode. codehere coordinates.'));
|
|
80
|
-
newline();
|
|
81
|
-
console.log(' → Run ' + colors.cyan('codehere start') + ' to open the task UI');
|
|
82
|
-
newline();
|
|
83
|
-
}
|
|
84
|
-
else {
|
|
85
|
-
console.log(colors.bold('Quick start:'));
|
|
86
|
-
newline();
|
|
87
|
-
console.log(' ' + colors.cyan('codehere start') + ' Task intake UI at http://127.0.0.1:3773');
|
|
88
|
-
console.log(' ' + colors.cyan('codehere status') + ' Dashboard · sessions · blocked calls');
|
|
89
|
-
console.log(' ' + colors.cyan('codehere report') + ' Generate a shareable audit report');
|
|
90
|
-
console.log(' ' + colors.cyan('codehere trust .') + ' Scan this project now');
|
|
91
|
-
newline();
|
|
92
|
-
console.log(colors.dim(' Run `codehere --help` for all commands.'));
|
|
93
|
-
newline();
|
|
94
|
-
}
|
|
85
|
+
const { runInteractiveRepl } = await import('./presentation/cli/repl.js');
|
|
86
|
+
await runInteractiveRepl();
|
|
95
87
|
});
|
|
96
88
|
// ── setup ────────────────────────────────────────────────────────────────────
|
|
97
89
|
program
|
|
@@ -133,8 +125,23 @@ program
|
|
|
133
125
|
.command('health')
|
|
134
126
|
.description('Check system health and metrics')
|
|
135
127
|
.option('-m, --metrics', 'Show detailed metrics')
|
|
128
|
+
.option('--json', 'Machine-readable JSON (for monitoring/CI)')
|
|
136
129
|
.action((options) => {
|
|
137
130
|
const health = performHealthCheck();
|
|
131
|
+
if (options.json) {
|
|
132
|
+
// Machine-readable: status + checks (+ metrics when --metrics).
|
|
133
|
+
// Stdout is the contract — never mix with the human banner.
|
|
134
|
+
// Use process.exitCode (not process.exit) so a piped consumer sees the
|
|
135
|
+
// full JSON before the process tears down (rc.16: Codex flagged the old
|
|
136
|
+
// process.exit call as a truncation hazard under stdout redirection).
|
|
137
|
+
const payload = { status: health.status, checks: health.checks };
|
|
138
|
+
if (options.metrics)
|
|
139
|
+
payload.metrics = getMetrics();
|
|
140
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
141
|
+
if (health.status === 'unhealthy')
|
|
142
|
+
process.exitCode = 1;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
138
145
|
if (isMinimalStyle()) {
|
|
139
146
|
printMinimalHeader('health', '');
|
|
140
147
|
}
|
|
@@ -232,9 +239,9 @@ program
|
|
|
232
239
|
.command('report')
|
|
233
240
|
.description('Generate a shareable security audit report — narrative, not just a score')
|
|
234
241
|
.argument('[target]', 'File or directory to audit (default: current directory)')
|
|
235
|
-
.option('--out <file>', 'Write report to a specific file (default: codehere-audit.md)')
|
|
236
|
-
.option('--stdout', 'Print the report to stdout
|
|
237
|
-
.option('--json', 'Output machine-readable JSON
|
|
242
|
+
.option('--out <file>', 'Write report to a specific file (default: codehere-audit.md for markdown)')
|
|
243
|
+
.option('--stdout', 'Print the report to stdout (already the default for --json)')
|
|
244
|
+
.option('--json', 'Output machine-readable JSON to stdout (pipe to jq, etc.)')
|
|
238
245
|
.option('--simple', 'Plain English output — no jargon, for non-technical stakeholders')
|
|
239
246
|
.addHelpText('after', `
|
|
240
247
|
Examples:
|
|
@@ -354,10 +361,30 @@ program
|
|
|
354
361
|
const port = parseInt(options?.port ?? '3773', 10);
|
|
355
362
|
const host = options?.host ?? '127.0.0.1';
|
|
356
363
|
const shouldOpen = options?.open !== false;
|
|
364
|
+
const url = `http://${host}:${port}/`;
|
|
365
|
+
const openBrowser = async () => {
|
|
366
|
+
if (!shouldOpen)
|
|
367
|
+
return;
|
|
368
|
+
const { spawn } = await import('child_process');
|
|
369
|
+
const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
|
|
370
|
+
try {
|
|
371
|
+
spawn(opener, [url], { detached: true, stdio: 'ignore' }).unref();
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
/* browser open is best-effort */
|
|
375
|
+
}
|
|
376
|
+
};
|
|
357
377
|
try {
|
|
358
378
|
const { startMCPServer } = await import('./infrastructure/protocols/mcp-server-impl.js');
|
|
359
379
|
const server = startMCPServer({ port, host });
|
|
360
|
-
|
|
380
|
+
// Wait for the server to either start listening or fail. The default
|
|
381
|
+
// Node behavior on listen() failure is an unhandled 'error' event which
|
|
382
|
+
// crashes the process with a stack trace. We catch it here so the user
|
|
383
|
+
// sees a friendly message instead.
|
|
384
|
+
await new Promise((resolve, reject) => {
|
|
385
|
+
server.once('listening', () => resolve());
|
|
386
|
+
server.once('error', reject);
|
|
387
|
+
});
|
|
361
388
|
newline();
|
|
362
389
|
console.log(success('codehere is running'));
|
|
363
390
|
newline();
|
|
@@ -367,16 +394,7 @@ program
|
|
|
367
394
|
newline();
|
|
368
395
|
console.log(colors.dim(' Press Ctrl+C to stop'));
|
|
369
396
|
newline();
|
|
370
|
-
|
|
371
|
-
const { spawn } = await import('child_process');
|
|
372
|
-
const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
|
|
373
|
-
try {
|
|
374
|
-
spawn(opener, [url], { detached: true, stdio: 'ignore' }).unref();
|
|
375
|
-
}
|
|
376
|
-
catch {
|
|
377
|
-
/* browser open is best-effort */
|
|
378
|
-
}
|
|
379
|
-
}
|
|
397
|
+
await openBrowser();
|
|
380
398
|
process.on('SIGINT', () => {
|
|
381
399
|
server.close();
|
|
382
400
|
console.log(colors.dim('\ncodehere stopped'));
|
|
@@ -387,6 +405,28 @@ program
|
|
|
387
405
|
});
|
|
388
406
|
}
|
|
389
407
|
catch (err) {
|
|
408
|
+
const code = err?.code;
|
|
409
|
+
if (code === 'EADDRINUSE') {
|
|
410
|
+
// Port is taken. Probe to find out by what — if it's a running codehere,
|
|
411
|
+
// we should hand the user the existing URL; if it's something else,
|
|
412
|
+
// tell them to pick a different port.
|
|
413
|
+
const { isCodehereOnPort } = await import('./infrastructure/protocols/probe-port.js');
|
|
414
|
+
const existing = await isCodehereOnPort(host, port);
|
|
415
|
+
newline();
|
|
416
|
+
if (existing.isCodehere) {
|
|
417
|
+
console.log(success(`codehere is already running at ${url}`));
|
|
418
|
+
if (existing.version) {
|
|
419
|
+
console.log(colors.dim(` version: ${existing.version}`));
|
|
420
|
+
}
|
|
421
|
+
newline();
|
|
422
|
+
console.log(colors.dim(' Opening browser...'));
|
|
423
|
+
await openBrowser();
|
|
424
|
+
process.exit(0);
|
|
425
|
+
}
|
|
426
|
+
console.error(error(`Port ${port} is in use by another process.`));
|
|
427
|
+
console.error(colors.dim(` Try: codehere start --port ${port + 1}`));
|
|
428
|
+
process.exit(1);
|
|
429
|
+
}
|
|
390
430
|
console.error(error('Failed to start:'), err instanceof Error ? err.message : String(err));
|
|
391
431
|
process.exit(1);
|
|
392
432
|
}
|
|
@@ -44,7 +44,7 @@ const PATTERNS = [
|
|
|
44
44
|
description: 'Role hijacking attempt',
|
|
45
45
|
},
|
|
46
46
|
{
|
|
47
|
-
regex:
|
|
47
|
+
regex: /\bsystem\s+prompt\b|<\/?system>|(?<!['"\\])<\/?instruction>/i,
|
|
48
48
|
severity: 'critical',
|
|
49
49
|
category: 'Prompt Injection',
|
|
50
50
|
description: 'System prompt injection',
|
|
@@ -56,7 +56,7 @@ const PATTERNS = [
|
|
|
56
56
|
description: 'Instruction override attempt',
|
|
57
57
|
},
|
|
58
58
|
{
|
|
59
|
-
regex:
|
|
59
|
+
regex: /\bjailbreak\b|\bDAN\s+mode\b|\bdeveloper\s+mode\s+enabled\b/i,
|
|
60
60
|
severity: 'critical',
|
|
61
61
|
category: 'Prompt Injection',
|
|
62
62
|
description: 'Jailbreak attempt',
|
|
@@ -93,7 +93,7 @@ const PATTERNS = [
|
|
|
93
93
|
description: 'Exfiltrates env secrets',
|
|
94
94
|
},
|
|
95
95
|
{
|
|
96
|
-
regex:
|
|
96
|
+
regex: /\bprintenv\b|\benv\s*\|\s*(grep|curl|wget|nc)\b/i,
|
|
97
97
|
severity: 'high',
|
|
98
98
|
category: 'Credential Theft',
|
|
99
99
|
description: 'Environment variable exfiltration',
|
|
@@ -119,7 +119,7 @@ const PATTERNS = [
|
|
|
119
119
|
description: 'SSH key tooling access',
|
|
120
120
|
},
|
|
121
121
|
{
|
|
122
|
-
regex:
|
|
122
|
+
regex: /\bkeychain\b|\bsecurity\s+find-generic-password\b/i,
|
|
123
123
|
severity: 'high',
|
|
124
124
|
category: 'Credential Theft',
|
|
125
125
|
description: 'macOS keychain access attempt',
|
|
@@ -76,17 +76,26 @@ export function detectAmplificationAlerts(sessions) {
|
|
|
76
76
|
continue;
|
|
77
77
|
let message = '';
|
|
78
78
|
const risk = session.amplificationRisk;
|
|
79
|
-
|
|
80
|
-
|
|
79
|
+
// rc.17 framing: don't accuse "injection" by default — that wording scares
|
|
80
|
+
// users on perfectly normal long attended sessions. Reserve the strong
|
|
81
|
+
// language for cases where the *blocked-call ratio* is high (real signal
|
|
82
|
+
// of prompts trying things they shouldn't), not just call volume.
|
|
83
|
+
// UX_OBSERVATIONS.md P1.
|
|
84
|
+
const blockRatio = session.totalCalls > 0 ? session.blockedCalls / session.totalCalls : 0;
|
|
85
|
+
if (session.blockedCalls > 0 && session.totalCalls > 20 && blockRatio > 0.05) {
|
|
86
|
+
message = `${session.totalCalls} tool calls, ${session.blockedCalls} blocked (${(blockRatio * 100).toFixed(0)}%) — high block ratio, review for injection`;
|
|
87
|
+
}
|
|
88
|
+
else if (session.blockedCalls > 0 && session.totalCalls > 20) {
|
|
89
|
+
message = `${session.totalCalls} tool calls, ${session.blockedCalls} blocked — long session, review if unattended`;
|
|
81
90
|
}
|
|
82
91
|
else if (session.totalCalls > 50) {
|
|
83
|
-
message = `${session.totalCalls} tool calls in one session —
|
|
92
|
+
message = `${session.totalCalls} tool calls in one session — high density, review if unattended`;
|
|
84
93
|
}
|
|
85
94
|
else if ((session.toolMix['Bash'] ?? 0) > 10) {
|
|
86
|
-
message = `${session.toolMix['Bash']} Bash calls in one session — elevated
|
|
95
|
+
message = `${session.toolMix['Bash']} Bash calls in one session — elevated tool-mix`;
|
|
87
96
|
}
|
|
88
97
|
else {
|
|
89
|
-
message = `${session.totalCalls} calls, ${session.blockedCalls} blocked — worth
|
|
98
|
+
message = `${session.totalCalls} calls, ${session.blockedCalls} blocked — worth a glance`;
|
|
90
99
|
}
|
|
91
100
|
alerts.push({
|
|
92
101
|
sessionId: session.sessionId,
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* F6 Conductor — codehere's own meta-agent.
|
|
3
|
+
*
|
|
4
|
+
* Plain English in, agent actions out. The Conductor is a first-class
|
|
5
|
+
* AgentAdapter that doesn't fork a subprocess — instead it ROUTES the
|
|
6
|
+
* incoming prompt to one of the dogfooded specialists (Claude Code, Codex,
|
|
7
|
+
* Aider, OpenCode) based on intent, then proxies the spawned session's
|
|
8
|
+
* events back to the caller verbatim, with a single Conductor-attributed
|
|
9
|
+
* "delegated to X" event prepended so the audit log records the routing
|
|
10
|
+
* decision.
|
|
11
|
+
*
|
|
12
|
+
* This is the v0.4-alpha SCAFFOLD. Routing is rule-based (keyword → adapter)
|
|
13
|
+
* for now. The v0.4 stable target replaces the rule lookup with an LLM
|
|
14
|
+
* classifier — Claude Haiku 4.5 prompted to pick the best specialist given
|
|
15
|
+
* the user's request, the available agents, and any context from past
|
|
16
|
+
* sessions. The seam (`pickSpecialist`) is the same; only the body changes.
|
|
17
|
+
*
|
|
18
|
+
* Why this matters: until Conductor exists, codehere is "a UI over other
|
|
19
|
+
* people's agents." With Conductor, codehere becomes a participant in the
|
|
20
|
+
* thread — the user talks to *codehere*, codehere talks to the agents, and
|
|
21
|
+
* the user gets a single conversational surface instead of having to know
|
|
22
|
+
* which specialist suits the task. This is the seam the v0.4+ Slack-shape
|
|
23
|
+
* thread UX (`@conductor` mention) attaches to.
|
|
24
|
+
*
|
|
25
|
+
* What v0.4-alpha intentionally does NOT do:
|
|
26
|
+
* - LLM-backed classifier (rule-based only)
|
|
27
|
+
* - Multi-step plans (one prompt → one specialist)
|
|
28
|
+
* - Cross-session memory (Conductor sees only the current prompt)
|
|
29
|
+
* - Mid-session redirection (once delegated, the specialist owns the session)
|
|
30
|
+
*
|
|
31
|
+
* Adding any of those before v0.4-stable rc.1 violates the "rc.N is feature-
|
|
32
|
+
* frozen, beta.N+1 may only harden or fix" rule.
|
|
33
|
+
*
|
|
34
|
+
* @see docs/CONDUCTOR.md for the full design + roadmap from scaffold → stable
|
|
35
|
+
* @see memory/project_decisions_log.md Decision 05 (F6 as first-class foundation)
|
|
36
|
+
*/
|
|
37
|
+
import { EventEmitter } from 'events';
|
|
38
|
+
import { randomUUID } from 'crypto';
|
|
39
|
+
const ROUTING_RULES = [
|
|
40
|
+
{
|
|
41
|
+
triggers: ['review', 'audit', 'explain', 'understand', 'analyze', 'analyse', 'why', 'what does'],
|
|
42
|
+
preferred: ['claude-code', 'codex', 'aider'],
|
|
43
|
+
reason: 'review/audit/explain tasks favor Claude Code',
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
triggers: ['refactor', 'restructure', 'reorganize', 'reorganise', 'rewrite the', 'extract'],
|
|
47
|
+
preferred: ['codex', 'claude-code', 'aider'],
|
|
48
|
+
reason: 'structural refactors favor Codex',
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
triggers: ['fix', 'patch', 'bugfix', 'hotfix', 'repair', 'resolve'],
|
|
52
|
+
preferred: ['aider', 'claude-code', 'codex'],
|
|
53
|
+
reason: 'targeted fixes favor Aider',
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
triggers: ['scaffold', 'generate', 'create new', 'bootstrap', 'set up'],
|
|
57
|
+
preferred: ['opencode', 'claude-code', 'codex'],
|
|
58
|
+
reason: 'greenfield generation favors OpenCode',
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
triggers: ['add tests', 'write tests', 'test coverage', 'unit test', 'integration test'],
|
|
62
|
+
preferred: ['codex', 'claude-code', 'aider'],
|
|
63
|
+
reason: 'test authoring favors Codex',
|
|
64
|
+
},
|
|
65
|
+
];
|
|
66
|
+
/** Default specialist when no routing rule matches. */
|
|
67
|
+
const DEFAULT_SPECIALIST = 'claude-code';
|
|
68
|
+
/**
|
|
69
|
+
* Tokenize a prompt for trigger matching. Splits on any non-alphanumeric
|
|
70
|
+
* boundary (whitespace, hyphens, punctuation), lowercases everything. So:
|
|
71
|
+
*
|
|
72
|
+
* "Bug fix" → ["bug", "fix"]
|
|
73
|
+
* "set-up auth" → ["set", "up", "auth"] (trigger "set up" still matches via phrase below)
|
|
74
|
+
* "unit-test it" → ["unit", "test", "it"]
|
|
75
|
+
* "prefix matter" → ["prefix", "matter"] (does NOT match `fix`)
|
|
76
|
+
* "hotfixes" → ["hotfixes"] (does NOT match `fix`)
|
|
77
|
+
*
|
|
78
|
+
* Multi-word triggers ("add tests", "create new") are matched against the
|
|
79
|
+
* normalized prompt directly using word boundaries — so they catch
|
|
80
|
+
* "add tests" but not "added testing harness".
|
|
81
|
+
*/
|
|
82
|
+
function tokenize(prompt) {
|
|
83
|
+
const tokens = new Set(prompt
|
|
84
|
+
.toLowerCase()
|
|
85
|
+
.split(/[^a-z0-9]+/)
|
|
86
|
+
.filter(Boolean));
|
|
87
|
+
// Normalized form for multi-word phrase matching: ANY non-alphanumeric char
|
|
88
|
+
// (hyphens, underscores, slashes, dots, colons, commas, etc.) becomes a space,
|
|
89
|
+
// then collapse runs of whitespace. This matches the tokenizer's split rule
|
|
90
|
+
// exactly, so multi-word triggers like "add tests" catch all of:
|
|
91
|
+
// "add tests" "add-tests" "add_tests" "add/tests" "add:tests" "add.tests"
|
|
92
|
+
// Note: must NOT collapse the leading/trailing spaces — they're load-bearing
|
|
93
|
+
// for the boundary check below (`.includes(' ' + t + ' ')`).
|
|
94
|
+
const normalized = ' ' +
|
|
95
|
+
prompt
|
|
96
|
+
.toLowerCase()
|
|
97
|
+
.replace(/[^a-z0-9]+/g, ' ')
|
|
98
|
+
.trim() +
|
|
99
|
+
' ';
|
|
100
|
+
return { tokens, normalized };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Test whether a routing trigger matches a prompt. Single-word triggers must
|
|
104
|
+
* appear as whole tokens (no substring matches). Multi-word triggers must
|
|
105
|
+
* appear as a phrase in the normalized prompt (with leading/trailing spaces
|
|
106
|
+
* to enforce word boundaries on the ends).
|
|
107
|
+
*/
|
|
108
|
+
function triggerMatches(trigger, tokens, normalized) {
|
|
109
|
+
const t = trigger.toLowerCase().trim();
|
|
110
|
+
if (!t)
|
|
111
|
+
return false;
|
|
112
|
+
if (t.includes(' ')) {
|
|
113
|
+
return normalized.includes(' ' + t + ' ');
|
|
114
|
+
}
|
|
115
|
+
return tokens.has(t);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Pick the right specialist for a given prompt.
|
|
119
|
+
*
|
|
120
|
+
* Algorithm:
|
|
121
|
+
* 1. Tokenize the prompt (whole-word matching, no substring false-positives).
|
|
122
|
+
* 2. Walk routing rules in order. Stop at the first rule whose triggers match.
|
|
123
|
+
* 3. Within that rule, return the first preferred adapter that's installed.
|
|
124
|
+
* 4. If that rule had a match but none of its preferred adapters are
|
|
125
|
+
* installed, return DEFAULT_SPECIALIST (or first installed) with a
|
|
126
|
+
* HONEST reason that names the matched rule and the fallback.
|
|
127
|
+
* 5. If no rule matched at all, return DEFAULT_SPECIALIST (or first
|
|
128
|
+
* installed) with a "no intent matched" reason.
|
|
129
|
+
*
|
|
130
|
+
* Returns null if NO specialist is installed (caller must handle).
|
|
131
|
+
*
|
|
132
|
+
* Known limitation: a prompt with multiple intents (e.g. "fix the bug and
|
|
133
|
+
* add tests") routes by the first matching rule, not the dominant intent.
|
|
134
|
+
* The v0.4 LLM classifier inherently handles dominance via confidence
|
|
135
|
+
* scoring; the rule-based path here keeps the deterministic-priority
|
|
136
|
+
* contract instead.
|
|
137
|
+
*/
|
|
138
|
+
export function pickSpecialist(prompt, installedAgentIds) {
|
|
139
|
+
if (installedAgentIds.length === 0) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const installedSet = new Set(installedAgentIds);
|
|
143
|
+
const { tokens, normalized } = tokenize(prompt);
|
|
144
|
+
for (const rule of ROUTING_RULES) {
|
|
145
|
+
const matches = rule.triggers.some((t) => triggerMatches(t, tokens, normalized));
|
|
146
|
+
if (!matches)
|
|
147
|
+
continue;
|
|
148
|
+
// Rule matched. Walk preferred specialists in order.
|
|
149
|
+
for (const candidate of rule.preferred) {
|
|
150
|
+
if (installedSet.has(candidate)) {
|
|
151
|
+
return { agentId: candidate, reason: rule.reason };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// Rule matched but none of its preferred specialists are installed.
|
|
155
|
+
// Fall through with an HONEST reason that names the matched rule + fallback,
|
|
156
|
+
// so the audit log records what actually happened (Codex review caught
|
|
157
|
+
// the prior version saying "default routing" here, which was a lie).
|
|
158
|
+
const fallbackId = installedSet.has(DEFAULT_SPECIALIST) ? DEFAULT_SPECIALIST : installedAgentIds[0];
|
|
159
|
+
return {
|
|
160
|
+
agentId: fallbackId,
|
|
161
|
+
reason: `${rule.reason} — but none of [${rule.preferred.join(', ')}] installed; falling back to ${fallbackId}`,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
// No rule matched. Default routing.
|
|
165
|
+
if (installedSet.has(DEFAULT_SPECIALIST)) {
|
|
166
|
+
return { agentId: DEFAULT_SPECIALIST, reason: 'default routing (no specific intent matched)' };
|
|
167
|
+
}
|
|
168
|
+
return { agentId: installedAgentIds[0], reason: 'fallback to first available specialist' };
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Build the Conductor adapter. The lookup function is injected so we can
|
|
172
|
+
* register against the same registry without creating an import cycle.
|
|
173
|
+
*
|
|
174
|
+
* IMPORTANT: the lookup is called at spawn time, NOT module-load time, so
|
|
175
|
+
* it sees the fully-populated registry including any user-config adapters.
|
|
176
|
+
*/
|
|
177
|
+
export function buildConductorAdapter(lookup) {
|
|
178
|
+
const adapter = {
|
|
179
|
+
id: 'conductor',
|
|
180
|
+
label: 'Conductor (codehere)',
|
|
181
|
+
// Conductor doesn't run as its own OS process — there's nothing to detect
|
|
182
|
+
// via `ps`. The processPattern returned here will never match, by design.
|
|
183
|
+
processPattern: /__conductor_never_matches__/,
|
|
184
|
+
isInstalled() {
|
|
185
|
+
// Conductor is "installed" iff at least one specialist is installed.
|
|
186
|
+
// Anything else would be a confusing UX (offer Conductor when it has
|
|
187
|
+
// nothing to delegate to).
|
|
188
|
+
return lookup().some((a) => a.id !== 'conductor' && a.isInstalled());
|
|
189
|
+
},
|
|
190
|
+
checkReadiness() {
|
|
191
|
+
const specialists = lookup().filter((a) => a.id !== 'conductor');
|
|
192
|
+
const installedSpecialists = specialists.filter((a) => a.isInstalled());
|
|
193
|
+
if (installedSpecialists.length === 0) {
|
|
194
|
+
return {
|
|
195
|
+
id: 'conductor',
|
|
196
|
+
label: 'Conductor (codehere)',
|
|
197
|
+
state: 'needs_install',
|
|
198
|
+
installed: false,
|
|
199
|
+
installHint: {
|
|
200
|
+
command: 'npm install -g @anthropic-ai/claude-code',
|
|
201
|
+
url: 'https://github.com/codehere/codehere#install',
|
|
202
|
+
},
|
|
203
|
+
authHint: {
|
|
204
|
+
detail: 'Conductor delegates to specialists. Install at least one (Claude Code, Codex, Aider, or OpenCode) and Conductor becomes available automatically.',
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
id: 'conductor',
|
|
210
|
+
label: 'Conductor (codehere)',
|
|
211
|
+
state: 'ready',
|
|
212
|
+
installed: true,
|
|
213
|
+
};
|
|
214
|
+
},
|
|
215
|
+
spawn(prompt, options) {
|
|
216
|
+
return spawnConductor(prompt, options ?? {}, lookup);
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
return adapter;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Spawn the Conductor session. Does not fork a process — instead picks a
|
|
223
|
+
* specialist, spawns it, and proxies its events through with a single
|
|
224
|
+
* "delegated" event prepended to the buffer.
|
|
225
|
+
*/
|
|
226
|
+
function spawnConductor(prompt, options, lookup) {
|
|
227
|
+
const sessionId = randomUUID();
|
|
228
|
+
const startedAt = Date.now();
|
|
229
|
+
const emitter = new EventEmitter();
|
|
230
|
+
const buffer = [];
|
|
231
|
+
let statusValue = 'running';
|
|
232
|
+
// Look up installed specialists (excluding Conductor itself to avoid recursion)
|
|
233
|
+
const installedAgentIds = lookup()
|
|
234
|
+
.filter((a) => a.id !== 'conductor' && a.isInstalled())
|
|
235
|
+
.map((a) => a.id);
|
|
236
|
+
const decision = pickSpecialist(prompt, installedAgentIds);
|
|
237
|
+
// If nothing's installed, emit an error event and return a non-running session.
|
|
238
|
+
if (!decision) {
|
|
239
|
+
statusValue = 'error';
|
|
240
|
+
const errEvent = {
|
|
241
|
+
type: 'error',
|
|
242
|
+
timestamp: Date.now(),
|
|
243
|
+
data: {
|
|
244
|
+
message: 'Conductor has no specialists to delegate to. Install at least one of: Claude Code, Codex, Aider, OpenCode.',
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
buffer.push(errEvent);
|
|
248
|
+
return synthesizeSession({ sessionId, startedAt, prompt, statusValue, emitter, buffer });
|
|
249
|
+
}
|
|
250
|
+
// Emit the routing-decision event FIRST so the audit log records WHY this
|
|
251
|
+
// specialist was chosen. Layer 7 agent-provenance — every action attributable.
|
|
252
|
+
const routingEvent = {
|
|
253
|
+
type: 'codehere:conductor-routing',
|
|
254
|
+
timestamp: Date.now(),
|
|
255
|
+
data: {
|
|
256
|
+
conductorSessionId: sessionId,
|
|
257
|
+
delegatedTo: decision.agentId,
|
|
258
|
+
reason: decision.reason,
|
|
259
|
+
promptExcerpt: prompt.slice(0, 200),
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
// Buffer replay on subscribe() handles delivery to the first subscriber. Do
|
|
263
|
+
// NOT also queueMicrotask(emit) — the microtask fires AFTER subscribe attaches
|
|
264
|
+
// its handler, so the handler would receive routingEvent twice (rc.13 bug:
|
|
265
|
+
// duplicate "routing → ..." line in the REPL).
|
|
266
|
+
buffer.push(routingEvent);
|
|
267
|
+
// Find the chosen specialist adapter and spawn against it.
|
|
268
|
+
const specialist = lookup().find((a) => a.id === decision.agentId);
|
|
269
|
+
if (!specialist) {
|
|
270
|
+
// Defensive: pickSpecialist returned an ID not in the registry. Shouldn't
|
|
271
|
+
// happen if installedAgentIds was derived from lookup(), but guard anyway.
|
|
272
|
+
statusValue = 'error';
|
|
273
|
+
const errEvent = {
|
|
274
|
+
type: 'error',
|
|
275
|
+
timestamp: Date.now(),
|
|
276
|
+
data: { message: `Conductor picked '${decision.agentId}' but no adapter with that ID is registered.` },
|
|
277
|
+
};
|
|
278
|
+
buffer.push(errEvent);
|
|
279
|
+
return synthesizeSession({ sessionId, startedAt, prompt, statusValue, emitter, buffer });
|
|
280
|
+
}
|
|
281
|
+
// Spawn the specialist session and proxy every event through.
|
|
282
|
+
const specialistSession = specialist.spawn(prompt, options);
|
|
283
|
+
let stepsSnapshot = [];
|
|
284
|
+
let artifactsSnapshot;
|
|
285
|
+
specialistSession.subscribe((evt) => {
|
|
286
|
+
buffer.push(evt);
|
|
287
|
+
emitter.emit('event', evt);
|
|
288
|
+
// Mirror progress + artifacts so PM-UX layers see them on the Conductor session, too.
|
|
289
|
+
if (specialistSession.steps)
|
|
290
|
+
stepsSnapshot = specialistSession.steps;
|
|
291
|
+
if (specialistSession.artifacts)
|
|
292
|
+
artifactsSnapshot = specialistSession.artifacts;
|
|
293
|
+
// Specialist adapters terminate with an 'exit' event — never emit
|
|
294
|
+
// 'codehere:complete' / 'codehere:error'. Without mirroring on 'exit',
|
|
295
|
+
// session.status stayed 'running' forever and the REPL printed
|
|
296
|
+
// "✗ └─ running" (rc.13 bug). Also keep the legacy types for safety in
|
|
297
|
+
// case a future adapter emits them.
|
|
298
|
+
if (evt.type === 'exit' || evt.type === 'codehere:complete' || evt.type === 'codehere:error') {
|
|
299
|
+
statusValue = specialistSession.status;
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
return {
|
|
303
|
+
sessionId,
|
|
304
|
+
startedAt,
|
|
305
|
+
prompt,
|
|
306
|
+
agent: 'conductor',
|
|
307
|
+
get status() {
|
|
308
|
+
return statusValue;
|
|
309
|
+
},
|
|
310
|
+
get steps() {
|
|
311
|
+
return stepsSnapshot;
|
|
312
|
+
},
|
|
313
|
+
get artifacts() {
|
|
314
|
+
return artifactsSnapshot;
|
|
315
|
+
},
|
|
316
|
+
canAppendMessage: false, // v0.4-alpha doesn't support mid-session redirection
|
|
317
|
+
subscribe(handler) {
|
|
318
|
+
for (const e of buffer)
|
|
319
|
+
handler(e);
|
|
320
|
+
emitter.on('event', handler);
|
|
321
|
+
return () => emitter.off('event', handler);
|
|
322
|
+
},
|
|
323
|
+
kill() {
|
|
324
|
+
specialistSession.kill();
|
|
325
|
+
statusValue = 'killed';
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
/** Build a TaskSession that just replays an event buffer — used for error states. */
|
|
330
|
+
function synthesizeSession(args) {
|
|
331
|
+
const { sessionId, startedAt, prompt, statusValue, emitter, buffer } = args;
|
|
332
|
+
return {
|
|
333
|
+
sessionId,
|
|
334
|
+
startedAt,
|
|
335
|
+
prompt,
|
|
336
|
+
agent: 'conductor',
|
|
337
|
+
get status() {
|
|
338
|
+
return statusValue;
|
|
339
|
+
},
|
|
340
|
+
subscribe(handler) {
|
|
341
|
+
for (const e of buffer)
|
|
342
|
+
handler(e);
|
|
343
|
+
emitter.on('event', handler);
|
|
344
|
+
return () => emitter.off('event', handler);
|
|
345
|
+
},
|
|
346
|
+
kill() {
|
|
347
|
+
/* nothing to kill — never started */
|
|
348
|
+
},
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
//# sourceMappingURL=conductor-adapter.js.map
|