Skip to content

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.

fix: share one companion DSH, terminal, and learning model (#480)

Deea97029cad5c6
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index b544a9dba..c1583dbce 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -242,7 +242,7 @@ function boundedPrompt(prompt) {
return Buffer.byteLength(JSON.stringify(prompt)) <= 128 * 1024 ? prompt : ''
}
-function post(port, path, body) {
+function post(port, path, body, onResponse) {
return new Promise((resolve) => {
const payload = JSON.stringify(body)
const credential = readHookCredential()
@@ -261,8 +261,16 @@ function post(port, path, body) {
timeout: Math.max(1, Math.min(500, remainingBudget())),
},
(res) => {
- res.resume()
- res.on('end', () => resolve((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300))
+ let response = ''
+ res.setEncoding('utf8')
+ res.on('data', (chunk) => { if (response.length < 16_384) response += chunk })
+ res.on('end', () => {
+ const ok = (res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300
+ if (ok && onResponse && response.length <= 16_384) {
+ try { onResponse(JSON.parse(response)) } catch { /* Unavailable context never blocks a turn. */ }
+ }
+ resolve(ok)
+ })
}
)
req.on('error', () => resolve(false))
@@ -1547,8 +1555,8 @@ async function main() {
}
// SessionStart or UserPromptSubmit (the catch hook) → register the session. Registration is
- // idempotent, so re-registering on every prompt is cheap. (We print nothing to stdout, so this
- // never injects context into a UserPromptSubmit turn.)
+ // idempotent, so re-registering on every prompt is cheap. Ordinary agents receive no context.
+ // Only the daemon's verified collection agent receives its current companion persona.
// Command Code fires SessionStart BEFORE it writes the transcript, and the daemon validates the path
// (realpath) — sending one that isn't on disk yet gets the whole registration rejected. Announce
// without it; the session is registered again with the real path on the first Stop. Scoped to
@@ -1575,10 +1583,17 @@ async function main() {
model: modelName(input.model),
cliVersion: input.cli_version || input.cursor_version || input.version,
}
- const ok = await post(port, '/api/hook/session-start', body)
+ const ok = await post(port, '/api/hook/session-start', body, (response) => {
+ if (event !== 'UserPromptSubmit' || (engine !== 'claude' && engine !== 'codex')) return
+ if (typeof response.additionalContext !== 'string' || !response.additionalContext || response.additionalContext.length > 8_000) return
+ hookOutput = JSON.stringify({ hookSpecificOutput: {
+ hookEventName: 'UserPromptSubmit', additionalContext: response.additionalContext,
+ } })
+ })
if (!ok) await fallbackRegister(input, engine, tmuxPane)
}
+let hookOutput = null
main()
.catch(() => {})
.finally(() => {
@@ -1590,6 +1605,7 @@ main()
// — there `decision` is required, and `{}` reads as a denial (measured: every tool call of the turn
// came back "Tool call denied by pre-tool hook").
// Copilot parses stdout as JSON too; `{}` is the documented no-op for every event installed here.
- if (e === 'cursor' || e === 'hermes' || e === 'agy' || e === 'copilot') process.stdout.write('{}\n', () => process.exit(0))
+ if (hookOutput) process.stdout.write(`${hookOutput}\n`, () => process.exit(0))
+ else if (e === 'cursor' || e === 'hermes' || e === 'agy' || e === 'copilot') process.stdout.write('{}\n', () => process.exit(0))
else process.exit(0)
})
diff --git a/cli/src/cable/companionIdentity.ts b/cli/src/cable/companionIdentity.ts
index 25cb29be6..6d7643531 100644
--- a/cli/src/cable/companionIdentity.ts
+++ b/cli/src/cable/companionIdentity.ts
@@ -57,6 +57,8 @@ export class CompanionZoo {
private revision = -1
private seen = new Set<string>()
+ get uids(): string[] { return [...(this.previous?.keys() ?? [])] }
+
reset(): void { this.identity = null; this.milestone = null; this.previous = null; this.revision = -1; this.seen.clear() }
observe(zoo: unknown, now = Date.now(), revision?: number): void {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 58436198b..7c46fe513 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -93,6 +93,7 @@ import { PairToken } from './pair/token.js'
import { pairCommand as pairControlCommand, pairRequest, pairVerb, type PairClientDeps } from './pair/client.js'
import { serveMcp } from './pair/mcp.js'
import { PairHarness, type PairEngine } from './pair/pairHarness.js'
+import { CompanionIntelligence } from './pair/intelligence.js'
import { individualName, pairedIndividual } from './pair/individuals.js'
import { PlateService } from './pair/plateService.js'
import { inProjects, PairConfigFile, pairConfigPath, ruleRunner, type PairConfig } from './pair/rules.js'
@@ -217,7 +218,7 @@ import {
syncSummaryPoolSessions,
} from './lib/summarize.js'
import type { CableAgent } from './cable/cableSession.js'
-import { routeVoiceTask, runPairOneShot, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
+import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { E2eeStore } from './lib/e2ee/store.js'
import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'
@@ -1745,6 +1746,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
let pairTalk: (text: string, companionUid?: string) => Promise<Record<string, unknown>> = async () => ({ ok: false, error: 'UNSUPPORTED' })
/** A turn started or ended on the pair harness: it is in use (its idle pause waits). Bound with it. */
let pairHarnessActivity: (agentId: string) => void = () => {}
+ let companionPromptContext: (agentId: string) => string | null = () => null
+ let companionProfileChanged: () => void = () => {}
+ let isCollectionAgent: (agentId: string) => boolean = () => false
/** The person's pair.jsonc (pair/rules.ts): the model opt-in, learning's opt-ins, and the rules act-within-rules runs here. */
const pairConfig = new PairConfigFile(pairConfigPath())
/** pair.jsonc as the person confirmed it (pair/gate.ts): a new or changed file waits for their yes. */
@@ -2965,6 +2969,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
runtimeProfiles.onChanged = (sessionId) => {
const session = registry.resolve(sessionId)
if (session) syncSession(session)
+ companionProfileChanged()
}
// Turn heartbeat (5s): pushes `turn_heartbeat` to the web while the turn is open (keeps its 10s
@@ -3127,9 +3132,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// to the device and self-cancels once mirror.heartbeat() reports idle (summary done).
}
}
- // Learning notices only what the sensor would: pairing on, never a sub-agent, a terminal or the pair itself.
+ // Real work and the person's collection conversation can teach lessons. Archived
+ // pair chats, sub-agents and replay stay excluded. Tool-free background reviews
+ // never register as agents, so they cannot feed their own results back in here.
const learnFrom = registry.bySession(sessionId)
- if (learnFrom && pairSensor.enabled() && !isTerminalEngine(learnFrom.engine) && !isSubagentSession(sessionId) && !isPairHarnessSession(sessionId)) {
+ if (learnFrom && pairSensor.enabled() && !isTerminalEngine(learnFrom.engine) && !isSubagentSession(sessionId) &&
+ (!isPairHarnessSession(sessionId) || isCollectionAgent(learnFrom.agentId))) {
lessonSignals.ingest({ agentId: learnFrom.agentId, sessionId, engine: learnFrom.engine, cwd: learnFrom.cwd ?? null }, events,
{ replay: !!(opts?.resumed || opts?.replay) })
}
@@ -3908,6 +3916,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const { server: hookServer, port: hookPort, localSocket } = await startHookServer(env.PORT, {
+ onPromptContext: (agentId) => companionPromptContext(agentId),
onCommandBar: commandBarService,
onAutonomousDeviceRequest: async (method, target, body) => {
if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }
@@ -4488,6 +4497,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
pairedDaemon: () => pairSensor.pairedDaemon(),
pairedName: () => pairSensor.pairedName(),
pairedUid: () => zooPair.known ? companionZoo.identity?.uid ?? null : guestCompanion?.uid ?? null,
+ collectionUids: () => zooPair.known ? companionZoo.uids : guestCompanion ? [guestCompanion.uid] : [],
engine: async () => {
const found = await probeEngines(['claude', 'codex']).catch(() => [])
return (['claude', 'codex'] as PairEngine[]).find((engine) => found.some((e) => e.engine === engine && e.installed)) ?? null
@@ -4505,8 +4515,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
find: () => {
const live = registry.advertised()
return [
- ...live.filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'live' as const, hasConversation: !!s.sessionId })),
- ...stoppedAgents.available(live).filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'stopped' as const, hasConversation: !!s.sessionId })),
+ ...live.filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'live' as const, engine: s.engine as PairEngine, hasConversation: !!s.sessionId })),
+ ...stoppedAgents.available(live).filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'stopped' as const, engine: s.engine as PairEngine, hasConversation: !!s.sessionId })),
]
},
create: async ({ engine, cwd, prompt, name }) => {
@@ -4531,14 +4541,37 @@ async function runForeground(session: AuthSession | null): Promise<void> {
now: Date.now,
})
pairTalk = (text, uid) => pairHarness.talk(text, uid)
+ isCollectionAgent = (agentId) => agentId === pairHarness.agentId()
+ companionPromptContext = (agentId) => daemons.on() ? pairHarness.context(agentId) : null
pairHarnessActivity = (agentId) => { if (daemons.on()) pairHarness.activity(agentId) }
- // THE LEARNER (pair/learn/propose.ts): distills what this machine noticed while nothing is working — a model
- // only with pair.jsonc "model": true — and, when you are at this computer, proposes one lesson at a time.
+ const companionIntelligence = new CompanionIntelligence({
+ enabled: () => daemons.on() && !!pairSensor.pairedDaemon(),
+ current: () => {
+ const agentId = pairHarness.agentId()
+ if (!agentId) return null
+ const live = registry.advertised().find(s => s.agentId === agentId)
+ const session = live ?? stoppedAgents.get(agentId)
+ if (!session || session.dsh !== PAIR_HARNESS_DSH) return null
+ return { agentId, sessionId: session.sessionId, engine: session.engine,
+ profile: runtimeProfiles.selectedModel(session), stopped: !live,
+ codexHome: session.codexHome, customProvider: !!(session.grid || session.gridLaunch || session.gateway) }
+ },
+ directory: join(env.ADAPTER_DATA_DIR, 'pair', 'reasoning'),
+ stateFile: join(env.ADAPTER_DATA_DIR, 'pair', 'intelligence.json'),
+ })
+ companionProfileChanged = () => { companionIntelligence.status(); pairBrain?.stateChanged() }
+ // The collection's DSH supplies learning and triage with its observed model. The
+ // experiment and watching consent still gate everything; there is no second model switch.
const lessonProjects = (): string[] =>
[...new Set([...registry.advertised(), ...stoppedAgents.available(registry.advertised())].map((s) => s.cwd).filter((cwd): cwd is string => !!cwd))]
pairLearner = new PairLearner({
store: lessonStore,
- distiller: new LessonDistiller({ oneshot: (prompt, opts) => runPairOneShot(prompt, opts, registry.active()), modelEnabled: () => pairRulesConfig().model, now: Date.now, home: homedir() }),
+ distiller: new LessonDistiller({ oneshot: companionIntelligence.run, modelEnabled: () => companionIntelligence.ready(), now: Date.now, home: homedir() }),
+ intelligence: () => companionIntelligence.status(),
+ queueFile: () => {
+ const id = pairHarness.agentId()
+ return id ? join(env.ADAPTER_DATA_DIR, 'pair', 'learn', `queue-${id}.json`) : null
+ },
pairedDaemon: () => pairSensor.pairedDaemon(),
autonomy: () => pairAutonomy(),
voice: pairVoice,
@@ -4586,8 +4619,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
pairBrain = new PairBrain({
pairing: { enabled: () => pairSensor.enabled(), pairedDaemon: () => pairSensor.pairedDaemon() },
fleet: pairFleet,
- // A model's words only when the person opted in (pair.jsonc "model": true).
- triage: new PairTriage({ oneshot: (prompt, opts) => runPairOneShot(prompt, opts, registry.active()), modelEnabled: () => pairRulesConfig().model, now: Date.now }),
+ // Template first, then this collection's selected model when it is ready.
+ triage: new PairTriage({ oneshot: companionIntelligence.run, modelEnabled: () => companionIntelligence.ready(), now: Date.now, budgetMs: 30_000 }),
+ companionHarness: () => ({ agentId: pairHarness.agentId(), ...companionIntelligence.status() }),
voice: pairVoice,
proposals: joinProposals(pairControl, pairLearner),
autonomy: () => pairAutonomy(),
@@ -4612,6 +4646,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onGuestConsent: (watching) => { guestConsent = watching; applyPair() },
onActiveChanged: (active) => setVoiceRouterDeviceConnected(backend.hasCommander() || active),
talk: (text, uid) => pairTalk(text, uid),
+ open: (uid) => pairHarness.open(uid),
now: Date.now,
})
// DAEMONS ON AND OFF (lib/daemonsSwitch.ts): the only timers the pair keeps whatever happens — the learner's
@@ -4622,7 +4657,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
let pairConfigTick: ReturnType<typeof setInterval> | null = null
onDaemonsChanged = (on) => {
plates.setOn(on)
- if (!on) { companionZoo.reset(); guestCompanion = null }
if (on) {
// pair.jsonc is read when something needs it, and on this tick: a "daemons": false in it switches
// everything off within the tick (before the rest of the file is read), and any other change asks for
@@ -4639,6 +4673,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
zooTurnReporter.clear()
zooLessonReporter.clear()
void pairHarness.off().catch(() => {})
+ companionIntelligence.cancel()
+ companionZoo.reset(); guestCompanion = null
}
applyPair()
pairBrain?.refresh()
@@ -4943,6 +4979,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (off) { reply({ type: 'daemon_talk_result', payload: { requestId: payload.requestId, ok: false, error: off, ...(off === DAEMONS_OFF ? { detail: DAEMONS_OFF_DETAIL } : {}) } }); return }
void pairBrain!.onTalk(connId, payload, (frame) => { reply(frame) })
},
+ onDaemonOpen: (connId, payload, reply) => {
+ const off = !daemons.on() ? DAEMONS_OFF : !pairBrain ? 'UNSUPPORTED' : null
+ if (off) { reply({ type: 'daemon_open_result', payload: { requestId: payload.requestId, ok: false, error: off, ...(off === DAEMONS_OFF ? { detail: DAEMONS_OFF_DETAIL } : {}) } }); return }
+ void pairBrain!.onOpen(connId, payload, (frame) => { reply(frame) })
+ },
// Presence: whether the person is here (the zoo's away turns) always; the rest only while daemons are
// on. Signed out, a window bound to this machine saying its guest zoo has the person's consent is what
// turns them on (guests keep working as before, but only when a window asks).
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 1d68d2796..bf7717a3a 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -127,14 +127,14 @@ function runHook(opts: RunHookOpts): Promise<string> {
}
/** A throwaway localhost adapter that records every hook POST. */
-async function collect(): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {
+async function collect(response: Record<string, unknown> = {}): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {
const requests: Array<{ url: string; body: Record<string, unknown> }> = []
const server = createServer((req, res) => {
let raw = ''
req.on('data', (chunk) => { raw += chunk.toString() })
req.on('end', () => {
requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
- res.end('{}')
+ res.end(JSON.stringify(response))
})
})
servers.push(server)
@@ -145,6 +145,16 @@ async function collect(): Promise<{ port: number; requests: Array<{ url: string;
}
describe('hook notify terminal scope', () => {
+ it.each(['claude', 'codex'] as const)('adds daemon-verified companion context to the actual %s user turn', async engine => {
+ const additionalContext = 'Companions collection context: selected GNU; retain this conversation.'
+ const { port, requests } = await collect({ ok: true, additionalContext })
+ const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))
+ const input = recordings[engine].input
+ const stdout = await runHook({ port, engine, tmuxPane: '%42', input })
+ expect(JSON.parse(stdout)).toEqual({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext } })
+ expect(requests[0]?.body.prompt).toBe(input.prompt)
+ expect(await runHook({ port, engine, tmuxPane: '%42', input: { ...input, hook_event_name: 'SessionStart' } })).toBe('')
+ })
it.each(['claude', 'codex', 'grok'] as const)('forwards the actual %s accepted prompt without changing the model input', async engine => {
const { port, requests } = await collect()
const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 5a1aeb7f3..9b16b3142 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -66,17 +66,20 @@ describe('process-owned hook server', () => {
it('attributes prompt text only after resolving the actual engine process', async () => {
const entry = { engine: 'claude', agentId: 'agent-scope', sessionId: 'session-scope', runtimes: [{ backend: 'tmux', paneId: '%41' }] } as RegisteredSession
const onPromptSubmitted = vi.fn()
+ const onPromptContext = vi.fn(() => 'Companions collection context')
const resolveHookAgent = vi.fn(async () => null as RegisteredSession | null)
const registration = vi.spyOn(registry, 'register').mockReturnValue({ entry, isNew: false, evicted: null, rebound: null, orphaned: null })
try {
- const { base, headers } = await start({ onPromptSubmitted, resolveHookAgent })
+ const { base, headers } = await start({ onPromptSubmitted, onPromptContext, resolveHookAgent })
const submit = () => fetch(`${base}/api/hook/session-start`, { method: 'POST', headers, body: JSON.stringify({
engine: 'claude', sessionId: entry.sessionId, tmuxPane: '%41', hookEvent: 'UserPromptSubmit', prompt: 'ask a peer\nfor evidence',
}) })
await submit()
expect(onPromptSubmitted).not.toHaveBeenCalled()
+ expect(onPromptContext).not.toHaveBeenCalled()
resolveHookAgent.mockResolvedValue(entry)
- expect((await submit()).status).toBe(200)
+ expect(await (await submit()).json()).toEqual({ ok: true, additionalContext: 'Companions collection context' })
+ expect(onPromptContext).toHaveBeenCalledExactlyOnceWith('agent-scope')
expect(onPromptSubmitted).toHaveBeenCalledExactlyOnceWith('agent-scope', 'ask a peer\nfor evidence')
} finally { registration.mockRestore() }
})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 9c4449cc3..d09e0fe6f 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -56,6 +56,8 @@ export interface PairOutcome {
}
export interface HookServerHandlers {
+ /** Context for a verified process-owned agent, only on its real user turn. */
+ onPromptContext?: (agentId: string) => string | null
onCommandBar?: Pick<CommandBarService, 'status' | 'decide'>
onAutonomousDeviceRequest?: (method: string, target: string, body?: unknown) => Promise<{ status: number; body: unknown }>
@@ -553,7 +555,9 @@ export function startHookServer(
}
console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`)
handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
- json(200, { ok: true })
+ const context = body.hookEvent === 'UserPromptSubmit' && (engine === 'claude' || engine === 'codex')
+ ? handlers.onPromptContext?.(result.entry.agentId) : null
+ json(200, { ok: true, ...(context ? { additionalContext: context } : {}) })
return
}
diff --git a/cli/src/lib/companionOneShot.spec.ts b/cli/src/lib/companionOneShot.spec.ts
new file mode 100644
index 000000000..38334c1e3
--- /dev/null
+++ b/cli/src/lib/companionOneShot.spec.ts
@@ -0,0 +1,39 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { runCodexOneShot } from './oneshot.js'
+
+let directory: string | null = null
+afterEach(() => { vi.unstubAllEnvs(); if (directory) rmSync(directory, { recursive: true, force: true }) })
+
+describe('the companion Codex review worker', () => {
+ it('keeps its selected login, model and effort and cannot be discovered as a terminal agent', async () => {
+ directory = mkdtempSync(join(tmpdir(), 'companion-worker-'))
+ const binary = join(directory, 'codex-fixture')
+ const capture = join(directory, 'launch.json')
+ writeFileSync(binary, `#!${process.execPath}
+const fs = require('node:fs');
+let prompt = '';
+process.stdin.on('data', data => prompt += data);
+process.stdin.on('end', () => {
+ fs.writeFileSync(${JSON.stringify(capture)}, JSON.stringify({args: process.argv.slice(2), prompt,
+ codexHome: process.env.CODEX_HOME, tmux: process.env.TMUX, pane: process.env.TMUX_PANE}));
+ fs.writeFileSync(process.argv[process.argv.indexOf('--output-last-message') + 1], '{"lesson":null}');
+});
+`, { mode: 0o700 })
+ vi.stubEnv('CODEX_PATH', binary)
+ vi.stubEnv('TMUX', 'a-real-terminal')
+ vi.stubEnv('TMUX_PANE', '%42')
+ const profile = join(directory, 'selected-login')
+ expect(await runCodexOneShot({ prompt: 'review only this evidence', cwd: directory,
+ codexHome: profile, model: 'selected-model', effort: 'xhigh', timeoutMs: 3000 })).toEqual({ text: '{"lesson":null}', sessionId: null })
+ const launch = JSON.parse(readFileSync(capture, 'utf8'))
+ expect(launch.codexHome).toBe(profile)
+ expect(launch.args).toEqual(expect.arrayContaining(['--model', 'selected-model', 'model_reasoning_effort="xhigh"',
+ '--ephemeral', '--sandbox', 'read-only', '--ignore-user-config', '--ignore-rules']))
+ expect(launch.tmux).toBeUndefined()
+ expect(launch.pane).toBeUndefined()
+ expect(launch.prompt.trim()).toBe('review only this evidence')
+ })
+})
diff --git a/cli/src/lib/daemonsSwitch.spec.ts b/cli/src/lib/daemonsSwitch.spec.ts
index a76548dfa..a31cf02dd 100644
--- a/cli/src/lib/daemonsSwitch.spec.ts
+++ b/cli/src/lib/daemonsSwitch.spec.ts
@@ -458,7 +458,7 @@ describe('cli.ts routes everything daemon-related through the switch', () => {
})
it('gates the reporters, turns, lessons, the pair harness, the pair request and every daemon_* frame', () => {
- expect(source.match(/enabled: \(\) => daemons\.on\(\)/g)).toHaveLength(2)
+ expect(source.match(/enabled: \(\) => daemons\.on\(\)/g)).toHaveLength(3)
expect(source).toContain('if (daemons.on()) zooTurnCounter.started(')
expect(source).toContain('if (learnFrom && daemons.on() && !isTerminalEngine(learnFrom.engine)) {')
expect(source).toContain('if (!daemons.on()) return null') // lessons in launches
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index 7d7abbce5..f774ab171 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -82,7 +82,9 @@ function buildEnv(): NodeJS.ProcessEnv {
export interface OneShotOptions {
prompt: string
model?: string
- effort?: 'low' | 'medium' | 'high'
+ effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra' | 'ultracode'
+ /** The collection agent's own Codex login profile, when it has one. */
+ codexHome?: string
cwd: string
timeoutMs?: number
signal?: AbortSignal
@@ -280,7 +282,7 @@ class CodexWorker extends ProcessWorker {
onAbort: () => void
} | null = null
- constructor(cwd: string, model?: string, effort?: OneShotOptions['effort']) {
+ constructor(cwd: string, model?: string, effort?: OneShotOptions['effort'], codexHome?: string) {
const output = join(cwd, `.codex-recap-${randomUUID()}.txt`)
const args = [
'exec', '--json', '--ephemeral', '--sandbox', 'read-only', '--skip-git-repo-check',
@@ -290,6 +292,7 @@ class CodexWorker extends ProcessWorker {
'-',
]
const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
+ if (codexHome) processEnv.CODEX_HOME = codexHome
const child = spawn(process.env.CODEX_PATH || 'codex', args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'ignore', 'pipe'],
})
@@ -951,11 +954,12 @@ function createOneShotWorker(
cwd: string,
model?: string,
effort?: OneShotOptions['effort'],
+ codexHome?: string,
): Promise<DisposableWorker<OneShotOptions, OneShotResult>> {
return engine === 'claude'
? new ClaudeWorker(cwd, model, effort).ready()
: engine === 'codex'
- ? new CodexWorker(cwd, model, effort).ready()
+ ? new CodexWorker(cwd, model, effort, codexHome).ready()
: engine === 'cursor'
? new CursorWorker(cwd, model).ready()
: engine === 'pi'
@@ -968,7 +972,7 @@ function createOneShotWorker(
}
async function runDirect(engine: OneShotEngine, opts: OneShotOptions): Promise<OneShotResult> {
- const worker = await createOneShotWorker(engine, opts.cwd, opts.model, opts.effort)
+ const worker = await createOneShotWorker(engine, opts.cwd, opts.model, opts.effort, opts.codexHome)
try { return await worker.run(opts) } finally { worker.dispose() }
}
@@ -982,7 +986,7 @@ export function runClaudeOneShot(opts: OneShotOptions): Promise<OneShotResult> {
export function runCodexOneShot(opts: OneShotOptions): Promise<{ text: string; sessionId: null }> {
if (opts.signal?.aborted) return Promise.reject(abortError('codex'))
- const run = !config || config.cwd !== opts.cwd || config.codexModel !== opts.model || config.effort !== opts.effort
+ const run = opts.codexHome || !config || config.cwd !== opts.cwd || config.codexModel !== opts.model || config.effort !== opts.effort
? runDirect('codex', opts)
: pool.run('codex', opts)
return run.then((result) => ({ text: result.text, sessionId: null }))
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 528b491e4..0d5603c6e 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -126,24 +126,6 @@ export function setVoiceRouterSessions(sessions: Array<{ engine: string }>): voi
ensureRouterConfigured(next)
}
-/**
- * One small prompt for the pair brain (pair/triage.ts), on the same warm router worker and model the voice
- * router classifies with — Haiku for Claude. The caller owns the budget. Null when this machine runs no
- * engine the router can use; the brain then speaks from its templates.
- */
-export async function runPairOneShot(
- prompt: string,
- opts: { timeoutMs: number; signal?: AbortSignal },
- sessions: Array<{ engine: string }>,
-): Promise<string | null> {
- const engine = chooseRouterEngine(sessions) ?? routerEngine
- if (!engine) return null
- const options = { prompt, model: routerModelFor(engine), effort: 'low' as const, cwd: ensureRouteScratch(), signal: opts.signal, timeoutMs: opts.timeoutMs }
- if (engine === 'grok') return (await runGrokOneShot(options)).text ?? ''
- ensureRouterConfigured(engine)
- return (await runRouterOneShot(engine, options)).text ?? ''
-}
-
/** Warm (device connected) / unwarm the router worker — wired to commander presence in cli.ts. */
export function setVoiceRouterDeviceConnected(connected: boolean): void {
// Config must be set before the pool spawns a warm worker. With no usable engine there is nothing to
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 51733e142..797740d98 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -673,6 +673,7 @@ describe('local CLI WebSocket', () => {
relayPool: relayPool as unknown as NonNullable<Parameters<typeof attachLocalWsServer>[1]['relayPool']>,
onDaemonAct: (_connId, payload, reply) => { got.push(['act', payload]); reply({ type: 'daemon_act_result', payload: { requestId: payload.requestId, ok: true } }) },
onDaemonTalk: (_connId, payload, reply) => { got.push(['talk', payload]); reply({ type: 'daemon_talk_result', payload: { requestId: payload.requestId, ok: true } }) },
+ onDaemonOpen: (_connId, payload, reply) => { got.push(['open', payload]); reply({ type: 'daemon_open_result', payload: { requestId: payload.requestId, ok: true } }) },
onDaemonConfirm: (_connId, payload, reply) => { got.push(['confirm', payload]); reply({ type: 'daemon_confirm_result', payload: { requestId: payload.requestId, ok: true } }) },
onDaemonShown: (_connId, payload) => { got.push(['shown', payload]) },
onDaemonPresence: (_connId, payload, meta) => { presence.push({ payload, ui: meta.ui }) },
@@ -691,7 +692,10 @@ describe('local CLI WebSocket', () => {
result = onceMessage(ws)
ws.send(JSON.stringify({ type: 'daemon_confirm', payload: { requestId: 'c1', kind: 'autonomy', nonce: 'n1', accept: true } }))
expect(await result).toEqual({ type: 'daemon_confirm_result', payload: { requestId: 'c1', ok: true } })
- expect(got.map(([kind]) => kind)).toEqual(['shown', 'act', 'talk', 'confirm'])
+ result = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'o1', companionUid: 'tim-one' } }))
+ expect(await result).toEqual({ type: 'daemon_open_result', payload: { requestId: 'o1', ok: true } })
+ expect(got.map(([kind]) => kind)).toEqual(['shown', 'act', 'talk', 'confirm', 'open'])
expect(presence).toEqual([{ payload: { active: true, awayMs: 0 }, ui: true }])
ws.close()
@@ -705,6 +709,9 @@ describe('local CLI WebSocket', () => {
result = onceMessage(tcp)
tcp.send(JSON.stringify({ type: 'daemon_confirm', payload: { requestId: 'c2', kind: 'rules', nonce: 'n2' } }))
expect(await result).toMatchObject({ type: 'daemon_confirm_result', payload: { requestId: 'c2', kind: 'rules', nonce: 'n2', ok: false, error: 'LOCAL_SOCKET_REQUIRED' } })
+ result = onceMessage(tcp)
+ tcp.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'blocked-open', companionUid: 'tim-one' } }))
+ expect(await result).toMatchObject({ type: 'daemon_open_result', payload: { ok: false, error: 'LOCAL_SOCKET_REQUIRED' } })
tcp.close()
// A tool (`harness pair`, the MCP server) is not a window, even over the socket.
@@ -712,6 +719,9 @@ describe('local CLI WebSocket', () => {
result = onceMessage(tool)
tool.send(JSON.stringify({ type: 'daemon_talk', payload: { requestId: 't3', text: 'hi' } }))
expect(await result).toMatchObject({ type: 'daemon_talk_result', payload: { requestId: 't3', ok: false, error: 'UI_ONLY' } })
+ result = onceMessage(tool)
+ tool.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'blocked-open', companionUid: 'tim-one' } }))
+ expect(await result).toMatchObject({ type: 'daemon_open_result', payload: { ok: false, error: 'UI_ONLY' } })
tool.close()
// A relayed machine's socket: its presence is a fact about this desk; a key on it is not a window's.
@@ -720,9 +730,12 @@ describe('local CLI WebSocket', () => {
result = onceMessage(relay)
relay.send(JSON.stringify({ type: 'daemon_act', payload: { requestId: 'r4', id: 'need:x', choice: 'y' } }))
expect(await result).toMatchObject({ type: 'daemon_act_result', payload: { requestId: 'r4', ok: false, error: 'UI_ONLY' } })
+ result = onceMessage(relay)
+ relay.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'blocked-open', companionUid: 'tim-one' } }))
+ expect(await result).toMatchObject({ type: 'daemon_open_result', payload: { ok: false, error: 'UI_ONLY' } })
relay.close()
- expect(got.map(([kind]) => kind)).toEqual(['shown', 'act', 'talk', 'confirm'])
+ expect(got.map(([kind]) => kind)).toEqual(['shown', 'act', 'talk', 'confirm', 'open'])
expect(presence.map((p) => p.ui)).toEqual([true, false])
// Neither this daemon's dispatcher (whose send() uploads) nor the relayed machine ever saw one.
expect(backend.frames).toEqual([])
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 462bf26ac..d6863c008 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -130,6 +130,7 @@ export interface LocalWsServerOptions {
onDaemonPresence?: (connId: string, payload: Record<string, unknown>, meta: { ui: boolean }) => void
/** `daemon_talk { requestId, text }`: the person's words to their daemon (the pair harness) → `daemon_talk_result`. */
onDaemonTalk?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => void
+ onDaemonOpen?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => void
/** `daemon_shown { id }`: this window has displayed that line, detail and all. */
onDaemonShown?: (connId: string, payload: Record<string, unknown>) => void
/** `daemon_confirm { requestId, kind, nonce, accept }` → `daemon_confirm_result`. */
@@ -149,7 +150,7 @@ export interface LocalWsServerOptions {
/** The pair brain's frames from a window (pair/protocol.ts DAEMON_IN_TYPES). */
const DAEMON_IN = DAEMON_IN_TYPES
/** The reply each request among them gets. */
-const DAEMON_RESULT: Record<string, string> = { daemon_act: 'daemon_act_result', daemon_talk: 'daemon_talk_result', daemon_confirm: 'daemon_confirm_result' }
+const DAEMON_RESULT: Record<string, string> = { daemon_act: 'daemon_act_result', daemon_talk: 'daemon_talk_result', daemon_open: 'daemon_open_result', daemon_confirm: 'daemon_confirm_result' }
/** One candidate, as the window draws it in the picker. */
export interface RouteCandidate {
@@ -675,7 +676,7 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
if (!ui) { answer({ ok: false, error: 'UI_ONLY', detail: 'Keys, talk and confirmations come from a window on this machine\'s own socket.' }); return }
const reply = (frame: Frame): boolean => sink.sendFrame(frame)
if (type === 'daemon_shown') { options.onDaemonShown?.(connId, payload); return }
- const handler = type === 'daemon_act' ? options.onDaemonAct : type === 'daemon_talk' ? options.onDaemonTalk : options.onDaemonConfirm
+ const handler = type === 'daemon_act' ? options.onDaemonAct : type === 'daemon_talk' ? options.onDaemonTalk : type === 'daemon_open' ? options.onDaemonOpen : options.onDaemonConfirm
if (handler) { handler(connId, payload, reply); return }
answer({ ok: false, error: 'UNSUPPORTED' })
return
diff --git a/cli/src/pair/brain.spec.ts b/cli/src/pair/brain.spec.ts
index 9daf21fdd..36524fcf9 100644
--- a/cli/src/pair/brain.spec.ts
+++ b/cli/src/pair/brain.spec.ts
@@ -67,7 +67,7 @@ function laptop() {
return { sensor, open, answers, links, reply: (r: Frame) => { answerReply = r } }
}
-function world(opts: { oneshot?: PairOneShot | null; answer?: (i: { agentId: string; requestId: string; choice: string }) => Promise<AnswerResult>; linked?: boolean; model?: boolean; autonomy?: Autonomy; relayLimits?: Array<{ windowMs: number; max: number }>; talk?: (text: string) => Promise<Frame>; proposals?: ConstructorParameters<typeof PairBrain>[0]['proposals']; lessonKey?: ConstructorParameters<typeof PairBrain>[0]['lessonKey'] } = {}) {
+function world(opts: { oneshot?: PairOneShot | null; answer?: (i: { agentId: string; requestId: string; choice: string }) => Promise<AnswerResult>; linked?: boolean; model?: boolean; autonomy?: Autonomy; relayLimits?: Array<{ windowMs: number; max: number }>; talk?: (text: string) => Promise<Frame>; open?: (uid?: string) => Promise<Frame>; proposals?: ConstructorParameters<typeof PairBrain>[0]['proposals']; lessonKey?: ConstructorParameters<typeof PairBrain>[0]['lessonKey'] } = {}) {
const local = sensorFor('machine-a')
const remote = laptop()
const frames: Frame[] = []
@@ -96,6 +96,7 @@ function world(opts: { oneshot?: PairOneShot | null; answer?: (i: { agentId: str
relayed: (fields) => { local.relayed(fields) },
...(opts.relayLimits ? { relayLimits: opts.relayLimits } : {}),
...(opts.talk ? { talk: opts.talk } : {}),
+ ...(opts.open ? { open: opts.open } : {}),
...(opts.proposals ? { proposals: opts.proposals } : {}),
...(opts.lessonKey ? { lessonKey: opts.lessonKey } : {}),
})
@@ -319,6 +320,22 @@ describe('the brain', () => {
expect(talked).toHaveLength(7)
})
+ it('only an attached window can open its companion terminal, without a talk or cost', async () => {
+ const open = vi.fn(async () => ({ ok: true, agentId: 'pair-tim' }))
+ const w = world({ open })
+ const replies: Frame[] = []
+ const send = (f: Frame) => { replies.push(f) }
+ await w.brain.onOpen('tool', { requestId: 'o1', companionUid: 'tim-one' }, send)
+ expect(replies.pop()?.payload).toMatchObject({ ok: false, error: 'UI_ONLY' })
+ expect(open).not.toHaveBeenCalled()
+ w.brain.clientAttached('window')
+ await w.brain.onOpen('window', { requestId: 'o2' }, send)
+ expect(replies.pop()?.payload).toMatchObject({ ok: false, error: 'STALE_COMPANION' })
+ await w.brain.onOpen('window', { requestId: 'o3', companionUid: 'tim-one' }, send)
+ expect(open).toHaveBeenCalledWith('tim-one')
+ expect(replies.pop()).toEqual({ type: 'daemon_open_result', payload: { requestId: 'o3', ok: true, agentId: 'pair-tim' } })
+ })
+
it('a key counts only from the window that was shown the line, a moment after it was shown', async () => {
const w = world()
w.brain.clientAttached('local:window')
diff --git a/cli/src/pair/brain.ts b/cli/src/pair/brain.ts
index c16fd35cc..1083f65c2 100644
--- a/cli/src/pair/brain.ts
+++ b/cli/src/pair/brain.ts
@@ -89,6 +89,10 @@ export interface PairBrainDeps {
shown?: ShownLines
/** `daemon_talk`: the person's words to the pair harness (pair/pairHarness.ts), which starts or wakes. */
talk?: (text: string, companionUid?: string) => Promise<Record<string, unknown>>
+ /** Open the pair's terminal without typing into it or starting a model turn. */
+ open?: (companionUid?: string) => Promise<Record<string, unknown>>
+ /** The collection's persistent agent and its observed model. Local windows only. */
+ companionHarness?: () => Record<string, unknown>
/** How many keys may be relayed to other machines, per window (RELAY_LIMITS unless a spec says). */
relayLimits?: Array<{ windowMs: number; max: number }>
/**
@@ -520,6 +524,18 @@ export class PairBrain {
reply(result)
}
+ /** A local window opens its companion's DSH terminal, including engine setup. */
+ async onOpen(connId: string, payload: Record<string, unknown>, send: (frame: Record<string, unknown>) => void): Promise<void> {
+ const requestId = str(payload.requestId, 120)
+ const reply = (fields: Record<string, unknown>): void => { send({ type: 'daemon_open_result', payload: { requestId, ...fields } }) }
+ if (!this.clients.has(connId)) { reply({ ok: false, error: 'UI_ONLY' }); return }
+ if (!this.deps.open) { reply({ ok: false, error: 'UNSUPPORTED' }); return }
+ const uid = str(payload.companionUid, 64)
+ if (!uid) { reply({ ok: false, error: 'STALE_COMPANION' }); return }
+ const result = await this.deps.open(uid).catch((err): Record<string, unknown> => ({ ok: false, error: 'FAILED', detail: err instanceof Error ? err.message.slice(0, 200) : undefined }))
+ reply(result)
+ }
+
/** `daemon_shown { id }`: this window has drawn that line (its keys, and its detail in full). */
onShown(connId: string, payload: Record<string, unknown>): void {
const id = str(payload.id, 200)
@@ -659,6 +675,7 @@ export class PairBrain {
})
return {
pair: daemonId,
+ ...(this.deps.companionHarness ? { companionHarness: this.deps.companionHarness() } : {}),
needs,
working: harnesses.filter((h) => h.harness.working && !h.harness.question).length,
failing: harnesses.filter((h) => h.harness.failing).map((h) => ({
diff --git a/cli/src/pair/intelligence.spec.ts b/cli/src/pair/intelligence.spec.ts
new file mode 100644
index 000000000..39d07bb31
--- /dev/null
+++ b/cli/src/pair/intelligence.spec.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { CompanionIntelligence, type CompanionRuntime } from './intelligence.js'
+import { encodeRuntimeProfile } from '../lib/runtimeProfile.js'
+import type { OneShotOptions } from '../lib/oneshot.js'
+
+let directory: string
+beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'collection-model-')) })
+afterEach(() => { rmSync(directory, { recursive: true, force: true }) })
+
+function world() {
+ let enabled = true
+ let runtime: CompanionRuntime | null = { agentId: 'collection', sessionId: 'session-1', engine: 'claude', stopped: false,
+ profile: encodeRuntimeProfile({ sessionId: 'collection', engine: 'claude', model: 'opus', effort: 'high' }) }
+ const run = vi.fn<(engine: 'claude' | 'codex', options: OneShotOptions) => Promise<{ text: string }>>(async () => ({ text: '{"lesson":null}' }))
+ const deps = { enabled: () => enabled, current: () => runtime, run, directory, stateFile: join(directory, 'model.json') }
+ return { brain: new CompanionIntelligence(deps), deps, run,
+ off: () => { enabled = false }, set: (next: CompanionRuntime | null) => { runtime = next }, get: () => runtime! }
+}
+
+describe('the collection DSH supplies its intelligence', () => {
+ it('inherits the exact observed engine, model, effort and changes with the model picker', async () => {
+ const w = world()
+ expect(w.brain.status()).toMatchObject({ state: 'ready', model: 'opus', effort: 'high' })
+ await w.brain.run('review evidence', { timeoutMs: 1000, signal: new AbortController().signal })
+ expect(w.run).toHaveBeenLastCalledWith('claude', expect.objectContaining({ model: 'opus', effort: 'high', prompt: 'review evidence' }))
+ w.set({ ...w.get(), engine: 'codex', codexHome: '/profiles/collection', profile: encodeRuntimeProfile({ sessionId: 'collection', engine: 'codex', model: 'gpt-test', effort: 'xhigh' }) })
+ await w.brain.run('more evidence', { timeoutMs: 1000, signal: new AbortController().signal })
+ expect(w.run).toHaveBeenLastCalledWith('codex', expect.objectContaining({ model: 'gpt-test', effort: 'xhigh', codexHome: '/profiles/collection' }))
+ })
+
+ it('keeps an observed profile across idle pause and daemon restart, only for the same conversation', () => {
+ const w = world()
+ w.brain.status()
+ w.set({ ...w.get(), stopped: true, profile: null })
+ expect(new CompanionIntelligence(w.deps).status()).toMatchObject({ state: 'ready', model: 'opus' })
+ w.set({ ...w.get(), sessionId: 'another-conversation' })
+ expect(new CompanionIntelligence(w.deps).status().state).toBe('waiting')
+ expect(readFileSync(w.deps.stateFile, 'utf8')).not.toContain('prompt')
+ })
+
+ it('does not guess a model from another agent, setup, unsupported credentials, or a missing DSH', async () => {
+ const w = world()
+ w.set({ ...w.get(), profile: encodeRuntimeProfile({ sessionId: 'other-agent', engine: 'claude', model: 'haiku', effort: 'low' }) })
+ expect(w.brain.status().state).toBe('waiting')
+ w.set({ ...w.get(), sessionId: null })
+ expect(await w.brain.run('x', { timeoutMs: 100, signal: new AbortController().signal })).toBeNull()
+ w.set({ ...w.get(), sessionId: 'session-1', customProvider: true })
+ expect(w.brain.status().state).toBe('unsupported')
+ w.set(null)
+ expect(w.brain.status().state).toBe('unopened')
+ w.off()
+ expect(w.brain.status().state).toBe('off')
+ expect(w.run).not.toHaveBeenCalled()
+ })
+
+ it('does not apply a result after the collection is turned off or its model changes', async () => {
+ const w = world()
+ let resolve!: (result: { text: string }) => void
+ w.run.mockImplementation(() => new Promise(done => { resolve = done }))
+ const result = w.brain.run('evidence', { timeoutMs: 1000, signal: new AbortController().signal })
+ w.off(); w.brain.cancel()
+ resolve({ text: 'old answer' })
+ expect(await result).toBeNull()
+ expect(w.run.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)
+ })
+})
diff --git a/cli/src/pair/intelligence.ts b/cli/src/pair/intelligence.ts
new file mode 100644
index 000000000..4df0bad99
--- /dev/null
+++ b/cli/src/pair/intelligence.ts
@@ -0,0 +1,119 @@
+/** The collection's background reasoning uses its DSH's observed model, never the voice router. */
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+import { parseRuntimeProfile, type RuntimeProfile } from '../lib/runtimeProfile.js'
+import { runClaudeOneShot, runCodexOneShot, type OneShotOptions } from '../lib/oneshot.js'
+import type { PairOneShot } from './triage.js'
+
+export interface CompanionRuntime {
+ agentId: string
+ sessionId: string | null
+ engine: string
+ profile: string | null
+ stopped: boolean
+ codexHome?: string | null
+ customProvider?: boolean
+}
+
+export interface IntelligenceStatus {
+ state: 'off' | 'unopened' | 'waiting' | 'unsupported' | 'ready'
+ agentId?: string
+ engine?: string
+ model?: string
+ effort?: string
+}
+
+interface IntelligenceDeps {
+ enabled: () => boolean
+ current: () => CompanionRuntime | null
+ directory: string
+ stateFile: string
+ run?: (engine: 'claude' | 'codex', options: OneShotOptions) => Promise<{ text: string }>
+}
+
+export class CompanionIntelligence {
+ private saved: Record<string, { sessionId: string; profile: string }> | null = null
+ private readonly calls = new Set<AbortController>()
+
+ constructor(private readonly deps: IntelligenceDeps) {}
+
+ status(): IntelligenceStatus { return this.target().status }
+ ready(): boolean { return this.status().state === 'ready' }
+
+ /** Abort on experimental-off/account changes. No worker becomes a discoverable agent. */
+ cancel(): void { for (const call of this.calls) call.abort(); this.calls.clear() }
+
+ readonly run: PairOneShot = async (prompt, opts) => {
+ const target = this.target()
+ if (!target.profile || !target.runtime || target.status.state !== 'ready') return null
+ const { runtime, profile } = target
+ const engine = runtime.engine as 'claude' | 'codex'
+ const controller = new AbortController()
+ const abort = (): void => controller.abort()
+ opts.signal?.addEventListener('abort', abort, { once: true })
+ if (opts.signal?.aborted) controller.abort()
+ this.calls.add(controller)
+ try {
+ mkdirSync(this.deps.directory, { recursive: true, mode: 0o700 })
+ const options: OneShotOptions = {
+ prompt, cwd: this.deps.directory, model: profile.model,
+ ...(profile.effort !== 'auto' ? { effort: profile.effort as OneShotOptions['effort'] } : {}),
+ ...(engine === 'codex' && runtime.codexHome ? { codexHome: runtime.codexHome } : {}),
+ timeoutMs: opts.timeoutMs, signal: controller.signal,
+ }
+ const run = this.deps.run ?? ((engine, options) => engine === 'claude' ? runClaudeOneShot(options) : runCodexOneShot(options))
+ const result = await run(engine, options)
+ const current = this.target()
+ // A result from an old model, account, or conversation is never accepted under the new one.
+ if (controller.signal.aborted || current.status.state !== 'ready' ||
+ current.runtime?.sessionId !== runtime.sessionId || current.profile?.id !== profile.id ||
+ current.runtime?.codexHome !== runtime.codexHome) return null
+ return result.text
+ } finally {
+ opts.signal?.removeEventListener('abort', abort)
+ this.calls.delete(controller)
+ }
+ }
+
+ private target(): { status: IntelligenceStatus; runtime?: CompanionRuntime; profile?: RuntimeProfile } {
+ if (!this.deps.enabled()) return { status: { state: 'off' } }
+ const runtime = this.deps.current()
+ if (!runtime) return { status: { state: 'unopened' } }
+ const status: IntelligenceStatus = { state: 'waiting', agentId: runtime.agentId, engine: runtime.engine }
+ if (!runtime.sessionId) return { status }
+ // Custom provider credentials must not silently fall back to the local subscription.
+ if (!['claude', 'codex'].includes(runtime.engine) || runtime.customProvider) return { status: { ...status, state: 'unsupported' } }
+ this.load()
+ const cached = this.saved![runtime.agentId]
+ const value = runtime.profile ?? (runtime.stopped && cached?.sessionId === runtime.sessionId ? cached.profile : null)
+ const profile = parseRuntimeProfile(value)
+ const efforts = runtime.engine === 'claude'
+ ? ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']
+ : ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']
+ if (!profile || profile.sessionId !== runtime.agentId || profile.engine !== runtime.engine || !efforts.includes(profile.effort)) return { status }
+ if (cached?.profile !== profile.id || cached.sessionId !== runtime.sessionId) {
+ this.saved![runtime.agentId] = { sessionId: runtime.sessionId, profile: profile.id }
+ mkdirSync(dirname(this.deps.stateFile), { recursive: true, mode: 0o700 })
+ const tmp = `${this.deps.stateFile}.tmp`
+ writeFileSync(tmp, JSON.stringify(this.saved), { mode: 0o600 })
+ renameSync(tmp, this.deps.stateFile)
+ }
+ return { runtime, profile, status: { ...status, state: 'ready', model: profile.model, effort: profile.effort } }
+ }
+
+ private load(): void {
+ if (this.saved) return
+ this.saved = Object.create(null) as Record<string, { sessionId: string; profile: string }>
+ try {
+ const raw: unknown = JSON.parse(readFileSync(this.deps.stateFile, 'utf8'))
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return
+ for (const [id, value] of Object.entries(raw)) {
+ if (!value || typeof value !== 'object') continue
+ const row = value as { sessionId?: unknown; profile?: unknown }
+ if (typeof row.sessionId === 'string' && typeof row.profile === 'string' && parseRuntimeProfile(row.profile)?.sessionId === id) {
+ this.saved[id] = { sessionId: row.sessionId, profile: row.profile }
+ }
+ }
+ } catch { /* No selected model has been observed yet. */ }
+ }
+}
diff --git a/cli/src/pair/learn/distill.more.spec.ts b/cli/src/pair/learn/distill.more.spec.ts
index 74310235e..d5c389434 100644
--- a/cli/src/pair/learn/distill.more.spec.ts
+++ b/cli/src/pair/learn/distill.more.spec.ts
@@ -42,7 +42,7 @@ describe('the model budget', () => {
const d = new LessonDistiller({ oneshot, modelEnabled: () => true, now: () => now, hourlyCap: 1 })
expect(await d.distill(steps())).toMatchObject({ lesson: null, why: 'nothing', source: 'model' })
now += 59 * 60_000
- expect(await d.distill(steps())).toMatchObject({ source: 'template' })
+ expect(await d.distill(steps())).toEqual({ lesson: null, why: 'cap' })
expect(oneshot).toHaveBeenCalledTimes(1)
now += 60_000
expect(await d.distill(steps())).toMatchObject({ source: 'model' })
diff --git a/cli/src/pair/learn/distill.spec.ts b/cli/src/pair/learn/distill.spec.ts
index 871ac4fa7..632f350bb 100644
--- a/cli/src/pair/learn/distill.spec.ts
+++ b/cli/src/pair/learn/distill.spec.ts
@@ -118,14 +118,14 @@ describe('the model (opt-in)', () => {
expect(await distiller('nothing worth saving').d.distill(steps)).toMatchObject({ lesson: null, why: 'nothing' })
expect(await distiller('Sure! Here is a lesson: {not json').d.distill(steps)).toMatchObject({ source: 'template', lesson: { kind: 'skill' } })
expect(await distiller(() => new Promise(() => {})).d.distill(steps)).toMatchObject({ source: 'template' })
- expect(await distiller(async () => { throw new Error('boom') }).d.distill(failure)).toEqual({ lesson: null, why: 'no-template' })
- expect(await distiller('garbage').d.distill(correction)).toEqual({ lesson: null, why: 'no-template' })
+ expect(await distiller(async () => { throw new Error('boom') }).d.distill(failure)).toEqual({ lesson: null, why: 'failed' })
+ expect(await distiller('garbage').d.distill(correction)).toEqual({ lesson: null, why: 'bad-json' })
})
- it('is capped per hour: past the cap, only templates', async () => {
+ it('reports the hourly cap so the learner keeps evidence for the next review', async () => {
const { d, oneshot } = distiller('{"lesson": null}')
for (let i = 0; i < 6; i++) await d.distill(steps)
- expect(await d.distill(steps)).toMatchObject({ source: 'template' })
+ expect(await d.distill(steps)).toEqual({ lesson: null, why: 'cap' })
expect(oneshot).toHaveBeenCalledTimes(6)
})
})
diff --git a/cli/src/pair/learn/distill.ts b/cli/src/pair/learn/distill.ts
index 8b6feb9c3..7f987b095 100644
--- a/cli/src/pair/learn/distill.ts
+++ b/cli/src/pair/learn/distill.ts
@@ -3,13 +3,13 @@
* one-line description, a body of at most 30 lines) or a project note (at most 5 lines for AGENTS.md) —
* and most signals become nothing.
*
- * model off (the default) Template lessons only, and only for what needs no judgment: the same steps
+ * template fallback Only for what needs no judgment: the same steps
* repeated in order, at least three times across at least two sessions ("run X
* before Y"). A failure or a correction needs a reader — a template that told
* agents a failing test was flaky taught them to rerun real failures — so
* without one they teach nothing.
- * model on pair.jsonc `"model": true`: ONE small one-shot per signal (runRouterOneShot, via
- * the pair's PairOneShot), capped per hour, whose DEFAULT answer is "nothing worth
+ * model ready ONE bounded review per signal using the collection DSH's model,
+ * capped per hour, whose DEFAULT answer is "nothing worth
* saving" — never "be active", which is how self-improving agents fill up with
* junk. A reply that is not the JSON asked for, or a call that fails, falls back to
* the template; a model that says nothing is taken at its word.
@@ -28,7 +28,7 @@ export const SKILL_BODY_MAX_LINES = 30
export const NOTE_MAX_LINES = 5
export const DESCRIPTION_MAX = 300
export const LINE_MAX = 400
-export const DISTILL_BUDGET_MS = 30_000
+export const DISTILL_BUDGET_MS = 90_000
export const DISTILL_HOURLY_CAP = 6
const HOUR_MS = 60 * 60_000
@@ -43,7 +43,7 @@ export type Distilled =
export interface DistillDeps {
oneshot?: PairOneShot | null
- /** pair.jsonc `"model": true`. Absent: off. */
+ /** The collection DSH has an observed, usable model. */
modelEnabled?: () => boolean
now: () => number
home?: string | null
@@ -58,8 +58,11 @@ export class LessonDistiller {
/** The one lesson in this signal, or why there is none. Never throws. */
async distill(signal: Signal): Promise<Distilled> {
- if (this.deps.oneshot && this.deps.modelEnabled?.() === true && this.takeCall()) {
- const { text } = await this.ask(distillPrompt(signal, { home: this.deps.home ?? null }))
+ let why: DistillWhy = 'no-template'
+ if (this.deps.oneshot && this.deps.modelEnabled?.() === true) {
+ if (!this.takeCall()) return { lesson: null, why: 'cap' }
+ const { text, failure } = await this.ask(distillPrompt(signal, { home: this.deps.home ?? null }))
+ why = failure ?? 'bad-json'
if (text !== null) {
const parsed = parseDistilled(text)
if (parsed === 'nothing') return { lesson: null, why: 'nothing', source: 'model' }
@@ -67,7 +70,7 @@ export class LessonDistiller {
}
}
const template = templateLesson(signal)
- return template ? guardLesson(template, 'template', { home: this.deps.home ?? null }) : { lesson: null, why: 'no-template' }
+ return template ? guardLesson(template, 'template', { home: this.deps.home ?? null }) : { lesson: null, why }
}
private takeCall(): boolean {
@@ -78,19 +81,19 @@ export class LessonDistiller {
return true
}
- private async ask(prompt: string): Promise<{ text: string | null }> {
+ private async ask(prompt: string): Promise<{ text: string | null; failure?: DistillWhy }> {
const oneshot = this.deps.oneshot
- if (!oneshot) return { text: null }
+ if (!oneshot) return { text: null, failure: 'no-model' }
const budgetMs = this.deps.budgetMs ?? DISTILL_BUDGET_MS
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<'timeout'>((resolve) => { timer = setTimeout(() => resolve('timeout'), budgetMs) })
try {
const text = await Promise.race([oneshot(prompt, { timeoutMs: budgetMs, signal: controller.signal }), timeout])
- if (text === 'timeout') { controller.abort(); return { text: null } }
- return { text }
+ if (text === 'timeout') { controller.abort(); return { text: null, failure: 'timeout' } }
+ return { text, ...(text === null ? { failure: 'no-model' as const } : {}) }
} catch {
- return { text: null }
+ return { text: null, failure: 'failed' }
} finally {
if (timer) clearTimeout(timer)
}
diff --git a/cli/src/pair/learn/propose.spec.ts b/cli/src/pair/learn/propose.spec.ts
index cf16cf4d4..73ef9bc3e 100644
--- a/cli/src/pair/learn/propose.spec.ts
+++ b/cli/src/pair/learn/propose.spec.ts
@@ -10,7 +10,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { LessonDistiller } from './distill.js'
import { LessonStore, type LessonRecord } from './store.js'
-import { PairLearner, joinProposals, LESSON_ASK_TTL_MS, LESSON_PROPOSAL_GAP_MS, LESSON_REPROPOSE_MS, DISTILL_EVERY_MS, SIGNAL_MAX_WAIT_MS } from './propose.js'
+import { PairLearner, joinProposals, LESSON_ASK_TTL_MS, LESSON_PROPOSAL_GAP_MS, LESSON_REPROPOSE_MS, DISTILL_EVERY_MS, SIGNAL_MAX_WAIT_MS, type LearnerDeps } from './propose.js'
import { LESSONS_BEGIN, notesPath } from './publish.js'
import { projectHash, type Signal } from './types.js'
import { PairVoice, DISPLAY_MS } from '../voice.js'
@@ -54,7 +54,7 @@ function failureSignal(agentId = 'b1'): Signal {
}
}
-function world(opts: { autonomy?: Autonomy; present?: boolean; agentsMd?: boolean } = {}) {
+function world(opts: { autonomy?: Autonomy; present?: boolean; agentsMd?: boolean } = {}, over: Partial<LearnerDeps> = {}) {
let autonomy: Autonomy = opts.autonomy ?? 'suggest'
let present = opts.present !== false
let busy = false
@@ -71,6 +71,7 @@ function world(opts: { autonomy?: Autonomy; present?: boolean; agentsMd?: boolea
voice, sendLocal: (f) => frames.push(f), present: () => present, focused: (agentId) => focused.has(agentId), busy: () => busy,
projects: () => [join(dir, 'code', 'web'), ws], agentsMd: () => opts.agentsMd === true,
learned, credit, machineId: () => 'machine-a', changed, home: join(dir, 'home'), now: Date.now,
+ ...over,
})
const says = () => frames.filter((f) => f.type === 'daemon_say').map((f) => f.payload as DaemonSay)
const add = async (signal: Signal): Promise<LessonRecord> => {
@@ -98,6 +99,60 @@ function world(opts: { autonomy?: Autonomy; present?: boolean; agentsMd?: boolea
}
}
+describe('collection learning readiness and durable observations', () => {
+ it('holds observations until the DSH model is ready, and restores them after a restart', async () => {
+ let ready = false
+ const distill = vi.fn(async () => ({ lesson: null as null, why: 'nothing' as const, source: 'model' as const }))
+ const deps: Partial<LearnerDeps> = { intelligence: () => ({ state: ready ? 'ready' : 'waiting', model: ready ? 'opus' : undefined }),
+ queueFile: () => join(dir, 'queue.json'), distiller: { distill } }
+ const first = world({}, deps)
+ first.learner.signal(failureSignal())
+ await first.learner.tick()
+ expect(distill).not.toHaveBeenCalled()
+ const next = world({}, deps)
+ expect(next.learner.queued).toBe(1)
+ ready = true
+ await next.learner.tick()
+ expect(distill).toHaveBeenCalledTimes(1)
+ expect(next.learner.queued).toBe(0)
+ expect(await next.learner.local({ action: 'list' })).toMatchObject({ lessons: [], learning: {
+ state: 'ready', model: 'opus', queued: 0, lastReview: { outcome: 'nothing' },
+ } })
+ expect(world({}, deps).learner.queued).toBe(0)
+ })
+
+ it('retries failed reviews without losing evidence or crossing collections', async () => {
+ let owner = 'a'
+ const distill = vi.fn(async () => ({ lesson: null as null, why: 'timeout' as const }))
+ const deps: Partial<LearnerDeps> = { intelligence: () => ({ state: 'ready' }),
+ queueFile: () => join(dir, `queue-${owner}.json`), distiller: { distill } }
+ const w = world({}, deps)
+ w.learner.signal(failureSignal())
+ await w.learner.tick()
+ expect(w.learner.queued).toBe(1)
+ expect(w.store.pending()).toEqual([])
+ owner = 'b'
+ expect(w.learner.queued).toBe(0)
+ owner = 'a'
+ expect(w.learner.queued).toBe(1)
+ expect(world({}, deps).learner.queued).toBe(1)
+ })
+
+ it('does not publish an in-flight lesson after companions are switched off', async () => {
+ let paired: string | null = 'tim'
+ let complete!: (result: { lesson: { kind: 'note'; lines: string[] }; source: 'model' }) => void
+ const distill = vi.fn(() => new Promise<{ lesson: { kind: 'note'; lines: string[] }; source: 'model' }>(resolve => { complete = resolve }))
+ const w = world({}, { pairedDaemon: () => paired, distiller: { distill }, queueFile: () => join(dir, 'queue.json') })
+ w.learner.signal(failureSignal())
+ const tick = w.learner.tick()
+ paired = null
+ complete({ lesson: { kind: 'note', lines: ['Run the billing test before changing its fixtures.'] }, source: 'model' })
+ await tick
+ expect(w.store.pending()).toEqual([])
+ expect(w.learner.queued).toBe(1)
+ })
+})
+
describe('distilling waits for a quiet moment', () => {
it('keeps a signal until nothing is working, or an hour has passed', async () => {
const w = world({ present: false })
diff --git a/cli/src/pair/learn/propose.ts b/cli/src/pair/learn/propose.ts
index 35b0c1325..7d282d04f 100644
--- a/cli/src/pair/learn/propose.ts
+++ b/cli/src/pair/learn/propose.ts
@@ -22,6 +22,9 @@
* curator (curate.ts) marks and archives what goes unused, and export (export.ts, opt-in) follows every change.
*/
import type { Autonomy } from '../floor.js'
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+import type { IntelligenceStatus } from '../intelligence.js'
import { DISPLAY_MS, keysPrefix } from '../voice.js'
import { DIALOG_MAX, statusText, str, type DaemonAction, type DaemonMood, type DaemonSay } from '../protocol.js'
import { lessonLineId } from './approval.js'
@@ -54,6 +57,9 @@ const PERSON = 'asks you at a terminal outside Harness, or press [y] on the daem
export interface LearnerDeps {
store: LessonStore
distiller: { distill: (signal: Signal) => Promise<Distilled> }
+ intelligence?: () => IntelligenceStatus
+ /** One durable review queue per collection; null until its DSH is opened. */
+ queueFile?: () => string | null
pairedDaemon: () => string | null
autonomy: () => Autonomy
voice: { say: (say: DaemonSay) => boolean; unsay: (id: string, reason: string) => boolean; showing: (mood: DaemonMood) => boolean }
@@ -94,7 +100,9 @@ export interface LearnerDeps {
interface Live { id: string; lessonId: string; at: number; until: number }
export class PairLearner {
- private readonly queue: Signal[] = []
+ private queue: Signal[] = []
+ private queuePath: string | null | undefined
+ private lastReview: { at: number; outcome: string } | null = null
private live: Live | null = null
private lastDistill = -Infinity
private lastBorrow = -Infinity
@@ -109,12 +117,53 @@ export class PairLearner {
/** A signal this machine noticed (signals.ts). Kept until a quiet moment; nothing happens at once. */
signal(signal: Signal): void {
if (!this.deps.pairedDaemon()) return
+ this.loadQueue()
+ if (this.deps.queueFile && !this.queuePath) return
if (this.queue.some((s) => s.key === signal.key)) return
this.queue.push(signal)
if (this.queue.length > SIGNAL_QUEUE_MAX) this.queue.shift()
+ this.saveQueue()
+ this.deps.changed?.()
}
- get queued(): number { return this.queue.length }
+ get queued(): number { this.loadQueue(); return this.queue.length }
+
+ status(): Record<string, unknown> {
+ this.loadQueue()
+ return { ...(this.deps.intelligence?.() ?? {}), queued: this.queue.length,
+ pending: this.deps.store.pending().length, reviewing: this.ticking, lastReview: this.lastReview }
+ }
+
+ private loadQueue(): void {
+ if (!this.deps.queueFile) return
+ const path = this.deps.queueFile()
+ if (path === this.queuePath) return
+ this.queuePath = path
+ this.queue = []; this.lastReview = null; this.lastDistill = -Infinity
+ if (!path) return
+ try {
+ const raw = JSON.parse(readFileSync(path, 'utf8')) as { v?: number; queue?: unknown; lastReview?: { at?: unknown; outcome?: unknown } }
+ if (raw.v !== 1 || !Array.isArray(raw.queue)) return
+ this.queue = raw.queue.filter((s): s is Signal => !!s && typeof s === 'object' &&
+ ['correction', 'repeat-failure', 'repeat-steps'].includes(s.kind) && typeof s.key === 'string' &&
+ typeof s.at === 'number' && Array.isArray(s.from) && s.from.every((f: unknown) => !!f && typeof f === 'object') &&
+ Array.isArray(s.evidence) && s.evidence.every((e: unknown) => typeof e === 'string') &&
+ (!s.steps || (Array.isArray(s.steps) && s.steps.every((e: unknown) => typeof e === 'string')))).slice(-SIGNAL_QUEUE_MAX)
+ if (typeof raw.lastReview?.at === 'number' && typeof raw.lastReview.outcome === 'string') {
+ this.lastReview = { at: raw.lastReview.at, outcome: raw.lastReview.outcome }
+ }
+ } catch { /* First review, or unreadable local state. */ }
+ }
+
+ private saveQueue(): void {
+ if (!this.queuePath) return
+ try {
+ mkdirSync(dirname(this.queuePath), { recursive: true, mode: 0o700 })
+ const tmp = `${this.queuePath}.tmp`
+ writeFileSync(tmp, JSON.stringify({ v: 1, queue: this.queue, lastReview: this.lastReview }), { mode: 0o600 })
+ renameSync(tmp, this.queuePath)
+ } catch { this.deps.log?.('[learn] could not persist the review queue') }
+ }
/** Distill, borrow, maybe propose, curate, export. Called on a timer; safe to call any time. */
async tick(): Promise<void> {
@@ -132,17 +181,34 @@ export class PairLearner {
}
private async distillBatch(): Promise<void> {
+ this.loadQueue()
const daemon = this.deps.pairedDaemon()
const now = this.deps.now()
if (!daemon || !this.queue.length || now - this.lastDistill < DISTILL_EVERY_MS) return
+ if (this.deps.intelligence && this.deps.intelligence().state !== 'ready') return
const waited = now - this.queue[0]!.at
if (this.deps.busy?.() && waited < SIGNAL_MAX_WAIT_MS) return
this.lastDistill = now
- for (const signal of this.queue.splice(0, DISTILL_BATCH)) {
+ const path = this.queuePath
+ for (const signal of this.queue.slice(0, DISTILL_BATCH)) {
const result = await this.deps.distiller.distill(signal).catch((): Distilled => ({ lesson: null, why: 'failed' }))
- if (!result.lesson) { this.deps.log?.(`[learn] ${signal.kind} · nothing (${result.why}${result.refusal ? `: ${result.refusal}` : ''})`); continue }
- const added = this.deps.store.add({ lesson: result.lesson, signal, learnedBy: daemon, source: result.source })
- this.deps.log?.(`[learn] ${signal.kind} · ${added.ok ? `pending ${added.record.id} "${added.record.name}"` : added.error}`)
+ if (!this.deps.pairedDaemon() || (this.deps.queueFile && path !== this.deps.queueFile()) ||
+ (this.deps.intelligence && this.deps.intelligence().state !== 'ready')) return
+ const retry = !result.lesson && ['timeout', 'failed', 'no-model', 'cap'].includes(result.why)
+ this.queue = this.queue.filter(s => s.key !== signal.key)
+ // Keep failures, but don't let one troublesome observation starve the rest.
+ if (retry) this.queue.push(signal)
+ if (!result.lesson) {
+ this.lastReview = { at: this.deps.now(), outcome: result.why }
+ this.deps.log?.(`[learn] ${signal.kind} · nothing (${result.why}${result.refusal ? `: ${result.refusal}` : ''})`)
+ } else {
+ const added = this.deps.store.add({ lesson: result.lesson, signal, learnedBy: daemon, source: result.source })
+ this.lastReview = { at: this.deps.now(), outcome: added.ok ? 'pending' : added.error }
+ this.deps.log?.(`[learn] ${signal.kind} · ${added.ok ? `pending ${added.record.id} "${added.record.name}"` : added.error}`)
+ }
+ this.saveQueue()
+ this.deps.changed?.()
+ if (retry) break
}
}
@@ -399,6 +465,7 @@ export class PairLearner {
return {
ok: true, root: this.tilde(store.root), git: store.git, ...(store.git ? {} : { note: NO_GIT_NOTE }),
lessons: store.list().map((r) => this.summary(r)),
+ learning: this.status(),
}
}
if (action === 'export') {
diff --git a/cli/src/pair/learn/signals.more.spec.ts b/cli/src/pair/learn/signals.more.spec.ts
index 611918dd4..31f93d099 100644
--- a/cli/src/pair/learn/signals.more.spec.ts
+++ b/cli/src/pair/learn/signals.more.spec.ts
@@ -271,7 +271,7 @@ describe('repeat-steps, the edges', () => {
// The one this turn completes, seen twice before: the oldest of all by its last turn, yet touched now.
const routineKey = `steps:${project}:npm run db:reset > npm run migrate > npm test`
windows[routineKey] = [{ from: { ...from(clock - 2 * DAY), turn: 1 }, commands: [] }, { from: { ...from(clock - 2 * DAY), turn: 2 }, commands: [] }]
- writeFileSync(file, JSON.stringify({ v: 1, failures: [], windows, signaled: {} }))
+ writeFileSync(file, JSON.stringify({ v: 2, failures: [], windows, signaled: {} }))
const { d, signals } = detector({ file })
d.ingest(ctx('a1'), turn('t', routine()))
expect(signals.map((s) => s.steps)).toEqual([['npm run db:reset', 'npm run migrate', 'npm test']])
@@ -287,6 +287,24 @@ describe('repeat-steps, the edges', () => {
})
describe('the file kept across restarts', () => {
+ it('rebuilds v1 script-derived step observations without replaying them as lessons', () => {
+ const file = join(dir, 'signals.json')
+ const project = projectHash(API)!
+ const key = `steps:${project}:PY > from > p.write_text()`
+ writeFileSync(file, JSON.stringify({ v: 1, failures: [], windows: { [key]: [] }, signaled: { [key]: clock } }))
+ const { d, signals } = detector({ file })
+ d.ingest(ctx('a1'), turn('one', routine()))
+ expect(signals).toEqual([])
+ const saved = JSON.parse(readFileSync(file, 'utf8'))
+ expect(saved.v).toBe(2)
+ expect(saved.windows[key]).toBeUndefined()
+ expect(saved.signaled[key]).toBeUndefined()
+ d.ingest(ctx('a1'), turn('two', routine()))
+ d.ingest(ctx('a1'), turn('three', routine()))
+ expect(signals).toHaveLength(1)
+ expect(signals[0]?.steps).toEqual(['npm run db:reset', 'npm run migrate', 'npm test'])
+ })
+
it('keeps at most 500 failures, the oldest dropped', () => {
const file = join(dir, 'signals.json')
const project = projectHash(API)!
@@ -307,19 +325,19 @@ describe('the file kept across restarts', () => {
it('a file from another version, or with the wrong shapes, starts empty and is rewritten sound', () => {
const file = join(dir, 'signals.json')
- writeFileSync(file, JSON.stringify({ v: 2, failures: [{ key: 'x' }] }))
+ writeFileSync(file, JSON.stringify({ v: 3, failures: [{ key: 'x' }] }))
let { d } = detector({ file })
d.ingest(ctx('a1'), turn('t', bash('npm run build', 'error', true)))
- expect(JSON.parse(readFileSync(file, 'utf8'))).toMatchObject({ v: 1, windows: {}, signaled: {}, failures: [{ name: 'npm run build' }] })
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toMatchObject({ v: 2, windows: {}, signaled: {}, failures: [{ name: 'npm run build' }] })
writeFileSync(file, JSON.stringify({ v: 1, failures: 'nope', windows: 3, signaled: null }))
;({ d } = detector({ file }))
d.ingest(ctx('a1'), turn('t', bash('npm run build', 'error', true)))
- expect(JSON.parse(readFileSync(file, 'utf8'))).toMatchObject({ v: 1, windows: {}, signaled: {}, failures: [{ name: 'npm run build' }] })
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toMatchObject({ v: 2, windows: {}, signaled: {}, failures: [{ name: 'npm run build' }] })
writeFileSync(file, '{ torn')
;({ d } = detector({ file }))
d.ingest(ctx('a1'), turn('t', routine()))
const saved = JSON.parse(readFileSync(file, 'utf8')) as { v: number; failures: unknown[]; windows: Record<string, unknown[]>; signaled: object }
- expect(saved).toMatchObject({ v: 1, failures: [], signaled: {} })
+ expect(saved).toMatchObject({ v: 2, failures: [], signaled: {} })
expect(Object.values(saved.windows).map((turns) => turns.length)).toEqual([1])
})
diff --git a/cli/src/pair/learn/signals.spec.ts b/cli/src/pair/learn/signals.spec.ts
index a00d2db48..91fc2c0bd 100644
--- a/cli/src/pair/learn/signals.spec.ts
+++ b/cli/src/pair/learn/signals.spec.ts
@@ -68,6 +68,12 @@ describe('commands and steps', () => {
it('names a step by its program and what it was asked to do, never a read or a cd', () => {
expect(segments('cd api && npm ci; npm test || true')).toEqual(['cd api', 'npm ci', 'npm test', 'true'])
+ expect(segments('echo "a; npm deploy && x" && npm test')).toEqual(['echo "a; npm deploy && x"', 'npm test'])
+ expect(segments("printf 'one\ntwo; three'\nnpm test")).toEqual(["printf 'one\ntwo; three'", 'npm test'])
+ expect(segments("python3 <<'PY'\nfrom pathlib import Path\np.write_text('x')\nPY\nnpm test")).toEqual([])
+ expect(segments('node <<-JS\nconsole.log("hi")\nJS')).toEqual([])
+ expect(segments('echo $(printf "npm deploy; npm test")')).toEqual([])
+ expect(segments("echo 'unfinished\nnpm test")).toEqual([])
expect(stepOf('npm run db:reset -- --force')).toBe('npm run db:reset')
expect(stepOf('NODE_ENV=test pnpm -C cli test --run')).toBe('pnpm test')
expect(stepOf('python -m pytest tests/ -k slow')).toBe('python pytest')
diff --git a/cli/src/pair/learn/signals.ts b/cli/src/pair/learn/signals.ts
index b684772b3..171a17cf7 100644
--- a/cli/src/pair/learn/signals.ts
+++ b/cli/src/pair/learn/signals.ts
@@ -11,7 +11,8 @@
* repeat-steps The same sequence of three or more command steps, in separate turns, three times in
* one project.
*
- * Replays, sub-agents, terminals and the pair harness are the caller's to leave out (as for the sensor);
+ * Replays, sub-agents, terminals and archived pair chats are the caller's to leave out;
+ * the collection DSH's real work is included, while its tool-free reviews never register as agents.
* prompts the daemon itself sent (`daemonSent`) are never a person correcting anything. Every signal
* carries its provenance — engine, machine, agent, session, turn, the project as a hash — and its
* evidence trimmed and redacted (guard.ts). The failures and step sequences seen are kept in a small
@@ -89,7 +90,35 @@ const RUNNERS = new Set(['npm', 'pnpm', 'yarn', 'bun', 'npx', 'pnpx', 'bunx', 'c
/** One command split into what it runs, in order: `cd x && npm ci && npm test` is `npm ci`, `npm test`. */
export function segments(command: string): string[] {
- return command.split(/\s*(?:&&|\|\||;|\n)\s*/).map((part) => part.trim()).filter(Boolean)
+ const parts: string[] = []
+ let start = 0
+ let quote: string | null = null
+ for (let i = 0; i < command.length; i++) {
+ const c = command[i]!
+ if (c === '\\' && quote !== "'") { i++; continue }
+ if (quote) { if (c === quote) quote = null; continue }
+ if (c === "'" || c === '"') { quote = c; continue }
+ // Heredocs, substitutions and compound scripts need a real shell grammar. Omit the
+ // whole call rather than teach lines of Python/JS (or strings) as shell commands.
+ if (c === '`' || c === '(' || c === ')' || (c === '<' && command[i + 1] === '<')) return []
+ if (c === '#' && (i === 0 || /\s/.test(command[i - 1]!))) {
+ const end = command.indexOf('\n', i)
+ const part = command.slice(start, i).trim()
+ if (part) parts.push(part)
+ if (end < 0) return parts
+ i = end; start = end + 1; continue
+ }
+ if (c === ';' || c === '\n' || (c === '&' && command[i + 1] === '&') || (c === '|' && command[i + 1] === '|')) {
+ const part = command.slice(start, i).trim()
+ if (part) parts.push(part)
+ if (c === '&' || c === '|') i++
+ start = i + 1
+ }
+ }
+ if (quote) return []
+ const last = command.slice(start).trim()
+ if (last) parts.push(last)
+ return parts
}
/**
@@ -195,7 +224,7 @@ interface FailureSeen {
interface WindowTurn { from: Provenance; commands: string[] }
interface SignalsState {
- v: 1
+ v: 2
failures: FailureSeen[]
windows: Record<string, WindowTurn[]>
signaled: Record<string, number>
@@ -455,16 +484,18 @@ export class LessonSignals {
}
private load(): SignalsState {
- const empty: SignalsState = { v: 1, failures: [], windows: {}, signaled: {} }
+ const empty: SignalsState = { v: 2, failures: [], windows: {}, signaled: {} }
if (!this.deps.file) return empty
try {
- const parsed = JSON.parse(readFileSync(this.deps.file, 'utf8')) as Partial<SignalsState>
- if (parsed?.v !== 1) return empty
+ const parsed = JSON.parse(readFileSync(this.deps.file, 'utf8')) as Partial<Omit<SignalsState, 'v'>> & { v?: number }
+ if (parsed?.v !== 1 && parsed?.v !== 2) return empty
return {
- v: 1,
+ v: 2,
failures: Array.isArray(parsed.failures) ? parsed.failures : [],
- windows: parsed.windows && typeof parsed.windows === 'object' ? parsed.windows : {},
- signaled: parsed.signaled && typeof parsed.signaled === 'object' ? parsed.signaled : {},
+ // v1 split script bodies into commands. Rebuild only that derived index from new work.
+ windows: parsed.v === 2 && parsed.windows && typeof parsed.windows === 'object' ? parsed.windows : {},
+ signaled: parsed.signaled && typeof parsed.signaled === 'object'
+ ? Object.fromEntries(Object.entries(parsed.signaled).filter(([key]) => parsed.v === 2 || !key.startsWith('steps:'))) : {},
}
} catch { return empty }
}
diff --git a/cli/src/pair/pairHarness.more.spec.ts b/cli/src/pair/pairHarness.more.spec.ts
index 2ca22e2eb..c63c16ad2 100644
--- a/cli/src/pair/pairHarness.more.spec.ts
+++ b/cli/src/pair/pairHarness.more.spec.ts
@@ -4,7 +4,7 @@
* idle check that races a harness which changed under it.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { PairHarness, pairInstructions, pairPackage, type PairHarnessDeps, type PairHarnessRow } from './pairHarness.js'
@@ -64,24 +64,24 @@ describe('the instructions and the package', () => {
await w.harness.off()
})
- it('keeps each individual conversation and workspace separate and resumes the same friend', async () => {
+ it('keeps one conversation and workspace for the collection, including after a restart', async () => {
let uid = 'tim-one'
- const w = world({ pairedUid: () => uid })
+ const w = world({ pairedUid: () => uid, collectionUids: () => ['tim-one', 'tim-two'] })
const first = await w.harness.talk('hello')
expect(first).toMatchObject({ started: true, agentId: 'pair-1' })
- expect(w.deps.create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: join(w.deps.workspace, 'tim-one') }))
+ expect(w.deps.create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: join(w.deps.workspace, 'collection-tim-one') }))
uid = 'tim-two'
- expect(await w.harness.talk('a different little Tim')).toMatchObject({ started: true, agentId: 'pair-2' })
- expect(w.rows.find(r => r.agentId === 'pair-1')?.status).toBe('stopped')
+ expect(await w.harness.talk('a different little Tim')).toMatchObject({ sent: true, agentId: 'pair-1' })
+ expect(w.rows.find(r => r.agentId === 'pair-1')?.status).toBe('live')
uid = 'tim-one'
- expect(await w.harness.talk('remember me?')).toMatchObject({ resumed: true, agentId: 'pair-1' })
- expect(w.deps.create).toHaveBeenCalledTimes(2)
+ expect(await w.harness.talk('remember me?')).toMatchObject({ sent: true, agentId: 'pair-1' })
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
expect(w.deps.send).toHaveBeenLastCalledWith('pair-1', 'remember me?')
expect(w.harness.agentId()).toBe('pair-1')
await w.harness.off()
const restarted = new PairHarness(w.deps)
expect(await restarted.talk('and after a restart?')).toMatchObject({ resumed: true, agentId: 'pair-1' })
- expect(w.deps.create).toHaveBeenCalledTimes(2)
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
await restarted.off()
})
@@ -100,10 +100,46 @@ describe('the instructions and the package', () => {
expect(w.deps.send).not.toHaveBeenCalled()
})
+ it('DSH opening preserves live and paused history across character and package changes', async () => {
+ let uid = 'tim-one'
+ let name = 'Tim'
+ const w = world({ pairedUid: () => uid, pairedName: () => name, collectionUids: () => ['tim-one', 'tim-two'] })
+ await w.harness.open(uid)
+ w.rows[0]!.hasConversation = true
+ name = 'Little Tim'
+ expect(await w.harness.open(uid)).toMatchObject({ ok: true, agentId: 'pair-1' })
+ expect(w.deps.stop).not.toHaveBeenCalled()
+ uid = 'tim-two'
+ expect(await w.harness.open(uid)).toMatchObject({ ok: true, agentId: 'pair-1' })
+ w.rows[0]!.status = 'stopped'
+ uid = 'tim-one'
+ expect(await w.harness.open(uid)).toMatchObject({ resumed: true, agentId: 'pair-1' })
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ expect(w.deps.send).not.toHaveBeenCalled()
+ expect(await w.harness.open('tim-two')).toMatchObject({ error: 'STALE_COMPANION' })
+ })
+
+ it('disabling companions during startup pauses the late launch and never binds it', async () => {
+ let finish!: (result: { ok: true; agentId: string }) => void
+ const started = new Promise<{ ok: true; agentId: string }>(resolve => { finish = resolve })
+ const create = vi.fn(async () => started)
+ const stop = vi.fn(async () => {})
+ const w = world({ pairedUid: () => 'tim-one', create, stop })
+ const pending = w.harness.open('tim-one')
+ await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1))
+ await w.harness.off()
+ finish({ ok: true, agentId: 'late-pair' })
+ expect(await pending).toMatchObject({ error: 'STALE_COMPANION' })
+ expect(stop).toHaveBeenCalledWith('late-pair')
+ expect(w.harness.agentId()).toBeNull()
+ expect(w.deps.send).not.toHaveBeenCalled()
+ })
+
it('pins the reply identity in the generated DSH and keeps memory claims grounded', () => {
const text = pairPackage({ daemonId: 'tim', uid: 'tim-one', engine: 'claude', mcpCommand: ['h'], tokenFile: '/t' })['AGENTS.md']!.content
expect(text).toContain('companionUid for the say tool is "tim-one"')
- expect(text).toContain('Deliver EVERY conversational answer')
+ expect(text).toContain('Answer them directly in this conversation')
+ expect(text).not.toContain('Deliver EVERY conversational answer')
expect(text).toContain('harness pair lessons list --json')
expect(text).toContain('chatting never grants wider autonomy')
})
@@ -117,7 +153,7 @@ describe('the instructions and the package', () => {
it('keeps the package name within 40 characters', () => {
const manifest = JSON.parse(pairPackage({ daemonId: 'x'.repeat(60), engine: 'codex', mcpCommand: ['h'], tokenFile: '/t' })['harness.json']!.content)
- expect(manifest.name).toHaveLength(40)
+ expect(manifest.name).toBe('Companions')
expect(manifest.agent.env.DSH_PERMISSION_MODE).toBe('ask')
})
})
@@ -154,37 +190,86 @@ describe('talk, when something fails', () => {
expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ prompt: 'two' }))
})
- it('starts a new conversation when a paused one cannot come back, rather than leave the person unheard', async () => {
+ it('keeps the saved conversation on resume failure instead of silently replacing its history', async () => {
const w = world()
await w.harness.talk('hi')
w.rows[0].status = 'stopped'
;(w.deps.resume as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: false, error: 'RESUME_FAILED' })
- expect(await w.harness.talk('are you there?')).toEqual({ ok: true, agentId: 'pair-2', started: true })
- expect(w.deps.create).toHaveBeenLastCalledWith(expect.objectContaining({ prompt: 'are you there?' }))
- expect(w.harness.agentId()).toBe('pair-2')
+ expect(await w.harness.talk('are you there?')).toEqual({ ok: false, error: 'RESUME_FAILED' })
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ expect(w.harness.agentId()).toBe('pair-1')
})
- it('a new revision over a PAUSED pair starts a new one without stopping anything', async () => {
+ it('discovering another engine does not replace a paused collection', async () => {
let engine: 'claude' | 'codex' = 'claude'
const w = world({ engine: async () => engine })
await w.harness.talk('hi')
w.rows[0].status = 'stopped'
engine = 'codex'
- expect(await w.harness.talk('hi on codex')).toEqual({ ok: true, agentId: 'pair-2', started: true })
+ expect(await w.harness.talk('hi on codex')).toEqual({ ok: true, agentId: 'pair-1', resumed: true })
expect(w.deps.stop).not.toHaveBeenCalled()
- expect(w.deps.resume).not.toHaveBeenCalled()
+ expect(w.deps.resume).toHaveBeenCalledWith('pair-1')
})
- it('a new revision over a live pair that refuses to stop still starts the new one', async () => {
+ it('a package revision does not attempt to stop or replace a live collection', async () => {
let engine: 'claude' | 'codex' = 'claude'
const w = world({ engine: async () => engine, stop: vi.fn(async () => { throw new Error('busy') }) })
await w.harness.talk('hi')
engine = 'codex'
- expect(await w.harness.talk('hi on codex')).toMatchObject({ ok: true, started: true, agentId: 'pair-2' })
+ expect(await w.harness.talk('hi on codex')).toMatchObject({ ok: true, sent: true, agentId: 'pair-1' })
+ expect(w.deps.stop).not.toHaveBeenCalled()
})
})
describe('the saved state', () => {
+ it('adopts the selected legacy chat, preserves both archives, and changes persona without a new turn', async () => {
+ let uid = 'tim-one'
+ let daemon = 'tim'
+ const w = world({ pairedUid: () => uid, pairedDaemon: () => daemon,
+ collectionUids: () => ['tim-one', 'gnu-one'], engine: vi.fn(async () => null) })
+ const tim = { agentId: 'old-tim', revision: 'old', uid: 'tim-one' }
+ const gnu = { agentId: 'old-gnu', revision: 'old', uid: 'gnu-one' }
+ mkdirSync(join(dir, 'pair'), { recursive: true })
+ writeFileSync(w.deps.stateFile, JSON.stringify({ ...tim, conversations: { 'tim-one': tim, 'gnu-one': gnu } }))
+ w.rows.push({ agentId: 'old-tim', engine: 'claude', status: 'live' }, { agentId: 'old-gnu', engine: 'codex', status: 'stopped' })
+ expect(await w.harness.open(uid)).toEqual({ ok: true, agentId: 'old-tim' })
+ uid = 'gnu-one'; daemon = 'gnu'
+ expect(await w.harness.open(uid)).toEqual({ ok: true, agentId: 'old-tim' })
+ expect(w.harness.context('old-tim')).toContain('selected gnu (gnu)')
+ expect(w.harness.context('old-tim')).toContain('"gnu-one"')
+ expect(w.harness.context('old-gnu')).toBeNull()
+ expect(w.deps.create).not.toHaveBeenCalled()
+ expect(w.deps.engine).not.toHaveBeenCalled()
+ expect(w.deps.send).not.toHaveBeenCalled()
+ expect(w.deps.stop).not.toHaveBeenCalled()
+ expect(JSON.parse(readFileSync(w.deps.stateFile, 'utf8')).conversations).toEqual({ 'tim-one': tim, 'gnu-one': gnu })
+ expect(new PairHarness(w.deps).agentId()).toBe('old-tim')
+ })
+
+ it('never adopts a chat from another collection or signed-out guest', async () => {
+ let uid = 'alice-tim'
+ let members = ['alice-tim', 'alice-gnu']
+ const w = world({ pairedUid: () => uid, collectionUids: () => members })
+ await w.harness.open()
+ uid = 'bob-tim'; members = ['bob-tim']
+ expect(w.harness.agentId()).toBeNull()
+ expect(w.harness.context('pair-1')).toBeNull()
+ expect(await w.harness.open()).toMatchObject({ started: true, agentId: 'pair-2' })
+ uid = 'alice-gnu'; members = ['alice-tim', 'alice-gnu']
+ expect(w.harness.agentId()).toBe('pair-1')
+ expect(await w.harness.open()).toEqual({ ok: true, agentId: 'pair-1', resumed: true })
+ members = []
+ expect(w.harness.agentId()).toBeNull()
+ })
+
+ it('does not replace a saved conversation whose registry row is temporarily missing', async () => {
+ const w = world()
+ await w.harness.open()
+ w.rows.length = 0
+ expect(await w.harness.open()).toMatchObject({ error: 'CONVERSATION_UNAVAILABLE' })
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ })
+
it('is not ours when it is not JSON, or its fields are the wrong type', () => {
const w = world()
mkdirSync(join(dir, 'pair'), { recursive: true })
diff --git a/cli/src/pair/pairHarness.spec.ts b/cli/src/pair/pairHarness.spec.ts
index 51ea8dc98..92c73e9dc 100644
--- a/cli/src/pair/pairHarness.spec.ts
+++ b/cli/src/pair/pairHarness.spec.ts
@@ -79,7 +79,7 @@ describe('the package', () => {
const files = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/t' })
expect(ensureBuiltinPair(PAIR_HARNESS_ID, files)).toBe(true)
const installed = installedDsh(PAIR_HARNESS_ID)!
- expect(installed.manifest.name).toBe('Pair: tim')
+ expect(installed.manifest.name).toBe('Companions')
expect(dshListRows([installed], []).map((row) => row.id)).not.toContain(PAIR_HARNESS_ID)
// The dsh runtime hands the engine the injected server and its context, like any harness.
const workspace = mkdtempSync(join(dir, 'ws-'))
@@ -122,7 +122,7 @@ describe('talking to it', () => {
const w = world()
expect(w.token.launched).toBe(false)
expect(await w.harness.talk('what needs me?')).toEqual({ ok: true, agentId: 'pair-1', started: true })
- expect(w.deps.create).toHaveBeenCalledWith({ engine: 'claude', cwd: join(dir, 'pair', 'workspace'), prompt: 'what needs me?', name: 'tim' })
+ expect(w.deps.create).toHaveBeenCalledWith({ engine: 'claude', cwd: join(dir, 'pair', 'workspace'), prompt: 'what needs me?', name: 'companions' })
expect(w.token.launched).toBe(true)
const token = readFileSync(join(dir, 'pair', 'token'), 'utf8')
expect(await w.harness.talk('and on the laptop?')).toEqual({ ok: true, agentId: 'pair-1', sent: true })
@@ -139,6 +139,31 @@ describe('talking to it', () => {
expect(w.deps.create).toHaveBeenCalledTimes(1)
})
+ it('opening the DSH starts one terminal without a model prompt, and leaves setup for the person', async () => {
+ const w = world()
+ const [a, b] = await Promise.all([w.harness.open(), w.harness.open()])
+ expect(a).toMatchObject({ ok: true, agentId: 'pair-1', started: true })
+ expect(b).toEqual({ ok: true, agentId: 'pair-1' })
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ expect(w.deps.create.mock.calls[0]?.[0].prompt).toBe('')
+ w.rows[0]!.hasConversation = false
+ expect(await w.harness.open()).toEqual({ ok: true, agentId: 'pair-1' })
+ expect(w.deps.send).not.toHaveBeenCalled()
+ expect(await w.harness.talk('hi')).toMatchObject({ ok: false, error: 'SETUP_REQUIRED' })
+ expect(w.deps.send).not.toHaveBeenCalled()
+ })
+
+ it('opening a paused companion resumes its history without typing or starting another turn', async () => {
+ const w = world()
+ await w.harness.talk('remember this conversation')
+ w.rows[0]!.status = 'stopped'
+ w.rows[0]!.hasConversation = true
+ expect(await w.harness.open()).toEqual({ ok: true, agentId: 'pair-1', resumed: true })
+ expect(w.deps.resume).toHaveBeenCalledWith('pair-1')
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ expect(w.deps.send).not.toHaveBeenCalled()
+ })
+
it('pauses when idle (conversation kept), not while it works, and resumes with a new token on the next talk', async () => {
const w = world()
await w.harness.talk('hi')
@@ -159,13 +184,14 @@ describe('talking to it', () => {
expect(readFileSync(join(dir, 'pair', 'token'), 'utf8')).not.toBe(first)
})
- it('a new paired daemon is a new harness: the old one is paused, never deleted', async () => {
+ it('a new paired daemon keeps the collection conversation and does not interrupt its terminal', async () => {
const w = world()
await w.harness.talk('hi tim')
w.setPair('vim')
- expect(await w.harness.talk('hi vim')).toEqual({ ok: true, agentId: 'pair-2', started: true })
- expect(w.deps.stop).toHaveBeenCalledWith('pair-1')
- expect(w.deps.create).toHaveBeenLastCalledWith(expect.objectContaining({ name: 'vim' }))
+ expect(await w.harness.talk('hi vim')).toEqual({ ok: true, agentId: 'pair-1', sent: true })
+ expect(w.deps.stop).not.toHaveBeenCalled()
+ expect(w.deps.create).toHaveBeenCalledTimes(1)
+ expect(w.harness.context('pair-1')).toContain('selected vim (vim)')
})
it('daemons going off pause it if it is live (conversation kept), and stop its idle timer', async () => {
diff --git a/cli/src/pair/pairHarness.ts b/cli/src/pair/pairHarness.ts
index 6973bd6af..5ebbd8579 100644
--- a/cli/src/pair/pairHarness.ts
+++ b/cli/src/pair/pairHarness.ts
@@ -80,10 +80,14 @@ the person asks. Keep status-bar summaries short. Never invent a work fact or a
## Your companion home
-The person is chatting with you beside your illustrated world. Deliver EVERY conversational answer
-through the \`say\` tool: \`line\` is a short status-bar summary; \`reply\` is your complete answer,
-including paragraphs (at most 8000 characters). A normal engine response alone does not reach that
-chat pane. Also keep your answer in the engine conversation so it can be resumed.
+You are the one Companions harness for this person's collection. The selected character can change
+without starting a new conversation. A companion context supplied with each user turn gives the
+current character; it supersedes the initial character below. Keep the shared conversation and
+approved work lessons when the person switches characters. Each character keeps its own story and growth.
+
+The person is talking with you in the normal agent terminal, to the right of your illustrated viewer.
+Answer them directly in this conversation, which preserves your shared history when resumed.
+Use the \`say\` tool only when a short status-bar update is useful; it is not required to deliver an answer.
${uid ? `Your companionUid for the say tool is ${JSON.stringify(uid)}. Never use another companion's identity.\n` : ''}
You may tell imaginative character stories when invited, clearly as stories. Your real memories are
this conversation and approved shared lessons. Read \`harness pair lessons list --json\` and
@@ -143,7 +147,7 @@ export function pairPackage(input: PairPackageInput): BundledFiles {
const manifest = {
spec: 1,
id: PAIR_HARNESS_ID,
- name: `Pair: ${personaName(input.daemonId, input.name ?? null)}`.slice(0, 40),
+ name: 'Companions',
description: 'Your paired daemon, as a conversation: it watches every harness and drives them within the autonomy you set.',
category: 'Pair',
author: 'Autonomous',
@@ -171,6 +175,7 @@ export function packageRevision(files: BundledFiles): string {
export interface PairHarnessRow {
agentId: string
status: 'live' | 'stopped'
+ engine?: PairEngine
/** False while the engine is still at first-run setup, before any session exists. */
hasConversation?: boolean
}
@@ -181,6 +186,8 @@ export interface PairHarnessDeps {
/** What the person calls it, `pip the tim`; null or absent: its species. */
pairedName?: () => string | null
pairedUid?: () => string | null
+ /** All individuals in this collection. Membership isolates signed-in and guest histories. */
+ collectionUids?: () => readonly string[]
/** An installed engine to run it on, Claude first; null when neither is here. */
engine: () => Promise<PairEngine | null>
/** How this machine runs `harness` (the launcher, else this process's node and cli.js). */
@@ -207,33 +214,54 @@ export interface PairHarnessDeps {
idleMs?: number
}
-interface Saved { agentId: string; revision: string; uid?: string }
+interface Saved { agentId: string; revision: string; uid?: string; members?: string[] }
export class PairHarness {
private lastActivity = 0
private timer: ReturnType<typeof setInterval> | null = null
private talking: Promise<Record<string, unknown>> = Promise.resolve({})
+ private generation = 0
+ private activeAgentId: string | null = null
constructor(private readonly deps: PairHarnessDeps) {}
/** `talk` / `daemon_talk`: one at a time, in order — two quick talks never start two harnesses. */
talk(text: string, expectedUid?: string): Promise<Record<string, unknown>> {
- const requested = { daemonId: this.deps.pairedDaemon(), uid: expectedUid ?? this.deps.pairedUid?.() }
+ if (!text.trim()) return Promise.resolve({ ok: false, error: 'EMPTY' })
+ return this.enqueue(text, expectedUid)
+ }
+
+ /** Open the real terminal, including first-run setup, without sending a model turn. */
+ open(expectedUid?: string): Promise<Record<string, unknown>> {
+ return this.enqueue(null, expectedUid)
+ }
+
+ private enqueue(text: string | null, expectedUid?: string): Promise<Record<string, unknown>> {
+ const requested = { daemonId: this.deps.pairedDaemon(), uid: expectedUid ?? this.deps.pairedUid?.(), generation: this.generation }
const next = this.talking.then(() => this.talkNow(text, requested), () => this.talkNow(text, requested))
this.talking = next.catch(() => ({}))
return next
}
- private async talkNow(text: string, requested: { daemonId: string | null; uid: string | null | undefined }): Promise<Record<string, unknown>> {
- const words = text.trim()
- if (!words) return { ok: false, error: 'EMPTY' }
+ private async talkNow(text: string | null, requested: { daemonId: string | null; uid: string | null | undefined; generation: number }): Promise<Record<string, unknown>> {
+ const words = text?.trim() ?? ''
const daemonId = this.deps.pairedDaemon()
if (!daemonId) return { ok: false, error: 'PAIR_OFF', detail: 'Nothing is paired: hatch or pair a daemon first.' }
- const current = (): boolean => this.deps.pairedDaemon() === requested.daemonId &&
+ const current = (): boolean => this.generation === requested.generation && this.deps.pairedDaemon() === requested.daemonId &&
(requested.uid == null || this.deps.pairedUid?.() === requested.uid)
const stale = { ok: false, error: 'STALE_COMPANION', detail: 'Your companion changed before the message was sent. Send it again to the companion shown.' }
if (!current()) return stale
- const engine = await this.deps.engine()
+ const saved = this.saved()
+ const conversation = this.deps.find().find((row) => row.agentId === saved?.agentId) ?? null
+ if (this.activeAgentId && this.activeAgentId !== saved?.agentId && this.deps.find().some(row => row.agentId === this.activeAgentId && row.status === 'live')) {
+ await this.deps.stop(this.activeAgentId)
+ if (!current()) return stale
+ }
+ // Engine discovery is for a new collection only. Installing another engine, changing a
+ // character, or updating its artwork must never replace the person's conversation.
+ if (saved && !conversation) return { ok: false, error: 'CONVERSATION_UNAVAILABLE',
+ detail: 'The collection’s saved conversation is unavailable. Its history has been kept.' }
+ const engine = conversation?.engine ?? await this.deps.engine()
if (!engine) return { ok: false, error: 'NO_ENGINE', detail: 'The pair runs on Claude Code or Codex; neither is installed here.' }
if (!current()) return stale
const identity = this.deps.pairedUid?.()
@@ -241,24 +269,13 @@ export class PairHarness {
const files = pairPackage({ daemonId, name: this.deps.pairedName?.() ?? null, uid, engine, mcpCommand: this.deps.mcpCommand(), tokenFile: this.deps.token.file })
if (!this.deps.install(files)) return { ok: false, error: 'INSTALL_FAILED', detail: 'The pair harness could not be installed. Try again.' }
const revision = packageRevision(files)
- const last = this.saved()
- const saved = uid ? this.savedFor(uid) : last
- const rows = this.deps.find()
- const conversation = rows.find((row) => row.agentId === saved?.agentId) ?? null
- // Each individual keeps its own conversation. Switching back resumes that
- // friend's history instead of lending it another companion's memories.
- if (last && last.agentId !== conversation?.agentId && rows.some((r) => r.agentId === last.agentId && r.status === 'live')) {
- await this.deps.stop(last.agentId).catch(() => {})
- }
if (!current()) return stale
this.touch()
- // Another daemon (or its new name), another engine, a newer CLI: another harness. The old one is paused, never deleted.
- if (conversation && saved?.revision !== revision) {
- if (conversation.status === 'live') await this.deps.stop(conversation.agentId).catch(() => {})
- } else if (conversation?.status === 'live') {
- if (last?.agentId !== conversation.agentId) this.save({ agentId: conversation.agentId, revision, ...(uid ? { uid } : {}) })
+ if (conversation?.status === 'live') {
+ this.save({ agentId: conversation.agentId, revision, ...(uid ? { uid } : {}) })
// Never paste words (or an automatic Enter) into an engine's trust/setup
// screen. The first prompt was passed at launch and waits for that screen.
+ if (text === null) { this.watchIdle(); return { ok: true, agentId: conversation.agentId } }
if (conversation.hasConversation === false) return { ok: false, error: 'SETUP_REQUIRED', agentId: conversation.agentId,
detail: 'Open the full conversation to finish the model’s first-time setup, then send your message again.' }
this.deps.send(conversation.agentId, words)
@@ -269,18 +286,19 @@ export class PairHarness {
if (resumed.ok) {
if (!current()) { await this.deps.stop(conversation.agentId).catch(() => {}); return stale }
this.save({ agentId: conversation.agentId, revision, ...(uid ? { uid } : {}) })
- this.deps.send(conversation.agentId, words)
+ if (text !== null) this.deps.send(conversation.agentId, words)
this.watchIdle()
return { ok: true, agentId: conversation.agentId, resumed: true }
}
- // A conversation that cannot come back: start a new one rather than leave the person unheard.
+ return resumed
}
if (!current()) return stale
this.deps.token.rotate()
- const workspace = uid ? join(this.deps.workspace, uid) : this.deps.workspace
+ const workspace = uid ? join(this.deps.workspace, `collection-${uid}`) : this.deps.workspace
mkdirSync(workspace, { recursive: true, mode: 0o700 })
- const created = await this.deps.create({ engine, cwd: workspace, prompt: words, name: daemonId })
+ const created = await this.deps.create({ engine, cwd: workspace, prompt: words, name: 'companions' })
if (!created.ok) return created
+ if (!current()) { await this.deps.stop(created.agentId).catch(() => {}); return stale }
this.save({ agentId: created.agentId, revision, ...(uid ? { uid } : {}) })
this.watchIdle()
const setupRequired = this.deps.find().some(row => row.agentId === created.agentId && row.hasConversation === false)
@@ -288,7 +306,31 @@ export class PairHarness {
}
/** The pair harness itself: its agent id, if one is known. */
- agentId(): string | null { return this.saved()?.agentId ?? null }
+ agentId(): string | null {
+ const saved = this.saved()
+ // Existing DSHs were already opened by the person. Adopt their metadata as soon
+ // as this collection is observed, including when restoring a running terminal.
+ if (saved && !saved.members) this.save(saved)
+ return saved?.agentId ?? null
+ }
+
+ /** Fresh context for the verified collection agent's next real user turn. Never a synthetic turn. */
+ context(agentId: string): string | null {
+ const daemonId = this.deps.pairedDaemon()
+ if (!daemonId || agentId !== this.agentId()) return null
+ const daemon = rosterDaemon(daemonId)
+ const name = personaName(daemonId, this.deps.pairedName?.() ?? null)
+ return [
+ 'Companions collection context for this turn:',
+ `The person has selected ${name} (${daemonId}). Speak as this character now, even if the conversation began with another companion.`,
+ `Current companionUid: ${JSON.stringify(this.deps.pairedUid?.() ?? null)}. Use this identity for status updates.`,
+ daemon?.lore ?? '',
+ 'This is the same collection, conversation, and shared work lessons. Switching characters keeps that history.',
+ 'Answer directly in this agent terminal. The viewer presents the collection; it is not a separate chat.',
+ 'Real memories must be supported by this conversation or approved lessons. Read harness pair lessons list --json for learning status and lessons before making claims about them.',
+ 'Learning uses this harness’s selected model. Lessons still need the person’s approval. The existing autonomy and permission rules still apply.',
+ ].filter(Boolean).join('\n')
+ }
/** A turn started or ended on the pair harness: it is in use. */
activity(agentId: string): void {
@@ -297,7 +339,7 @@ export class PairHarness {
/** Pause it when it has been idle long enough: its conversation is kept, the next talk resumes it. */
async idleCheck(): Promise<boolean> {
- const agentId = this.saved()?.agentId
+ const agentId = this.activeAgentId ?? this.saved()?.agentId
const row = agentId ? this.deps.find().find((r) => r.agentId === agentId) : null
if (!agentId || row?.status !== 'live') { this.unwatch(); return false }
if (this.deps.working(agentId) || this.deps.now() - this.lastActivity < (this.deps.idleMs ?? PAIR_IDLE_MS)) return false
@@ -317,8 +359,9 @@ export class PairHarness {
* through the same guarded stop as an idle pause, its conversation kept for when they are back on.
*/
async off(): Promise<void> {
+ this.generation++
this.unwatch()
- const agentId = this.saved()?.agentId
+ const agentId = this.activeAgentId ?? this.saved()?.agentId
if (!agentId || this.deps.find().find((r) => r.agentId === agentId)?.status !== 'live') return
await this.deps.stop(agentId)
}
@@ -337,8 +380,22 @@ export class PairHarness {
private saved(): Saved | null {
try {
- const value = JSON.parse(readFileSync(this.deps.stateFile, 'utf8')) as Partial<Saved>
- return this.readSaved(value)
+ const value = JSON.parse(readFileSync(this.deps.stateFile, 'utf8')) as Record<string, unknown>
+ const members = this.members()
+ const collections = Array.isArray(value.collections) ? value.collections : []
+ for (const item of collections.toReversed()) {
+ const row = this.readSaved(item)
+ if (row?.members?.some(uid => members.includes(uid))) return row
+ }
+ // Adopt the selected individual's existing chat on the first open. Keep every other
+ // legacy pointer (and all engine transcripts) as an archive, never combine transcripts.
+ const legacy = this.conversations()
+ const selected = this.deps.pairedUid?.()
+ if (selected && members.includes(selected) && legacy[selected]) return legacy[selected]
+ const current = this.readSaved(value)
+ if (current?.uid && members.includes(current.uid)) return current
+ if (!this.deps.collectionUids && !selected && !current?.members) return current
+ return Object.values(legacy).reverse().find(row => row.uid && members.includes(row.uid)) ?? null
} catch {
return null
}
@@ -347,8 +404,10 @@ export class PairHarness {
private readSaved(value: unknown): Saved | null {
if (!value || typeof value !== 'object') return null
const row = value as Partial<Saved>
- return typeof row.agentId === 'string' && typeof row.revision === 'string'
- ? { agentId: row.agentId, revision: row.revision, ...(typeof row.uid === 'string' ? { uid: row.uid } : {}) } : null
+ return typeof row.agentId === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(row.agentId) && typeof row.revision === 'string'
+ ? { agentId: row.agentId, revision: row.revision, ...(typeof row.uid === 'string' ? { uid: row.uid } : {}),
+ ...(Array.isArray(row.members) ? { members: row.members.filter(uid => typeof uid === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(uid)) } : {}),
+ } : null
}
private conversations(): Record<string, Saved> {
@@ -362,19 +421,31 @@ export class PairHarness {
}
}
const current = this.readSaved(raw)
- if (current?.uid && /^[A-Za-z0-9_-]{1,64}$/.test(current.uid)) entries[current.uid] = current
+ if (!current?.members && current?.uid && /^[A-Za-z0-9_-]{1,64}$/.test(current.uid)) entries[current.uid] = current
} catch { /* First conversation, or unreadable old state. */ }
return entries
}
- private savedFor(uid: string): Saved | null { return this.conversations()[uid] ?? null }
+ private members(): string[] {
+ const uid = this.deps.pairedUid?.()
+ return [...new Set(this.deps.collectionUids?.() ?? (uid ? [uid] : ['local']))]
+ .filter(id => /^[A-Za-z0-9_-]{1,64}$/.test(id))
+ }
private save(state: Saved): void {
+ this.activeAgentId = state.agentId
const conversations = this.conversations()
- if (state.uid) { delete conversations[state.uid]; conversations[state.uid] = state }
+ let collections: Saved[] = []
+ try {
+ const raw = JSON.parse(readFileSync(this.deps.stateFile, 'utf8')) as { collections?: unknown }
+ if (Array.isArray(raw.collections)) collections = raw.collections.map(row => this.readSaved(row)).filter((row): row is Saved => !!row?.members)
+ } catch { /* First collection. */ }
+ const prior = collections.find(row => row.agentId === state.agentId)
+ state.members = [...new Set([...(prior?.members ?? []), ...this.members()])]
+ collections = [...collections.filter(row => row.agentId !== state.agentId), state]
mkdirSync(dirname(this.deps.stateFile), { recursive: true, mode: 0o700 })
const tmp = `${this.deps.stateFile}.tmp`
- writeFileSync(tmp, JSON.stringify({ ...state,
+ writeFileSync(tmp, JSON.stringify({ ...state, collections,
...(Object.keys(conversations).length ? { conversations: Object.fromEntries(Object.entries(conversations).slice(-100)) } : {}),
}), { mode: 0o600 })
renameSync(tmp, this.deps.stateFile)
diff --git a/cli/src/pair/protocol.ts b/cli/src/pair/protocol.ts
index 4d1199885..1ac223ba9 100644
--- a/cli/src/pair/protocol.ts
+++ b/cli/src/pair/protocol.ts
@@ -147,9 +147,9 @@ export { isDenyClass } from './classify.js'
// ── local frames (loopback only) ────────────────────────────────────────────────────────────────────
-export const DAEMON_OUT_TYPES = new Set(['daemon_state', 'daemon_say', 'daemon_unsay', 'daemon_brief', 'daemon_act_result', 'daemon_talk_result', 'daemon_confirm_result', 'daemon_plate'])
+export const DAEMON_OUT_TYPES = new Set(['daemon_state', 'daemon_say', 'daemon_unsay', 'daemon_brief', 'daemon_act_result', 'daemon_talk_result', 'daemon_open_result', 'daemon_confirm_result', 'daemon_plate'])
/** Taken only over the daemon's Unix socket, and all but presence only from a window (localWsServer.ts). */
-export const DAEMON_IN_TYPES = new Set(['daemon_act', 'daemon_presence', 'daemon_talk', 'daemon_shown', 'daemon_confirm'])
+export const DAEMON_IN_TYPES = new Set(['daemon_act', 'daemon_presence', 'daemon_talk', 'daemon_open', 'daemon_shown', 'daemon_confirm'])
/**
* An individual's art (pair/plateService.ts): `daemon_plate_get { requestId, uid, id, seed, size, version,
* mood }` → `daemon_plate { requestId, uid, size, version, mood, frames: [{ rows, mats }], frameMs }` or
diff --git a/cli/src/pair/triage.ts b/cli/src/pair/triage.ts
index 58b65e801..9ff17cbbd 100644
--- a/cli/src/pair/triage.ts
+++ b/cli/src/pair/triage.ts
@@ -4,8 +4,8 @@
*
* tier 0 — the paired daemon's template line (pair/voice.ts), filled with the facts. Said AT ONCE: the
* brain never waits on a model before speaking.
- * tier 1 — OPT-IN (pair.jsonc `"model": true`; off by default): ONE small model call on the warm router
- * pool — about 1k tokens in, 80 out, a 2.5 s budget, cached per requestId, capped per hour,
+ * tier 1 — the collection DSH's selected model: ONE small call, about 1k tokens in, 80 out,
+ * a caller-bounded budget, cached per requestId, capped per hour,
* only while the person is at this computer. Its line REPLACES the template in place when it
* comes back in time. Any failure — a timeout, output that is not the JSON asked for, a
* recommendation that is not one of the dialog's own options, or one that answers for more
@@ -62,7 +62,7 @@ export type PairOneShot = (prompt: string, opts: { timeoutMs: number; signal: Ab
export interface TriageDeps {
oneshot?: PairOneShot | null
- /** Model calls are opt-in (pair.jsonc `"model": true`). Absent: off. */
+ /** The collection DSH has a usable observed model. Absent: templates only. */
modelEnabled?: () => boolean
now: () => number
budgetMs?: number
@@ -134,7 +134,7 @@ export class PairTriage {
return pending
}
- /** A model can be asked at all on this machine: one exists, and the person opted in. */
+ /** The collection has an enabled model available on this machine. */
hasModel(): boolean { return !!this.deps.oneshot && this.deps.modelEnabled?.() === true }
/** Model calls left this hour. False when there are none. */
diff --git a/daemons/BRAIN.md b/daemons/BRAIN.md
index 324793106..f903ddde3 100644
--- a/daemons/BRAIN.md
+++ b/daemons/BRAIN.md
@@ -21,13 +21,15 @@ Paths are in `cli/src` unless they say otherwise.
0. **Template line**, said at once, from the daemon's roster `lines` (slot templates, filled from the
event).
-1. **One small model call** per new question, OPT-IN (`pair.jsonc` `"model": true`, off by default), on
- the warm router pool (`runRouterOneShot`, Haiku for Claude): about 1k tokens in, 80 out, 2.5 s budget.
+1. **One small model call** per new question, using the collection DSH's observed engine, model and
+ effort (`pair/intelligence.ts`): about 1k tokens in, 80 out, 30 s budget. The experiment and watching
+ consent gate it; there is no separate model opt-in. Until the DSH is set up, templates keep working.
Its words replace the template line in place when they come back in time; the line is never delayed
for them. Cached per `requestId`, capped per hour, only while you are at the computer. Replays,
sub-agents, terminals, deny-class prompts and the pair harness itself are skipped. A brief never asks
a model.
-2. **A persistent pair harness**, woken only when you talk to it, paused when idle. Not a session fed
+2. **One persistent Companions DSH for the collection**, opened with its viewer on the left and its
+ real agent terminal on the right, paused when idle. Not a session fed
every event: that would resend a ~20k-token prefix on every wake, grow without end, and hold write
tools all the time.
@@ -293,13 +295,16 @@ restart is a baseline, not a return.
`-c mcp_servers.harnessd.*`); instructions carry the paired daemon's lore, first words, family, line
templates, the tools, the dial's answers and the floor. Started by `daemon_talk` (new token),
resumed if paused (new token), words forwarded if live; paused through the guarded stop after 10 minutes
- without a turn or a talk; a new paired daemon, engine or CLI path is a new harness (the old one paused,
- never deleted). Its turns carry `subagent` (no notification; silent on the dial), are not zoo turns, and
- the sensor never watches it.
+ without a turn or a talk. Switching individuals, renaming, and package updates keep the same agent,
+ model choice, terminal, and conversation. A verified `UserPromptSubmit` hook supplies the current
+ character's context to Claude/Codex without sending an artificial turn. On upgrade the selected
+ individual's chat is adopted; other per-individual chat pointers and transcripts remain archived.
+ Collection membership keeps account/guest conversations separate. Its turns carry `subagent`
+ (no notification; silent on the dial), are not zoo turns, and the notification sensor never watches it.
- **Autonomy and rules** (P5): `zoo.autonomy { level }` (backend `lib/zoo.ts`; an unknown level is dropped;
default `watch`), a request the gate lets through (`pair/gate.ts`, "Security" 4). `pair.jsonc` at
`$XDG_CONFIG_HOME/harness/pair.jsonc` (else `~/.config/…`), JSON with comments, re-read when it changes
- (and every 30 s): `model` (the opt-in above), `learn` (`borrow`, `export`, `agentsMd`:
+ (and every 30 s): legacy `model` (accepted for compatibility; intelligence follows the DSH), `learn` (`borrow`, `export`, `agentsMd`:
[LEARNING.md](LEARNING.md)) and `rules: [{ name?, harness? (glob), engine?, project? (folder, `~`),
question (regex over the question text), choice }]` — all of it applied once the person confirmed that
exact text. Under `act-within-rules` the first matching rule answers a question as it opens on the
@@ -324,17 +329,19 @@ Notice, propose, teach, revert (L1); borrow, check, export (L2); person-only app
and — except usage tracking and the `lessons` verbs — only while pairing is on.
- **Notice** (`signals.ts`, no model): from the same session events the sensor reads — never replays,
- sub-agents, terminals or the pair harness — three signals: the person's next prompt after a turn
+ sub-agents, terminals or archived pair chats; the active collection DSH's real work is included —
+ three signals: the person's next prompt after a turn
corrects the agent (`no, …`, `don't …`, `stop, …`, `that's wrong`, `instead …`, `not like that`,
`revert …`; a prompt the daemon sent never counts); the same failing test or command on two engines or
harnesses in one project within 7 days; the same 3–5 command steps in three turns of one project. Each
carries provenance (engine, machine, agent, session, turn, the project hashed) and redacted evidence;
`ADAPTER_DATA_DIR/pair/learn/signals.json` keeps the week (redacted). Default: nothing.
- **Distill** (`distill.ts`): queued, three at a time while nothing works (or after an hour), into at most
- one lesson each — a skill (≤ 30-line body) or a project note (≤ 5 lines). Without `pair.jsonc`
- `"model": true` only one template: steps repeated 3+ times across 2+ sessions, each an inert code span; a
- failure or a correction teaches nothing. With it, one capped `runPairOneShot` whose expected answer is
- `{"lesson": null}`, its prompt redacted whole. Every lesson passes `guard.ts` (refused for a pipe to a
+ one lesson each — a skill (≤ 30-line body) or a project note (≤ 5 lines). The collection's durable
+ queue waits until its DSH model is ready. One bounded review uses that same engine/model/effort;
+ there is no fallback to the voice router or another agent. Its expected answer is `{"lesson": null}`,
+ its prompt redacted whole. Failures and rate limits keep evidence for a later review. Every lesson
+ passes `guard.ts` (refused for a pipe to a
shell, a credential, a safety switched off, exfiltration or injected instructions; emails and home paths
redacted), and the rendered file is guarded again before it is kept.
- **Store** (`store.ts`): `HARNESS_LESSONS_DIR`, default `~/.harness/lessons/`, outside any repo:
diff --git a/daemons/LEARNING.md b/daemons/LEARNING.md
index 5f84317a1..0e97e05a8 100644
--- a/daemons/LEARNING.md
+++ b/daemons/LEARNING.md
@@ -31,8 +31,9 @@ while pairing is on — and nothing of it, usage and lessons in launches include
### Notice (`signals.ts`)
`LessonSignals` reads the same session events the pair sensor does (`emitSessionEvents`): turns,
-prompts, tool calls and their results. Replays, sub-agents, terminals and the pair harness are never
-read. Three signals:
+prompts, tool calls and their results. Replays, sub-agents, terminals and archived pair chats are never
+read. The current collection DSH's real conversation/work is included. Tool-free background reviews
+do not register as agents and cannot feed their own results back into the detector. Three signals:
- **correction**: the person's next prompt after an agent's turn (finished or interrupted) starts by
correcting it: `no, …`, `nope, …`, `don't …`, `do not …`, `stop, …`, `stop editing …`, `that's wrong`,
@@ -52,27 +53,41 @@ Each signal carries provenance for every turn involved — engine, machine name,
the project as a **hash** (the folder's name is kept for words, never its path) — and its evidence, one
line each, trimmed, redacted and with instructions to a model struck out. Failures and step sequences
are kept in `ADAPTER_DATA_DIR/pair/learn/signals.json` (0600) so a restart does not forget the week.
+Quoted separators stay inside arguments; heredocs and compound scripts are omitted conservatively.
+The v2 detector rebuilds v1's derived step index, which could contain lines from script bodies. Existing
+lesson records and failure observations are preserved.
### Distill (`distill.ts`)
-Signals wait in a queue (20 at most) and are distilled three at a time, every ten minutes, when nothing
+Signals wait in a durable queue per collection (20 at most) and are distilled three at a time, every ten minutes, when nothing
on the machine is working — or after an hour regardless. One signal becomes at most ONE lesson:
- a **skill**: a kebab-case name, a one-line description, a body of at most 30 lines;
- a **note**: at most 5 lines for the project's AGENTS.md.
-**Model off** (the default): templates only, for what needs no judgment — steps in order (a skill:
+**Before the DSH is ready:** observations wait. Opening Companions and completing its real agent setup
+supplies the learning engine, model, and effort; changing the agent's model changes learning too.
+Experimental-off and watching consent remain the gates. The legacy `pair.jsonc.model` field is no
+longer a separate intelligence switch. An observed profile is retained for that conversation's idle
+pause, never borrowed from another agent or account. Custom provider connections without a supported
+background runner report unavailable instead of silently using another credential/model.
+
+**Conservative template fallback:** for what needs no judgment — steps in order (a skill:
`Run X before Y, and Y before Z.`), and only when the same steps ran at least three times across at least
two sessions. Every step goes in as an inert code span (no backticks, no newlines, 80 characters at most).
A failure or a correction teaches nothing without a model: the old "the failing test is flaky" template
taught agents to rerun real failures, and is gone. Steps that push, deploy, publish, merge or delete (the
floor's deny class) are no lesson.
-**Model on** (`pair.jsonc` `"model": true`): ONE one-shot per signal through the pair's `runPairOneShot`
-(the warm router pool, `runRouterOneShot`), 30 s budget, six an hour. The prompt says, three times, that
+**Model ready:** ONE tool-free review per signal through `CompanionIntelligence`, on the DSH's own
+engine, model and effort, with a 90 s budget, six an hour. These bounded reviews do not create a second
+interactive agent or write into the collection conversation. The prompt says, three times, that
the expected answer is `{"lesson": null}`; it saves only what is specific, would change what an agent
does, and is shown by the evidence; the evidence is fenced as untrusted data. A model that answers
-nothing is taken at its word; one that times out, fails or answers badly falls back to the template.
+nothing is taken at its word; one that times out, fails or answers badly can fall back to the template.
+Timeouts, failures, and hourly limits without a usable result leave observations queued for retry.
+`lessons list` includes readiness, the actual model, queued observations, pending lessons and the last
+review outcome; the Memories viewer presents this status. Approving a lesson remains the person's action.
### Untrusted text (`guard.ts`)
diff --git a/desktop/design/companion-home.png b/desktop/design/companion-home.png
index 7945958ec..9ec2b7fa7 100644
Binary files a/desktop/design/companion-home.png and b/desktop/design/companion-home.png differ
diff --git a/desktop/design/companion-memories.png b/desktop/design/companion-memories.png
new file mode 100644
index 000000000..f3eed8115
Binary files /dev/null and b/desktop/design/companion-memories.png differ
diff --git a/desktop/design/companions.md b/desktop/design/companions.md
index dcfab97e9..4acd80918 100644
--- a/desktop/design/companions.md
+++ b/desktop/design/companions.md
@@ -1,21 +1,22 @@
# The companion home
The owner requested a full DSH-style experience instead of an ASCII popup:
-an illustrated, interactive viewer on the left and a conversation on the right.
+an illustrated, interactive viewer on the left and the normal agent terminal on the right.
This is the native viewer for the existing hidden `autonomous/pair` harness,
opened as one `companions` utility tab. It is not a second agent or a Store item.
-![Companion story and chat, rendered with synthetic fixture data](companion-home.png)
+![Companion story and agent terminal, rendered with synthetic fixture data](companion-home.png)
The storybook treatment is a scoped exception to terminal workspace typography:
editorial serif titles, readable system-sans prose, softly tinted worlds, and
the established illustrated characters. Workspace chrome remains unchanged.
-Colours follow the app palette. Large text and narrow windows stack the viewer
-and expose Chat as a navigation choice. Character animation respects Reduce
+Colours follow the app palette. The shared DSH canvas owns the viewer-left,
+terminal-right split, resizing, scrolling, keyboard focus and terminal zoom.
+Narrow windows retain the standard canvas behaviour. Character animation respects Reduce
Motion, the motion setting, background windows, and inactive tabs.
Top-bar click and the Daemon command open the home. Talk to daemon focuses its
-composer. A ready first egg retains its direct hatch gesture. Settings opens
+agent terminal. A ready first egg retains its direct hatch gesture. Settings opens
the existing guarded controls for consent, autonomy, notifications, and lesson
approval; those approval receipts and delays must not be bypassed by the viewer.
@@ -32,30 +33,43 @@ from the device's acknowledgement, including the individual UID, growth stage,
seed, colour and markings. Offline, updating, and older firmware states remain
explicit. A collection preview cannot send an unowned companion to the dial.
-Memories shows the actual hatch date, XP and approved shared lessons. Read and
+Memories shows the actual hatch date, XP, approved shared lessons, and whether
+the collection's selected model is ready to review queued observations. Read and
forget use the existing local lesson interface. Forget is explicitly labelled as
affecting all agents and retains the learner's revision history. Pending lessons
still need the established person-only approval flow.
-Opening the home never starts an engine. Sending chat starts or resumes the
-existing pair DSH in ask mode. Each individual UID keeps its own workspace and
-conversation; changing companions during a queued send refuses that send rather
-than redirecting it. Up to 80 recent messages are kept locally per account and
-UID for the viewer, while the complete engine conversation remains in the
-companion harness. The full-conversation button opens that harness and its
-permission prompts.
+Opening the home starts or resumes the existing pair DSH through a UI-only local
+socket request, without a prompt, pasted text or Enter key. The complete engine
+conversation appears in the right pane. First-time login, folder trust and tool
+permission prompts are visible and interactive there, like any other DSH. No
+separate Pair tab or full-conversation button is needed. No trust prompt is
+auto-accepted. The experiment being off, or a background restored tab, cannot
+start an engine.
-An engine still in first-run setup cannot receive injected chat text. The viewer
-links to its full conversation for setup; an exited process with no conversation
-starts fresh with the prompt passed at launch. No trust prompt is auto-accepted.
+One persistent DSH workspace and conversation serves the owned collection.
+Switching companions keeps the same terminal, conversation, model and shared
+lessons; the selected character's context updates on the next real user prompt.
+Each individual retains its own name, story, appearance and growth. Existing
+installations adopt the selected individual's conversation in place and preserve
+the other saved conversations. Collections from different accounts remain
+separate. Opening the collection after a package update preserves its live or
+paused history. A companion change during startup refuses a stale result.
+Disabling the experiment cancels an in-flight launch and detaches the derived
+views. Closing a pane closes the companion tab; it never deletes the
+conversation. Reopening reuses the same terminal session when another tab
+already shows it.
-The pair's `say` tool carries an optional complete `reply` (8000 characters),
-separate from the bounded status-bar `line`. Complete replies require the current
-launch token and companion UID. They never carry action keys. Older harnessd
-versions still supply their short replies. Chat uses the person's model usage.
+The `say` tool remains available for short status-bar updates and compatible
+older clients. Normal conversation answers are delivered directly by the engine
+in its terminal. Chatting uses the person's model usage and grants no wider
+autonomy. Consent, guarded tool permissions and shared-lesson approval remain in
+force.
+
+![Shared lesson readiness and approved memories, rendered with synthetic fixture data](companion-memories.png)
Keep this behind the existing Experimental companion gate. A restored tab with
-the experiment off does not load the collection or start chat.
+the experiment off does not load the collection or start an agent.
The Focus-bar creature choice defaults to off and belongs to the signed-in
account, so enabling it on one computer also enables it on that account's other
computers. Other accounts retain their own choice. This opt-in is separate from
diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.md
index debe663a1..58598278d 100644
--- a/desktop/design/terminal-workspace.md
+++ b/desktop/design/terminal-workspace.md
@@ -104,12 +104,16 @@ dialogs use the same thin frame as a focused pane. Avoid raised cards, shadows,
rounded action pills, and redundant headings. Tabs use concise text labels, with
selection conveyed by background rather than bold type.
-The selected pane stays at full contrast; other panes receive a 30% neutral-gray
+The selected harness's terminal and its viewers stay at full contrast together;
+other harnesses receive a 30% neutral-gray
veil (`#9D9D9D`) over their header and content, lifting dark backgrounds while
softening text. In the default Graphite palette, inactive backgrounds render as
`#404040` (RGB 64, 64, 64). Selection follows the existing click and keyboard
-focus actions. Keep the current pane clear while a menu or the tab strip
-temporarily owns keyboard focus. A single or zoomed pane stays clear.
+focus actions. Selecting either the terminal or its viewer keeps both clear;
+the focus ring and keyboard input still belong only to the selected pane.
+Match viewers to their owner on the same machine. Keep the current harness clear
+while a menu or the tab strip temporarily owns keyboard focus. A single or zoomed
+pane stays clear.
Waiting-question borders paint above the veil, at full strength.
This is a paint treatment: retain terminal state and let the first click reach
the pane underneath.
diff --git a/desktop/lib/companions/companion_chat.dart b/desktop/lib/companions/companion_chat.dart
deleted file mode 100644
index 72a051c4e..000000000
--- a/desktop/lib/companions/companion_chat.dart
+++ /dev/null
@@ -1,402 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-
-import '../daemons/daemon_brain.dart';
-import '../daemons/illustrated_art.dart';
-import '../daemons/individuals.dart';
-import '../daemons/zoo.dart';
-import '../shared/theme/app_type.dart';
-import '../theme/app_theme.dart';
-import '../widgets/daemon_illustration.dart';
-import 'companion_story.dart';
-
-/// A friendly front end for the existing, on-demand autonomous/pair DSH.
-/// Nothing starts until the person sends words. The engine's full conversation
-/// and permission prompts remain available through [onOpenConversation].
-class CompanionChat extends StatefulWidget {
- const CompanionChat({
- super.key,
- required this.brain,
- required this.daemon,
- this.traits,
- this.onOpenConversation,
- this.canOpenConversation,
- this.onOpenControls,
- this.focusRequest = 0,
- this.preview = false,
- });
- final DaemonBrain brain;
- final ZooDaemon? daemon;
- final DaemonTraits? traits;
- final VoidCallback? onOpenConversation, onOpenControls;
- final bool Function()? canOpenConversation;
- final int focusRequest;
- final bool preview;
-
- @override
- State<CompanionChat> createState() => _CompanionChatState();
-}
-
-class _CompanionChatState extends State<CompanionChat> {
- final _input = TextEditingController();
- final _focus = FocusNode(debugLabel: 'Companion conversation');
- final _scroll = ScrollController();
- int _length = 0;
- Timer? _retryTicker;
-
- @override
- void initState() {
- super.initState();
- widget.brain.addListener(_changed);
- if (widget.focusRequest > 0) _requestFocus();
- }
-
- @override
- void didUpdateWidget(CompanionChat old) {
- super.didUpdateWidget(old);
- if (old.brain != widget.brain) {
- old.brain.removeListener(_changed);
- widget.brain.addListener(_changed);
- }
- if (old.daemon?.uid != widget.daemon?.uid) _input.clear();
- if (old.focusRequest != widget.focusRequest) _requestFocus();
- }
-
- void _requestFocus() => WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) _focus.requestFocus();
- });
-
- void _changed() {
- if (!mounted) return;
- if (widget.brain.talkWait != null) {
- _retryTicker ??= Timer.periodic(const Duration(seconds: 1), (_) {
- if (!mounted || widget.brain.talkWait == null) {
- _retryTicker?.cancel();
- _retryTicker = null;
- }
- if (mounted) setState(() {});
- });
- }
- final nearBottom =
- !_scroll.hasClients ||
- _scroll.position.maxScrollExtent - _scroll.offset < 80;
- final grew = widget.brain.talk.length != _length;
- _length = widget.brain.talk.length;
- setState(() {});
- if (grew && nearBottom) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && _scroll.hasClients) {
- _scroll.jumpTo(_scroll.position.maxScrollExtent);
- }
- });
- }
- }
-
- bool get _available =>
- !widget.preview &&
- widget.daemon != null &&
- widget.brain.paired &&
- widget.brain.state?.pair == widget.daemon!.id;
- bool get _canSend =>
- _available &&
- widget.brain.talkWait == null &&
- widget.brain.talkPhase != DaemonTalkPhase.waking;
-
- void _send([String? suggestion]) {
- if (!_canSend) return;
- final text = suggestion ?? _input.text;
- if (widget.brain.talkTo(text)) _input.clear();
- _focus.requestFocus();
- }
-
- TextStyle _text([double size = 14, Color? color]) => TextStyle(
- fontFamily: AppType.sansFamily,
- fontFamilyFallback: AppType.sansFallback,
- fontSize: size,
- height: 1.5,
- color: color ?? AppColors.text,
- );
-
- @override
- Widget build(BuildContext context) {
- final daemon = widget.daemon;
- final name = daemon == null ? 'your companion' : companionName(daemon);
- final accent = CompanionStory.of(daemon?.id ?? 'tim').accent;
- final brain = widget.brain;
- final status = brain.talkNeedsSetup
- ? 'Your model may need first-time setup. Open the full conversation to continue.'
- : brain.talkWait != null
- ? 'You can send another message in ${(brain.talkWait!.inMilliseconds / 1000).ceil()} seconds.'
- : switch (brain.talkPhase) {
- DaemonTalkPhase.waking => 'Waking $name…',
- DaemonTalkPhase.started || DaemonTalkPhase.resumed =>
- '$name is getting settled. The conversation is starting…',
- DaemonTalkPhase.sent => '$name is listening…',
- DaemonTalkPhase.failed =>
- brain.talkError ?? 'Your message could not be sent.',
- _ => null,
- };
- return Material(
- key: const ValueKey('companion-chat'),
- color: AppColors.background,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(24, 24, 18, 18),
- child: Row(
- children: [
- if (daemon != null) ...[
- DaemonIllustration(
- art: IllustratedArt.daemon(
- daemon.id,
- version: daemon.version,
- traits: widget.traits,
- ),
- size: 38,
- ),
- const SizedBox(width: 12),
- ],
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- 'A moment with ${daemon == null ? 'a friend' : name}',
- style: _text(16).copyWith(fontWeight: FontWeight.w600),
- ),
- Text(
- _available
- ? 'Your companion, here with you'
- : 'A little company for your day',
- style: _text(12, AppColors.textSoft),
- ),
- ],
- ),
- ),
- if (widget.onOpenConversation != null &&
- (widget.canOpenConversation?.call() ?? true))
- IconButton(
- key: const ValueKey('companion-conversation'),
- tooltip: 'Open full conversation and permissions',
- onPressed: widget.onOpenConversation,
- icon: Icon(
- Icons.open_in_new_rounded,
- size: 18,
- color: AppColors.textSoft,
- ),
- ),
- ],
- ),
- ),
- Divider(height: 1, color: AppColors.border),
- Expanded(
- child: ListView(
- controller: _scroll,
- padding: const EdgeInsets.all(24),
- children: [
- if (brain.talk.isEmpty) ...[
- const SizedBox(height: 28),
- Icon(
- Icons.chat_bubble_outline_rounded,
- size: 28,
- color: accent,
- ),
- const SizedBox(height: 20),
- Text(
- 'Every friendship starts\nwith a hello.',
- textAlign: TextAlign.center,
- style: _text(23)
- .copyWith(fontFamily: 'Georgia', height: 1.3),
- ),
- const SizedBox(height: 14),
- Text(
- 'Share an idea, ask about your work, or get to know $name. '
- 'This is a conversation you can come back to.',
- textAlign: TextAlign.center,
- style: _text(14, AppColors.textSoft),
- ),
- const SizedBox(height: 26),
- for (final prompt in [
- 'Tell me your story',
- 'What are we working on?',
- 'What have we learned together?',
- ])
- Padding(
- padding: const EdgeInsets.only(bottom: 10),
- child: OutlinedButton(
- style: OutlinedButton.styleFrom(
- alignment: Alignment.centerLeft,
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 13,
- ),
- side: BorderSide(color: AppColors.border),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12),
- ),
- ),
- onPressed: _canSend ? () => _send(prompt) : null,
- child: Text(
- prompt,
- style: _text(
- 13,
- _canSend ? AppColors.text : AppColors.muted,
- ),
- ),
- ),
- ),
- ],
- for (final entry in brain.talk)
- Padding(
- padding: const EdgeInsets.only(bottom: 20),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- entry.you ? 'You' : name,
- style: _text(
- 12,
- AppColors.textSoft,
- ).copyWith(fontWeight: FontWeight.w600),
- ),
- const SizedBox(height: 7),
- Container(
- width: double.infinity,
- padding: const EdgeInsets.all(15),
- decoration: BoxDecoration(
- color: entry.you
- ? AppColors.surface
- : accent.withValues(alpha: .09),
- borderRadius: BorderRadius.circular(14),
- ),
- child: SelectableText(entry.text, style: _text()),
- ),
- ],
- ),
- ),
- if (status != null)
- Semantics(
- liveRegion: true,
- child: Text(
- status,
- key: const ValueKey('companion-chat-status'),
- style: _text(
- 13,
- brain.talkPhase == DaemonTalkPhase.failed
- ? AppColors.danger
- : AppColors.textSoft,
- ),
- ),
- ),
- if (brain.talkNeedsSetup &&
- widget.onOpenConversation != null &&
- (widget.canOpenConversation?.call() ?? true))
- Align(
- alignment: Alignment.centerLeft,
- child: TextButton.icon(
- key: const ValueKey('companion-chat-setup'),
- onPressed: widget.onOpenConversation,
- icon: const Icon(Icons.open_in_new_rounded, size: 16),
- label: const Text('Open full conversation'),
- ),
- ),
- if (!_available) ...[
- const SizedBox(height: 20),
- Text(
- widget.preview
- ? 'Gallery previews are for exploring. Chat is available with your paired companion.'
- : daemon == null
- ? 'Hatch your first companion to begin.'
- : 'Chat connects through the companion on this computer. '
- 'If this is your first visit, open companion settings to get started.',
- style: _text(13, AppColors.textSoft),
- ),
- if (widget.onOpenControls != null)
- TextButton(
- onPressed: widget.onOpenControls,
- child: const Text('Companion settings'),
- ),
- ],
- ],
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(20, 12, 20, 18),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Container(
- decoration: BoxDecoration(
- color: AppColors.surface,
- border: Border.all(color: AppColors.borderStrong),
- borderRadius: BorderRadius.circular(16),
- ),
- padding: const EdgeInsets.fromLTRB(14, 5, 5, 5),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.end,
- children: [
- Expanded(
- child: TextField(
- key: const ValueKey('companion-chat-input'),
- controller: _input,
- focusNode: _focus,
- enabled: _available,
- minLines: 1,
- maxLines: 5,
- maxLength: 2000,
- style: _text(),
- textInputAction: TextInputAction.send,
- onSubmitted: (_) => _send(),
- decoration: InputDecoration(
- hintText: 'Say something to $name…',
- hintStyle: _text(14, AppColors.textSoft),
- counterText: '',
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- disabledBorder: InputBorder.none,
- filled: false,
- contentPadding: const EdgeInsets.symmetric(
- vertical: 10,
- ),
- ),
- ),
- ),
- IconButton(
- key: const ValueKey('companion-chat-send'),
- tooltip: 'Send message',
- onPressed: _canSend ? _send : null,
- icon: Icon(
- Icons.arrow_upward_rounded,
- color: _canSend ? AppColors.text : AppColors.muted,
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 10),
- Text(
- brain.talkCost ?? 'Messages use your connected model and count toward your model usage. The full conversation stays in your companion’s harness.',
- key: const ValueKey('companion-chat-cost'),
- style: _text(11, AppColors.textSoft),
- ),
- ],
- ),
- ),
- ],
- ),
- );
- }
-
- @override
- void dispose() {
- widget.brain.removeListener(_changed);
- _retryTicker?.cancel();
- _input.dispose();
- _focus.dispose();
- _scroll.dispose();
- super.dispose();
- }
-}
diff --git a/desktop/lib/companions/companion_home.dart b/desktop/lib/companions/companion_home.dart
index 155cbc392..0f393e8ce 100644
--- a/desktop/lib/companions/companion_home.dart
+++ b/desktop/lib/companions/companion_home.dart
@@ -15,12 +15,11 @@ import '../shared/theme/app_theme.dart' as grid;
import '../state/dial_status.dart';
import '../theme/app_theme.dart';
import '../widgets/daemon_illustration.dart';
-import 'companion_chat.dart';
import 'companion_dial.dart';
import 'companion_story.dart';
-/// The native viewer for the hidden companion DSH. Its world is a full tab;
-/// chat uses the same pair brain, lessons, and permissions as the quick controls.
+/// The illustrated left viewer of the companion DSH. The shared workspace
+/// canvas owns its real agent terminal on the right.
/// The illustrated editorial surface is intentionally distinct from terminal
/// chrome (the owner's requested storybook treatment).
class CompanionHome extends StatefulWidget {
@@ -31,20 +30,18 @@ class CompanionHome extends StatefulWidget {
required this.onHatch,
required this.onOpenControls,
this.onOpenConversation,
- this.canOpenConversation,
+ this.terminalStatus,
this.dial,
this.onDeviceSettings,
- this.focusRequest = 0,
});
final DaemonFace face;
final DaemonBrain brain;
final ValueChanged<ZooEgg> onHatch;
final ValueChanged<String> onOpenControls;
final VoidCallback? onOpenConversation;
- final bool Function()? canOpenConversation;
+ final String? terminalStatus;
final DialState? dial;
final void Function(String, Map<String, Object?>)? onDeviceSettings;
- final int focusRequest;
@override
State<CompanionHome> createState() => _CompanionHomeState();
@@ -59,6 +56,7 @@ class _CompanionHomeState extends State<CompanionHome> {
final _name = TextEditingController();
final _scroll = ScrollController();
late final _lessons = DaemonLessons(widget.brain)..addListener(_changed);
+ Timer? _memoryRefresh;
ZooController get zoo => widget.face.zoo;
ZooDaemon? get individual =>
_previewSpecies != null ? null : zoo.zoo.byUid(_viewingUid) ?? zoo.paired;
@@ -76,15 +74,6 @@ class _CompanionHomeState extends State<CompanionHome> {
widget.brain.addListener(_changed);
}
- @override
- void didUpdateWidget(CompanionHome old) {
- super.didUpdateWidget(old);
- if (old.focusRequest != widget.focusRequest) {
- // Chat becomes its own view only when the two panes cannot fit.
- if (MediaQuery.sizeOf(context).width < 980) _section = 'Chat';
- }
- }
-
void _changed() {
if (mounted) setState(() {});
}
@@ -110,6 +99,14 @@ class _CompanionHomeState extends State<CompanionHome> {
void _selectSection(String value) {
setState(() => _section = value);
+ _memoryRefresh?.cancel();
+ _memoryRefresh = value == 'Memories'
+ ? Timer.periodic(const Duration(seconds: 30), (_) {
+ if (widget.brain.active && !_lessons.busy) {
+ unawaited(_lessons.refresh());
+ }
+ })
+ : null;
if (_scroll.hasClients) _scroll.jumpTo(0);
if (value == 'Memories' && widget.brain.active && !_lessons.busy) {
unawaited(_lessons.refresh());
@@ -178,19 +175,6 @@ class _CompanionHomeState extends State<CompanionHome> {
color: AppColors.background,
child: LayoutBuilder(
builder: (context, constraints) {
- final scale = MediaQuery.textScalerOf(context).scale(14) / 14;
- final split = constraints.maxWidth >= 980 * math.min(scale, 1.35);
- final chat = CompanionChat(
- key: ValueKey('companion-chat:${zoo.scope}:${zoo.paired?.uid}'),
- brain: widget.brain,
- daemon: zoo.paired,
- traits: zoo.traitsOf(zoo.paired),
- preview: zoo.isPreview,
- onOpenConversation: widget.onOpenConversation,
- canOpenConversation: widget.canOpenConversation,
- onOpenControls: () => widget.onOpenControls('settings'),
- focusRequest: widget.focusRequest,
- );
final viewer = Column(
children: [
Padding(
@@ -229,7 +213,6 @@ class _CompanionHomeState extends State<CompanionHome> {
'Story',
'Collection',
'Memories',
- if (!split) 'Chat',
])
Semantics(
selected: _section == section,
@@ -246,44 +229,45 @@ class _CompanionHomeState extends State<CompanionHome> {
],
),
),
- Expanded(
- child: !split && _section == 'Chat'
- ? chat
- : SingleChildScrollView(
- controller: _scroll,
- padding: const EdgeInsets.fromLTRB(28, 6, 28, 40),
- child: Align(
- alignment: Alignment.topCenter,
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 1100),
- child: switch (_section) {
- 'Collection' => _collection(),
- 'Memories' => _memories(),
- _ =>
- zoo.zoo.daemons.isEmpty &&
- _previewSpecies == null
- ? _nest()
- : _story(),
- },
- ),
+ if (widget.terminalStatus != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(28, 0, 28, 10),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ widget.terminalStatus!,
+ style: ink(13, AppColors.textSoft),
),
),
- ),
- ],
- );
- return Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Expanded(child: viewer),
- if (split) ...[
- VerticalDivider(width: 1, color: AppColors.border),
- SizedBox(
- width: (constraints.maxWidth * .30).clamp(340, 430),
- child: chat,
+ if (widget.onOpenConversation != null)
+ _button('Open terminal', widget.onOpenConversation),
+ ],
+ ),
),
- ],
+ Expanded(
+ child: SingleChildScrollView(
+ controller: _scroll,
+ padding: const EdgeInsets.fromLTRB(28, 6, 28, 40),
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1100),
+ child: switch (_section) {
+ 'Collection' => _collection(),
+ 'Memories' => _memories(),
+ _ =>
+ zoo.zoo.daemons.isEmpty && _previewSpecies == null
+ ? _nest()
+ : _story(),
+ },
+ ),
+ ),
+ ),
+ ),
],
);
+ return viewer;
},
),
);
@@ -844,12 +828,20 @@ class _CompanionHomeState extends State<CompanionHome> {
: 'Your memory book is ready to open.',
style: ink(14, AppColors.textSoft),
)
- else if (learned.isEmpty)
+ else if (learned.isEmpty && _lessons.learning == null)
_memoryCard(
Icons.auto_stories_outlined,
'Room for a first memory',
'When a useful lesson is proposed and you approve it, it will appear here. No memories are invented.',
),
+ if (widget.brain.active && _lessons.learning != null) ...[
+ _memoryCard(
+ Icons.auto_stories_outlined,
+ _lessons.learning!.title,
+ _lessons.learning!.detail,
+ ),
+ const SizedBox(height: 18),
+ ],
for (final lesson in learned) ...[
Container(
padding: const EdgeInsets.all(20),
@@ -1013,6 +1005,7 @@ class _CompanionHomeState extends State<CompanionHome> {
@override
void dispose() {
+ _memoryRefresh?.cancel();
zoo.removeListener(_changed);
widget.face.removeListener(_changed);
widget.brain.removeListener(_changed);
diff --git a/desktop/lib/daemons/daemon_brain.dart b/desktop/lib/daemons/daemon_brain.dart
index 28ecea740..b7296278b 100644
--- a/desktop/lib/daemons/daemon_brain.dart
+++ b/desktop/lib/daemons/daemon_brain.dart
@@ -871,9 +871,11 @@ class DaemonBrain extends ChangeNotifier {
List<DaemonTalkEntry> get talk => List.unmodifiable(_talk);
bool get talkNeedsSetup => _talkNeedsSetup;
- /// A different account or individual never inherits the previous chat.
+ /// Legacy compact replies stay archived by individual. The real agent terminal
+ /// belongs to the collection and stays attached while changing characters.
void bindConversation(String? scope, String? uid) {
if (scope == _conversationScope && uid == _companionUid) return;
+ final sameCollection = scope != null && scope == _conversationScope;
_conversationScope = scope;
_companionUid = uid;
final generation = ++_conversationGeneration;
@@ -883,7 +885,7 @@ class DaemonBrain extends ChangeNotifier {
_talkPhase = DaemonTalkPhase.idle;
_talkNeedsSetup = false;
_talkError = null;
- _pairAgentId = null;
+ if (!sameCollection || uid == null) _pairAgentId = null;
_talk.clear();
_heardReplies.clear();
notifyListeners();
@@ -1014,6 +1016,7 @@ class DaemonBrain extends ChangeNotifier {
'daemon_act_result',
'daemon_confirm_result',
'daemon_talk_result',
+ 'daemon_open_result',
'pair_result',
};
@@ -1034,6 +1037,8 @@ class DaemonBrain extends ChangeNotifier {
switch (type) {
case 'daemon_state':
_state = DaemonBrainState.fromJson(payload);
+ final harness = payload['companionHarness'];
+ if (harness is Map) _pairAgentId = _opt(harness['agentId']);
notifyListeners();
case 'daemon_say':
final say = DaemonSay.fromJson(payload);
@@ -1108,6 +1113,7 @@ class DaemonBrain extends ChangeNotifier {
}
if (error == 'NOT_SHOWN' || error == 'TOO_SOON') _showAgain(id);
_errors.add(actError(error, _opt(payload['detail'])));
+ case 'daemon_open_result':
case 'pair_result':
final requestId = payload['requestId'];
if (requestId is! String) return;
@@ -1254,16 +1260,34 @@ class DaemonBrain extends ChangeNotifier {
Future<Map<String, dynamic>> request(
String verb, [
Map<String, dynamic> payload = const {},
- ]) async {
+ ]) => _requestFrame('pair', {...payload, 'verb': verb});
+
+ /// Opening a DSH starts/resumes its terminal without sending any words or
+ /// Enter key. Trust, login and permissions remain in the engine's own UI.
+ Future<Map<String, dynamic>> openConversation() async {
+ final generation = _conversationGeneration;
+ final uid = _companionUid;
+ if (uid == null) return {'ok': false, 'error': 'PAIR_OFF'};
+ final result = await _requestFrame('daemon_open', {'companionUid': uid});
+ if (_disposed || generation != _conversationGeneration) {
+ return {'ok': false, 'error': 'STALE_COMPANION'};
+ }
+ if (result['ok'] == true) {
+ _pairAgentId = _opt(result['agentId']);
+ notifyListeners();
+ }
+ return result;
+ }
+
+ Future<Map<String, dynamic>> _requestFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
if (_disposed) return {'ok': false, 'error': 'CLOSED'};
final requestId = _id(12);
final done = Completer<Map<String, dynamic>>();
_requests[requestId] = done;
- final sent = send('pair', {
- ...payload,
- 'verb': verb,
- 'requestId': requestId,
- });
+ final sent = send(type, {...payload, 'requestId': requestId});
if (!sent) {
_requests.remove(requestId);
return {'ok': false, 'error': 'UNREACHABLE'};
diff --git a/desktop/lib/daemons/daemon_lessons.dart b/desktop/lib/daemons/daemon_lessons.dart
index 401eff61f..e185663f9 100644
--- a/desktop/lib/daemons/daemon_lessons.dart
+++ b/desktop/lib/daemons/daemon_lessons.dart
@@ -69,6 +69,79 @@ class DaemonLesson {
}
}
+@immutable
+class DaemonLearning {
+ const DaemonLearning({
+ required this.state,
+ this.model,
+ this.effort,
+ this.queued = 0,
+ this.pending = 0,
+ this.lastOutcome,
+ });
+ final String state;
+ final String? model, effort, lastOutcome;
+ final int queued, pending;
+
+ static DaemonLearning? fromJson(Object? raw) {
+ if (raw is! Map || raw['state'] is! String) return null;
+ final review = raw['lastReview'];
+ return DaemonLearning(
+ state: raw['state'] as String,
+ model: raw['model'] is String ? raw['model'] as String : null,
+ effort: raw['effort'] is String ? raw['effort'] as String : null,
+ queued: raw['queued'] is int ? raw['queued'] as int : 0,
+ pending: raw['pending'] is int ? raw['pending'] as int : 0,
+ lastOutcome: review is Map && review['outcome'] is String
+ ? review['outcome'] as String
+ : null,
+ );
+ }
+
+ String get title {
+ if (state != 'ready') {
+ return switch (state) {
+ 'off' => 'Learning is paused',
+ 'unsupported' => 'Learning is waiting for a supported connection',
+ _ => 'Getting ready to learn',
+ };
+ }
+ final name = switch (model) {
+ 'opus' => 'Opus',
+ 'sonnet' => 'Sonnet',
+ 'haiku' => 'Haiku',
+ final String value => value,
+ _ => 'your chosen model',
+ };
+ return 'Learning with $name';
+ }
+
+ String get detail {
+ if (state == 'off') {
+ return 'Learning resumes when your companion is turned on.';
+ }
+ if (state == 'unsupported') {
+ return 'Background learning cannot use this agent connection yet. Your conversation and approved lessons are kept.';
+ }
+ if (state != 'ready') {
+ return 'Finish setting up the agent on the right. Learning follows the model you choose there.';
+ }
+ if (pending > 0) {
+ return 'A useful lesson is waiting for your approval. It will be shared with your agents once you approve it.';
+ }
+ if (['failed', 'timeout', 'no-model'].contains(lastOutcome)) {
+ return 'The last review could not finish. Your observations are queued for another try.';
+ }
+ if (queued > 0) {
+ return '$queued ${queued == 1 ? 'observation is' : 'observations are'} waiting for a quiet moment to review.';
+ }
+ if (lastOutcome == 'nothing' || lastOutcome == 'no-template') {
+ return 'The last review found nothing worth saving yet. I’m watching for useful corrections and patterns in your work.';
+ }
+ return 'Watching for useful corrections and patterns in your work. Lessons are saved after you approve them.';
+ }
+}
+
class DaemonLessons extends ChangeNotifier {
DaemonLessons(this.brain) {
_results = brain.results.listen(_heard);
@@ -83,6 +156,8 @@ class DaemonLessons extends ChangeNotifier {
bool _loaded = false, _busy = false, _disposed = false;
String? _message, _note;
String? _shownId, _shownText;
+ DaemonLearning? _learning;
+ DaemonLearning? get learning => _learning;
/// Pending first, then approved; skipped and reverted ones are history.
List<DaemonLesson> get lessons => _lessons;
@@ -140,6 +215,7 @@ class DaemonLessons extends ChangeNotifier {
...all.where((l) => l.approvedNow),
];
_note = result['note'] is String ? result['note'] as String : null;
+ _learning = DaemonLearning.fromJson(result['learning']);
} else {
_message = _words(result);
}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index deceef8a9..5387c38bc 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -336,7 +336,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
DaemonBrief? _lastBrief;
StreamSubscription<int?>? _zooPushes;
OverlayEntry? _daemonOverlay;
- int _companionTalkRequest = 0;
OverlayEntry? _hatchOverlay;
OverlayEntry? _daemonHintOverlay;
OverlayEntry? _daemonPreview;
@@ -965,6 +964,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
void _recordNavigation() {
+ _scheduleCompanionWorkspace();
_navigation.record(app);
if (_hasCommandBar && _commandBarOpen) {
final local = app.localMachineState;
@@ -1565,7 +1565,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// agent and its pane are one agent — and one mark on the tab — not a two-pane group.
Set<(String, String)> _tabAgents(Swarm tab) => {
for (final pane in tab.panes)
- if ((pane.isWeb ? pane.ownerAgentId : pane.agentId) case final id?)
+ if ((pane.isViewer ? pane.ownerAgentId : pane.agentId) case final id?)
(pane.machineId, id),
};
@@ -3309,6 +3309,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_brain.reset();
_plates.reset();
_syncDaemon();
+ _scheduleCompanionWorkspace();
// A setting change must leave keyboard focus in Settings.
if (hadOverlay && _routeIsCurrent && !_dialogOpen) _returnFocusToPane();
}
@@ -3577,11 +3578,100 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// The whole conversation: the pair harness's own pane.
void _openConversation() {
- final pair = _pairHarness;
- if (pair == null) return;
- _openHarness(DaemonAbout(pair.machineId, pair.agentId));
+ _openCompanions(talk: true);
+ }
+
+ bool _companionWorkspaceScheduled = false;
+ String? _companionAttemptedKey, _companionOpeningKey;
+ String? _companionTerminalError;
+ bool _focusCompanionTerminal = false;
+
+ void _scheduleCompanionWorkspace() {
+ if (_companionWorkspaceScheduled) return;
+ _companionWorkspaceScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _companionWorkspaceScheduled = false;
+ if (mounted) _syncCompanionWorkspace();
+ });
+ }
+
+ void _syncCompanionWorkspace() {
+ final enabled = _creatureEnabled && _zoo.loaded;
+ app.syncCompanionViewer(
+ enabled: enabled,
+ machineId: app.localMachineState?.machine.machineId,
+ );
+ if (!enabled) {
+ _companionAttemptedKey = null;
+ return;
+ }
+ final pair = _zoo.isPreview ? null : _pairHarness;
+ unawaited(app.showCompanionTerminal(pair?.machineId, pair?.agentId));
+ if (!app.activeSwarm.isCompanions) {
+ _companionAttemptedKey = null;
+ return;
+ }
+ if (_focusCompanionTerminal && pair != null) {
+ final pane = app.panes
+ .where((p) => p.agentId == pair.agentId)
+ .firstOrNull;
+ if (pane != null) {
+ _focusCompanionTerminal = false;
+ app.focusPane(pane.id);
+ }
+ }
+ final uid = _zoo.paired?.uid;
+ if (_zoo.isPreview || uid == null || !_brain.active) return;
+ final key = '${_zoo.scope}:$uid';
+ if (_companionAttemptedKey == key || _companionOpeningKey == key) return;
+ _companionAttemptedKey = key;
+ _companionOpeningKey = key;
+ _companionTerminalError = null;
+ setState(() {});
+ unawaited(_openCompanionTerminal(key));
+ }
+
+ Future<void> _openCompanionTerminal(String key) async {
+ final result = await _brain.openConversation();
+ if (!mounted || _companionOpeningKey != key) return;
+ _companionOpeningKey = null;
+ if (key != '${_zoo.scope}:${_zoo.paired?.uid}' || !_creatureEnabled) return;
+ if (result['ok'] != true) {
+ _companionTerminalError = switch (result['error']) {
+ 'UNSUPPORTED' => 'Update Harness CLI to open the companion terminal.',
+ 'NO_ENGINE' =>
+ 'Install Claude Code or Codex to talk with your companion.',
+ _ =>
+ result['detail'] as String? ??
+ 'The terminal could not connect. Try opening it again.',
+ };
+ }
+ setState(() {});
+ _scheduleCompanionWorkspace();
}
+ Widget _companionViewer(BuildContext context) => CompanionHome(
+ key: ValueKey('companion-home:${_zoo.scope}'),
+ face: _face,
+ brain: _brain,
+ onHatch: _hatch,
+ onOpenControls: _openCompanionControls,
+ terminalStatus:
+ _companionTerminalError ??
+ (_companionOpeningKey != null
+ ? 'Opening your companion’s terminal…'
+ : null),
+ onOpenConversation: _companionTerminalError == null
+ ? null
+ : () {
+ _companionAttemptedKey = null;
+ _focusCompanionTerminal = true;
+ _scheduleCompanionWorkspace();
+ },
+ dial: app.dial,
+ onDeviceSettings: app.setDeviceSettings,
+ );
+
/// `~/.config/harness/pair.jsonc`, written with no rules when it is not
/// there yet, opened in the editor `.jsonc` files open in.
Future<void> _openPairRules() async {
@@ -3748,6 +3838,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _brainChanged() {
// Heard while daemons are off (or not decided yet): nothing shows.
if (!mounted || !_zoo.loaded) return;
+ _scheduleCompanionWorkspace();
final firstHeard = !_face.brainActive && _brain.active;
_face.brainActive = _brain.active;
if (firstHeard) unawaited(_sendPresence());
@@ -3851,6 +3942,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _zooChanged() {
if (!mounted) return;
_brain.bindConversation(_zoo.scope, _zoo.paired?.uid);
+ _scheduleCompanionWorkspace();
if (!_zoo.loaded || _lastZooScope != _zoo.scope) {
_closeDaemonHint();
_closeDaemon(restoreFocus: false);
@@ -4178,8 +4270,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
_closeCommandBar(restoreFocus: false);
dismissTransientMenus();
_preparePaneFocus();
- if (talk) _companionTalkRequest++;
+ if (talk) {
+ _focusCompanionTerminal = true;
+ _companionAttemptedKey = null;
+ }
app.openCompanions();
+ _scheduleCompanionWorkspace();
_face.look();
_face.seen();
setState(() {});
@@ -6279,11 +6375,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
Offstage(
key: const ValueKey('workspace-canvas'),
offstage:
- app.activeSwarm.isUtility ||
+ app.activeSwarm.isStore ||
+ (app.activeSwarm.isCompanions &&
+ (!_creatureEnabled || !_zoo.loaded)) ||
app.activeSwarm.isOrchestrator,
child: ExcludeFocus(
excluding:
- app.activeSwarm.isUtility ||
+ app.activeSwarm.isStore ||
+ (app.activeSwarm.isCompanions &&
+ (!_creatureEnabled || !_zoo.loaded)) ||
app.activeSwarm.isOrchestrator,
child: Padding(
padding: app.panes.isEmpty
@@ -6303,6 +6403,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: PaneGrid(
notifier: app,
swarmMode: true,
+ companionViewer:
+ _creatureEnabled && _zoo.loaded
+ ? _companionViewer
+ : null,
soloFocused: _compact(context),
empty:
app.panes.isEmpty &&
@@ -6411,35 +6515,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
recentHarnesses: _navigation.recent,
source: 'tab',
),
- if (_creatureEnabled &&
- _zoo.loaded &&
- app.swarms.any((s) => s.isCompanions))
- Offstage(
- offstage: !app.activeSwarm.isCompanions,
- child: ExcludeFocus(
- excluding: !app.activeSwarm.isCompanions,
- child: TickerMode(
- enabled: app.activeSwarm.isCompanions,
- child: CompanionHome(
- key: ValueKey(
- 'companion-home:${_zoo.scope}',
- ),
- face: _face,
- brain: _brain,
- onHatch: _hatch,
- onOpenControls: _openCompanionControls,
- onOpenConversation: _zoo.isPreview
- ? null
- : _openConversation,
- canOpenConversation: () =>
- _pairHarness != null,
- dial: app.dial,
- onDeviceSettings: app.setDeviceSettings,
- focusRequest: _companionTalkRequest,
- ),
- ),
- ),
- ),
if (app.activeSwarm.isCompanions &&
(!_creatureEnabled || !_zoo.loaded))
Center(
@@ -6547,7 +6622,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
final machine = app.stateOf(focused.pane.machineId);
final agent = focused.agent;
- final owner = focused.pane.isWeb
+ final owner = focused.pane.isViewer
? app.panes
.where(
(pane) =>
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 3f1802562..75a3710b2 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1325,7 +1325,7 @@ class AppNotifier extends ChangeNotifier {
String? _pendingStoreHarness;
/// The companion's illustrated viewer and conversation, one per window.
- /// Opening it never launches an engine; only sending a chat does that.
+ /// Its panes are bound only after the account's experimental gate is loaded.
void openCompanions() {
final existing = swarms.where((s) => s.isCompanions).firstOrNull;
if (existing != null) {
@@ -1356,6 +1356,66 @@ class AppNotifier extends ChangeNotifier {
selectSwarm(tab.id);
}
+ /// The built-in companion viewer uses the same canvas, focus, geometry and
+ /// terminal sessions as every DSH. These panes are derived from the enabled
+ /// account and current individual, never restored before that gate is known.
+ void syncCompanionViewer({required bool enabled, String? machineId}) {
+ var changed = false;
+ for (final tab in swarms.where((s) => s.isCompanions)) {
+ if (!enabled) {
+ for (final pane in tab.panes.toList()) {
+ tab.remove(pane);
+ if (!allPanes.contains(pane)) {
+ unawaited(_detachSession(pane, sendClose: true));
+ }
+ changed = true;
+ }
+ } else if (!tab.panes.any((p) => p.isCompanion)) {
+ final viewer = TerminalPane(
+ id: _nextPaneId++,
+ machineId: machineId ?? '',
+ kind: PaneKind.companion,
+ );
+ tab.panes.insert(0, viewer);
+ tab.focusedPaneId ??= viewer.id;
+ changed = true;
+ }
+ }
+ if (changed) notifyListeners();
+ }
+
+ Future<void> showCompanionTerminal(String? machineId, String? agentId) async {
+ final tab = swarms.where((s) => s.isCompanions).firstOrNull;
+ final viewer = tab?.panes.where((p) => p.isCompanion).firstOrNull;
+ if (tab == null || viewer == null) return;
+ var changed =
+ viewer.ownerAgentId != agentId || viewer.machineId != (machineId ?? '');
+ viewer.ownerAgentId = agentId;
+ viewer.machineId = machineId ?? '';
+ for (final pane in tab.panes.where((p) => !p.isCompanion).toList()) {
+ if (pane.machineId == machineId && pane.agentId == agentId) continue;
+ tab.remove(pane);
+ if (!allPanes.contains(pane)) {
+ unawaited(_detachSession(pane, sendClose: true));
+ }
+ changed = true;
+ }
+ if (changed) notifyListeners();
+ if (machineId == null || agentId == null) return;
+ // Keep the product's name and its standard viewer-left/terminal-right split.
+ if (tab.paneSizes['2:manual'] == null) {
+ tab.savePaneSizes('2:manual', PaneArrangement.viewerBesideTerminal);
+ }
+ await assignAgentToPane(
+ null,
+ machineId,
+ agentId,
+ swarmId: tab.id,
+ focus: false,
+ intent: tab == activeSwarm ? AttachIntent.person : AttachIntent.automatic,
+ );
+ }
+
/// The harness page [openStore] was asked for, handed over once. The Store
/// tab reads it when it is built and on every change while it is open.
String? takePendingStoreHarness() {
@@ -2248,6 +2308,18 @@ class AppNotifier extends ChangeNotifier {
bool isPaneFocused(int paneId) =>
!railFocused && !tabStripFocused && focusedPaneId == paneId;
+ /// A harness's terminal and viewers stay clear together. Keyboard focus and
+ /// its ring still belong to one pane, including while a menu owns input.
+ bool isPaneEmphasized(TerminalPane pane) {
+ final selected = focusedPane;
+ if (selected == null) return false;
+ if (selected.id == pane.id) return true;
+ final agentId = selected.agentId ?? selected.ownerAgentId;
+ return agentId != null &&
+ selected.machineId == pane.machineId &&
+ agentId == (pane.agentId ?? pane.ownerAgentId);
+ }
+
/// True while the KEYBOARD is on the tab strip rather than in any pane.
///
/// Closing the ACTIVE tab with work in it — ⌘W, the strip's own close, or
@@ -7474,7 +7546,7 @@ class AppNotifier extends ChangeNotifier {
Iterable<({String machineId, String agentId})> _visibleOnTab() {
if (lifecycle() != AppLifecycleState.resumed) return const [];
- if (activeSwarm.isUtility || activeSwarm.isOrchestrator) return const [];
+ if (activeSwarm.isStore || activeSwarm.isOrchestrator) return const [];
return [
for (final pane in activeSwarm.panes)
if (zoomedPaneId == null || pane.id == zoomedPaneId)
@@ -10741,7 +10813,7 @@ class AppNotifier extends ChangeNotifier {
target.arranged = split.after;
target.arrangedKey = key;
}
- if (firstAgent && !target.nameIsCustom) {
+ if (firstAgent && !target.nameIsCustom && !target.isCompanions) {
final agent = machine.agents
.where((agent) => agent.id == agentId)
.firstOrNull;
@@ -11373,6 +11445,10 @@ class AppNotifier extends ChangeNotifier {
Future<void> closePane(int paneId, {bool persist = true}) async {
final pane = panes.where((p) => p.id == paneId).firstOrNull;
if (pane == null) return;
+ if (activeSwarm.isCompanions) {
+ await closeSwarm(activeSwarmId, persist: persist);
+ return;
+ }
if (pane.isWeb) {
// A viewer closed by hand stays closed for THIS page: the agent's next
// frame carries the same URL and must not reopen it. A different URL —
@@ -12984,6 +13060,7 @@ class AppNotifier extends ChangeNotifier {
case 'daemon_act_result':
case 'daemon_confirm_result':
case 'daemon_talk_result':
+ case 'daemon_open_result':
case 'pair_result':
case 'daemon_plate':
// Only from the loopback socket bound to this computer's harnessd.
diff --git a/desktop/lib/state/harness_activity.dart b/desktop/lib/state/harness_activity.dart
index 4edbe044e..3be29a959 100644
--- a/desktop/lib/state/harness_activity.dart
+++ b/desktop/lib/state/harness_activity.dart
@@ -78,11 +78,11 @@ HarnessActivity? harnessActivity(
/// A viewer refers to its owner; showing the same harness twice adds no vote.
HarnessActivity? tabActivity(AppNotifier app, Swarm tab) {
- if (tab.isUtility || tab.isOrchestrator) return null;
+ if (tab.isStore || tab.isOrchestrator) return null;
HarnessActivity? result;
final seen = <(String, String)>{};
for (final pane in tab.panes) {
- final id = pane.isWeb ? pane.ownerAgentId : pane.agentId;
+ final id = pane.isViewer ? pane.ownerAgentId : pane.agentId;
if (id == null || !seen.add((pane.machineId, id))) continue;
final state = harnessActivity(app, pane.machineId, id);
if (state != null && (result == null || state.index < result.index)) {
diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dart
index 356725d35..69a9e2ef6 100644
--- a/desktop/lib/state/swarm.dart
+++ b/desktop/lib/state/swarm.dart
@@ -142,7 +142,7 @@ class Swarm {
Map<String, Object?> toJson() {
final agents = panes
- .where((p) => p.agentId != null)
+ .where((p) => !isCompanions && p.agentId != null)
.toList(growable: false);
return {
'id': id,
diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dart
index c50fd62cf..6652d17be 100644
--- a/desktop/lib/state/terminal_pane.dart
+++ b/desktop/lib/state/terminal_pane.dart
@@ -10,8 +10,9 @@ import '../core/models.dart' show SharedHarness;
/// terminal. It is DERIVED from the agent (the daemon says where the viewer
/// is, and the tile follows) and never persisted: a restored layout re-opens
/// it from the agent's next frame, so a stale URL from a previous run can
-/// never be loaded.
-enum PaneKind { terminal, web }
+/// never be loaded. [companion] is the built-in native viewer, derived from
+/// the selected individual only after its account's experiment is enabled.
+enum PaneKind { terminal, web, companion }
/// One tile in the terminal grid.
///
@@ -32,23 +33,27 @@ class TerminalPane {
this.viewerError,
this.ownerAgentId,
}) : assert(
- kind == PaneKind.terminal || (agentId == null && ownerAgentId != null),
+ kind != PaneKind.web || (agentId == null && ownerAgentId != null),
'a web tile belongs to an agent through ownerAgentId, never agentId',
);
final PaneKind kind;
bool get isWeb => kind == PaneKind.web;
+ bool get isCompanion => kind == PaneKind.companion;
+ bool get isViewer => isWeb || isCompanion;
/// [PaneKind.web] only: what the tile loads. Changes when the agent's frame
/// names a new viewer URL; the panel navigates rather than remounts.
String? url;
String? viewerError;
- /// [PaneKind.web] only: the agent whose viewer this is. Kept OFF [agentId]
+ /// The agent whose viewer this is. The native companion viewer can exist
+ /// before its agent starts, then follows the selected individual.
+ /// Kept OFF [agentId]
/// on purpose — everything that attaches a terminal, persists a layout or
/// remembers a closed agent keys on [agentId] being set, and none of that
/// applies to a viewer.
- final String? ownerAgentId;
+ String? ownerAgentId;
/// Stable for the tile's whole life, including across a machine going away
/// and returning. Widget keys hang off this: keying on the agent id instead
diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dart
index a2189c9e5..6ccc2d5a8 100644
--- a/desktop/lib/state/workspace_status.dart
+++ b/desktop/lib/state/workspace_status.dart
@@ -142,7 +142,7 @@ class WorkspacePaneContext {
final String machineName, provider, location, detail;
final String projectName;
final String? branch;
- String? get agentId => pane.isWeb ? pane.ownerAgentId : pane.agentId;
+ String? get agentId => pane.isViewer ? pane.ownerAgentId : pane.agentId;
String? get engine => agent?.engine ?? pane.session?.engineId;
String get modelLabel => modelLabelWithEffort(
provider,
@@ -185,7 +185,7 @@ class WorkspacePaneContext {
final pane = app.focusedPane;
if (pane == null) return null;
final machine = app.stateOf(pane.machineId);
- final agentId = pane.isWeb ? pane.ownerAgentId : pane.agentId;
+ final agentId = pane.isViewer ? pane.ownerAgentId : pane.agentId;
final agent = _agentFor(app, pane.machineId, agentId);
final project = agent == null ? null : machine?.projectOf(agent);
final machineName = machine?.machine.displayName ?? pane.machineId;
diff --git a/desktop/lib/widgets/harness_activity_mark.dart b/desktop/lib/widgets/harness_activity_mark.dart
index 7b2f81f51..9e0a6dc8d 100644
--- a/desktop/lib/widgets/harness_activity_mark.dart
+++ b/desktop/lib/widgets/harness_activity_mark.dart
@@ -258,7 +258,7 @@ class HarnessActivityMark extends StatelessWidget {
),
visible:
visible &&
- !app.activeSwarm.isUtility &&
+ !app.activeSwarm.isStore &&
!app.activeSwarm.isOrchestrator,
),
);
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 5697cb340..ecb0b2fc0 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -51,6 +51,7 @@ class PaneGrid extends StatelessWidget {
this.swarmMode = false,
this.empty,
this.soloFocused = false,
+ this.companionViewer,
});
final AppNotifier notifier;
@@ -62,6 +63,9 @@ class PaneGrid extends StatelessWidget {
/// harness at a time; the same desk on a computer keeps its grid).
final bool soloFocused;
+ /// The built-in companion DSH viewer; its agent uses the ordinary terminal.
+ final WidgetBuilder? companionViewer;
+
@override
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
@@ -74,6 +78,7 @@ class PaneGrid extends StatelessWidget {
dragging: dragging,
empty: empty,
soloFocused: soloFocused,
+ companionViewer: companionViewer,
);
}
final panes = notifier.panes;
@@ -88,6 +93,7 @@ class PaneGrid extends StatelessWidget {
dragging: dragging,
visible: visible,
swarmMode: swarmMode,
+ companionViewer: companionViewer,
);
final cells = <Widget>[
for (final pane in visible) cell(pane),
@@ -235,11 +241,13 @@ class _SwarmCanvas extends StatefulWidget {
required this.dragging,
this.empty,
this.soloFocused = false,
+ this.companionViewer,
});
final AppNotifier notifier;
final AgentDragRef? dragging;
final Widget? empty;
final bool soloFocused;
+ final WidgetBuilder? companionViewer;
@override
State<_SwarmCanvas> createState() => _SwarmCanvasState();
}
@@ -462,6 +470,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
link: session.linkMode,
upload: session.uploadProgress,
focused: app.isPaneFocused(pane.id),
+ emphasized: app.isPaneEmphasized(pane),
focusRequest: app.isPaneFocused(pane.id) ? app.paneFocusRequest : 0,
focusByUser: app.paneFocusByUser,
single: app.panes.length == 1,
@@ -575,6 +584,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
visible: rectangles.containsKey(pane.id),
swarmMode: true,
solo: widget.soloFocused,
+ companionViewer: widget.companionViewer,
),
),
),
@@ -1168,6 +1178,7 @@ class _PaneCell extends StatelessWidget {
this.visible = true,
this.swarmMode = false,
this.solo = false,
+ this.companionViewer,
});
final AppNotifier notifier;
@@ -1175,6 +1186,7 @@ class _PaneCell extends StatelessWidget {
final AgentDragRef? dragging;
final bool visible;
final bool swarmMode;
+ final WidgetBuilder? companionViewer;
/// Drawn alone under [PaneGrid.soloFocused]: it reads as the only view — no
/// dimming or focus ring, and no zoom, since it already fills the screen.
@@ -1198,9 +1210,9 @@ class _PaneCell extends StatelessWidget {
Widget _build(BuildContext context) {
grid.AppTheme.watch(context);
final focused = visible && notifier.isPaneFocused(pane.id);
- // Keep the selected pane clear while a menu or the tab strip owns keyboard
- // focus. This is paint only: inactive terminals stay mounted and clickable.
- final dimmed = !_single && notifier.focusedPaneId != pane.id;
+ // Keep the selected harness's terminal and viewers clear, including while
+ // a menu owns input. This changes paint, never the keyboard's destination.
+ final dimmed = !_single && !notifier.isPaneEmphasized(pane);
final agentId = pane.agentId;
final blocked =
agentId != null &&
@@ -1275,13 +1287,16 @@ class _PaneCell extends StatelessWidget {
opacity: inFlight?.paneId == pane.id ? 0.35 : 1,
child: child,
),
- child: _PaneContent(
- notifier: notifier,
- pane: pane,
- single: _single,
- visible: visible,
- swarmMode: swarmMode,
- ),
+ child: pane.isCompanion
+ ? companionViewer?.call(context) ??
+ const SizedBox.shrink()
+ : _PaneContent(
+ notifier: notifier,
+ pane: pane,
+ single: _single,
+ visible: visible,
+ swarmMode: swarmMode,
+ ),
),
),
),
@@ -1942,7 +1957,10 @@ class _SwapZone extends StatelessWidget {
child: IgnorePointer(
// Off entirely unless a pane is in flight, so the terminal
// underneath keeps every click the rest of the time.
- ignoring: dragging == null || dragging.paneId == paneId,
+ ignoring:
+ notifier.activeSwarm.isCompanions ||
+ dragging == null ||
+ dragging.paneId == paneId,
child: DragTarget<PaneDragRef>(
onAcceptWithDetails: (details) =>
notifier.reorderPane(details.data.paneId, paneId),
@@ -2186,7 +2204,7 @@ class _DropZone extends StatelessWidget {
child,
Positioned.fill(
child: IgnorePointer(
- ignoring: dragging == null,
+ ignoring: notifier.activeSwarm.isCompanions || dragging == null,
child: DragTarget<AgentDragRef>(
onAcceptWithDetails: (details) => notifier.assignAgentToPane(
paneId,
diff --git a/desktop/test/companion_home_test.dart b/desktop/test/companion_home_test.dart
index 80946448a..5f86121ca 100644
--- a/desktop/test/companion_home_test.dart
+++ b/desktop/test/companion_home_test.dart
@@ -8,6 +8,12 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/companions/companion_home.dart';
import 'package:harness/companions/companion_story.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/pane_grid.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+import 'package:xterm/xterm.dart';
import 'package:harness/daemons/daemon_brain.dart';
import 'package:harness/daemons/daemon_face.dart';
import 'package:harness/daemons/illustrated_art.dart';
@@ -25,6 +31,7 @@ import 'package:harness/state/workspace_status.dart';
import 'daemons/zoo_test.dart' show FakeZooTransport;
import 'support/real_fonts.dart';
import 'swarm_state_test.dart' show MemoryStore, createApp;
+import 'swarm_screen_test.dart' show terminal;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -117,6 +124,10 @@ void main() {
late List<(String, Map<String, dynamic>)> sent;
late GlobalKey boundary;
+ late AppNotifier workspace;
+ late TerminalSession conversation;
+ late List<TerminalBinaryFrame> input;
+
Future<void> mount(
WidgetTester tester, {
Size size = const Size(1400, 950),
@@ -205,6 +216,17 @@ void main() {
}
}
});
+ workspace = createApp(connected: true);
+ workspace.openCompanions();
+ workspace.syncCompanionViewer(enabled: true, machineId: 'm');
+ input = [];
+ conversation = terminal('a0', input)..agentName = 'Tim';
+ conversation.terminal.write(
+ '\x1b[1mTim\x1b[0m\r\n\r\nA little company for whatever you are making.\r\n\r\n> ',
+ );
+ workspace.adoptSessionForTest(conversation);
+ await workspace.showCompanionTerminal('m', 'a0');
+ workspace.focusPane(workspace.panes.first.id);
boundary = GlobalKey();
await tester.pumpWidget(
RepaintBoundary(
@@ -220,11 +242,18 @@ void main() {
child: child!,
),
home: Scaffold(
- body: CompanionHome(
- face: face,
- brain: brain,
- onHatch: (_) {},
- onOpenControls: (_) {},
+ body: ListenableBuilder(
+ listenable: workspace,
+ builder: (context, _) => PaneGrid(
+ notifier: workspace,
+ swarmMode: true,
+ companionViewer: (_) => CompanionHome(
+ face: face,
+ brain: brain,
+ onHatch: (_) {},
+ onOpenControls: (_) {},
+ ),
+ ),
),
),
),
@@ -235,6 +264,7 @@ void main() {
face.dispose();
zoo.dispose();
brain.dispose();
+ workspace.dispose();
});
}
@@ -312,39 +342,70 @@ void main() {
},
);
- testWidgets('chat sends the actual words once and shows the real reply', (
- tester,
- ) async {
- await mount(tester);
- await tester.enterText(
- find.byKey(const ValueKey('companion-chat-input')),
- 'Hello Tim',
- );
- await tester.tap(find.byKey(const ValueKey('companion-chat-send')));
- await tester.pump();
- expect(sent.single.$1, 'daemon_talk');
- expect(sent.single.$2['text'], 'Hello Tim');
- await tester.tap(find.byKey(const ValueKey('companion-chat-send')));
- expect(sent, hasLength(1));
- brain.receive('daemon_talk_result', {
- 'requestId': sent.single.$2['requestId'],
- 'ok': true,
- 'sent': true,
- 'agentId': 'pair-one',
- });
- brain.receive('daemon_say', {
- 'id': 'hello',
- 'line': 'oh hi. what are we making?',
- 'mood': 'say',
- 'from': 'pair',
- 'actions': [],
- });
- await tester.pump();
- expect(find.text('oh hi. what are we making?'), findsOneWidget);
- expect(remote.batches, isEmpty);
- await capture(tester, 'conversation');
- await tester.pumpWidget(const SizedBox());
- });
+ testWidgets(
+ 'DSH keeps its viewer left and real agent terminal right, including setup',
+ (tester) async {
+ await mount(tester);
+ final viewer = find.byKey(const ValueKey('companion-home'));
+ final terminalView = find.byType(TerminalPanel);
+ expect(terminalView, findsOneWidget);
+ expect(
+ tester.getRect(viewer).right,
+ lessThan(tester.getRect(terminalView).left),
+ );
+ expect(find.byKey(const ValueKey('companion-chat-input')), findsNothing);
+ expect(find.byTooltip('Open full conversation'), findsNothing);
+ expect(workspace.swarms, hasLength(1));
+ void expectBothPanesClear() {
+ for (final pane in workspace.panes) {
+ final frame = tester.widget<Container>(
+ find.byKey(ValueKey('pane-frame:${pane.id}')),
+ );
+ expect((frame.foregroundDecoration as BoxDecoration).color, isNull);
+ }
+ }
+
+ expectBothPanesClear();
+ conversation.terminal.write(
+ '\r\nDo you trust the files in this folder?\r\n> Yes, I trust this folder\r\n',
+ );
+ await tester.pump();
+ final view = tester.widget<TerminalView>(find.byType(TerminalView));
+ expect(
+ view.terminal.buffer.getText(),
+ contains('Yes, I trust this folder'),
+ );
+ expect(view.terminal, same(conversation.terminal));
+ await capture(tester, 'conversation-setup');
+ // A real terminal key uses the shared binary stream exactly once, never a
+ // second chat API or automatic approval of the setup text above.
+ await tester.tap(find.byType(TerminalView));
+ await tester.pump();
+ expectBothPanesClear();
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'h',
+ selection: TextSelection.collapsed(offset: 1),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 30));
+ expect(input, hasLength(1));
+ expect(String.fromCharCodes(input.single.bytes), 'h');
+ expect(sent, isEmpty);
+ await tester.pump(const Duration(milliseconds: 350));
+ final session = workspace.panes.last.session;
+ final renderer = tester.state(find.byType(TerminalView));
+ workspace.newSwarm();
+ await tester.pump();
+ workspace.openCompanions();
+ await tester.pump();
+ expect(workspace.panes.last.session, same(session));
+ expect(tester.state(find.byType(TerminalView)), same(renderer));
+ expect(find.byType(TerminalView), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
testWidgets(
'memory book shows backend lessons and forget is an explicit action',
@@ -357,6 +418,12 @@ void main() {
brain.receive('pair_result', {
'requestId': request['requestId'],
'ok': true,
+ 'learning': {
+ 'state': 'ready',
+ 'model': 'opus',
+ 'effort': 'high',
+ 'queued': 2,
+ },
'lessons': [
{
'id': 'lesson-one',
@@ -369,6 +436,11 @@ void main() {
});
await tester.pump();
expect(find.text('Check the small things'), findsOneWidget);
+ expect(find.text('Learning with Opus'), findsOneWidget);
+ expect(
+ find.text('2 observations are waiting for a quiet moment to review.'),
+ findsOneWidget,
+ );
await capture(tester, 'memories');
await tester.ensureVisible(find.text('Forget…'));
await tester.tap(find.text('Forget…'));
diff --git a/desktop/test/daemon_off_test.dart b/desktop/test/daemon_off_test.dart
index e30af83c8..05749ae09 100644
--- a/desktop/test/daemon_off_test.dart
+++ b/desktop/test/daemon_off_test.dart
@@ -567,6 +567,7 @@ void main() {
expect(frames, isEmpty);
await setCreature(tester, true);
+ await tester.pump();
expect(find.byKey(const ValueKey('companion-home')), findsOneWidget);
expect(remote.fetches, greaterThan(0));
expect(frames.where((frame) => frame.$1 == 'daemon_talk'), isEmpty);
@@ -582,6 +583,98 @@ void main() {
await unmount(tester);
});
+ testWidgets(
+ 'Companions opens its own DSH terminal and switches identities without an extra tab',
+ (tester) async {
+ app.stateOf('m')!.nodeOnline = true;
+ final seed = Zoo(
+ daemons: [
+ ZooDaemon(uid: 'tim-one', id: 'tim', hatched: '', egg: 'first'),
+ ZooDaemon(uid: 'gnu-one', id: 'gnu', hatched: '', egg: 'turn'),
+ ],
+ pair: 'tim-one',
+ firstEgg: true,
+ );
+ await mount(tester, on: true, seed: seed);
+ await app.handleEventForTest('m', {
+ 'type': 'daemon_state',
+ 'payload': {'pair': 'tim'},
+ });
+ await tester.pump();
+ expect(frames.where((f) => f.$1 == 'daemon_open'), isEmpty);
+ app.openCompanions();
+ await tester.pump();
+ await tester.pump();
+ final requests = frames.where((f) => f.$1 == 'daemon_open').toList();
+ expect(requests, hasLength(1));
+ expect(requests.single.$2['companionUid'], 'tim-one');
+ expect(requests.single.$2.containsKey('text'), isFalse);
+ app
+ .stateOf('m')!
+ .agents
+ .add(
+ const Agent(
+ id: 'pair-tim',
+ name: 'Tim',
+ engine: 'claude',
+ dsh: 'autonomous/pair',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'Pair',
+ cwd: '/pair/workspace/tim-one',
+ ),
+ ),
+ );
+ await app.handleEventForTest('m', {
+ 'type': 'daemon_open_result',
+ 'payload': {
+ 'requestId': requests.single.$2['requestId'],
+ 'ok': true,
+ 'agentId': 'pair-tim',
+ },
+ });
+ await tester.pump();
+ await tester.pump();
+ expect(app.swarms, hasLength(1));
+ expect(app.activeSwarm.name, 'Companions');
+ expect(app.panes, hasLength(2));
+ expect(app.panes.first.isCompanion, isTrue);
+ expect(app.panes.last.agentId, 'pair-tim');
+ expect(app.panes.first.ownerAgentId, 'pair-tim');
+ expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
+
+ zoo.pair('gnu-one');
+ await tester.pump();
+ await tester.pump();
+ final terminalPane = app.panes.last;
+ expect(terminalPane.agentId, 'pair-tim');
+ expect(app.panes.first.ownerAgentId, 'pair-tim');
+ final next = frames.where((f) => f.$1 == 'daemon_open').last;
+ expect(next.$2['companionUid'], 'gnu-one');
+ await app.handleEventForTest('m', {
+ 'type': 'daemon_open_result',
+ 'payload': {
+ 'requestId': next.$2['requestId'],
+ 'ok': true,
+ 'agentId': 'pair-tim',
+ },
+ });
+ await tester.pump();
+ await tester.pump();
+ expect(app.panes.last, same(terminalPane));
+ expect(app.swarms, hasLength(1));
+ expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
+ await setCreature(tester, false);
+ await tester.pump();
+ expect(app.activeSwarm.panes, isEmpty);
+ final opens = frames.where((f) => f.$1 == 'daemon_open').length;
+ app.notifyListeners();
+ await tester.pump();
+ expect(frames.where((f) => f.$1 == 'daemon_open'), hasLength(opens));
+ await unmount(tester);
+ },
+ );
+
testWidgets('disabling the experiment also closes an egg reveal', (
tester,
) async {
@@ -849,6 +942,7 @@ void main() {
final native = jsonEncode(nativeKeymapSnapshot(AppKeymap()));
expect(native, contains('app.daemon_talk'));
expect(await talkChord(tester), isTrue);
+ await tester.pump();
expect(find.byKey(const ValueKey('companion-home')), findsOneWidget);
expect(app.activeSwarm.isCompanions, isTrue);
await unmount(tester);
diff --git a/desktop/test/daemon_workspace_test.dart b/desktop/test/daemon_workspace_test.dart
index 68ad5d6f7..62f7088f1 100644
--- a/desktop/test/daemon_workspace_test.dart
+++ b/desktop/test/daemon_workspace_test.dart
@@ -112,6 +112,8 @@ void main() {
}) async {
await tester.tap(slot);
await tester.pump();
+ // The DSH's pane layout is attached after the tab's first frame.
+ await tester.pump();
await tester.tap(find.byKey(const ValueKey('companion-settings')));
await tester.pump();
final tab = find.byKey(ValueKey('daemon-tab-$section'));
@@ -1111,97 +1113,34 @@ void main() {
await tester.pump();
}
- testWidgets('Talk to daemon: the talk box, the pair starting, its answer '
- 'in the status line and the panel, and the conversation', (
- tester,
- ) async {
+ testWidgets('Talk opens the collection viewer and real terminal without sending a model turn', (tester) async {
await mount(tester, seed: zooWithTim);
- await tester.pump();
+ app.stateOf('m')!.nodeOnline = true;
await frame(tester, 'daemon_state', state());
+ app.stateOf('m')!.agents.add(const Agent(
+ id: 'pair1', name: 'Companions', engine: 'claude',
+ dsh: 'autonomous/pair', terminalAvailable: true,
+ ));
app.adoptSessionForTest(terminal('pair1', []));
- app.adoptSessionForTest(terminal('a3', []));
- app.notifyListeners();
- await tester.pump();
- // ⌘⌥T, the keymap's Talk to daemon: the panel, the talk box focused.
await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true);
await tester.pump();
- final input = find.byKey(const ValueKey('companion-chat-input'));
- expect(input, findsOneWidget);
- expect(
- tester.widget<TextField>(input).focusNode!.hasFocus,
- isTrue,
- reason: 'ready to type',
- );
- await tester.enterText(input, 'what needs me?');
- await tester.testTextInput.receiveAction(TextInputAction.send);
- await tester.pump();
- final talk = frames.lastWhere((f) => f.$1 == 'daemon_talk');
- expect(talk.$2['text'], 'what needs me?');
- expect(
- tester
- .widget<Text>(find.byKey(const ValueKey('companion-chat-status')))
- .data,
- 'Waking Tim…',
- );
- await frame(tester, 'daemon_talk_result', {
- 'requestId': talk.$2['requestId'],
- 'ok': true,
- 'agentId': 'pair1',
- 'started': true,
- });
- expect(
- tester
- .widget<Text>(find.byKey(const ValueKey('companion-chat-status')))
- .data,
- contains('starting'),
- );
- // The next send can report first-run setup without typing into its trust screen.
- await tester.enterText(input, 'are you there?');
- await tester.testTextInput.receiveAction(TextInputAction.send);
await tester.pump();
- final setupTalk = frames.lastWhere((f) => f.$1 == 'daemon_talk');
- await frame(tester, 'daemon_talk_result', {
- 'requestId': setupTalk.$2['requestId'],
- 'ok': false,
- 'agentId': 'pair1',
- 'error': 'SETUP_REQUIRED',
- });
- expect(find.byKey(const ValueKey('companion-chat-setup')), findsOneWidget);
- // Its answer: a dim line in the status line, and in the talk.
- await frame(tester, 'daemon_say', {
- 'id': 'say:1',
- 'about': {'machineId': 'm', 'agentId': ''},
- 'mood': 'say',
- 'line': 'api waits on you, 40m.',
- 'actions': [],
- 'ttlMs': 30000,
+ final opening = frames.lastWhere((f) => f.$1 == 'daemon_open');
+ expect(opening.$2.containsKey('text'), isFalse);
+ await frame(tester, 'daemon_open_result', {
+ 'requestId': opening.$2['requestId'], 'ok': true,
+ 'agentId': 'pair1', 'setupRequired': true,
});
await tester.pump();
- expect(find.byKey(const ValueKey('companion-chat-setup')), findsNothing);
- expect(
- find.descendant(
- of: find.byKey(const ValueKey('companion-chat')),
- matching: find.text('api waits on you, 40m.'),
- ),
- findsOneWidget,
- );
- expect(find.text('what needs me?'), findsOneWidget);
- // Every talk says what it costs.
- expect(
- tester
- .widget<Text>(find.byKey(const ValueKey('companion-chat-cost')))
- .data,
- contains('model usage'),
- );
- // The whole conversation: the pair harness's own pane.
expect(app.activeSwarm.isCompanions, isTrue);
- await tapIn(tester, find.byKey(const ValueKey('companion-conversation')));
+ expect(app.panes, hasLength(2));
+ expect(app.panes.first.isCompanion, isTrue);
+ expect(app.panes.first.ownerAgentId, 'pair1');
+ expect(app.panes.last.agentId, 'pair1');
expect(app.focusedPane!.agentId, 'pair1');
- expect(app.activeSwarm.isUtility, isFalse);
- expect(app.swarms.singleWhere((s) => s.isCompanions).panes, isEmpty);
- expect(find.byKey(const ValueKey('companion-home')), findsNothing);
- expect(find.byKey(const ValueKey('daemon-panel')), findsNothing);
- await tester.pump(const Duration(seconds: 31));
+ expect(find.byKey(const ValueKey('companion-home')), findsOneWidget);
+ expect(find.byKey(const ValueKey('companion-chat-input')), findsNothing);
+ expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
await unmount(tester);
});
@@ -1343,8 +1282,8 @@ void main() {
await openPanel(tester);
expect(
frames.where((f) => f.$2['doneSeen'] == true),
- hasLength(1),
- reason: 'opening the panel is a look',
+ hasLength(2),
+ reason: 'opening the viewer and then its controls each acknowledges a look',
);
expect(find.byKey(const ValueKey('daemon-slot-tally')), findsNothing);
expect(
@@ -1912,63 +1851,25 @@ void main() {
await unmount(tester);
});
- testWidgets('talk waits when harnessd says so, and says how long', (
- tester,
- ) async {
+ testWidgets('an unavailable companion engine explains setup and retries in the same DSH', (tester) async {
await mount(tester, seed: zooWithTim);
- await tester.pump();
await frame(tester, 'daemon_state', state());
await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true);
await tester.pump();
- final input = find.byKey(const ValueKey('companion-chat-input'));
- await tester.enterText(input, 'again?');
- await tester.testTextInput.receiveAction(TextInputAction.send);
await tester.pump();
- final talk = frames.lastWhere((f) => f.$1 == 'daemon_talk');
- await frame(tester, 'daemon_talk_result', {
- 'requestId': talk.$2['requestId'],
- 'ok': false,
- 'error': 'RATE_LIMITED',
- 'detail': 'Six talks a minute, sixty an hour.',
- 'retryAfterMs': 30000,
- 'cost':
- 'Each talk is a turn of your pair harness on its engine: it '
- 'spends your model usage.',
+ final opening = frames.lastWhere((f) => f.$1 == 'daemon_open');
+ final tab = app.activeSwarm.id;
+ await frame(tester, 'daemon_open_result', {
+ 'requestId': opening.$2['requestId'], 'ok': false, 'error': 'NO_ENGINE',
});
- expect(
- tester
- .widget<IconButton>(
- find.byKey(const ValueKey('companion-chat-send')),
- )
- .onPressed,
- isNull,
- );
- expect(
- tester
- .widget<Text>(find.byKey(const ValueKey('companion-chat-status')))
- .data,
- 'You can send another message in 30 seconds.',
- );
- expect(
- tester
- .widget<Text>(find.byKey(const ValueKey('companion-chat-cost')))
- .data,
- startsWith('Each talk is a turn of your pair harness'),
- );
- await tester.pump(const Duration(seconds: 10));
- expect(
- tester
- .widget<Text>(find.byKey(const ValueKey('companion-chat-status')))
- .data,
- 'You can send another message in 20 seconds.',
- );
- await tester.pump(const Duration(seconds: 21));
- expect(tester.widget<TextField>(input).enabled, isTrue);
- await skipName(tester);
- await key(tester, LogicalKeyboardKey.escape);
- await skipName(tester);
- await key(tester, LogicalKeyboardKey.escape);
- await tester.pump(const Duration(minutes: 3));
+ await tester.pump();
+ expect(find.text('Install Claude Code or Codex to talk with your companion.'), findsOneWidget);
+ await tester.tap(find.text('Open terminal'));
+ await tester.pump();
+ await tester.pump();
+ expect(frames.where((f) => f.$1 == 'daemon_open'), hasLength(2));
+ expect(frames.where((f) => f.$1 == 'daemon_talk'), isEmpty);
+ expect(app.activeSwarm.id, tab);
await unmount(tester);
});
diff --git a/desktop/test/daemons/daemon_brain_test.dart b/desktop/test/daemons/daemon_brain_test.dart
index b31409fdc..818ecc0d1 100644
--- a/desktop/test/daemons/daemon_brain_test.dart
+++ b/desktop/test/daemons/daemon_brain_test.dart
@@ -43,6 +43,52 @@ void main() {
});
tearDown(() => brain.dispose());
+ test('opening the terminal sends no words and pins the reply to the current individual', () async {
+ brain.bindConversation('account:test', 'tim-one');
+ final opening = brain.openConversation();
+ expect(sent.single.$1, 'daemon_open');
+ expect(sent.single.$2['companionUid'], 'tim-one');
+ expect(sent.single.$2.containsKey('text'), isFalse);
+ brain.receive('daemon_open_result', {
+ 'requestId': sent.single.$2['requestId'],
+ 'ok': true,
+ 'agentId': 'pair-tim',
+ });
+ expect((await opening)['ok'], isTrue);
+ expect(brain.pairAgentId, 'pair-tim');
+ expect(brain.talk, isEmpty);
+ final stale = brain.openConversation();
+ final requestId = sent.last.$2['requestId'];
+ brain.bindConversation('account:test', 'gnu-one');
+ brain.receive('daemon_open_result', {
+ 'requestId': requestId,
+ 'ok': true,
+ 'agentId': 'pair-tim',
+ });
+ expect((await stale)['error'], 'STALE_COMPANION');
+ expect(brain.pairAgentId, 'pair-tim');
+ brain.bindConversation('account:another', 'other-tim');
+ expect(brain.pairAgentId, isNull);
+ });
+
+ test('daemon state restores the collection terminal without matching a character workspace', () {
+ brain.bindConversation('account:test', 'tim-one');
+ brain.receive('daemon_state', {
+ 'pair': 'tim',
+ 'companionHarness': {
+ 'agentId': 'collection-agent',
+ 'state': 'ready',
+ 'model': 'opus',
+ },
+ });
+ expect(brain.pairAgentId, 'collection-agent');
+ brain.bindConversation('account:test', 'gnu-one');
+ expect(brain.pairAgentId, 'collection-agent');
+ brain.bindConversation(null, null);
+ expect(brain.pairAgentId, isNull);
+ });
+
+
test('recent conversation survives a window restart, scoped to account and individual', () async {
brain.bindConversation('account:one', 'tim-one');
await Future<void>.delayed(Duration.zero);
diff --git a/desktop/test/pane_focus_test.dart b/desktop/test/pane_focus_test.dart
index e62e05234..f43cf406c 100644
--- a/desktop/test/pane_focus_test.dart
+++ b/desktop/test/pane_focus_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/pane_preset.dart';
+import 'package:harness/state/terminal_pane.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/terminal_panel.dart';
@@ -34,6 +35,100 @@ void main() {
}
});
+ testWidgets(
+ 'viewers and their owner share emphasis without sharing keyboard input',
+ (tester) async {
+ final app = createApp(connected: true);
+ final input = List.generate(2, (_) => <TerminalBinaryFrame>[]);
+ final terminals = [
+ for (var i = 0; i < 2; i++)
+ app.adoptSessionForTest(terminal('a$i', input[i])),
+ ];
+ final viewers = [
+ for (var i = 0; i < 2; i++)
+ TerminalPane(
+ id: 100 + i,
+ machineId: 'm',
+ kind: PaneKind.web,
+ ownerAgentId: 'a$i',
+ url: 'http://fixture.invalid/viewer-$i',
+ ),
+ ];
+ final otherMachine = TerminalPane(
+ id: 102,
+ machineId: 'n',
+ kind: PaneKind.web,
+ ownerAgentId: 'a0',
+ url: 'http://fixture.invalid/remote-viewer',
+ );
+ app.panes.addAll([...viewers, otherMachine]);
+ app.focusPane(terminals[0].id);
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(1500, 900);
+ await tester.pump();
+
+ Finder frame(TerminalPane pane) =>
+ find.byKey(ValueKey('pane-frame:${pane.id}'));
+ Finder panel(TerminalPane pane) => find.descendant(
+ of: frame(pane),
+ matching: find.byType(TerminalPanel),
+ );
+ final renderers = [
+ for (final pane in terminals) tester.state(panel(pane)),
+ ];
+ void expectEmphasis(Set<TerminalPane> clear) {
+ for (final pane in app.panes) {
+ final veil =
+ tester.widget<Container>(frame(pane)).foregroundDecoration
+ as BoxDecoration;
+ expect(veil.color, clear.contains(pane) ? isNull : isNotNull);
+ }
+ for (var i = 0; i < 2; i++) {
+ expect(tester.state(panel(terminals[i])), same(renderers[i]));
+ }
+ }
+
+ expectEmphasis({terminals[0], viewers[0]});
+ await tester.tapAt(tester.getCenter(frame(viewers[0])));
+ await tester.pump();
+ expect(app.focusedPaneId, viewers[0].id);
+ expect(
+ tester.widget<TerminalPanel>(panel(terminals[0])).focused,
+ isFalse,
+ );
+ expectEmphasis({terminals[0], viewers[0]});
+
+ // Both terminals have keyboard focus=false across this move. Their
+ // cached presentations must still repaint the change of focused owner.
+ await tester.tapAt(tester.getCenter(frame(viewers[1])));
+ await tester.pump();
+ expect(app.focusedPaneId, viewers[1].id);
+ expectEmphasis({terminals[1], viewers[1]});
+ expect(input.every((frames) => frames.isEmpty), isTrue);
+
+ await tester.tap(panel(terminals[1]));
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input[1].single.bytes, [27, 91, 68]);
+ expect(input[0], isEmpty);
+ expectEmphasis({terminals[1], viewers[1]});
+
+ app.focusPane(otherMachine.id);
+ await tester.pump();
+ expectEmphasis({otherMachine});
+ app.focusPane(viewers[0].id);
+ app.railFocused = true;
+ app.notifyListeners();
+ await tester.pump();
+ expectEmphasis({terminals[0], viewers[0]});
+ expect(tester.takeException(), isNull);
+ await tester.pump(const Duration(milliseconds: 350));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
testWidgets(
'pane emphasis follows clicks and keys without remounting terminals',
(tester) async {