The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
⌘B: say what you want and it is done (#1142)
Dee526d6bb9d081
diff --git a/cli/AGENTS.md b/cli/AGENTS.mdindex 87b36987a..49f185be7 100644--- a/cli/AGENTS.md+++ b/cli/AGENTS.md@@ -33,7 +33,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd| models | grid, local models, the Model Manager | on demand: once grid is in use here (a managed grid, saved grid pictures, local models), or on a models request || updater | checks, downloads and stages a new build (`src/services/updaterProcess.ts`) | by the master, for the installed copy only || devices | the dials, the window bridges, the fleet, the voice router, the Wi-Fi device | on demand: once there is a device |-| orchestrator, teams (with Tab collaboration), sharing, memory | the experiments | on demand: on a request, or saved state at start |+| orchestrator, teams (with Tab collaboration), sharing, memory, router | the experiments | on demand: on a request, or saved state at start |`HARNESSD_SERVICES` names a subset to run in their own processes, by service or by process.`HARNESSD_SERVICES=none` runs every service in the core's process, for debugging or a quick way back. Howdiff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex eda79c3d5..eaeeaf954 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -464,6 +464,9 @@ export const MONITOR_REQUESTS = ['machine_resources'] as const/** Memories (services/memory.ts), an experiment: what this machine's agents remember, for the owner's Memories* panes on their other machines, and the About You profile and its on/off choice from them. */export const MEMORY_REQUESTS = ['memory_snapshot', 'memory_about_put', 'memory_deliver'] as const+/** The router (services/router.ts), an experiment: where a task a person typed or said should go, decided for+ * the client that asks, which acts on it. */+export const ROUTER_REQUESTS = ['route_decide'] as const/** The project and folder readers (services/projects.ts). */export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const/** A window's name for its repo and its work, by a small model in the background (services/windowNames.ts). */@@ -554,6 +557,8 @@ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[];// Request-only, on from its first request until the daemon stops: another machine's Memories pane asks, and// the package's own files are its state.memory: { requests: MEMORY_REQUESTS, state: [] },+ // Request-only too: it keeps nothing, and asks Jev only when a client asks it.+ router: { requests: ROUTER_REQUESTS, state: [] },}/** The core's calls into Share: an observer's frame as the relay handed it over, the relay gone (every observerdiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 6ca4beba9..add2eddd3 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -149,7 +149,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawnimport { createCursorDiscovery } from './engines/cursorDiscovery.js'import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'-import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'+import { CONNECTORS_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -1391,6 +1391,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (!outOfProcess.has('projects')) serviceHost.serve('projects', inline!.startProjects, coreApi, PROJECTS_REQUESTS)if (!outOfProcess.has('windowNames')) serviceHost.serve('windowNames', inline!.startWindowNames, coreApi, WINDOW_NAMES_REQUESTS)if (!outOfProcess.has('memory')) serviceHost.serve('memory', inline!.startMemory, coreApi, MEMORY_REQUESTS)+ if (!outOfProcess.has('router')) serviceHost.serve('router', inline!.startRouter, coreApi, ROUTER_REQUESTS)if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)// Connected services' MCP bridge and the Connectors screen (services/connectors.ts): here, or in the edge host.if (!outOfProcess.has('connectors')) serviceHost.serve('connectors', inline!.startConnectors, coreApi, CONNECTORS_REQUESTS)diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex b4d2d0d16..53ea0cfca 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -390,6 +390,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// Memories pane asking. It runs the Memories package's own command: writes one at a time, snapshots// asked together as one read, each answer at most 8 MB.memory: { services: ['memory'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },+ // The router (services/routerProcess.ts), an experiment: started at its first request. A few decisions in+ // flight, each one bounded Jev answer.+ router: { services: ['router'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },// Tab collaboration and teams, an experiment: the prompt scopes, a few drafts and fingerprints per agent, and// beside them the teams, their mailbox and the tab channels (services/collaborationProcess.ts), each on its// own link to the core. Started only once it is on (core/api.ts `EXPERIMENTS`).diff --git a/cli/src/lib/jev/jevClient.spec.ts b/cli/src/lib/jev/jevClient.spec.tsnew file mode 100644index 000000000..b71d2cd67--- /dev/null+++ b/cli/src/lib/jev/jevClient.spec.ts@@ -0,0 +1,185 @@+// Jev through OpenRouter, as the router asks it: where the person's key is found, the one request it makes+// (an injected fetch here, never the network), how each refusal is named, and what of an answer is kept.+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import { resolveOpenRouterKey } from '../openrouter.js'+import { createJevDecide, JevUnavailable, resolveJevKey, type JevChoice } from './jevClient.js'++// The env key and `ori login`'s file are openrouter.ts's to read, and its spec's to test: here they are none,+// unless a test says otherwise.+vi.mock('../openrouter.js', () => ({ resolveOpenRouterKey: vi.fn(async () => null) }))++let root: string+beforeAll(() => { root = mkdtempSync(join(tmpdir(), 'jev-client-')) })+afterAll(() => { rmSync(root, { recursive: true, force: true }) })+beforeEach(() => { vi.mocked(resolveOpenRouterKey).mockResolvedValue(null) })+afterEach(() => {+ vi.unstubAllEnvs()+ vi.unstubAllGlobals()+})++/** A credentials file with [text] in it. */+function credentials(text: string): string {+ const path = join(root, `credentials-${Math.random().toString(36).slice(2)}`)+ writeFileSync(path, text)+ return path+}++describe('the person\'s OpenRouter key', () => {+ it('is the one OpenRouter\'s own lookup finds (OPENROUTER_API_KEY, `ori login`), before any file of Jev\'s', async () => {+ vi.mocked(resolveOpenRouterKey).mockResolvedValue('sk-or-known')+ expect(await resolveJevKey({ TYPESAFE_CREDENTIALS: credentials('OPENROUTER_API_KEY=sk-or-file\n') })).toBe('sk-or-known')+ })++ it('is read from the credentials file the Store\'s Jev tools keep, in the shell forms they write', async () => {+ const read = (text: string) => resolveJevKey({ TYPESAFE_CREDENTIALS: credentials(text) })+ expect(await read('OPENROUTER_API_KEY=sk-or-bare\n')).toBe('sk-or-bare')+ expect(await read('# Jev\nOTHER=1\n export OPENROUTER_API_KEY = "sk-or-double" \n')).toBe('sk-or-double')+ expect(await read("export OPENROUTER_API_KEY='sk-or-single'")).toBe('sk-or-single')+ // An empty value is passed over for one further down; quotes that do not match are the key's own.+ expect(await read('OPENROUTER_API_KEY=\nOPENROUTER_API_KEY=""\nOPENROUTER_API_KEY=sk-or-later\n')).toBe('sk-or-later')+ expect(await read('OPENROUTER_API_KEY="sk-or-odd\'')).toBe('"sk-or-odd\'')+ })++ it('is none when the file has no key, or there is no file', async () => {+ expect(await resolveJevKey({ TYPESAFE_CREDENTIALS: credentials('ANTHROPIC_API_KEY=sk-ant\n# OPENROUTER_API_KEY=commented\n') })).toBeNull()+ expect(await resolveJevKey({ TYPESAFE_CREDENTIALS: join(root, 'missing') })).toBeNull()+ })++ it('reads $TYPESAFE_CREDENTIALS from this process by default', async () => {+ vi.stubEnv('TYPESAFE_CREDENTIALS', credentials('OPENROUTER_API_KEY=sk-or-from-env-path'))+ expect(await resolveJevKey()).toBe('sk-or-from-env-path')+ })++ it('looks in ~/.config/typesafe/credentials when nothing names another file', async () => {+ const home = mkdtempSync(join(root, 'home-'))+ vi.stubEnv('HOME', home)+ expect(await resolveJevKey({})).toBeNull()+ mkdirSync(join(home, '.config', 'typesafe'), { recursive: true })+ writeFileSync(join(home, '.config', 'typesafe', 'credentials'), 'OPENROUTER_API_KEY=sk-or-home\n')+ expect(await resolveJevKey({ TYPESAFE_CREDENTIALS: '' })).toBe('sk-or-home')+ })+})++describe('asking Jev', () => {+ const QUESTIONS: Record<string, JevChoice> = { target: { type: 'choice', instructions: 'Which?', criteria: { s0: 'billing', new: 'none' } } }+ const STATE = { message: 'why was the card charged twice' }+ const ANSWER = { answers: { target: { choice: 's0', probabilities: { s0: 0.9, new: 0.1 } } } }++ /** A fetch answering [reply] (a Response, or a body for a 200) and recording what it was asked. */+ function fetching(reply: Response | string = JSON.stringify(ANSWER)) {+ return vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => (typeof reply === 'string' ? new Response(reply) : reply))+ }++ it('posts the state and the questions to the Decisions API with the person\'s key, and reads the answers', async () => {+ const fetch = fetching()+ const decide = createJevDecide({ key: async () => 'sk-or-fixture', fetch })+ expect(await decide(STATE, QUESTIONS)).toEqual(ANSWER.answers)+ expect(fetch).toHaveBeenCalledOnce()+ const [url, init] = fetch.mock.calls[0]!+ expect(url).toBe('https://openrouter.ai/api/alpha/decisions')+ expect(init).toMatchObject({+ method: 'POST',+ headers: {+ Authorization: 'Bearer sk-or-fixture', 'Content-Type': 'application/json',+ 'HTTP-Referer': 'https://harness.autonomous.ai', 'X-Title': 'Harness router',+ },+ })+ expect(JSON.parse(init!.body as string)).toEqual({ model: 'typesafe/jev-1.13', state: STATE, questions: QUESTIONS })+ // Bounded by its own timeout when the caller gives no signal.+ expect(init!.signal).toBeInstanceOf(AbortSignal)+ expect(init!.signal!.aborted).toBe(false)+ })++ it('gives up when the caller does', async () => {+ const fetch = fetching()+ const caller = new AbortController()+ await createJevDecide({ key: async () => 'sk-or-fixture', fetch })(STATE, QUESTIONS, caller.signal)+ const signal = fetch.mock.calls[0]![1]!.signal!+ expect(signal.aborted).toBe(false)+ caller.abort()+ expect(signal.aborted).toBe(true)+ })++ it('tells what each answer cost, as OpenRouter reports it, and nothing when it does not say', async () => {+ const costs: Array<[number, number]> = []+ const onCost = (usd: number, tokens: number) => { costs.push([usd, tokens]) }+ const priced = JSON.stringify({ answers: {}, usage: { cost: 0.000167, input_tokens: 3986 } })+ await createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(priced), onCost })(STATE, QUESTIONS)+ const noTokens = JSON.stringify({ answers: {}, usage: { cost: 0.0001 } })+ await createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(noTokens), onCost })(STATE, QUESTIONS)+ await createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(JSON.stringify({ answers: {} })), onCost })(STATE, QUESTIONS)+ expect(costs).toEqual([[0.000167, 3986], [0.0001, 0]])+ })++ it('asks nothing without a key', async () => {+ const fetch = fetching()+ const failure = await createJevDecide({ key: async () => null, fetch })(STATE, QUESTIONS).catch((error: unknown) => error)+ expect(failure).toBeInstanceOf(JevUnavailable)+ expect(failure).toBeInstanceOf(Error)+ expect(failure).toMatchObject({ code: 'NO_KEY', message: 'no OpenRouter key on this computer' })+ expect(fetch).not.toHaveBeenCalled()+ })++ it('finds the key and calls fetch itself by default', async () => {+ vi.mocked(resolveOpenRouterKey).mockResolvedValue('sk-or-default')+ const fetch = fetching()+ vi.stubGlobal('fetch', fetch)+ expect(await createJevDecide()(STATE, QUESTIONS)).toEqual(ANSWER.answers)+ expect((fetch.mock.calls[0]![1]!.headers as Record<string, string>).Authorization).toBe('Bearer sk-or-default')+ // And with no key anywhere, says so.+ vi.mocked(resolveOpenRouterKey).mockResolvedValue(null)+ vi.stubEnv('TYPESAFE_CREDENTIALS', join(root, 'missing'))+ await expect(createJevDecide()(STATE, QUESTIONS)).rejects.toMatchObject({ code: 'NO_KEY' })+ })++ it.each([+ [401, 'AUTH', 'OpenRouter refused the key'],+ [403, 'AUTH', 'OpenRouter refused the key'],+ [402, 'CREDITS', 'the OpenRouter account is out of credit'],+ [429, 'BUSY', 'OpenRouter is busy'],+ [500, 'UNAVAILABLE', 'OpenRouter answered 500'],+ [503, 'UNAVAILABLE', 'OpenRouter answered 503'],+ ])('names a %i as %s, and lets the body go', async (status, code, message) => {+ let cancelled = false+ const body = new ReadableStream({ cancel: () => { cancelled = true } })+ const decide = createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(new Response(body, { status })) })+ await expect(decide(STATE, QUESTIONS)).rejects.toMatchObject({ code, message })+ expect(cancelled).toBe(true)+ })++ it('names a refusal with no body too', async () => {+ const decide = createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(new Response(null, { status: 429 })) })+ await expect(decide(STATE, QUESTIONS)).rejects.toMatchObject({ code: 'BUSY' })+ })++ it('refuses an answer that is too long, not JSON, or has no answers', async () => {+ const ask = (body: string) => createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(body) })(STATE, QUESTIONS)+ await expect(ask('x'.repeat(128_001))).rejects.toMatchObject({ code: 'INVALID', message: 'Jev answered too much' })+ // At the bound itself it is read.+ const padded = JSON.stringify({ ...ANSWER, pad: '' })+ expect(await ask(padded.replace('"pad":""', `"pad":"${'x'.repeat(128_000 - padded.length)}"`))).toEqual(ANSWER.answers)+ await expect(ask('{not json')).rejects.toMatchObject({ code: 'INVALID', message: 'Jev answered something that is not JSON' })+ for (const body of ['null', '{}', '{"answers":null}', '{"answers":"yes"}', '[]']) {+ await expect(ask(body), body).rejects.toMatchObject({ code: 'INVALID', message: 'Jev gave no answers' })+ }+ })++ it('keeps each answer that is a choice with probabilities, and drops the rest', async () => {+ const body = JSON.stringify({+ answers: {+ target: { choice: 's0', probabilities: { s0: 0.9, new: 0.1 } },+ empty: null,+ number: { choice: 3, probabilities: { s0: 1 } },+ bare: { choice: 's0' },+ flat: { choice: 's0', probabilities: 0.9 },+ },+ })+ const decide = createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching(body) })+ expect(await decide(STATE, QUESTIONS)).toEqual({ target: { choice: 's0', probabilities: { s0: 0.9, new: 0.1 } } })+ expect(await createJevDecide({ key: async () => 'sk-or-fixture', fetch: fetching('{"answers":{}}') })(STATE, QUESTIONS)).toEqual({})+ })+})diff --git a/cli/src/lib/jev/jevClient.ts b/cli/src/lib/jev/jevClient.tsnew file mode 100644index 000000000..8c28e8286--- /dev/null+++ b/cli/src/lib/jev/jevClient.ts@@ -0,0 +1,88 @@+/**+ * Jev 1.13, asked through OpenRouter's Decisions API: how ⌘B's router decides where a task goes+ * (lib/routeDecide.ts, docs/design/2026-10-09-auto-router.md). The only Jev in Harness.+ *+ * One POST answers several typed questions at once — which session, which project, which agent — in+ * about 0.6 s, for about $0.0002 on a desk of thirty sessions (measured 2026-10-10).+ *+ * The key is the person's OpenRouter key: OPENROUTER_API_KEY, the account `ori login` saved, or the+ * credentials file at ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). It is read when a+ * decision is asked for and never logged.+ */+import { readFile } from 'node:fs/promises'+import { homedir } from 'node:os'+import { join } from 'node:path'+import { resolveOpenRouterKey } from '../openrouter.js'++const ENDPOINT = 'https://openrouter.ai/api/alpha/decisions'+const MODEL = 'typesafe/jev-1.13'+const TIMEOUT_MS = 8_000+const MAX_REPLY_BYTES = 128_000++export interface JevChoice { type: 'choice'; instructions: string; criteria: Record<string, string> }+export interface JevChoiceAnswer { choice: string; probabilities: Record<string, number> }+export type JevDecide = (state: unknown, questions: Record<string, JevChoice>, signal?: AbortSignal) => Promise<Record<string, JevChoiceAnswer>>++/** Why Jev did not answer, in words the router can log and the person can act on. */+export class JevUnavailable extends Error {+ constructor(readonly code: 'NO_KEY' | 'AUTH' | 'CREDITS' | 'BUSY' | 'UNAVAILABLE' | 'INVALID', message: string) { super(message) }+}++/** The key, or null when this computer has none. */+export async function resolveJevKey(environment: NodeJS.ProcessEnv = process.env): Promise<string | null> {+ const known = await resolveOpenRouterKey()+ if (known) return known+ const path = environment.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')+ try {+ for (const line of (await readFile(path, 'utf8')).split('\n')) {+ const match = /^\s*(?:export\s+)?OPENROUTER_API_KEY\s*=\s*(.*?)\s*$/.exec(line)+ const value = match?.[1].replace(/^(['"])(.*)\1$/, '$2')+ if (value) return value+ }+ } catch { /* no file */ }+ return null+}++export function createJevDecide(options: {+ key?: () => Promise<string | null>+ fetch?: typeof fetch+ /** What each answer cost, as OpenRouter reports it (USD) — what a person's key is charged. */+ onCost?: (usd: number, inputTokens: number) => void+} = {}): JevDecide {+ return async (state, questions, signal) => {+ const key = await (options.key ?? resolveJevKey)()+ if (!key) throw new JevUnavailable('NO_KEY', 'no OpenRouter key on this computer')+ const timeout = AbortSignal.timeout(TIMEOUT_MS)+ const response = await (options.fetch ?? fetch)(ENDPOINT, {+ method: 'POST',+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,+ headers: {+ Authorization: `Bearer ${key}`, 'Content-Type': 'application/json',+ 'HTTP-Referer': 'https://harness.autonomous.ai', 'X-Title': 'Harness router',+ },+ body: JSON.stringify({ model: MODEL, state, questions }),+ })+ if (!response.ok) {+ await response.body?.cancel()+ if (response.status === 401 || response.status === 403) throw new JevUnavailable('AUTH', 'OpenRouter refused the key')+ if (response.status === 402) throw new JevUnavailable('CREDITS', 'the OpenRouter account is out of credit')+ if (response.status === 429) throw new JevUnavailable('BUSY', 'OpenRouter is busy')+ throw new JevUnavailable('UNAVAILABLE', `OpenRouter answered ${response.status}`)+ }+ const text = await response.text()+ if (text.length > MAX_REPLY_BYTES) throw new JevUnavailable('INVALID', 'Jev answered too much')+ let parsed: unknown+ try { parsed = JSON.parse(text) } catch { throw new JevUnavailable('INVALID', 'Jev answered something that is not JSON') }+ const answers = (parsed as { answers?: unknown } | null)?.answers+ if (!answers || typeof answers !== 'object') throw new JevUnavailable('INVALID', 'Jev gave no answers')+ const usage = (parsed as { usage?: { cost?: unknown; input_tokens?: unknown } }).usage+ if (typeof usage?.cost === 'number') options.onCost?.(usage.cost, typeof usage.input_tokens === 'number' ? usage.input_tokens : 0)+ const out: Record<string, JevChoiceAnswer> = {}+ for (const [id, raw] of Object.entries(answers as Record<string, unknown>)) {+ const answer = raw as { choice?: unknown; probabilities?: unknown } | null+ if (typeof answer?.choice !== 'string' || !answer.probabilities || typeof answer.probabilities !== 'object') continue+ out[id] = { choice: answer.choice, probabilities: answer.probabilities as Record<string, number> }+ }+ return out+ }+}diff --git a/cli/src/lib/routeDecide.spec.ts b/cli/src/lib/routeDecide.spec.tsnew file mode 100644index 000000000..1fb87e160--- /dev/null+++ b/cli/src/lib/routeDecide.spec.ts@@ -0,0 +1,243 @@+// Where a typed task goes: Jev alone, asked once (sure at 0.6 → its session, or new work; else new work; not+// asked at all → nothing decided), how a new harness is set up, what Jev is asked, and what is logged when it+// fails. Jev is a fake here: the question it is put and the answer it gives are the contract.+import { describe, expect, it, vi } from 'vitest'++import type { JevChoice, JevChoiceAnswer } from './jev/jevClient.js'+import { JevUnavailable } from './jev/jevClient.js'+import { decideRoute, JEV_SURE_P, jevPick, type RouteDeps, type RouteInput, type RouteOption, type RouteSession } from './routeDecide.js'++/** A choice of [choice] at [p] over [options], the rest shared evenly among the others. */+function said(choice: string, p: number, options: string[]): JevChoiceAnswer {+ const rest = (1 - p) / Math.max(1, options.length - 1)+ return { choice, probabilities: Object.fromEntries(options.map((id) => [id, id === choice ? p : rest])) }+}++/** A Jev that gives [answers] and records what it was asked. */+function jev(answers: Record<string, JevChoiceAnswer> = {}) {+ return vi.fn(async (_state: unknown, _questions: Record<string, JevChoice>, _signal?: AbortSignal) => answers)+}++const session = (id: string, name: string, asks: string[] = [], about?: string): RouteSession => ({ id, name, asks, ...(about ? { about } : {}) })++const DESK: RouteSession[] = [+ session('a1', 'billing retries', ['why was the card charged twice']),+ session('a2', 'Prometheus alerts', [], 'raised the alert threshold to 90%'),+]+const TARGETS = ['s0', 's1', 'new']+const PROJECTS: RouteOption[] = [{ id: '/code/billing', name: 'billing' }, { id: '/code/infra', name: 'infra monitoring' }]+const AGENTS: RouteOption[] = [{ id: 'claude', name: 'Claude Code' }, { id: 'codex', name: 'Codex' }]++const input = (over: Partial<RouteInput> = {}): RouteInput => ({ text: 'the prometheus alert fired again', sessions: DESK, projects: [], agents: [], ...over })+const steps = (trace: string) => trace.split(' · ')++describe('Jev\'s pick', () => {+ it('is its choice when it gives it 0.6 or more over exactly the options asked', () => {+ expect(JEV_SURE_P).toBe(0.6)+ expect(jevPick(said('s0', 0.6, ['s0', 'new']), ['s0', 'new'])).toBe('s0')+ expect(jevPick(said('new', 0.95, TARGETS), TARGETS)).toBe('new')+ expect(jevPick(said('s0', 0.59, ['s0', 'new']), ['s0', 'new'])).toBeUndefined()+ })++ it('is nothing for an answer that is not a whole one over those options', () => {+ expect(jevPick(undefined, ['s0'])).toBeUndefined()+ expect(jevPick({ choice: 's0' } as unknown as JevChoiceAnswer, ['s0'])).toBeUndefined()+ // A choice it was never offered.+ expect(jevPick({ choice: 's9', probabilities: { s9: 0.9, s0: 0.1 } }, ['s0', 'new'])).toBeUndefined()+ // An option it gave no probability, or one that is not a number.+ expect(jevPick({ choice: 's0', probabilities: { s0: 0.9 } }, ['s0', 'new'])).toBeUndefined()+ expect(jevPick({ choice: 's0', probabilities: { s0: 0.9, new: Number.NaN } }, ['s0', 'new'])).toBeUndefined()+ expect(jevPick({ choice: 's0', probabilities: { s0: Number.POSITIVE_INFINITY, new: 0 } }, ['s0', 'new'])).toBeUndefined()+ expect(jevPick({ choice: 's0', probabilities: { s0: 0.9, new: '0.1' } as unknown as Record<string, number> }, ['s0', 'new'])).toBeUndefined()+ })+})++describe('where a task goes', () => {+ it('goes to the session Jev is sure of, asked once about the session, the project and the agent', async () => {+ const remote = jev({ target: said('s1', 0.8, TARGETS), project: said('p1', 0.9, ['p0', 'p1']), agent: said('a1', 0.9, ['a0', 'a1']) })+ const verdict = await decideRoute(input({ projects: PROJECTS, agents: AGENTS }), { jev: remote })+ // A session needs no project or agent: Jev's picks of them are not part of the verdict.+ expect(verdict).toEqual({ kind: 'session', id: 'a2', p: 0.8, trace: '2 sessions · jev: "Prometheus alerts" 0.80' })+ expect(remote).toHaveBeenCalledOnce()+ const [state, questions] = remote.mock.calls[0]!+ expect(state).toEqual({ message: 'the prometheus alert fired again' })+ expect(questions).toEqual({+ target: {+ type: 'choice',+ instructions: 'A person typed this message to continue their work. Which of their ongoing sessions is it for?',+ criteria: {+ s0: 'billing retries — asked: why was the card charged twice',+ s1: 'Prometheus alerts — lately: raised the alert threshold to 90%',+ new: 'None of them: it starts new, unrelated work',+ },+ },+ project: {+ type: 'choice',+ instructions: 'If this becomes new work, which project folder does it belong in?',+ criteria: { p0: 'billing', p1: 'infra monitoring' },+ },+ agent: {+ type: 'choice',+ instructions: 'Which agent is best suited to do this work?',+ criteria: { a0: 'Claude Code', a1: 'Codex' },+ },+ })+ })++ it('describes a session to Jev by its name, its last ask and its last turns, in one line cut short', async () => {+ const remote = jev()+ const long = session('a1', ` ${'n'.repeat(250)}\n`, [`${'y'.repeat(200)}`, 'older'], 'z'.repeat(500))+ const tidy = session('a2', 'auth\n\n api', ['rotate the\ttokens'])+ await decideRoute(input({+ sessions: [long, tidy, session('a3', 'bare'), session('a4', 'quiet', [], 'only turns')],+ projects: [{ id: 'p', name: 'x'.repeat(700) }, { id: 'q', name: ' q\n' }],+ agents: [{ id: 'claude', name: 'Claude\nCode' }, { id: 'codex', name: 'Codex' }],+ }), { jev: remote })+ const [, questions] = remote.mock.calls[0]!+ const criteria = questions.target!.criteria+ // The name, then the first 120 of its last ask and the first 420 of its last turns: cut at 600 with an ellipsis.+ expect(criteria.s0).toBe(`${`${'n'.repeat(250)} — asked: ${'y'.repeat(120)} — lately: ${'z'.repeat(420)}`.slice(0, 599)}…`)+ expect(criteria.s0).toHaveLength(600)+ expect(criteria.s1).toBe('auth api — asked: rotate the tokens')+ expect(criteria.s2).toBe('bare')+ expect(criteria.s3).toBe('quiet — lately: only turns')+ // A project's or an agent's name is tidied and cut the same way.+ expect(questions.project!.criteria).toEqual({ p0: `${'x'.repeat(599)}…`, p1: 'q' })+ expect(questions.agent!.criteria).toEqual({ a0: 'Claude Code', a1: 'Codex' })+ })++ it('asks no project or agent question when there is one or none to choose from', async () => {+ const remote = jev()+ await decideRoute(input({ projects: [PROJECTS[0]!], agents: [AGENTS[0]!] }), { jev: remote })+ expect(Object.keys(remote.mock.calls[0]![1])).toEqual(['target'])+ await decideRoute(input(), { jev: remote })+ expect(Object.keys(remote.mock.calls[1]![1])).toEqual(['target'])+ // Two projects and one agent: the project is asked, the agent is not.+ await decideRoute(input({ projects: PROJECTS, agents: [AGENTS[0]!] }), { jev: remote })+ expect(Object.keys(remote.mock.calls[2]![1])).toEqual(['target', 'project'])+ })++ it('asks Jev about the sessions with "new" alone when the desk is empty', async () => {+ const remote = jev({ target: said('new', 1, ['new']) })+ const verdict = await decideRoute(input({ sessions: [] }), { jev: remote })+ expect(remote.mock.calls[0]![1].target!.criteria).toEqual({ new: 'None of them: it starts new, unrelated work' })+ expect(verdict).toEqual({ kind: 'new', via: 'jev', why: 'Jev: new work', trace: '0 sessions · jev: "new" 1.00' })+ })++ it('cuts a long rail to its first forty sessions, projects and agents for Jev, as the client ordered them', async () => {+ const remote = jev()+ const many = <T>(make: (i: number) => T) => Array.from({ length: 45 }, (_, i) => make(i))+ const verdict = await decideRoute(input({+ sessions: many((i) => session(`a${i}`, `topic ${i}`)),+ projects: many((i) => ({ id: `/code/${i}`, name: `project ${i}` })),+ agents: many((i) => ({ id: `agent-${i}`, name: `agent ${i}` })),+ }), { jev: remote })+ const [, questions] = remote.mock.calls[0]!+ expect(Object.keys(questions.target!.criteria)).toEqual([...Array.from({ length: 40 }, (_, i) => `s${i}`), 'new'])+ expect(questions.target!.criteria.s39).toBe('topic 39')+ expect(Object.keys(questions.project!.criteria)).toEqual(Array.from({ length: 40 }, (_, i) => `p${i}`))+ expect(Object.keys(questions.agent!.criteria)).toEqual(Array.from({ length: 40 }, (_, i) => `a${i}`))+ // The trace counts the sessions Jev weighed.+ expect(steps(verdict.trace)[0]).toBe('40 sessions')+ })++ it('tells Jev where the person\'s last task went when that was ten minutes ago or less, and that session is among those asked', async () => {+ const remote = jev()+ const stateFor = async (last: RouteInput['last'], sessions = DESK) => {+ await decideRoute(input({ text: 'and check it again tomorrow', sessions, ...(last ? { last } : {}) }), { jev: remote })+ return remote.mock.calls.at(-1)![0]+ }+ expect(await stateFor({ id: 'a2', agoMs: 600_000 })).toEqual({ message: 'and check it again tomorrow', previous_message_went_to: 'Prometheus alerts' })+ expect(await stateFor({ id: 'a1', agoMs: 0 })).toEqual({ message: 'and check it again tomorrow', previous_message_went_to: 'billing retries' })+ expect(await stateFor({ id: 'a2', agoMs: 600_001 })).toEqual({ message: 'and check it again tomorrow' })+ expect(await stateFor({ id: 'gone', agoMs: 1_000 })).toEqual({ message: 'and check it again tomorrow' })+ expect(await stateFor(undefined)).toEqual({ message: 'and check it again tomorrow' })+ // A session past the first forty is not one Jev was asked about, so it is not named either.+ const rail = Array.from({ length: 41 }, (_, i) => session(`a${i}`, `topic ${i}`))+ expect(await stateFor({ id: 'a40', agoMs: 1_000 }, rail)).toEqual({ message: 'and check it again tomorrow' })+ expect(await stateFor({ id: 'a39', agoMs: 1_000 }, rail)).toEqual({ message: 'and check it again tomorrow', previous_message_went_to: 'topic 39' })+ })++ it('is new work, set up as Jev says, when Jev is sure it is new', async () => {+ const remote = jev({+ target: said('new', 0.9, TARGETS),+ project: said('p1', 0.7, ['p0', 'p1']),+ agent: said('a0', 0.65, ['a0', 'a1']),+ })+ const verdict = await decideRoute(input({ text: 'rename my photos by date', projects: PROJECTS, agents: AGENTS }), { jev: remote })+ expect(verdict).toEqual({ kind: 'new', project: '/code/infra', agent: 'claude', via: 'jev', why: 'Jev: new work', trace: '2 sessions · jev: "new" 0.90' })+ })++ it('leaves the project and the agent to the caller when Jev is not sure of them, or did not answer them', async () => {+ const remote = jev({+ target: said('new', 0.9, TARGETS),+ project: said('p0', 0.5, ['p0', 'p1']),+ agent: said('a1', 0.4, ['a0', 'a1']),+ })+ const verdict = await decideRoute(input({ projects: PROJECTS, agents: AGENTS }), { jev: remote })+ expect(verdict).toEqual({ kind: 'new', via: 'jev', why: 'Jev: new work', trace: '2 sessions · jev: "new" 0.90' })+ const silent = await decideRoute(input({ projects: PROJECTS, agents: AGENTS }), { jev: jev({ target: said('new', 0.9, TARGETS) }) })+ expect(silent).not.toHaveProperty('project')+ expect(silent).not.toHaveProperty('agent')+ })++ it('is new work when Jev is not sure where it goes, still in the project and with the agent Jev is sure of', async () => {+ const remote = jev({+ target: said('s0', 0.5, TARGETS),+ project: said('p0', 0.9, ['p0', 'p1']),+ agent: said('a1', 0.8, ['a0', 'a1']),+ })+ const verdict = await decideRoute(input({ projects: PROJECTS, agents: AGENTS }), { jev: remote })+ expect(verdict).toEqual({ kind: 'new', project: '/code/billing', agent: 'codex', via: 'unsure', why: 'Jev was not sure', trace: '2 sessions · jev: "billing retries" 0.50' })+ })++ it('is new work Jev was not sure of when Jev leans to new work below the bar', async () => {+ const verdict = await decideRoute(input(), { jev: jev({ target: said('new', 0.55, TARGETS) }) })+ expect(verdict).toEqual({ kind: 'new', via: 'unsure', why: 'Jev was not sure', trace: '2 sessions · jev: "new" 0.55' })+ })++ it('traces what Jev said even when it is no session on the desk, or nothing', async () => {+ const strange = await decideRoute(input(), { jev: jev({ target: { choice: 's7', probabilities: { s0: 0.5, s1: 0.5 } } }) })+ expect(strange).toEqual({ kind: 'new', via: 'unsure', why: 'Jev was not sure', trace: '2 sessions · jev: "s7" 0.00' })+ const silent = await decideRoute(input(), { jev: jev({}) })+ expect(silent).toEqual({ kind: 'new', via: 'unsure', why: 'Jev was not sure', trace: '2 sessions · jev: no answer' })+ })++ it('decides nothing when Jev is not set up', async () => {+ const lines: string[] = []+ expect(await decideRoute(input({ projects: PROJECTS, agents: AGENTS }), { log: (line) => lines.push(line) }))+ .toEqual({ kind: 'unavailable', why: 'Jev is not set up', trace: '2 sessions · jev: not set up' })+ expect(await decideRoute(input({ sessions: [] }), {})).toEqual({ kind: 'unavailable', why: 'Jev is not set up', trace: '0 sessions · jev: not set up' })+ // Nothing failed: there is nothing to log.+ expect(lines).toEqual([])+ })++ it('logs Jev failing, with what caused it, and decides nothing', async () => {+ const lines: string[] = []+ const failing = vi.fn(async () => { throw Object.assign(new JevUnavailable('BUSY', 'OpenRouter is busy'), { cause: { code: 'UND_ERR_SOCKET' } }) })+ const verdict = await decideRoute(input({ projects: PROJECTS, agents: AGENTS }), { jev: failing, log: (line) => lines.push(line) })+ // The verdict says the error alone, for the person; the log says its cause too, for whoever debugs it.+ expect(verdict).toEqual({ kind: 'unavailable', why: 'OpenRouter is busy', trace: '2 sessions · jev: failed' })+ expect(lines).toEqual(['jev could not answer: OpenRouter is busy (UND_ERR_SOCKET)'])+ // A cause with no code says its message; no cause, the error alone.+ const logged = async (error: Error) => {+ const said: string[] = []+ const answer = await decideRoute(input(), { jev: async () => { throw error }, log: (line) => said.push(line) })+ return { answer, said }+ }+ expect(await logged(new Error('fetch failed', { cause: { message: 'socket hang up' } }))).toEqual({+ answer: { kind: 'unavailable', why: 'fetch failed', trace: '2 sessions · jev: failed' },+ said: ['jev could not answer: fetch failed (socket hang up)'],+ })+ expect(await logged(new JevUnavailable('NO_KEY', 'no OpenRouter key on this computer'))).toEqual({+ answer: { kind: 'unavailable', why: 'no OpenRouter key on this computer', trace: '2 sessions · jev: failed' },+ said: ['jev could not answer: no OpenRouter key on this computer'],+ })+ // Without a log it goes the same way.+ await expect(decideRoute(input(), { jev: failing })).resolves.toEqual({ kind: 'unavailable', why: 'OpenRouter is busy', trace: '2 sessions · jev: failed' })+ })+})++// The deps a router hands decideRoute are the same shape: a check that this file's fakes stay assignable.+const _deps: RouteDeps = { jev: jev(), log: () => {} }+void _depsdiff --git a/cli/src/lib/routeDecide.ts b/cli/src/lib/routeDecide.tsnew file mode 100644index 000000000..fca9e6369--- /dev/null+++ b/cli/src/lib/routeDecide.ts@@ -0,0 +1,163 @@+/**+ * Where a typed task goes, decided without asking the person (docs/design/2026-10-09-auto-router.md).+ *+ * Jev 1.13, through OpenRouter (~0.6 s), is asked once: which session the task is for (or none — new+ * work), and, for new work, which project and which agent. Its pick is taken at JEV_SURE_P or more; below+ * that Jev is unsure and the task is new work. A project or agent Jev is unsure of is left to the caller,+ * which uses the pane the person is in.+ *+ * Jev alone, owner's call 2026-10-10. It started as a ladder with julia-1, a local model, deciding first:+ * every task sent to a wrong session — on the benchmark and on the owner's desk ("how is lamp v2 going"+ * to "Catch up on lamp GTM") — was julia-1's, and Jev's alone sent none.+ *+ * The send is instant — the owner chose no undo window — so the bar is the safety: a session is chosen+ * only on Jev's word, and everything else becomes new work, which costs a little and pollutes nobody's+ * conversation. When Jev cannot be asked at all, nothing is decided: the caller says so and acts on+ * nothing, rather than guessing.+ */+import type { JevChoice, JevChoiceAnswer, JevDecide } from './jev/jevClient.js'++export interface RouteSession {+ id: string+ name: string+ /** The person's last prompts to it, newest first. */+ asks: string[]+ /** Its last few turns, summarised, newest first: often the only place its topic is said. "ok, check+ * again in 24 hours" names nothing, and neither did the newest summary; the two before it said+ * "activation and repeat use" — which is what "what's d30 retention" is about. */+ about?: string+}+/** A project a new harness could start in; [id] is the caller's, handed back untouched. */+export interface RouteOption { id: string; name: string }++export interface RouteInput {+ text: string+ sessions: RouteSession[]+ projects: RouteOption[]+ agents: RouteOption[]+ /** The session the person's last routed task went to, and how long ago. */+ last?: { id: string; agoMs: number }+}++export type RouteVerdict = (+ | { kind: 'session'; id: string; p: number }+ | { kind: 'new'; project?: string; agent?: string; via: 'jev' | 'unsure'; why: string }+ /** Jev could not be asked: no key, no network, no credit. Nothing is decided. */+ | { kind: 'unavailable'; why: string }+) & {+ /** What Jev said, for the log: a wrong decision has to be explainable after the fact. */+ trace: string+}++export interface RouteDeps {+ jev?: JevDecide+ log?: (line: string) => void+}++/** The sessions, projects and agents Jev weighs, at most: a client sends its most recently active first. */+const JEV_OPTIONS = 40+const LABEL_CHARS = 600+/** A follow-up names nothing; who the person was just talking to is what Jev gets to go on. */+const CONTINUITY_MS = 10 * 60_000+/** Below this Jev is unsure, and the task is new work. */+export const JEV_SURE_P = 0.6++/** Jev's pick when it is a whole answer over exactly [options] and Jev gives it JEV_SURE_P or more. */+export function jevPick(answer: JevChoiceAnswer | undefined, options: string[]): string | undefined {+ const p = answer?.probabilities+ if (!answer || !p || !options.includes(answer.choice)) return undefined+ if (options.some((id) => typeof p[id] !== 'number' || !Number.isFinite(p[id]))) return undefined+ return p[answer.choice] >= JEV_SURE_P ? answer.choice : undefined+}++/** An error and what caused it: fetch's own message ("fetch failed") says nothing by itself. */+const why = (error: unknown): string => {+ const cause = (error as { cause?: { code?: string; message?: string } })?.cause+ return `${(error as Error).message}${cause ? ` (${cause.code ?? cause.message})` : ''}`+}++const label = (text: string): string => {+ const clean = text.replace(/\s+/g, ' ').trim()+ return clean.length <= LABEL_CHARS ? clean : `${clean.slice(0, LABEL_CHARS - 1)}…`+}++/** A session as Jev reads it: its name, the person's last prompt and what its last turns were about. */+function describe(session: RouteSession): string {+ return label([+ session.name,+ session.asks[0] ? `asked: ${session.asks[0].slice(0, 120)}` : '',+ session.about ? `lately: ${session.about.slice(0, 420)}` : '',+ ].filter(Boolean).join(' — '))+}++/** [signal] stops the question when whoever asked has gone: Jev's answer would act on nothing. */+export async function decideRoute(input: RouteInput, deps: RouteDeps, signal?: AbortSignal): Promise<RouteVerdict> {+ const { text } = input+ const sessions = input.sessions.slice(0, JEV_OPTIONS)+ const projects = input.projects.slice(0, JEV_OPTIONS)+ const agents = input.agents.slice(0, JEV_OPTIONS)+ const trace: string[] = [`${sessions.length} sessions`]+ if (!deps.jev) return { kind: 'unavailable', why: 'Jev is not set up', trace: [...trace, 'jev: not set up'].join(' · ') }++ const questions: Record<string, JevChoice> = {+ target: {+ type: 'choice',+ // Worded as measured (docs/design/2026-10-09-auto-router.md): this framing — the person continuing+ // their own work — got 95% right against 85% for "which session should this message go to?", with+ // the same one wrong send.+ instructions: 'A person typed this message to continue their work. Which of their ongoing sessions is it for?',+ criteria: {+ ...Object.fromEntries(sessions.map((session, i) => [`s${i}`, describe(session)])),+ new: 'None of them: it starts new, unrelated work',+ },+ },+ }+ if (projects.length > 1) {+ questions.project = {+ type: 'choice',+ instructions: 'If this becomes new work, which project folder does it belong in?',+ criteria: Object.fromEntries(projects.map((project, i) => [`p${i}`, label(project.name)])),+ }+ }+ if (agents.length > 1) {+ questions.agent = {+ type: 'choice',+ instructions: 'Which agent is best suited to do this work?',+ criteria: Object.fromEntries(agents.map((agent, i) => [`a${i}`, label(agent.name)])),+ }+ }+ const last = input.last && input.last.agoMs <= CONTINUITY_MS ? sessions.find((session) => session.id === input.last!.id) : undefined+ const state = last ? { message: text, previous_message_went_to: last.name } : { message: text }++ let answers: Awaited<ReturnType<JevDecide>>+ try {+ answers = await deps.jev(state, questions, signal)+ } catch (error) {+ deps.log?.(`jev could not answer: ${why(error)}`)+ return { kind: 'unavailable', why: (error as Error).message, trace: [...trace, 'jev: failed'].join(' · ') }+ }+ const said = answers.target+ const named = said?.choice === 'new' ? 'new' : sessions[Number(said?.choice?.slice(1))]?.name+ trace.push(`jev: ${said ? `"${named ?? said.choice}" ${(said.probabilities[said.choice] ?? 0).toFixed(2)}` : 'no answer'}`)++ const target = jevPick(said, [...sessions.map((_, i) => `s${i}`), 'new'])+ if (target && target !== 'new') {+ const session = sessions[Number(target.slice(1))]+ return { kind: 'session', id: session.id, p: said!.probabilities[target], trace: trace.join(' · ') }+ }++ const pick = (key: 'project' | 'agent', prefix: string, options: RouteOption[]): string | undefined => {+ const choice = jevPick(answers[key], options.map((_, i) => `${prefix}${i}`))+ return choice === undefined ? undefined : options[Number(choice.slice(prefix.length))].id+ }+ const project = pick('project', 'p', projects)+ const agent = pick('agent', 'a', agents)+ return {+ kind: 'new',+ ...(project ? { project } : {}),+ ...(agent ? { agent } : {}),+ via: target ? 'jev' : 'unsure',+ why: target ? 'Jev: new work' : 'Jev was not sure',+ trace: trace.join(' · '),+ }+}diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex f6ed88452..42036511b 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -47,6 +47,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['sharing', async () => (await import('./services/sharingProcess.js')).runSharingService],['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],['memory', async () => (await import('./services/memoryProcess.js')).runMemoryService],+ ['router', async () => (await import('./services/routerProcess.js')).runRouterService],// Not a service the core knows: the master runs it beside them (harnessd/services.ts `UPDATER_HOST`).['updater', async () => (await import('./services/updaterProcess.js')).runUpdaterService],['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 10e4afde2..c6f10695a 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -62,6 +62,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne| `teams` | teams, collaboration | an experiment: Tab collaboration beside the prompt scopes | on demand || `sharing` | sharing | an experiment: Share | on demand || `memory` | memory | an experiment: Memories across machines | on demand |+| `router` | router | an experiment: where ⌘B sends a task, decided by Jev | on demand |A fault in one of the edge host's services can cost the others in it, never the core. Every service in`KNOWN_SERVICES` runs out of the core's process by default, unless `HARNESSD_SERVICES` names a subset, by@@ -206,7 +207,7 @@ like any other. Named in `HARNESSD_SERVICES`, it starts with the others.## Experiments-An experiment (the orchestrator, Tab collaboration, Share, memory) is a service that costs nothing until it is+An experiment (the orchestrator, Tab collaboration, Share, memory, the router) is a service that costs nothing until it ison: its own process, which the master starts only when the core asks for it (`want`), when one ofits requests arrives or, as the core starts, when its saved state is in the data folder. Off, nothing of it runs oris loaded anywhere; one failing costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it:diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 391d4e999..cc7546cf3 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -19,6 +19,7 @@ import { startMonitor } from './monitor.js'import { startOrchestrator } from './orchestrator.js'import { startProjects } from './projects.js'import { startRecaps } from './recaps.js'+import { startRouter } from './router.js'import { startSearch } from './search.js'import { startShell } from './shell.js'import { startSharing } from './sharing.js'@@ -31,6 +32,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStoreInCore, startTeamsInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startRouter, startSearch, startSharing, startShell, startStoreInCore, startTeamsInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 92e9f5d5b..2f080ab18 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -31,6 +31,7 @@ export { startMonitor } from './monitor.js'export { startOrchestrator } from './orchestrator.js'export { startProjects } from './projects.js'export { startRecaps } from './recaps.js'+export { startRouter } from './router.js'export { startSearch } from './search.js'export { startShell } from './shell.js'export { startSharing } from './sharing.js'diff --git a/cli/src/services/router.spec.ts b/cli/src/services/router.spec.tsnew file mode 100644index 000000000..90c5ce45b--- /dev/null+++ b/cli/src/services/router.spec.ts@@ -0,0 +1,269 @@+// The router: what a client may send and how it is bounded, who may ask, how many decisions at once, and the+// answer a client acts on. The decision itself is lib/routeDecide.spec.ts's; here Jev is a fake behind a fake+// router, and the client the default router builds is a fake too: no network is ever reached.+import { afterEach, describe, expect, it, vi } from 'vitest'++import { ROUTER_REQUESTS as DECLARED, type Asker } from '../core/api.js'+import { createJevDecide, JevUnavailable, type JevChoiceAnswer } from '../lib/jev/jevClient.js'+import { fakeCore } from '../testing/fakeCore.js'+import { defaultRouter, ROUTER_REQUESTS, routeInput, startRouter, type Router } from './router.js'++/** Jev's client as the default router builds it: what it was asked, and no answer, never a request sent. */+const client = vi.hoisted(() => ({ asked: [] as unknown[] }))+vi.mock('../lib/jev/jevClient.js', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../lib/jev/jevClient.js')>()+ return { ...actual, createJevDecide: vi.fn(() => async (state: unknown) => { client.asked.push(state); return {} }) }+})++const OWNER: Asker = { local: true, owner: true, connection: 'window-1' }+const DEVICE: Asker = { local: false, owner: false, connection: 'device-1' }++/** A router with no Jev unless [over] gives one, logging into [lines]. */+function router(over: Partial<Router> = {}) {+ const lines: string[] = []+ const made: Router = { log: (line) => lines.push(line), ...over }+ return { router: made, lines }+}++/** A choice of [choice] at [p], the rest on the other [options]. */+function said(choice: string, p: number, options: string[]): JevChoiceAnswer {+ return { choice, probabilities: Object.fromEntries(options.map((id) => [id, id === choice ? p : (1 - p) / (options.length - 1)])) }+}++const DESK = [{ id: 'a1', name: 'billing retries', asks: ['why was the card charged twice'] }, { id: 'a2', name: 'Prometheus alerts' }]++afterEach(() => {+ vi.restoreAllMocks()+ vi.mocked(createJevDecide).mockClear()+ client.asked.length = 0+})++describe('what a client sends', () => {+ it('is its task, trimmed, with the sessions, projects and agents it can see', () => {+ expect(routeInput({+ text: ' the alert fired again \n',+ sessions: DESK,+ projects: [{ id: '/code/infra', name: 'infra' }],+ agents: [{ id: 'claude', name: 'Claude Code' }],+ last: { id: 'a2', agoMs: 30_000 },+ })).toEqual({+ text: 'the alert fired again',+ sessions: [{ id: 'a1', name: 'billing retries', asks: ['why was the card charged twice'] }, { id: 'a2', name: 'Prometheus alerts', asks: [] }],+ projects: [{ id: '/code/infra', name: 'infra' }],+ agents: [{ id: 'claude', name: 'Claude Code' }],+ last: { id: 'a2', agoMs: 30_000 },+ })+ })++ it('is nothing without a task, or with one longer than 16,000 characters', () => {+ for (const text of [undefined, '', ' \n', 42, ['go']]) expect(routeInput({ text }), String(text)).toBeNull()+ expect(routeInput({ text: 'x'.repeat(16_001) })).toBeNull()+ expect(routeInput({ text: ` ${'x'.repeat(16_000)} ` })).toMatchObject({ text: 'x'.repeat(16_000) })+ })++ it('is no sessions, projects or agents where it sent something that is not a list', () => {+ expect(routeInput({ text: 'go', sessions: 'a1', projects: { id: 'p' }, agents: null })).toEqual({ text: 'go', sessions: [], projects: [], agents: [] })+ })++ it('drops the sessions it cannot read, and bounds what it keeps of each', () => {+ const sessions = routeInput({+ text: 'go',+ sessions: [+ null, 'a1', { id: 1, name: 'n' }, { id: 'a' }, { id: 'a', name: 7 },+ { id: 'x'.repeat(4201), name: 'too long an id' }, { id: 'long-name', name: 'n'.repeat(301) },+ { id: 'x'.repeat(4200), name: 'n'.repeat(300) },+ { id: 'asks', name: 'asks', asks: ['first', 2, null, 'second', `${'y'.repeat(600)}`, 'fourth'] },+ { id: 'not-a-list', name: 'asks', asks: 'first' },+ { id: 'about', name: 'about', about: ` ${'z'.repeat(600)}` },+ { id: 'blank-about', name: 'about', about: ' \n ' },+ { id: 'odd-about', name: 'about', about: 12 },+ ],+ })!.sessions+ expect(sessions).toEqual([+ { id: 'x'.repeat(4200), name: 'n'.repeat(300), asks: [] },+ { id: 'asks', name: 'asks', asks: ['first', 'second', 'y'.repeat(500)] },+ { id: 'not-a-list', name: 'asks', asks: [] },+ { id: 'about', name: 'about', asks: [], about: ` ${'z'.repeat(498)}` },+ { id: 'blank-about', name: 'about', asks: [] },+ { id: 'odd-about', name: 'about', asks: [] },+ ])+ })++ it('reads the first 200 sessions, projects and agents, and drops the options it cannot read', () => {+ const rows = Array.from({ length: 205 }, (_, i) => ({ id: `r${i}`, name: `row ${i}` }))+ const input = routeInput({ text: 'go', sessions: rows, projects: rows, agents: rows })!+ expect(input.sessions).toHaveLength(200)+ expect(input.projects).toHaveLength(200)+ expect(input.agents.at(-1)).toEqual({ id: 'r199', name: 'row 199' })+ const options = [+ null, 'p', { id: 3, name: 'n' }, { id: 'p' }, { id: 'p', name: false },+ { id: 'x'.repeat(4201), name: 'n' }, { id: 'p', name: 'n'.repeat(301) },+ { id: 'x'.repeat(4200), name: 'n'.repeat(300), extra: true },+ ]+ expect(routeInput({ text: 'go', projects: options, agents: options })).toMatchObject({+ projects: [{ id: 'x'.repeat(4200), name: 'n'.repeat(300) }],+ agents: [{ id: 'x'.repeat(4200), name: 'n'.repeat(300) }],+ })+ expect(routeInput({ text: 'go', projects: options })!.projects[0]).not.toHaveProperty('extra')+ })++ it('says where the last task went only with a session id and a finite time', () => {+ const last = (value: unknown) => routeInput({ text: 'go', last: value })!+ expect(last({ id: 'a1', agoMs: 0 }).last).toEqual({ id: 'a1', agoMs: 0 })+ for (const value of [undefined, null, 'a1', { id: 'a1' }, { agoMs: 5 }, { id: 3, agoMs: 5 }, { id: 'a1', agoMs: '5' },+ { id: 'a1', agoMs: Number.NaN }, { id: 'a1', agoMs: Number.POSITIVE_INFINITY }]) {+ expect(last(value), JSON.stringify(value)).not.toHaveProperty('last')+ }+ })+})++describe('the router', () => {+ it('declares the requests the core routes to it', () => {+ expect(ROUTER_REQUESTS).toBe(DECLARED)+ expect([...ROUTER_REQUESTS]).toEqual(['route_decide'])+ expect(Object.keys(startRouter(fakeCore(), router().router)).sort()).toEqual([...ROUTER_REQUESTS].sort())+ })++ it('decides for the owner alone, and only a task it can read', async () => {+ const jev = vi.fn(async () => ({}))+ const { router: made, lines } = router({ jev })+ const handlers = startRouter(fakeCore(), made)+ expect(await handlers.route_decide!({ text: 'go', sessions: DESK }, DEVICE)).toEqual({ error: 'OWNER_REQUIRED' })+ for (const payload of [{}, { text: ' ' }, { text: 7 }, { text: 'x'.repeat(16_001) }]) {+ expect(await handlers.route_decide!(payload, OWNER)).toEqual({ error: 'INVALID_REQUEST' })+ }+ expect(jev).not.toHaveBeenCalled()+ expect(lines).toEqual([])+ })++ it('answers a session Jev is sure of, and logs why', async () => {+ const jev = vi.fn(async () => ({ target: said('s0', 0.8, ['s0', 's1', 'new']) }))+ const { router: made, lines } = router({ jev })+ expect(await startRouter(fakeCore(), made).route_decide!({ text: 'refund it', sessions: DESK }, OWNER))+ .toEqual({ decided: 'session', id: 'a1', via: 'jev' })+ expect(lines).toEqual(['session — 2 sessions · jev: "billing retries" 0.80'])+ // Jev was asked the task as the client sent it, trimmed.+ expect(jev).toHaveBeenCalledWith({ message: 'refund it' }, expect.objectContaining({ target: expect.any(Object) }), undefined)+ })++ it('answers new work with the project and agent Jev chose, handing back the client\'s own ids', async () => {+ const jev = vi.fn(async () => ({+ target: said('new', 0.9, ['s0', 's1', 'new']),+ project: said('p1', 0.8, ['p0', 'p1']),+ agent: said('a0', 0.7, ['a0', 'a1']),+ }))+ const { router: made, lines } = router({ jev })+ const answer = await startRouter(fakeCore(), made).route_decide!({+ text: 'rename my photos by date',+ sessions: DESK,+ projects: [{ id: '/code/billing', name: 'billing' }, { id: '/Users/me/Pictures', name: 'Pictures' }],+ agents: [{ id: 'claude', name: 'Claude Code' }, { id: 'codex', name: 'Codex' }],+ }, OWNER)+ expect(answer).toEqual({ decided: 'new', via: 'jev', reason: 'Jev: new work', project: '/Users/me/Pictures', agent: 'claude' })+ expect(lines).toEqual(['new (Jev: new work) — 2 sessions · jev: "new" 0.90'])+ })++ it('answers new work with no project or agent when Jev was not sure, for the client to place', async () => {+ const jev = vi.fn(async () => ({ target: said('s1', 0.5, ['s0', 's1', 'new']) }))+ const { router: made, lines } = router({ jev })+ expect(await startRouter(fakeCore(), made).route_decide!({ text: 'go', sessions: DESK }, OWNER))+ .toEqual({ decided: 'new', via: 'unsure', reason: 'Jev was not sure' })+ expect(lines).toEqual(['new (Jev was not sure) — 2 sessions · jev: "Prometheus alerts" 0.50'])+ // And decides the same without a log.+ expect(await startRouter(fakeCore(), { jev }).route_decide!({ text: 'go', sessions: DESK }, OWNER))+ .toEqual({ decided: 'new', via: 'unsure', reason: 'Jev was not sure' })+ })++ it('decides nothing, and says why, when Jev cannot be asked', async () => {+ const jev = vi.fn(async () => { throw new JevUnavailable('NO_KEY', 'no OpenRouter key on this computer') })+ const { router: made, lines } = router({ jev })+ expect(await startRouter(fakeCore(), made).route_decide!({ text: 'go', sessions: DESK }, OWNER))+ .toEqual({ error: 'JEV_UNAVAILABLE', detail: 'no OpenRouter key on this computer' })+ expect(lines).toEqual([+ 'jev could not answer: no OpenRouter key on this computer',+ 'nothing decided (no OpenRouter key on this computer) — 2 sessions · jev: failed',+ ])+ // A router with no Jev at all, with a log and without.+ const { router: none, lines: noneLines } = router()+ expect(await startRouter(fakeCore(), none).route_decide!({ text: 'go', sessions: DESK }, OWNER))+ .toEqual({ error: 'JEV_UNAVAILABLE', detail: 'Jev is not set up' })+ expect(noneLines).toEqual(['nothing decided (Jev is not set up) — 2 sessions · jev: not set up'])+ expect(await startRouter(fakeCore(), {}).route_decide!({ text: 'go' }, OWNER)).toEqual({ error: 'JEV_UNAVAILABLE', detail: 'Jev is not set up' })+ })++ it('takes two decisions at once from a connection and eight in all, and answers BUSY beyond', async () => {+ // Jev holds each decision until the test lets it go, by the task it was asked about.+ const waiting = new Map<string, () => void>()+ const jev = vi.fn((state: unknown) => new Promise<Record<string, JevChoiceAnswer>>((resolve) => {+ waiting.set((state as { message: string }).message, () => resolve({}))+ }))+ const handlers = startRouter(fakeCore(), router({ jev }).router)+ const ask = (task: string, connection?: string) =>+ handlers.route_decide!({ text: task, sessions: DESK }, { local: true, owner: true, ...(connection ? { connection } : {}) }) as Promise<Record<string, unknown>>+ const mine = [ask('one-1', 'one'), ask('one-2', 'one')]+ expect(await ask('one-3', 'one')).toEqual({ error: 'BUSY' })+ // A request with no connection (the core's own, or a core from before connections) is its own.+ const others = [ask('two-1', 'two'), ask('two-2', 'two'), ask('none-1'), ask('none-2'), ask('none-3'), ask('three-1', 'three')]+ expect(await ask('four-1', 'four')).toEqual({ error: 'BUSY' })+ await vi.waitFor(() => expect(waiting.size).toBe(8))+ expect(waiting.has('one-3')).toBe(false)+ expect(waiting.has('four-1')).toBe(false)+ // A decision that ends gives its slot back, to its connection and to the count.+ waiting.get('one-1')!()+ expect(await mine[0]).toMatchObject({ decided: 'new' })+ const again = ask('one-4', 'one')+ await vi.waitFor(() => expect(waiting.has('one-4')).toBe(true))+ expect(await ask('one-5', 'one')).toEqual({ error: 'BUSY' })+ for (const [task, resolve] of waiting) if (task !== 'one-1') resolve()+ expect(await Promise.all([mine[1], again, ...others])).toEqual(Array.from({ length: 8 }, () => expect.objectContaining({ decided: 'new' })))+ expect(jev).toHaveBeenCalledTimes(9)+ })++ it('stops asking Jev when the connection that asked closes, and gives its slot back then', async () => {+ const jev = vi.fn((_state: unknown, _questions: unknown, signal?: AbortSignal) => new Promise<Record<string, JevChoiceAnswer>>((_, reject) => {+ signal?.addEventListener('abort', () => reject(new JevUnavailable('UNAVAILABLE', 'the asker went away')))+ }))+ const handlers = startRouter(fakeCore(), router({ jev }).router)+ const closing = new AbortController()+ const asked = [0, 1].map(() => handlers.route_decide!({ text: 'go', sessions: DESK }, OWNER, closing.signal))+ expect(await handlers.route_decide!({ text: 'go', sessions: DESK }, OWNER)).toEqual({ error: 'BUSY' })+ closing.abort()+ expect(await Promise.all(asked)).toEqual([0, 1].map(() => ({ error: 'JEV_UNAVAILABLE', detail: 'the asker went away' })))+ expect(jev.mock.calls.map((call) => call[2])).toEqual([closing.signal, closing.signal])+ })++ it('gives a slot back when its decision fails', async () => {+ const jev = vi.fn(async () => ({}))+ const handlers = startRouter(fakeCore(), { jev, log: () => { throw new Error('the log could not be written') } })+ // Three on one connection, past its two: each fails for itself, never BUSY.+ for (let i = 0; i < 3; i++) {+ await expect(handlers.route_decide!({ text: 'go', sessions: DESK }, OWNER)).rejects.toThrow('the log could not be written')+ }+ expect(jev).toHaveBeenCalledTimes(3)+ })+})++describe('the router this computer runs', () => {+ it('asks Jev through the person\'s key, and logs as [route]', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const made = defaultRouter()+ // No key or fetch of its own: the client finds the person's key when it is asked, and not before.+ expect(createJevDecide).toHaveBeenCalledWith({ onCost: expect.any(Function) })+ expect(made.jev).toEqual(expect.any(Function))+ expect(Object.keys(made).sort()).toEqual(['jev', 'log'])+ made.log!('session — 2 sessions')+ // What each answer cost the person's key, as OpenRouter reported it.+ vi.mocked(createJevDecide).mock.calls[0]![0]!.onCost!(0.000167, 3986)+ expect(log.mock.calls).toEqual([['[route] session — 2 sessions'], ['[route] jev cost $0.000167 for 3986 tokens']])+ expect(client.asked).toEqual([])+ })++ it('is what the router runs on when given none', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const handlers = startRouter(fakeCore())+ expect(createJevDecide).toHaveBeenCalledOnce()+ expect(await handlers.route_decide!({ text: 'go', sessions: DESK }, OWNER)).toEqual({ decided: 'new', via: 'unsure', reason: 'Jev was not sure' })+ expect(client.asked).toEqual([{ message: 'go' }])+ expect(log.mock.calls).toEqual([['[route] new (Jev was not sure) — 2 sessions · jev: no answer']])+ })+})diff --git a/cli/src/services/router.ts b/cli/src/services/router.tsnew file mode 100644index 000000000..2fea6b257--- /dev/null+++ b/cli/src/services/router.ts@@ -0,0 +1,91 @@+/**+ * The router: where a task a person typed or said should go — an existing session, or a new harness and+ * how to set it up (docs/design/2026-10-09-auto-router.md). An experiment in a process of its own, started+ * at its first request.+ *+ * It DECIDES and does nothing else. Every client that offers "say what you want" — the desktop's ⌘B box+ * today; the phone, the web, the TUI and the dial next — sends the task with the sessions, projects and+ * agents it can see, and acts on the answer through its own doors: it sends into the session the way it+ * sends anything, or makes the harness the way it makes one. So the router needs nothing from the core,+ * holds no session list of its own, and reaches no other machine: a client that can see a session on+ * another computer can route to it.+ *+ * It asks Jev through the person's OpenRouter key (lib/jev/); the decision is lib/routeDecide.ts.+ */+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { createJevDecide } from '../lib/jev/jevClient.js'+import { decideRoute, type RouteDeps, type RouteInput, type RouteOption, type RouteSession } from '../lib/routeDecide.js'++/** The requests the router answers, declared in core/api.ts for the core to route. */+export { ROUTER_REQUESTS } from '../core/api.js'++/** Bounds on what a client may send: a desk is tens of sessions, not thousands. */+const MAX_SESSIONS = 200+const MAX_OPTIONS = 200+const MAX_TEXT = 16_000++function options(raw: unknown): RouteOption[] {+ if (!Array.isArray(raw)) return []+ return raw.slice(0, MAX_OPTIONS).flatMap((row) => {+ const { id, name } = (row ?? {}) as { id?: unknown; name?: unknown }+ return typeof id === 'string' && typeof name === 'string' && id.length <= 4200 && name.length <= 300 ? [{ id, name }] : []+ })+}++function sessions(raw: unknown): RouteSession[] {+ if (!Array.isArray(raw)) return []+ return raw.slice(0, MAX_SESSIONS).flatMap((row) => {+ const { id, name, asks, about } = (row ?? {}) as { id?: unknown; name?: unknown; asks?: unknown; about?: unknown }+ if (typeof id !== 'string' || typeof name !== 'string' || id.length > 4200 || name.length > 300) return []+ const said = Array.isArray(asks) ? asks.filter((ask): ask is string => typeof ask === 'string').slice(0, 3).map((ask) => ask.slice(0, 500)) : []+ return [{ id, name, asks: said, ...(typeof about === 'string' && about.trim() ? { about: about.slice(0, 500) } : {}) }]+ })+}++/** A client's request, checked and bounded; null when it has no task. */+export function routeInput(payload: Record<string, unknown>): RouteInput | null {+ const text = typeof payload.text === 'string' ? payload.text.trim() : ''+ if (!text || text.length > MAX_TEXT) return null+ const last = payload.last as { id?: unknown; agoMs?: unknown } | undefined+ return {+ text,+ sessions: sessions(payload.sessions),+ projects: options(payload.projects),+ agents: options(payload.agents),+ ...(typeof last?.id === 'string' && typeof last.agoMs === 'number' && Number.isFinite(last.agoMs) ? { last: { id: last.id, agoMs: last.agoMs } } : {}),+ }+}++export type Router = RouteDeps++/** Jev through the person's key, and the router's log. */+export function defaultRouter(): Router {+ const log = (line: string): void => console.log(`[route] ${line}`)+ // Every answer's price, as OpenRouter charged it: the person pays for these with their own key.+ return { jev: createJevDecide({ onCost: (usd, tokens) => log(`jev cost $${usd.toFixed(6)} for ${tokens} tokens`) }), log }+}++export function startRouter(_core: CoreApi, router: Router = defaultRouter()): ServiceRequests {+ /** Decisions in flight, each with the connection that asked: what the limits count. */+ const pending = new Map<object, unknown>()+ return {+ route_decide: async (payload, asker, closed) => {+ if (!asker.owner) return { error: 'OWNER_REQUIRED' }+ const input = routeInput(payload)+ if (!input) return { error: 'INVALID_REQUEST' }+ const connection = asker.connection ?? {}+ if (pending.size >= 8 || [...pending.values()].filter((id) => id === connection).length >= 2) return { error: 'BUSY' }+ const request = {}+ pending.set(request, connection)+ try {+ // The asker gone frees its slot at once rather than when Jev answers (up to eight seconds later).+ const verdict = await decideRoute(input, router, closed)+ router.log?.(`${verdict.kind === 'session' ? 'session' : verdict.kind === 'new' ? `new (${verdict.why})` : `nothing decided (${verdict.why})`} — ${verdict.trace}`)+ if (verdict.kind === 'unavailable') return { error: 'JEV_UNAVAILABLE', detail: verdict.why }+ return verdict.kind === 'session'+ ? { decided: 'session', id: verdict.id, via: 'jev' }+ : { decided: 'new', via: verdict.via, reason: verdict.why, ...(verdict.project ? { project: verdict.project } : {}), ...(verdict.agent ? { agent: verdict.agent } : {}) }+ } finally { pending.delete(request) }+ },+ }+}diff --git a/cli/src/services/routerProcess.spec.ts b/cli/src/services/routerProcess.spec.tsnew file mode 100644index 000000000..2286952b1--- /dev/null+++ b/cli/src/services/routerProcess.spec.ts@@ -0,0 +1,34 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { runServiceProcess, type ServiceProcessOptions } from './process.js'+import { runRouterService } from './routerProcess.js'++// The real default reaches a real socket: never in a test. The real router it starts by default builds Jev's+// client, and asks it nothing until a request comes.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))++describe('the router in its own process', () => {+ afterEach(() => vi.clearAllMocks())++ it('answers with the same handlers as in the core\'s process', async () => {+ let options: ServiceProcessOptions | null = null+ const service = { stop: vi.fn() }+ const start = vi.fn(() => ({ route_decide: async () => ({ decided: 'session', id: 'a1', via: 'jev' }) }))+ const handle = runRouterService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (given) => { options = given; return service },+ start,+ })+ expect(handle).toBe(service)+ expect(options).toMatchObject({ name: 'router', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ // Its core is the process's own view of the core, in the data folder it was given.+ expect(start).toHaveBeenCalledWith(expect.objectContaining({ dataDir: '/data' }))+ expect(await options!.requests.route_decide!({ text: 'go' }, { local: true, owner: true })).toEqual({ decided: 'session', id: 'a1', via: 'jev' })+ })++ it('runs as a real service by default', () => {+ runRouterService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({+ name: 'router', requests: { route_decide: expect.any(Function) },+ }))+ })+})diff --git a/cli/src/services/routerProcess.ts b/cli/src/services/routerProcess.tsnew file mode 100644index 000000000..5cc57cd78--- /dev/null+++ b/cli/src/services/routerProcess.ts@@ -0,0 +1,29 @@+/**+ * The router in its own process (`harness __service router`): the same handler as in the core's process+ * (services/router.ts). It asks the core nothing; the OpenRouter key it reads and the Jev calls it makes+ * are this process's alone.+ */+import { startRouter } from './router.js'+import { runServiceProcess, type ServiceProcess } from './process.js'+import { processCoreApi } from './processCoreApi.js'++export interface RouterServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+ /** Swapped in tests for a router that runs no model. */+ start?: typeof startRouter+}++export function runRouterService(options: RouterServiceOptions): ServiceProcess {+ return (options.run ?? runServiceProcess)({+ name: 'router',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests: (options.start ?? startRouter)(processCoreApi(options.dataDir, 'router')),+ })+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 88f7d815c..8b5346f5d 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -17,6 +17,8 @@ import '../core/runtime_platform.dart';import '../api/api_client.dart';import '../core/desktop_window.dart';import '../core/harness_file_store.dart';+import '../core/first_task.dart';+import '../core/permission_modes.dart';import '../core/project_folder.dart';import '../core/launch_setup.dart';import '../core/test_run.dart';@@ -122,6 +124,7 @@ import '../widgets/swarm_switcher.dart';import '../widgets/swarm_resource_preview.dart';import '../widgets/swarm_wallpaper.dart';import '../widgets/task_palette.dart';+import '../state/task_route.dart';import '../orchestrator/orchestrator_launcher.dart';import '../orchestrator/orchestrator_workspace.dart';import '../teams/team_workspace.dart';@@ -6207,18 +6210,95 @@ class _SwarmScreenState extends State<SwarmScreen> {_closeSearch();_spokenPaletteOpen = true;if (_menuHost) _syncNative();+ NewHarnessFromTask? newTask;try {await revealWindow();if (!mounted) {spoken.cancelled();return;}- await showTaskPalette(context, app, spoken: spoken);+ newTask = await showTaskPalette(context, app, spoken: spoken);} finally {_spokenPaletteOpen = false;if (_menuHost && mounted) _syncNative();- spoken.cancelled();+ // New work is answered once its harness is made; every other way out has been answered already,+ // and this does nothing then.+ if (newTask == null || !mounted) spoken.cancelled();+ }+ if (newTask != null && mounted) {+ await _createFromTask(newTask, spoken: spoken);+ }+ }++ /// ⌘B, Boss mode: say what you want and it is done+ /// (docs/design/2026-10-09-auto-router.md). The card sends a task to the+ /// session it belongs to by itself; new work comes back here, once the card+ /// is gone, to be made.+ Future<void> _routeTask() async {+ NewHarnessFromTask? newTask;+ await _dialog(() async => newTask = await showTaskPalette(context, app));+ if (newTask != null && mounted) await _createFromTask(newTask!);+ }++ /// A new harness for a task the router called new work, made at once with+ /// the setup the models chose; what they were not sure of comes from the+ /// pane the person is in, as ⌘N then Return would — its permission mode+ /// too. With no folder to start in, or one that could not be read, New+ /// Harness opens on the task instead. A spoken task hears which harness took+ /// it, or that none did.+ Future<void> _createFromTask(+ NewHarnessFromTask plan, {+ SpokenTask? spoken,+ }) async {+ final fallback = taskRouteDefault(app);+ final machineId = plan.machineId ?? fallback?.machineId;+ final folder = plan.machineId != null ? plan.folder : fallback?.folder;+ final chosen = plan.engine ?? fallback?.engine ?? 'claude';+ // An agent that cannot take a first task would drop the words.+ final engine = takesFirstTask(chosen) ? chosen : 'claude';+ final start = machineId == null || folder == null+ ? null+ : await newWorkFolder(app, machineId, folder);+ if (!mounted) {+ spoken?.cancelled();+ return;+ }+ if (machineId == null || start == null) {+ spoken?.cancelled();+ await _newAgent(task: plan.prompt, placement: HarnessPlacement.currentTab);+ return;+ }+ final mode = taskRoutePermission(app, engine);+ final attempt = AgentCreationAttempt();+ final failure = await app.createAgent(+ machineId,+ engine: engine,+ folder: start.folder,+ projectFolder: start.request,+ prompt: plan.prompt,+ name: taskProjectTitle(plan.task),+ permissionMode: mode,+ bypassPermission: mode != null && permissionModeApproves(mode),+ swarmId: app.activeSwarmId,+ placement: HarnessPlacement.currentTab,+ attempt: attempt,+ );+ final agentId = failure == null ? attempt.agentId : null;+ if (agentId != null) {+ // A follow-up said next is about this work.+ app.lastRoutedTask = (+ id: taskRouteSessionId(machineId, agentId),+ at: DateTime.now(),+ );+ spoken?.sent(agentId);+ } else {+ spoken?.cancelled();}+ if (!mounted) return;+ _showPaneActionHint(+ failure ??+ 'New harness · ${engineIdentity(engine).label} · ${start.folder.split('/').where((part) => part.isNotEmpty).lastOrNull ?? start.folder}',+ );}void _maybeLink() {@@ -6411,8 +6491,7 @@ class _SwarmScreenState extends State<SwarmScreen> {ShortcutAction.cloneAgent: _cloneAgent,ShortcutAction.restartAgent: _restartAgent,ShortcutAction.shareAgent: _shareAgent,- ShortcutAction.routeTask: () =>- _dialog(() => showTaskPalette(context, app)),+ ShortcutAction.routeTask: _routeTask,ShortcutAction.orchestrate: () =>_dialog(() => showOrchestratorLauncher(context, app)),ShortcutAction.team: () =>diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 7879f9550..7a9c88266 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1,3 +1,5 @@+import 'attached_task_delivery.dart';+import 'task_route.dart';import '../core/permission_modes.dart';import 'dart:async';@@ -4087,6 +4089,121 @@ class AppNotifier extends ChangeNotifier {}}+ /// ⌘O's ranking of the person's sessions for words still being typed (docs/design/2026-10-09-auto-router.md).+ ///+ /// ⌘B's decision for a task (docs/design/2026-10-09-auto-router.md): the router, an experiment of its+ /// own in this computer's daemon (cli/src/services/router.ts), says which of [choices]' sessions the+ /// task belongs to, or that it is new work and how to set it up — Jev's pick, or new work when Jev is unsure. The card+ /// acts on it at once, through this app's own doors.+ ///+ /// A daemon that predates the router answers `UNSUPPORTED` at once and is not asked again until the+ /// app restarts; the card then asks Boss mode's old router, as it always did. Every other way the+ /// router can fail — Jev unreachable, the router busy, down or slow, an answer naming a session it was+ /// not offered — is a decision not made, which the card says and acts on by sending nothing: the old+ /// router sends on its own when it is confident, and that is not what ⌘B promised.+ Future<TaskRouteDecision?> routeDecide(+ String text,+ TaskRouteChoices choices,+ ) async {+ if (_routeDecideUnsupported) return null;+ final machineId = localMachineState?.machine.machineId;+ final connection =+ machineId == null || (_pool == null && connectionForTest == null)+ ? null+ : _conn(machineId);+ if (connection == null || !connection.isReady) return null;+ final last = lastRoutedTask;+ appLog.info(+ 'route',+ 'deciding over ${choices.sessions.length} sessions, ${choices.projects.length} projects, '+ '${choices.agents.length} agents',+ );+ try {+ final reply = await connection.request(+ 'route_decide',+ payload: {+ 'text': text,+ ...choices.toPayload(),+ if (last != null && choices.sessions.containsKey(last.id))+ 'last': {+ 'id': last.id,+ 'agoMs': DateTime.now().difference(last.at).inMilliseconds,+ },+ },+ timeout: const Duration(seconds: 20),+ );+ return TaskRouteDecision.fromJson(reply, choices) ??+ const TaskRouteDecision.unavailable(+ 'the router named a session it was not offered',+ );+ } on WsRequestFailure catch (failure) {+ if (failure.code == 'UNSUPPORTED') {+ _routeDecideUnsupported = true;+ return null;+ }+ return TaskRouteDecision.unavailable(+ failure.code == 'JEV_UNAVAILABLE'+ ? failure.detail ?? ''+ : 'the router answered ${failure.code}',+ );+ } catch (error) {+ appLog.warn('route', 'the router did not answer', error: error);+ return const TaskRouteDecision.unavailable('the router did not answer');+ }+ }++ bool _routeDecideUnsupported = false;++ /// A session's last turns as its machine tells them (`agent_recent`): the person's prompts (`asks`) and+ /// each turn's summary (`events`). Empty when the machine could not say.+ Future<Map<String, dynamic>> readRecentTurns(+ String machineId,+ String agentId,+ ) async {+ if (_pool == null && connectionForTest == null) return const {};+ try {+ final reply = await _conn(machineId).request(+ 'agent_recent',+ payload: {'agentId': agentId, 'n': 3},+ timeout: const Duration(seconds: 4),+ );+ return reply['error'] != null ? const {} : reply;+ } catch (_) {+ return const {};+ }+ }++ /// The session ⌘B last sent a task to, which the router tells Jev so a follow-up finds it.+ ({String id, DateTime at})? lastRoutedTask;++ /// ⌘B's send: the session's pane comes forward and the task goes into its prompt, through this app's+ /// own door on any machine (`deliverTask`). [stillWanted] is asked just before the words are typed:+ /// the pane comes forward first, and a person who sees the wrong one and presses Esc stops the send.+ /// Returns what went wrong, or null.+ Future<String?> sendTaskToSession(+ String machineId,+ String agentId,+ String task, {+ bool Function()? stillWanted,+ }) async {+ bringSessionForward(machineId, agentId);+ return deliverTask(+ this,+ machineId: machineId,+ agentId: agentId,+ task: task,+ stillWanted: stillWanted,+ );+ }++ /// The session's own pane, wherever it is: its tab comes forward and the pane takes focus. Only a+ /// session with no pane in any tab gets a new one, here. 2026-10-10: a task for "Personal AI+ /// Computer" opened a second pane on it in the current tab while its own sat in the Backlog tab.+ void bringSessionForward(String machineId, String agentId) {+ if (revealAgentView(machineId, agentId)) return;+ unawaited(selectAgent(machineId, agentId));+ }+/// Commit: deliver the task, then bring the agent onto the grid the way a rail click does.////// The daemon delivers it through the SAME door as the web's messages and the dial's — queueing,@@ -4147,7 +4264,7 @@ class AppNotifier extends ChangeNotifier {// …the PANE opens on the agent's machine. Falling back to this computer would open a tile for an// agent it does not have and leave the person looking at an empty terminal.final target = agentMachineId.isNotEmpty ? agentMachineId : localId;- await selectAgent(target, agentId);+ if (!revealAgentView(target, agentId)) await selectAgent(target, agentId);return null;}diff --git a/desktop/lib/state/attached_task_delivery.dart b/desktop/lib/state/attached_task_delivery.dartindex 2181ac76d..2932b824f 100644--- a/desktop/lib/state/attached_task_delivery.dart+++ b/desktop/lib/state/attached_task_delivery.dart@@ -192,3 +192,27 @@ Future<TerminalSession?> _readySession(app.removeListener(check);}}++/// Sends [task] into an existing harness through its pane, as a person typing it would: once its engine+/// takes input, as a composer message the machine submits and retries Enter for. ⌘B's router decides+/// where (docs/design/2026-10-09-auto-router.md); this is the app's own door, the same on every machine.+/// Returns what went wrong, or null. [stillWanted], when given, is asked once the pane takes input, the+/// moment before the words are typed: the wait for it can be seconds, and a send the person walked away+/// from in that time must not land.+Future<String?> deliverTask(+ AppNotifier app, {+ required String machineId,+ required String agentId,+ required String task,+ bool Function()? stillWanted,+}) async {+ final session = await _readySession(app, machineId, agentId);+ if (session == null) {+ appLog.warn('route', '$agentId never took input');+ return 'The harness did not open in time. Nothing was sent.';+ }+ if (stillWanted != null && !stillWanted()) return 'Nothing was sent.';+ return await session.sendComposerText(task)+ ? null+ : 'The task did not reach the harness. Send it from its pane.';+}diff --git a/desktop/lib/state/task_route.dart b/desktop/lib/state/task_route.dartnew file mode 100644index 000000000..6a79e2dd5--- /dev/null+++ b/desktop/lib/state/task_route.dart@@ -0,0 +1,387 @@+import 'package:path/path.dart' as p;++import '../core/git_worktree.dart';+import '../core/launch_setup.dart';+import '../core/permission_modes.dart';+import '../core/project_folder.dart';+import '../core/models.dart' show Agent, AgentProject, ConnectionStatus;+import 'session_preview.dart';+import '../widgets/engine_identity.dart';+import 'app_state.dart';+import 'new_harness.dart' show gitFolderRequest, worktreeByDefault;++/// What ⌘B tells the router (docs/design/2026-10-09-auto-router.md, cli/src/services/router.ts): the+/// sessions this app can see on every machine — the router reaches none itself — and, for new work, the+/// person's project folders and the agents they use. The ids come back untouched.+class TaskRouteChoices {+ const TaskRouteChoices(this.sessions, this.projects, this.agents);++ /// id → the session, as this app knows it. Plain terminals and shared views are not among them:+ /// a shell is not somewhere a task is sent, and a shared view takes no input.+ final Map<String, TaskRouteSession> sessions;++ /// id → (machine, folder). The id is what the daemon hands back.+ final Map<String, ({String machineId, String folder, String name})> projects;++ /// Engine ids, with the names the models read.+ final Map<String, String> agents;++ Map<String, dynamic> toPayload() => {+ 'sessions': [+ for (final MapEntry(:key, :value) in sessions.entries)+ {+ 'id': key,+ 'name': value.name,+ 'asks': value.asks,+ if (value.about != null) 'about': value.about,+ },+ ],+ 'projects': [+ for (final MapEntry(:key, :value) in projects.entries)+ {'id': key, 'name': value.name},+ ],+ 'agents': [+ for (final MapEntry(:key, :value) in agents.entries)+ {'id': key, 'name': value},+ ],+ };+}++/// The folder a session's work belongs to: the repository, not a temporary worktree of it.+String? _projectFolder(AgentProject? project) => project == null+ ? null+ : project.worktree && project.root != null+ ? project.root+ : project.cwd;++bool _usable(String folder) =>+ p.isAbsolute(folder) &&+ !isInternalLaunchFolder(folder) &&+ !folder.contains('/harnesses/worktrees/') &&+ // Harness's own folders (a Store fork's `project`, say) are not where a person's new work starts.+ !folder.contains('/.harness/') &&+ folder.length <= 4096;++const _sessionCap = 40;++TaskRouteChoices taskRouteChoices(AppNotifier app) {+ final machines =+ [+ ...app.machineStates.values.where((m) => m.isLocalMachine),+ ...app.machineStates.values.where((m) => !m.isLocalMachine),+ ]+ // Machines a task can reach now: the app also remembers the sessions of machines that are off.+ .where(+ (m) =>+ !m.machine.isShared &&+ !m.needsLink &&+ m.nodeOnline != false &&+ m.connectionStatus == ConnectionStatus.connected,+ )+ .toList();+ final found = <({String machineId, String machine, String folder})>[];+ final seen = <String>{};+ for (final machine in machines) {+ final id = machine.machine.machineId;+ for (final folder in [+ ...app.projectHistory.recent(id),+ for (final agent in machine.agents.reversed)+ ?_projectFolder(machine.projectOf(agent)),+ ]) {+ if (!_usable(folder) || !seen.add('$id\n${p.normalize(folder)}')) {+ continue;+ }+ found.add((+ machineId: id,+ machine: machine.machine.displayName,+ folder: p.normalize(folder),+ ));+ }+ }+ // A folder's name is what the models read. Two of the same name are told apart by their machine.+ final named = <String, int>{};+ for (final row in found) {+ named.update(p.basename(row.folder), (n) => n + 1, ifAbsent: () => 1);+ }+ final projects = {+ for (final row in found)+ '${row.machineId}\n${row.folder}': (+ machineId: row.machineId,+ folder: row.folder,+ name: named[p.basename(row.folder)]! > 1+ ? '${p.basename(row.folder)} on ${row.machine}'+ : p.basename(row.folder),+ ),+ };+ // Live sessions only, the most recently active first, and at most [_sessionCap]: the rail keeps every+ // stopped session it ever ran, and the first try sent all two hundred — the one the task was for was+ // not among the forty Jev was shown.+ final live =+ [+ for (final machine in machines)+ for (final agent in machine.agents)+ if (agent.engine != null &&+ !isTerminalEngine(agent.engine) &&+ !agent.isStopped)+ (machine: machine, agent: agent),+ ]..sort((a, b) {+ final at = a.agent.lastActivityAt, bt = b.agent.lastActivityAt;+ return bt == null+ ? (at == null ? 0 : -1)+ : at == null+ ? 1+ : bt.compareTo(at);+ });+ final sessions = {+ for (final (:machine, :agent) in live.take(_sessionCap))+ taskRouteSessionId(machine.machine.machineId, agent.id): (+ machineId: machine.machine.machineId,+ agentId: agent.id,+ name: agent.displayName,+ machine: machine.machine.displayName,+ engine: agent.engine!,+ asks:+ _recent[app]?['${machine.machine.machineId}\n${agent.id}']?.asks ??+ [+ ...?_preview(+ app,+ machine.machine.machineId,+ agent,+ )?.requests.take(2),+ ],+ about:+ _recent[app]?['${machine.machine.machineId}\n${agent.id}']?.about ??+ _about(_preview(app, machine.machine.machineId, agent)),+ ),+ };+ final engines = <String>{'claude', 'codex'};+ for (final machine in machines) {+ for (final agent in machine.agents) {+ final engine = agent.engine;+ if (engine != null && engine.isNotEmpty && !isTerminalEngine(engine)) {+ engines.add(engine);+ }+ }+ }+ return TaskRouteChoices(sessions, projects, {+ for (final engine in engines) engine: engineIdentity(engine).label,+ });+}++/// What each session was last asked and last did, as its machine told the router's box: the router+/// decides from it. Read for every session the box offers when it opens — all at once, not the preview+/// store's two at a time — and kept a couple of minutes.+final _recent =+ Expando<Map<String, ({DateTime at, List<String> asks, String? about})>>();+const _recentFresh = Duration(minutes: 2);++/// ⌘B opened: read what each session is about while the person types. Resolves once every read has answered (each is bounded by its own deadline).+///+/// 2026-10-10, "what's d30 retention on harness": with only names to go on Jev gave the right session+/// 0.53, under its bar, and the task became new work; with each session's last prompt and summary the+/// same question was sure.+Future<void> warmTaskRoute(AppNotifier app) {+ final cache = _recent[app] ??= {};+ final now = DateTime.now();+ return Future.wait([+ for (final MapEntry(:key, :value) in taskRouteChoices(app).sessions.entries)+ if (cache[key] == null || now.difference(cache[key]!.at) > _recentFresh)+ app.readRecentTurns(value.machineId, value.agentId).then((reply) {+ final asks = reply['asks'];+ final events = reply['events'];+ // Its last three turns, summarised: the newest alone often names nothing ("Tomorrow we'll+ // compare…"), the two before it name the topic ("activation and repeat use").+ final turns = events is List+ ? [+ for (final e in events.whereType<Map>())+ if ((e['recap'] ?? e['text']) case final String said)+ said.replaceAll(RegExp(r'\s+'), ' ').trim(),+ ].where((said) => said.isNotEmpty).take(3)+ : const <String>[];+ final about = turns.isEmpty+ ? null+ : turns+ .map(+ (said) =>+ said.length <= 140 ? said : said.substring(0, 140),+ )+ .join(' / ');+ cache[key] = (+ at: DateTime.now(),+ asks: [+ if (asks is List)+ for (final ask in asks.take(2))+ if (ask is String && ask.isNotEmpty) ask,+ ],+ about: about,+ );+ }),+ // A Future<void> in fact, not a Future<List<Null>> typed as one: the box puts a timeout on it, and+ // a timeout's fallback is checked against the runtime type.+ ]).then((_) {});+}++/// The new harness when neither model was sure of its setup: the pane the person is in — its machine,+/// its agent and its project — as ⌘N then Return would make it. Null when there is no folder to start+/// in at all; New Harness then asks.+({String machineId, String engine, String folder})? taskRouteDefault(+ AppNotifier app,+) {+ final pane = app.focusedPane;+ final machine = pane == null+ ? app.localMachineState+ : app.stateOf(pane.machineId);+ if (machine == null) return null;+ final agent = pane == null+ ? null+ : machine.agents.where((a) => a.id == pane.agentId).firstOrNull;+ final used = agent?.engine;+ final engine = used == null || used.isEmpty || isTerminalEngine(used)+ ? 'claude'+ : used;+ final id = machine.machine.machineId;+ // The pane's own folder even when it is a worktree: newWorkFolder starts from its repository.+ final paneFolder = agent == null+ ? null+ : _projectFolder(machine.projectOf(agent));+ final folder =+ (paneFolder != null && p.isAbsolute(paneFolder) ? paneFolder : null) ??+ app.projectHistory.recent(id).where(_usable).firstOrNull;+ return folder == null+ ? null+ : (machineId: id, engine: engine, folder: p.normalize(folder));+}++typedef TaskRouteSession = ({+ String machineId,+ String agentId,+ String name,+ String machine,+ String engine,+ List<String> asks,+ String? about,+});++SessionPreview? _preview(AppNotifier app, String machineId, Agent agent) =>+ app.sessionPreviews.read((+ machineId: machineId,+ agentId: agent.id,+ sessionId: agent.sessionId,+ ));++/// Its latest turn, summarised, in a line: often the only place a session's topic is said.+String? _about(SessionPreview? preview) {+ final text = preview?.response?.replaceAll(RegExp(r'\s+'), ' ').trim();+ if (text == null || text.isEmpty) return null;+ return text.length <= 240 ? text : text.substring(0, 240);+}++/// The router's answer, read against the lists it was given: a session of [TaskRouteChoices.sessions],+/// or new work with the project and agent a model was sure of (either may be null).+class TaskRouteDecision {+ const TaskRouteDecision._({+ this.session,+ this.sessionId,+ this.project,+ this.engine,+ required this.via,+ this.unavailableBecause,+ });++ /// Jev could not be asked — no key, no network, no credit — so nothing was decided, and the box says so+ /// rather than guessing.+ const TaskRouteDecision.unavailable(String because)+ : this._(via: '', unavailableBecause: because);++ final String? unavailableBecause;++ final TaskRouteSession? session;+ final String? sessionId;+ final ({String machineId, String folder, String name})? project;+ final String? engine;++ /// 'jev' when Jev was sure, 'unsure' when it was not and the task became new work.+ final String via;++ bool get isNew => session == null && unavailableBecause == null;++ /// Null for an answer that is not a decision (an error, or a session it was not given).+ static TaskRouteDecision? fromJson(+ Map<String, dynamic> json,+ TaskRouteChoices choices,+ ) {+ final via = json['via'] is String ? json['via'] as String : '';+ switch (json['decided']) {+ case 'session':+ final id = json['id'];+ final session = id is String ? choices.sessions[id] : null;+ return session == null+ ? null+ : TaskRouteDecision._(+ session: session,+ sessionId: id as String,+ via: via,+ );+ case 'new':+ final project = json['project'];+ final agent = json['agent'];+ return TaskRouteDecision._(+ project: project is String ? choices.projects[project] : null,+ engine: agent is String && choices.agents.containsKey(agent)+ ? agent+ : null,+ via: via,+ );+ }+ return null;+ }+}++/// Where new work starts, as ⌘N then Return would start it: in a Git project, a fresh worktree from its+/// main branch — never inside a checkout another harness may be working in — and in [folder]'s+/// repository when [folder] is itself a worktree. Outside Git, the folder as it is.+///+/// Null when the folder could not be read (a machine slow to answer, a folder gone): "not read" is not+/// "not Git", and taking it for that would start the work in the repository's own checkout.+Future<({String folder, ProjectFolderRequest? request})?> newWorkFolder(+ AppNotifier app,+ String machineId,+ String folder,+) async {+ var info = GitProjectInfo.fromJson(+ await app.readGitProject(machineId, folder),+ );+ var root = folder;+ if (info.mainFolder case final main?+ when info.error == null && p.normalize(main) != p.normalize(folder)) {+ root = main;+ info = GitProjectInfo.fromJson(await app.readGitProject(machineId, main));+ }+ if (info.error != null) return null;+ if (!info.isGit) return (folder: root, request: null);+ return (+ folder: root,+ request: gitFolderRequest(+ root,+ info,+ worktree: worktreeByDefault(info),+ branchRef: null,+ branchName: null,+ placeholder: placeholderBranch([for (final b in info.branches) b.name]),+ ),+ );+}++/// The permission mode New Harness would start [engine] in: the one the person last started it with,+/// else the default; null for an agent that has no modes. A spoken or typed task must not start an+/// agent that approves its own actions for someone who chose to be asked.+String? taskRoutePermission(AppNotifier app, String engine) {+ if (permissionModesOf(engine).isEmpty) return null;+ final last = app.agentPreference.successfulLaunch;+ return (last?.engine == engine ? last?.permissionMode : null) ??+ kDefaultPermissionMode;+}++/// A session as the router names it: its machine and its agent.+String taskRouteSessionId(String machineId, String agentId) =>+ '$machineId\n$agentId';diff --git a/desktop/lib/widgets/task_palette.dart b/desktop/lib/widgets/task_palette.dartindex 14a05e437..b33343e45 100644--- a/desktop/lib/widgets/task_palette.dart+++ b/desktop/lib/widgets/task_palette.dart@@ -8,6 +8,7 @@ import '../core/models.dart';import '../shared/theme/app_theme.dart' as grid;import 'desktop_chrome.dart';import '../state/app_state.dart';+import '../state/task_route.dart';import 'engine_identity.dart';/// ⌘B — describe the work, and let the daemon say whose it is.@@ -68,13 +69,37 @@ class SpokenTask {}}-Future<void> showTaskPalette(+/// A task the router decided is new work, and the setup it chose: [machineId] and [folder] when a model+/// was sure of the project, [engine] when one was sure of the agent. The caller makes the harness once+/// the card is gone, filling what is missing from the pane the person is in.+class NewHarnessFromTask {+ const NewHarnessFromTask({+ required this.task,+ this.command = '',+ this.machineId,+ this.folder,+ this.engine,+ });+ final String task;++ /// The dial's Goal or Loop button, when the task was spoken with one held (see [SpokenTask.cmd]).+ final String command;+ final String? machineId, folder, engine;++ /// What the new harness is first told: the words, as the slash command the person pressed.+ String get prompt => command.isEmpty ? task : '/$command $task';+}++/// Resolves to the new harness to make when the task was decided to be new work; null on every other+/// way out — sent to a session, cancelled, or asked and answered by the person. A spoken task that+/// became new work is still owed its answer: the caller gives it once the harness is made.+Future<NewHarnessFromTask?> showTaskPalette(BuildContext context,AppNotifier notifier, {SpokenTask? spoken,}) {// A keyboard palette opens fully drawn on its first frame.- return showGeneralDialog<void>(+ return showGeneralDialog<NewHarnessFromTask>(context: context,barrierDismissible: true,barrierLabel: 'Dismiss',@@ -86,7 +111,10 @@ Future<void> showTaskPalette(// Every exit lands here — Esc, a tap on the veil, and the self-close after a send. A commit has// already answered by then and this does nothing; anything else is a person walking away, which the// dial has to hear about or it keeps showing work that is not happening.- ).whenComplete(() => spoken?.cancelled());+ ).then((plan) {+ if (plan == null) spoken?.cancelled();+ return plan;+ });}/// Below this the palette stops guessing and asks.@@ -180,6 +208,12 @@ class _TaskPaletteState extends State<_TaskPalette> {/// and the rest is one flick or one arrow key away.static const double _listMaxHeight = 316;+ /// What the sessions are about, being read since the box opened (`warmTaskRoute`).+ late final Future<void> _context;++ /// How long Return waits for it: the reads take a few hundred milliseconds, another machine's more.+ static const _contextWait = Duration(milliseconds: 1500);+/// Which question is still ours. A second Enter — or an Esc and a re-open — must not let a slow first/// answer arrive and act: it belongs to a palette state nobody is looking at any more.int _generation = 0;@@ -187,6 +221,7 @@ class _TaskPaletteState extends State<_TaskPalette> {@overridevoid initState() {super.initState();+ _context = warmTaskRoute(widget.notifier);final spoken = widget.spoken;if (spoken == null) return;// The transcript goes in the field rather than into a variable the person cannot see: this is the@@ -202,7 +237,7 @@ class _TaskPaletteState extends State<_TaskPalette> {// works — routing takes up to twenty seconds, and a dialog that appears already-spinning reads as// a hang rather than as an answer being worked out.WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted) unawaited(_route());+ if (mounted) unawaited(_decide());});}@@ -216,6 +251,113 @@ class _TaskPaletteState extends State<_TaskPalette> {super.dispose();}+ /// SAY IT AND IT IS DONE (docs/design/2026-10-09-auto-router.md). Return asks the daemon to decide,+ /// and the card acts on the answer without asking: Jev's pick, or a new+ /// harness. A session gets the task at once — the owner chose no undo window — and new work closes+ /// the card with the setup the models chose, for the screen to make.+ ///+ /// A daemon that cannot decide (older, or signed out) leaves the card as it always was: the full+ /// router, and a question when it is unsure.+ Future<void> _decide() async {+ final task = _text.text.trim();+ // Not while one is in flight, and not during the receipt: Return held down, or pressed again as the+ // card says who took it, would send the same task twice.+ if (task.isEmpty || _stage == _Stage.routing || _stage == _Stage.sent) {+ return;+ }+ final mine = ++_generation;+ setState(() {+ _stage = _Stage.routing;+ _note = '';+ _answer = null;+ });+ _startClock();+ // What each session is about, read as the box opened: a fast Return waits for it, briefly.+ await _context.timeout(_contextWait, onTimeout: () {});+ if (!mounted || mine != _generation) return;+ final choices = taskRouteChoices(widget.notifier);+ final decision = await widget.notifier.routeDecide(task, choices);+ if (!mounted || mine != _generation) return;+ if (decision == null) {+ _stopClock();+ setState(() => _stage = _Stage.typing);+ return _route();+ }+ if (decision.unavailableBecause case final because?) {+ _stopClock();+ setState(() {+ _stage = _Stage.empty;+ _note =+ 'Jev could not decide${because.isEmpty ? '' : ' ($because)'}. Nothing was sent.';+ });+ return;+ }+ // The dial's Goal or Loop button, applied where the words are sent, as [_commit] does.+ final cmd = widget.spoken?.cmd ?? '';+ final session = decision.session;+ if (session == null) {+ _stopClock();+ // A follow-up belongs to the new harness now, not to wherever the last task went: the screen points+ // the hint at it once it is made.+ widget.notifier.lastRoutedTask = null;+ final project = decision.project;+ Navigator.of(context).pop(+ NewHarnessFromTask(+ task: task,+ command: cmd,+ machineId: project?.machineId,+ folder: project?.folder,+ engine: decision.engine,+ ),+ );+ return;+ }+ // The receipt lights the row of the session that took it.+ final taker = RouteCandidate(+ agentId: session.agentId,+ machineId: session.machineId,+ name: session.name,+ machine: session.machine,+ recent: session.asks.firstOrNull ?? '',+ engine: session.engine,+ );+ _answer = RouteAnswer(+ agentId: session.agentId,+ machineId: session.machineId,+ name: session.name,+ confidence: 1,+ reason: '',+ candidates: [taker],+ );+ final failure = await widget.notifier.sendTaskToSession(+ session.machineId,+ session.agentId,+ cmd.isEmpty ? task : '/$cmd $task',+ stillWanted: () => mounted && mine == _generation,+ );+ if (!mounted || mine != _generation) return;+ _stopClock();+ if (failure != null) {+ setState(() {+ _stage = _Stage.empty;+ _note = failure;+ });+ return;+ }+ widget.notifier.lastRoutedTask = (+ id: decision.sessionId!,+ at: DateTime.now(),+ );+ widget.spoken?.sent(session.agentId);+ setState(() {+ _stage = _Stage.sent;+ _committed = session.agentId;+ });+ await Future<void>.delayed(_confirmBeat);+ if (!mounted || mine != _generation) return;+ Navigator.of(context).pop();+ }+Future<void> _route() async {final task = _text.text.trim();if (task.isEmpty || _stage == _Stage.routing) return;@@ -344,6 +486,10 @@ class _TaskPaletteState extends State<_TaskPalette> {});return;}+ widget.notifier.lastRoutedTask = (+ id: taskRouteSessionId(machineId, agentId),+ at: DateTime.now(),+ );// Landed. Tell the daemon before the beat, not after: it is holding the dial's overlay open on this// answer, and three quarters of a second is long enough to be seen as a stall on a device whose only// feedback is that overlay.@@ -388,7 +534,7 @@ class _TaskPaletteState extends State<_TaskPalette> {// ⇧Enter is the newline — ignored here so the field does what it always does with it.final shift = HardwareKeyboard.instance.isShiftPressed;if (isEnter && !shift && _stage != _Stage.choosing) {- unawaited(_route());+ unawaited(_decide());return KeyEventResult.handled; // …and NOT a newline}if (_stage != _Stage.choosing) return KeyEventResult.ignored;diff --git a/desktop/test/route_card_test.dart b/desktop/test/route_card_test.dartnew file mode 100644index 000000000..539defefb--- /dev/null+++ b/desktop/test/route_card_test.dart@@ -0,0 +1,581 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/task_route.dart';+import 'package:harness/widgets/task_palette.dart';+import 'package:harness/ws/ws_conn.dart';++/// ⌘B, say it and it is done (docs/design/2026-10-09-auto-router.md): Return+/// asks the router to decide, and the card acts on the answer without asking.+class _App extends AppNotifier {+ _App()+ : super(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ ) {+ const machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Office',+ );+ machines = [machine];+ machineStates['m'] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = const [+ Agent(+ id: 'a0',+ name: 'Analyze Harness usage data',+ engine: 'codex',+ terminalAvailable: true,+ ),+ Agent(+ id: 'a1',+ name: 'zsh',+ engine: 'terminal',+ terminalAvailable: true,+ ),+ ]+ ..localProjects = const {+ 'a0': AgentProject(name: 'analytics', cwd: '/work/analytics'),+ };+ }++ Map<String, dynamic>? Function(String text) reply = (_) => null;+ final payloads = <Map<String, dynamic>>[];+ final routed = <String>[];+ final sent = <(String, String, String)>[];++ TaskRouteDecision? Function(String text)? decision;++ @override+ Future<TaskRouteDecision?> routeDecide(+ String text,+ TaskRouteChoices choices,+ ) async {+ payloads.add(choices.toPayload());+ if (decision case final decide?) return decide(text);+ final answer = reply(text);+ return answer == null ? null : TaskRouteDecision.fromJson(answer, choices);+ }++ Map<String, dynamic> recent = const {};++ @override+ Future<Map<String, dynamic>> readRecentTurns(+ String machineId,+ String agentId,+ ) async => recent;++ @override+ Future<RouteAnswer?> routeTask(String text) {+ routed.add(text);+ return Completer<RouteAnswer?>().future;+ }++ /// Held until the test lets it go, when set: the pane coming forward before the words are typed.+ Completer<void>? paneReady;++ @override+ Future<String?> sendTaskToSession(+ String machineId,+ String agentId,+ String task, {+ bool Function()? stillWanted,+ }) async {+ await paneReady?.future;+ if (stillWanted != null && !stillWanted()) return 'Nothing was sent.';+ sent.add((machineId, agentId, task));+ return null;+ }+}++/// This computer's daemon, answering `route_decide` with [answer]: a reply, or a refusal to throw.+class _Daemon extends WsConn {+ _Daemon(this.answer)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final Object Function() answer;+ var asked = 0;++ @override+ bool get isReady => true;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type != 'route_decide') return const {};+ asked++;+ final reply = answer();+ if (reply is Map<String, dynamic>) return reply;+ throw reply;+ }+}++/// The app's own reading of the router's answers, against a daemon that gives [answer].+Future<(TaskRouteDecision?, _Daemon)> _decided(Object Function() answer) async {+ final daemon = _Daemon(answer);+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ connectionForTest: (_) => daemon,+ );+ addTearDown(app.dispose);+ const machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Office',+ );+ app.machines = [machine];+ app.machineStates['m'] = MachineState(machine)+ ..localOnly = true+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = const [+ Agent(id: 'a0', name: 'Analyze', engine: 'codex', terminalAvailable: true),+ ];+ final decision = await app.routeDecide('go', taskRouteChoices(app));+ return (decision, daemon);+}++WsRequestFailure _refused(String code, [String? detail]) => WsRequestFailure(+ responseType: 'route_decide_result',+ code: code,+ detail: detail,+);++Future<(_App, Future<NewHarnessFromTask?> Function())> _open(+ WidgetTester tester,+) async {+ final app = _App();+ addTearDown(app.dispose);+ Future<NewHarnessFromTask?>? result;+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => result = showTaskPalette(context, app),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ return (app, () => result!);+}++Future<void> _say(WidgetTester tester, String text) async {+ await tester.enterText(find.byType(TextField), text);+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.pump();+}++const _session = 'm\na0';++Agent _agent(String id, {String status = 'idle', int minutesAgo = 0}) => Agent(+ id: id,+ name: 'Session $id',+ engine: 'claude',+ status: status,+ terminalAvailable: true,+ lastActivityAt: DateTime(+ 2026,+ 10,+ 10,+ 12,+ ).subtract(Duration(minutes: minutesAgo)),+);++void main() {+ test('the router is offered live sessions on reachable machines, newest first, forty at most', () {+ final app = _App();+ addTearDown(app.dispose);+ app.machineStates['m']!.agents = [+ for (var i = 0; i < 50; i++) _agent('a$i', minutesAgo: i),+ _agent('stopped', status: 'stopped'),+ const Agent(+ id: 'sh',+ name: 'zsh',+ engine: 'terminal',+ terminalAvailable: true,+ ),+ ];+ const away = Machine(+ machineId: 'off',+ authMode: MachineAuthMode.remote,+ name: 'Rig',+ );+ app.machines = [...app.machines, away];+ app.machineStates['off'] = MachineState(away)+ ..nodeOnline = false+ ..agents = [_agent('far')];+ final ids = taskRouteChoices(app).sessions.values+ .map((s) => s.agentId)+ .toList();+ expect(ids, [for (var i = 0; i < 40; i++) 'a$i']);+ });++ test(+ 'new work in a Git project starts in a fresh worktree of its repository',+ () async {+ final app = _App();+ addTearDown(app.dispose);+ final asked = <String>[];+ app.gitProjectReaderForTest = (machineId, path) async {+ asked.add(path);+ return path == '/repos/harness/.wt/feature'+ ? {+ 'isGit': true,+ 'mainFolder': '/repos/harness',+ 'branches': const [],+ }+ : {+ 'isGit': true,+ 'branch': 'main',+ 'branches': [+ {'ref': 'refs/heads/main', 'name': 'main'},+ ],+ };+ };+ final start = await newWorkFolder(app, 'm', '/repos/harness/.wt/feature');+ expect(asked, ['/repos/harness/.wt/feature', '/repos/harness']);+ expect(start?.folder, '/repos/harness');+ expect(start?.request?.payload['projectSource'], 'worktree');+ },+ );++ test('new work outside Git starts in the folder itself', () async {+ final app = _App();+ addTearDown(app.dispose);+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ final start = await newWorkFolder(app, 'm', '/notes');+ expect(start?.folder, '/notes');+ expect(start?.request, isNull);+ });++ test('a folder that could not be read is nowhere to start, not a plain folder', () async {+ final app = _App();+ addTearDown(app.dispose);+ app.gitProjectReaderForTest = (_, _) async => {'error': 'UNAVAILABLE'};+ expect(await newWorkFolder(app, 'm', '/repos/harness'), isNull);+ });++ testWidgets('each session goes with what it was last asked and last did', (+ tester,+ ) async {+ final app = _App()+ ..recent = {+ 'asks': ["ok we'll check again in 24 hours", 'did onboarding help'],+ 'events': [+ {+ 'kind': 'summary',+ 'recap': 'Compared 24-hour activation and cohort sizes.',+ },+ ],+ };+ addTearDown(app.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showTaskPalette(context, app),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ await _say(tester, "what's d30 retention on harness");+ final session = (app.payloads.single['sessions'] as List).single as Map;+ expect(session['asks'], [+ "ok we'll check again in 24 hours",+ 'did onboarding help',+ ]);+ expect(session['about'], 'Compared 24-hour activation and cohort sizes.');+ });++ testWidgets('it offers the router every session it can see, never a shell', (+ tester,+ ) async {+ final (app, _) = await _open(tester);+ await _say(tester, "what's the D3 retention rate");+ final payload = app.payloads.single;+ expect(+ [for (final s in payload['sessions'] as List) (s as Map)['id']],+ [_session],+ );+ expect(+ (payload['sessions'] as List).single['name'],+ 'Analyze Harness usage data',+ );+ expect(+ [for (final p in payload['projects'] as List) (p as Map)['name']],+ ['analytics'],+ );+ expect([+ for (final a in payload['agents'] as List) (a as Map)['id'],+ ], containsAll(['claude', 'codex']));+ });++ testWidgets('a task for a session is sent there at once, nothing asked', (+ tester,+ ) async {+ final (app, result) = await _open(tester);+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await _say(tester, "what's the D3 retention rate");+ expect(app.sent, [('m', 'a0', "what's the D3 retention rate")]);+ expect(app.routed, isEmpty);+ expect(app.lastRoutedTask?.id, _session);+ // The receipt names who took it, then the card goes.+ expect(find.text('Analyze Harness usage data'), findsOneWidget);+ await tester.pumpAndSettle(const Duration(seconds: 1));+ expect(find.byType(TextField), findsNothing);+ expect(await result(), isNull);+ });++ testWidgets('new work closes the card with the setup the models chose', (+ tester,+ ) async {+ final (app, result) = await _open(tester);+ app.reply = (_) => {+ 'decided': 'new',+ 'project': 'm\n/work/analytics',+ 'agent': 'codex',+ 'via': 'jev',+ };+ await _say(tester, 'write a script that plots signups by week');+ await tester.pumpAndSettle();+ final plan = await result();+ expect(plan?.task, 'write a script that plots signups by week');+ expect(plan?.machineId, 'm');+ expect(plan?.folder, '/work/analytics');+ expect(plan?.engine, 'codex');+ expect(app.sent, isEmpty);+ });++ testWidgets(+ 'new work the models were unsure of leaves the setup to the pane',+ (tester) async {+ final (app, result) = await _open(tester);+ app.reply = (_) => {'decided': 'new', 'via': 'unsure'};+ await _say(tester, 'write a haiku about autumn leaves');+ await tester.pumpAndSettle();+ final plan = await result();+ expect(plan?.machineId, isNull);+ expect(plan?.engine, isNull);+ },+ );++ group('the router\'s answer, as the app reads it', () {+ test('a session it was offered', () async {+ final (decision, _) = await _decided(+ () => {'decided': 'session', 'id': 'm\na0', 'via': 'jev'},+ );+ expect(decision?.sessionId, 'm\na0');+ });++ test('a session it was never offered is nothing decided', () async {+ final (decision, _) = await _decided(+ () => {'decided': 'session', 'id': 'm\nelsewhere', 'via': 'jev'},+ );+ expect(decision?.session, isNull);+ expect(+ decision?.unavailableBecause,+ 'the router named a session it was not offered',+ );+ });++ test('Jev unreachable is nothing decided, and says why', () async {+ final (decision, _) = await _decided(+ () => _refused('JEV_UNAVAILABLE', 'no OpenRouter key on this computer'),+ );+ expect(+ decision?.unavailableBecause,+ 'no OpenRouter key on this computer',+ );+ });++ test(+ 'a router busy, down or silent is nothing decided — never the old router',+ () async {+ for (final code in ['BUSY', 'SERVICE_UNAVAILABLE', 'SERVICE_FAILED']) {+ final (decision, _) = await _decided(() => _refused(code));+ expect(+ decision?.unavailableBecause,+ 'the router answered $code',+ reason: code,+ );+ }+ final (silent, _) = await _decided(+ () => WsRequestTimeout('route_decide'),+ );+ expect(silent?.unavailableBecause, 'the router did not answer');+ },+ );++ test('a daemon without the router hands the card back to the old one', () async {+ final (decision, daemon) = await _decided(() => _refused('UNSUPPORTED'));+ expect(decision, isNull);+ expect(daemon.asked, 1);+ });+ });++ testWidgets('when Jev cannot be asked, the box says so and sends nothing', (+ tester,+ ) async {+ final (app, _) = await _open(tester);+ app.decision = (_) => const TaskRouteDecision.unavailable('out of credit');+ await _say(tester, "what's d30 retention on harness");+ expect(+ find.textContaining('Jev could not decide (out of credit)'),+ findsOneWidget,+ );+ expect(app.sent, isEmpty);+ expect(app.routed, isEmpty);+ });++ testWidgets('Return during the receipt does not send the task again', (+ tester,+ ) async {+ final (app, _) = await _open(tester);+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await _say(tester, "what's the D3 retention rate");+ expect(app.sent, hasLength(1));+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.pumpAndSettle(const Duration(seconds: 1));+ expect(app.sent, hasLength(1));+ });++ testWidgets('Esc while the pane comes forward stops the send', (+ tester,+ ) async {+ final (app, result) = await _open(tester);+ app.paneReady = Completer<void>();+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ await _say(tester, "what's the D3 retention rate");+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ app.paneReady!.complete();+ await tester.pump();+ expect(app.sent, isEmpty);+ expect(app.lastRoutedTask, isNull);+ expect(await result(), isNull);+ });++ testWidgets('new work is not followed up in the session before it', (+ tester,+ ) async {+ final (app, _) = await _open(tester);+ app.lastRoutedTask = (id: _session, at: DateTime.now());+ app.reply = (_) => {'decided': 'new', 'via': 'jev'};+ await _say(tester, 'write a script that plots signups by week');+ await tester.pumpAndSettle();+ expect(app.lastRoutedTask, isNull);+ });++ testWidgets('a spoken task keeps the dial button it was said with', (+ tester,+ ) async {+ final app = _App();+ addTearDown(app.dispose);+ app.reply = (_) => {'decided': 'session', 'id': _session, 'via': 'jev'};+ final reports = <(String, String)>[];+ final spoken = SpokenTask(+ voiceId: 'v1',+ text: 'ship the retention chart',+ cmd: 'goal',+ report: (_, state, agentId) => reports.add((state, agentId)),+ );+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showTaskPalette(context, app, spoken: spoken),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle(const Duration(seconds: 1));+ expect(app.sent, [('m', 'a0', '/goal ship the retention chart')]);+ expect(reports, [('taken', ''), ('sent', 'a0')]);+ });++ testWidgets('spoken new work is answered by whoever makes the harness', (+ tester,+ ) async {+ final app = _App();+ addTearDown(app.dispose);+ app.reply = (_) => {'decided': 'new', 'via': 'jev'};+ final reports = <String>[];+ final spoken = SpokenTask(+ voiceId: 'v1',+ text: 'plot signups by week',+ cmd: 'loop',+ report: (_, state, _) => reports.add(state),+ );+ Future<NewHarnessFromTask?>? result;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () =>+ result = showTaskPalette(context, app, spoken: spoken),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ final plan = await result!;+ expect(plan?.prompt, '/loop plot signups by week');+ expect(reports, ['taken']);+ });++ testWidgets('a daemon without the router leaves the card as it was', (+ tester,+ ) async {+ final (app, _) = await _open(tester);+ await _say(tester, "what's the D3 retention rate");+ expect(app.routed, ["what's the D3 retention rate"]);+ expect(app.sent, isEmpty);+ });+}diff --git a/desktop/test/route_screen_test.dart b/desktop/test/route_screen_test.dartnew file mode 100644index 000000000..9841877d3--- /dev/null+++ b/desktop/test/route_screen_test.dart@@ -0,0 +1,154 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/launch_setup.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_interactions_test.dart' show chord;+import 'swarm_screen_test.dart' show mount, terminal;+import 'swarm_state_test.dart' show createApp;++/// ⌘B on the workspace: new work is made at once, with the agent and folder+/// the router chose and the words as its task (docs/design/2026-10-09-auto-router.md).+class _Connection extends WsConn {+ _Connection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final asked = <String, Map<String, dynamic>>{};++ @override+ bool get isReady => true;++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ asked[type] = payload;+ return switch (type) {+ 'route_decide' => {+ 'decided': 'new',+ 'project': 'm\n/work/analytics',+ 'agent': 'codex',+ 'via': 'jev',+ },+ // Far enough: what was asked for is the test.+ 'agent_create' => throw const WsRequestTimeout('agent_create'),+ _ => {},+ };+ }+}++/// ⌘B, the task typed and Return pressed, on a desk with one session in /work/analytics.+Future<_Connection> _routeNewWork(+ WidgetTester tester, {+ Future<Map<String, dynamic>> Function(String, String)? git,+ void Function(AppNotifier app)? before,+}) async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ app.machineStates['m']!+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..localOnly = true+ ..localProjects = const {+ 'a0': AgentProject(name: 'analytics', cwd: '/work/analytics'),+ };+ // Not a Git project; a real disk read would never finish under the test's clock.+ app.gitProjectReaderForTest = git ?? (_, _) async => {'isGit': false};+ before?.call(app);+ app.adoptSessionForTest(terminal('a0', []));+ await app.addAgentToSwarm('m', 'a0');+ await mount(tester, app);++ await chord(tester, LogicalKeyboardKey.keyB);+ await tester.enterText(_taskField, 'plot signups by week');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(connection.asked['route_decide']?['text'], 'plot signups by week');+ return connection;+}++final _taskField = find.byWidgetPredicate(+ (widget) =>+ widget is TextField && widget.decoration?.hintText == 'Describe the work…',+);++void main() {+ testWidgets('⌘B makes new work at once, set up as the router chose', (+ tester,+ ) async {+ final connection = await _routeNewWork(tester);+ final create = connection.asked['agent_create'];+ expect(create, isNotNull);+ expect(create!['engine'], 'codex');+ expect(create['cwd'], '/work/analytics');+ expect(create['prompt'], 'plot signups by week');+ // Nobody chose otherwise: New Harness's own default.+ expect(create['permissionMode'], 'auto');+ expect(create['bypassPermission'], isTrue);+ await tester.pump(const Duration(seconds: 1));+ });++ testWidgets('new work starts in the permission mode the person last chose', (+ tester,+ ) async {+ final connection = await _routeNewWork(+ tester,+ before: (app) => app.agentPreference.successfulLaunch =+ const LaunchSetup(engine: 'codex', permissionMode: 'ask'),+ );+ final create = connection.asked['agent_create']!;+ expect(create['permissionMode'], 'ask');+ expect(create['bypassPermission'], isFalse);+ await tester.pump(const Duration(seconds: 1));+ });++ testWidgets(+ 'a project that could not be read opens New Harness on the task, never its checkout',+ (tester) async {+ final connection = await _routeNewWork(+ tester,+ git: (_, _) async => {'error': 'UNAVAILABLE'},+ );+ expect(connection.asked['agent_create'], isNull);+ await tester.pump(const Duration(seconds: 1));+ expect(find.text('plot signups by week'), findsWidgets);+ },+ );++ testWidgets(+ 'a session with a pane in another tab is brought forward there, never opened twice',+ (tester) async {+ final app = createApp(connectionForTest: (_) => _Connection());+ app.machineStates['m']!+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ app.adoptSessionForTest(terminal('a0', []));+ await app.addAgentToSwarm('m', 'a0');+ final backlog = app.activeSwarmId;+ app.newSwarm(name: 'Work', newTabPage: true);+ expect(app.activeSwarmId, isNot(backlog));+ final panes = app.allPanes.length;++ app.bringSessionForward('m', 'a0');++ expect(app.activeSwarmId, backlog);+ expect(app.focusedPane?.agentId, 'a0');+ expect(app.allPanes.length, panes);+ },+ );+}diff --git a/docs/design/2026-10-09-auto-router.md b/docs/design/2026-10-09-auto-router.mdnew file mode 100644index 000000000..4c80581b1--- /dev/null+++ b/docs/design/2026-10-09-auto-router.md@@ -0,0 +1,86 @@+# The router: say what you want and it is done++Status: built on branch `auto-router-session`, 2026-10-10. Experimental.++## What a person does++⌘B opens one text box. Type what you want and press Return. It decides where the+task goes and does it, without a list and without a question:++- **A session it belongs to, on any of your machines:** that session's own pane+ comes forward — in whichever tab holds it; a session with no pane gets one in+ the current tab — and the words go into its prompt. The box shows who took it for+ a moment, then closes.+- **New work:** a new harness starts with the words as its task, set up as ⌘N then+ Return would make it (a fresh worktree from main in a Git project, in the+ permission mode last chosen for that agent), in the project and with the agent+ the router chose. A line says which. A project that cannot be read opens New+ Harness on the task instead of guessing.+- **Nothing decided** — Jev cannot be reached (no key, offline, no credit) or the+ router fails: the box says so and sends nothing.++There is no undo; the owner chose instant sends. Esc while the session's pane comes+forward still stops the words before they are typed. The safety is the bar: a session+is chosen only when Jev is sure, and everything else becomes new work, which costs+little and pollutes nobody's conversation.++The goal is for this one box to replace both ⌘P (go to a session) and ⌘N (make+one). Until it has proved itself, ⌘P and ⌘N are unchanged. ⌘B is the only place+Harness uses Jev.++## Where it lives++**The router is a subsystem of its own** (`cli/src/services/router.ts`), an+experiment in its own process that the master starts at its first request. It is+not part of the core and not part of the devices: the desktop is one client of it,+and the phone, the web, the TUI and the dial are meant to be the others.++It only **decides**. A client sends the task with the sessions it can see (live+sessions on connected machines, most recently active first, at most forty, each+with its last prompts and its last three turn summaries), the person's project+folders and the agents they use (`desktop/lib/state/task_route.dart`). The router+answers "this session" or "new work, in this project, with this agent". The client+acts through its own doors: the desktop types the task into the session's pane+(`deliverTask`), or creates the harness (`_createFromTask`). So the router needs+nothing from the core, keeps no session list, and reaches no other machine.++Request (`ROUTER_REQUESTS` in `cli/src/core/api.ts`): `route_decide`. A daemon+without the router answers `UNSUPPORTED` and the box falls back to Boss mode's old+router; every other failure is nothing decided, never the old router, which sends on+its own when it is confident.++## How it decides++One request to **Jev 1.13** through OpenRouter's Decisions API+(`cli/src/lib/jev/jevClient.ts`, `cli/src/lib/routeDecide.ts`): "A person typed+this message to continue their work. Which of their ongoing sessions is it for?"+(or "none of them: new, unrelated work"), which project and which agent. A pick is+taken at 0.6 or more; below that the task is new work, and a project or agent Jev+is unsure of comes from the pane the person is in. The session the person last sent+to (within ten minutes) is told to Jev, so a short follow-up finds it.++The key is the person's OpenRouter key (`OPENROUTER_API_KEY`, `ori login`, or+`~/.config/typesafe/credentials`). The router logs OpenRouter's reported cost of+every answer.++## What was measured++- **Accuracy**, on 43 synthetic English prompts over four desks: Jev alone was+ right 91–95% of the time, depending on the bar, and sent nothing to a wrong+ session. A first version had a local model (julia-1) decide first; every wrong+ send in the tests and on the owner's desk was julia-1's, so it was dropped.+ Rewording Jev's question as the person continuing their work raised accuracy from+ 85% to 95%.+- **On the owner's desk** (three machines, about thirty sessions), deciding only:+ 15 of 18 English prompts went where they should; the misses were new work where+ Jev's top pick was right but under the bar.+- **Cost**: $0.000167 per decision on that desk (about 4,000 tokens), as OpenRouter+ reported it; about 6,000 decisions per dollar.+- **Time**: about 0.6 s per decision.++## Not done++- The other clients: the phone, the web, the TUI and the dial still use their own+ routing. Voice through the desktop already uses this box.+- Whether to take Jev's top session pick below 0.6 (it was right in both misses+ above) is open.