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.

Merge origin/main into scm-seam

bubu-dudu7cad35f6be9a
diff --cc cli/src/backendSocket.spec.ts
index 69310658b,8d57e59f1..68a7c6394
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@@ -1013,54 -1359,6 +1360,56 @@@ describe('BackendSocket outbound queue'
await socket.stop()
})
+ it.each([false, true])('answers scm_project_info (refresh=%s) through the SCM seam, to the requesting encrypted connection only', async refresh => {
+ const preview = { kind: 'git' as const, git: { isGit: true, root: '/remote/workspace', branch: 'main', branches: [{ ref: 'refs/heads/private-branch', name: 'private-branch', remote: false }] } }
+ const detect = vi.spyOn(scmProjects, 'detectScmProject').mockResolvedValue(preview)
- const socket = new BackendSocket('token')
++ const socket = relaySocket('token')
++ serveProjects(socket)
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'scm_project_info', payload: {
++ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'scm_project_info', payload: {
+ requestId: 'preview-2', path: '/remote/workspace', refresh,
+ } })
- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)
- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({
++ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)
++ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({
+ type: 'scm_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },
+ })
+ ws.message({ t: 'down', connId: 'viewer-a', frame: {
+ type: 'scm_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },
+ } })
+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'scm_project_info_result', 'preview-2', preview))
+ // The same fence git_project_info passes: no registered agents here, so the home folder alone.
+ expect(detect).toHaveBeenCalledWith('/remote/workspace', { refresh, knownRoots: [] })
+ expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'viewer-a', frame: {
+ type: 'scm_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },
+ } }))
+ expect(JSON.stringify(parseSent(ws))).not.toContain('private-branch')
+ await socket.stop()
+ })
+
+ it('answers scm_project_info for a malformed path as the git probe does, correlated', async () => {
+ const read = vi.spyOn(gitProject, 'readGitProject')
- const socket = new BackendSocket('token')
++ const socket = relaySocket('token')
++ serveProjects(socket)
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'scm_project_info', payload: {
++ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'scm_project_info', payload: {
+ requestId: 'scm-error', path: 42,
+ } })
- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)
- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({
++ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)
++ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({
+ type: 'scm_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-error' } },
+ })
+ ws.message({ t: 'down', connId: 'viewer-a', frame: {
+ type: 'scm_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },
+ } })
+ await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'scm_project_info_result', 'scm-error', { kind: 'none', error: 'INVALID_PATH' }))
+ expect(read).toHaveBeenCalledWith('', { refresh: false, knownRoots: [] })
+ await socket.stop()
+ })
+
it('returns PR status only to the requesting encrypted connection', async () => {
const preview = { status: 'found' as const, number: 12, state: 'Merged' as const, url: 'https://github.com/private/repo/pull/12' }
vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)
@@@ -1830,37 -2121,6 +2172,38 @@@
} finally {
await socket.stop()
rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('hands the launch the SCM record the prepared workspace reported, and none for a folder no SCM made', async () => {
- const socket = new BackendSocket('token')
++ const socket = relaySocket('token')
++ bindLaunchRequests(socket)
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:scm', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })
+ const prepare = vi.spyOn(projectFolder, 'prepareProjectFolder').mockImplementation(async (project, options) => {
+ if (project.source === 'worktree') options?.onPrepared?.({ cwd: '/remote/harnesses/worktrees/repo/brave-otter', scmLaunchRecord: { kind: 'git' } })
+ return project.source === 'worktree' ? '/remote/harnesses/worktrees/repo/brave-otter' : '/remote/harnesses/codex-2026-09-24-12-00'
+ })
+ const create = vi.fn(async (_input: Record<string, unknown>) => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))
+ socket.onCreateAgent = create
+ const ask = (requestId: string, choices: Record<string, unknown>) =>
+ socket.handleLocalFrame('local:scm', { type: 'agent_create', payload: { requestId, creationId: randomUUID(), engine: 'claude', ...choices } })
+ try {
+ ask('worktree', { projectSource: 'worktree', gitSource: '/remote/repo', branchRef: 'refs/heads/main' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'worktree', state: 'failed' }) })))
+ expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: '/remote/harnesses/worktrees/repo/brave-otter', scmLaunchRecord: { kind: 'git' } }))
+ ask('new', { projectSource: 'new' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'new', state: 'failed' }) })))
+ expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: '/remote/harnesses/codex-2026-09-24-12-00', scmLaunchRecord: null }))
+ // A create that names its own folder prepared nothing, and says nothing about an SCM.
+ ask('cwd', { cwd: '/remote/own' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({ payload: expect.objectContaining({ requestId: 'cwd' }) })))
+ expect(create).toHaveBeenLastCalledWith(expect.objectContaining({ cwd: '/remote/own' }))
+ expect(create.mock.lastCall?.[0]).not.toHaveProperty('scmLaunchRecord')
+ expect(prepare).toHaveBeenCalledTimes(2)
+ } finally {
+ await socket.unregisterLocalClient('local:scm')
+ await socket.stop()
}
})
diff --cc cli/src/backendSocket.ts
index 9595c3dd1,bdd18324a..deb2c11d8
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@@ -1,191 -1,47 +1,48 @@@
import type { PurgeAgentService } from './lib/purgeAgentService.js'
+ import { SHARE_REQUESTS, TEAMS_REQUESTS, type Asker, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
import { ServiceUnavailableError } from './core/serviceHost.js'
+ import type { ViewerStreams } from './core/viewerStreams.js'
import type { ActivityFrame } from './lib/turnActivity.js'
- import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'
- import { MonitorCompletions, type MonitorActivity } from './lib/harnessMonitor.js'
- import type { HarnessShareOwner } from './sharing/owner.js'
- import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'
- import { AutonomousDeviceRelay } from './lib/autonomous-device/relay.js'
- import { deviceDump } from './lib/autonomous-device/dump.js'
- import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonomous-device/service.js'
+ import { MonitorCompletions } from './lib/harnessMonitor.js'
+ import type { WifiCore } from './core/wifi.js'
/**
- * BackendSocket — the CLI's dial-out connection to the backend's `/api/adapter-ws`.
+ * BackendSocket — the clients' hub and the request dispatch: the windows and tools on this computer
+ * (localWsServer.ts), and the remote clients the gateway hands on (gateway/gateway.ts), each in its own
+ * order, behind one gate until the daemon is ready.
*
- * The adapter occupies the NODE side of its agentId on the backend hub:
- * - `up` { t:'up', frame } → normalized claude events + `<x>_result` RPC replies
- * - `down` { t:'down', connId, frame } → web chat/control + data-plane RPC requests
- *
- * Mirrors the hosted runtime’s managerSocket: idempotent connect, exponential backoff (1s→30s),
- * WS liveness (`lib/wsLiveness.ts`: ping every 20s, 60s deadline on silence) + a 15s app-level
- * `{t:'ping'}` that refreshes the backend presence key, and a bounded FIFO queue for client-facing
- * outbound frames.
- *
- * Auth: the SSO access token rides as the first WS subprotocol.
+ * It holds no link and no key. The backend link, the E2EE sessions, the terminals' P2P channels and the
+ * Wi-Fi device's direct links are the gateway's (the core boundary, step 10, R1:
+ * docs/design/2026-10-06-core-boundary-next.md): a remote client's request reaches this socket opened,
+ * with the role its session proved, and everything this socket has for a remote client leaves through
+ * the gateway, which seals it.
*/
- import { WebSocket } from 'ws'
- import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from './lib/wsLiveness.js'
- import { stat, readdir } from 'fs/promises'
- import { existsSync } from 'node:fs'
- import { dirname, isAbsolute, join } from 'path'
- import { hostname, homedir } from 'os'
+ import { join } from 'path'
+ import { hostname } from 'os'
import { env } from './config/env.js'
- import { AuthSessionManager, AuthSessionError } from './lib/authSession.js'
- import { VERSION } from './version.js'
import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'
- import { AgentStopError } from './lib/stopAgentService.js'
- import type { CloseAgentService, CloseMode } from './lib/closeAgentService.js'
- import { MODEL_MANAGER_ID, isHiddenBuiltin } from './dsh/builtins.js'
- import { ENGINES, PROCESS_ENGINES, isTerminalEngine, type AgentEngine, type ProcessEngine } from './engines/types.js'
- import { listDir } from './lib/fsBrowse.js'
- import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
- import { gridCliPresence } from './lib/gridExec.js'
- import { GridFleetRpc, GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS, parseGridFleetRequest } from './lib/gridFleetRpc.js'
- import { LocalModels } from './lib/localModels.js'
- import { appEngineOps, scanAppModels } from './lib/appModels.js'
- import { ApiConnectionError, ApiConnections, apiConnectionsRequest } from './lib/apiConnections.js'
- import { apiModelsRequest, rememberSavedApis, resolveApiTarget } from './lib/apiModels.js'
- import { gridCapableEngines, isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
- import {
- forgetGridModels, gridInventory, listAllGridModels, onGridModelsChanged, presentGridSections, retargetPrewarm, type GridSection,
- } from './lib/gridModels.js'
- import { resolveGridTarget } from './lib/gridTarget.js'
- import type { GridAttachResult } from './lib/gridAttach.js'
- import { parseNewAgentModel, resolveNewAgentModel } from './lib/newAgentModel.js'
- import { deriveHarnessGridName } from './lib/gridDerive.js'
- import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'
- import { opencodeMajorVersion } from './engines/opencode/version.js'
- import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
+ import type { CloseAgentService } from './lib/closeAgentService.js'
+ import { ENGINES, type AgentEngine } from './engines/types.js'
+ import { gridCliPresence } from './lib/gridBinary.js'
+ import { GRID_FLEET_PROTOCOL, GRID_FLEET_MAX_TIMEOUT_MS } from './lib/gridFleetProtocol.js'
+ import { ApiConnectionError, ApiConnections } from './lib/apiConnections.js'
+ import { resolveApiTarget } from './lib/apiModels.js'
+ import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
++import type { ScmLaunchRecord } from './scm/types.js'
import { probeEngines } from './lib/engineProbe.js'
- import { readMachineResources } from './lib/machineResources.js'
- import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'
- import { createHarnessResourcesReader } from './lib/harnessResources.js'
- import { createHarnessStorageReader } from './lib/harnessTelemetry.js'
- import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
- import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from './lib/projectFolder.js'
- import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'
- import { projectPreview } from './lib/projectPreview.js'
- import { readGitProject } from './lib/gitProject.js'
- import { detectScmProject } from './scm/scmProjects.js'
- import type { ScmLaunchRecord } from './scm/types.js'
- import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
+ import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
- import { installedDsh, listInstalledDsh } from './dsh/installed.js'
- import { OrchestratorService } from './orchestrator/service.js'
- import { OrchestratorError } from './orchestrator/model.js'
- import { orchestratorRequest } from './orchestrator/wire.js'
- import { TeamService } from './teams/service.js'
- import { SwarmPromptScopes } from './teams/promptScope.js'
- import { ChannelDirectory } from './teams/channels.js'
- import { TeamMailbox } from './teams/mailbox.js'
- import { teamRequest, teamDeliveryRequest, TEAM_REQUEST_TYPES, teamFailure } from './teams/wire.js'
- import { teamRpc } from './teams/client.js'
- import { Address, Id, OperationId, Receipt, TeamError, type MemberRuntime } from './teams/model.js'
- import { shellQuote } from './orchestrator/prompts.js'
- import type { SessionInputDelivery } from './lib/sessionInput.js'
- import type { QuestionAnswerResult } from './lib/askQuestion.js'
- import { engineLabel } from './lib/agentNames.js'
- import { DSH_ID_RE, dshSupportedEngines } from './dsh/manifest.js'
- import { refreshDshRegistry } from './dsh/catalog.js'
- import type { DshInstallProgress } from './dsh/install.js'
- import { dshInstallReply, dshInstallRequest, dshInstallStatus, dshListRows, dshRemoveId, dshRemoveReply } from './dsh/wire.js'
import { terminalHandoffRequest } from './lib/terminalHandoff.js'
- import { routeVoiceTask } from './lib/voiceRouter.js'
- import { tailFile } from './lib/sessions.js'
- import { stoppedAgents } from './lib/stoppedAgents.js'
- import { messagesToEvents, windowRawLines, SubagentStats, type SessionEvent } from './lib/normalize.js'
- import { TranscriptPager } from './lib/transcriptPages.js'
- import { streamRecords } from './lib/transcriptTail.js'
- import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'
- import { ViewerForwarder } from './lib/viewerForwarder.js'
- import { InteractiveViewers } from './lib/interactiveViewer.js'
- import { OwnerCommands, OWNER_COMMAND_TYPES } from './lib/ownerCommands.js'
- import { VIEWER_DOWN_TYPES } from './lib/viewerWire.js'
- import { codexMessagesToEvents } from './engines/codex/normalizer.js'
- import { codexSubagentResolverFor } from './engines/codex/subagent.js'
- import { parseHostTheme, type HostTheme } from './lib/hostTheme.js'
- import { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normalizer.js'
- import { cursorConfigDir, cursorDataDir } from './engines/cursor/home.js'
- import { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'
- import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'
- import { kiloMessagesToEvents, windowKiloMessages } from './engines/kilo/normalizer.js'
- import { museMessagesToEvents } from './engines/muse/normalizer.js'
- import { ampMessagesToEvents } from './engines/amp/normalizer.js'
- import { grokMessagesToEvents } from './engines/grok/normalizer.js'
- import { agyMessagesToEvents } from './engines/agy/normalizer.js'
- import { copilotMessagesToEvents } from './engines/copilot/normalizer.js'
- import { ampThreadToEvents, readAmpThread } from './engines/amp/threadExport.js'
- import { piMessagesToEvents, windowPiLines } from './engines/pi/normalizer.js'
- import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/commandcode/normalizer.js'
- import { hermesMessagesToEvents, windowHermesMessages } from './engines/hermes/normalizer.js'
- import { devinMessagesToEvents, windowDevinMessages } from './engines/devin/normalizer.js'
- import { readHermesMessages } from './engines/hermes/reader.js'
- import { hermesDbForSession } from './lib/hermesHome.js'
- import { readDevinMessages } from './engines/devin/reader.js'
- import { readOpencodeMessages } from './engines/opencode/reader.js'
- import { readKiloMessages } from './engines/kilo/reader.js'
- import { E2eeManager, type LinkedPeer, type PairResult } from './lib/e2ee/manager.js'
- import { MachinePeerStore } from './lib/e2ee/machinePeers.js'
+ import { OwnerCommands, OWNER_COMMAND_TYPES, ROUTE_COMMAND_TYPES } from './lib/ownerCommands.js'
+ import { VIEWER_DOWN_TYPES } from './lib/viewerFrames.js'
import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
- import {
- decodeTerminalHop,
- encodeTerminalLocal,
- encodeTerminalHop,
- TerminalHopDirection,
- type TerminalBinaryClear,
- } from './lib/terminalBinary.js'
- import { b64d, fingerprint, isWrapped } from './lib/e2ee/core.js'
- import { encryptRpcResult, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType } from './lib/e2ee/applicationFrames.js'
- import { tmuxPaneInfo } from './lib/tmux.js'
- import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'
- import { shouldReplayCommander } from './lib/commanderReplay.js'
- import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'
- import { parseRuntimeProfile, type RuntimeModelOption } from './lib/runtimeProfile.js'
- import { sid, preview, logFrame } from './lib/log.js'
- import type { SessionSearchResult } from './lib/sessionSearch/indexer.js'
- import type { SessionTail } from './lib/sessionSearch/store.js'
- import {
- TerminalP2pResponderPool,
- TERMINAL_P2P_DOWN_TYPES,
- TERMINAL_P2P_SIGNAL_TYPES,
- type TerminalP2pData,
- type TerminalP2pSignal,
- } from './lib/terminalP2p.js'
-
- // OpenCode has no per-session transcript file — its history is read from this SQLite store.
- const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')
- /** History pages and line counts for the threads clients read (lib/transcriptPages.ts). */
- const transcriptPages = new TranscriptPager()
- // Kilo keeps history the same way opencode does, in its own store.
- const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')
- const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')
- // Hermes history likewise comes from a SQLite store, not a per-session file — one per HOME, so the
- // path is the session's own (`hermesDbForSession`) rather than this machine's default.
-
- /** Answers the device `project_recent` RPC — set by cli.ts to the CommanderMirror's `recent`. */
- export type RecentProvider = (sessionId: string, n: number) => Array<{ kind: string; text: string; recap?: string }>
-
-
- const APP_PING_MS = 15_000
- // Floor between two `app_presence` up-frames while a window is attached. Rides the 15s app-ping
- // tick; the backend only needs to hear about it about once a minute (it floors its own Mongo write
- // at five). `open` is never held back — it is the one that counts as a session in
- // `user_daily_presence`.
- const APP_PRESENCE_UP_MS = 60_000
- // How long the opening handshake may take before the attempt is abandoned and retried. `ws` waits
- // forever by default, and the heartbeat below only starts on 'open' — so a TCP connection that came
- // up while the network was flapping but never got its upgrade answered sat in CONNECTING for hours,
- // `this.ws` set, every later connect() returning early, and the daemon reporting "cloud
- // reconnecting…" until someone restarted it.
- const HANDSHAKE_TIMEOUT_MS = 15_000
- /** An `agent_update {opened: true}` for an agent opened less than this long ago is answered but not
- * stamped or broadcast: a person flicking between two tabs, or two apps opening the same agent at
- * once, would otherwise push a frame to every client for each flick. Exported for the spec. */
- export const AGENT_OPENED_THROTTLE_MS = 3_000
- const BASE_DELAY_MS = 1_000
- const MAX_DELAY_MS = 30_000
- const QUEUE_MAX = 2_000
+ import { encodeTerminalLocal, type TerminalBinaryClear } from './lib/terminalBinary.js'
+ import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType, type DownTransport } from './lib/relayFrames.js'
+ import { sid, logFrame } from './lib/log.js'
+
+ export { isLocalClientId, type DownTransport }
+
/** Requests one local connection may queue before the daemon is ready (see `openRequests`). The app
* sends a handful on connect; hundreds is a client looping, not a person. */
const MAX_REQUESTS_BEFORE_READY = 256
@@@ -569,172 -159,34 +160,37 @@@ export class BackendSocket
* only between turns, `now` whatever it is doing (then tells it to continue), `wait` when its
* turn ends. Absent, one open elsewhere is refused and the refusal says whether it is busy. */
takeOver?: 'idle' | 'now' | 'wait' | null
+ /** What the SCM that prepared `cwd` needs on every relaunch (registry `scmLaunch`). Present only
+ * when this create prepared a folder, and null when no SCM made it (a new folder, a clone). */
+ scmLaunchRecord?: ScmLaunchRecord | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
- /** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */
- onDshInstall: ((input: { id?: string; url?: string; ref?: string }, progress: (p: DshInstallProgress) => void) =>
- Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null
- /** An explicit update follows the installed source and retains the previous package on failure. */
- onDshUpdate: ((id: string, progress: (p: DshInstallProgress) => void) =>
- Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null
- /** Called on `dsh_remove` — cli.ts uninstalls the harness from this machine. */
- onDshRemove: ((id: string) => { ok: true } | { ok: false; error: string; detail: string }) | null = null
/** Called on `remote_terminal_handoff` — cli.ts names the agent whose tile is that tmux pane, or null. */
onTerminalHandoff: ((tmuxPane: string) => string | null) | null = null
+ /** Share's observers, as the relay hands their frames over and drops them all with the link (services/sharing.ts,
+ * through its port). Null answers none, as a daemon without Share did. */
+ observers: { receive(connId: string, type: string, payload: Record<string, unknown>): Promise<void> | void; closeAll(): void } | null = null
/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */
- harnessSharing: HarnessShareOwner | null = null
- /** Answers the trust group's roster exchange (`group_sync`); null until the daemon wires it. */
- groupSync: { handle: (peerPub: string, payload: Record<string, unknown>) => Record<string, unknown> } | null = null
activityFrameProvider: ((session: RegisteredSession) => ActivityFrame | null) | null = null
dshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = null
- viewerTargetProvider: ((agentId: string) => string | null) | null = null
- readonly interactiveViewers = new InteractiveViewers(agentId => this.viewerTargetProvider?.(agentId) ?? null)
- readonly viewerForwarder = new ViewerForwarder({
- target: (agentId) => this.viewerTargetProvider?.(agentId) ?? null,
- send: (connId, type, payload) => {
- if (this.localClients.has(connId)) { this.sendTo(connId, { type, payload }); return true }
- if (!this.isConnected()) return false
- const frame = this.e2ee.wrapTarget(connId, type, payload)
- if (!frame) return false
- this.sendTo(connId, frame)
- return true
- },
- })
- private readonly agentCreations = new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations'))
+ /** This machine's viewers, served to a client over its connection: the viewers' (core/viewerStreams.ts). */
+ viewerStreams: ViewerStreams | null = null
+ /** A viewer stream's frame to the one connection that opened it: false when it cannot reach it. */
+ sendViewerFrame(connId: string, type: string, payload: Record<string, unknown>): boolean {
+ if (this.localClients.has(connId)) { this.sendTo(connId, { type, payload }); return true }
+ return this.throughGateway('viewer', (gateway) => gateway.target(connId, type, payload), false)
+ }
/** Injectable for queue-isolation tests; production uses the machine-local probe. */
engineProbeProvider: typeof probeEngines = probeEngines
- /** Entrypoint override for isolated integration fixtures; never a wire option. */
- orchestratorCommand: string | null = null
readonly ownerCommands = new OwnerCommands()
+ /** Takes back a delivered turn not yet being written (core/deliveries.ts, cli.ts binds core/input.ts). */
onCancelOrchestratorMessage: ((deliveryId: string) => boolean) | null = null
- orchestratorDelivery(event: SessionInputDelivery): void {
- this.orchestratorService?.delivery(event)
- }
- private orchestratorService: OrchestratorService | null = null
- /** Isolated daemon fixtures can override these without touching installed state. */
- teamStateDir = join(env.ADAPTER_DATA_DIR, 'teams')
- teamCommand: string | null = null
- private teamService: TeamService | null = null
- readonly swarmPromptScopes = new SwarmPromptScopes()
- private teamMailboxService: TeamMailbox | null = null
- readChannelDesk: (() => Promise<unknown>) | null = null
- writeChannelSettings: ((enabled: boolean) => Promise<unknown>) | null = null
- private channelsEnabled = false
- private channelDirectory: ChannelDirectory | null = null
- private channels(): ChannelDirectory {
- if (!this.readChannelDesk) throw new TeamError('CHANNELS_UNSUPPORTED', 'Tab channels are not available on this daemon.')
- return this.channelDirectory ??= new ChannelDirectory({
- machineId: this.machineId, service: this.teams(), readDesk: () => this.readChannelDesk!(),
- writeSettings: async enabled => {
- if (!this.writeChannelSettings) throw new TeamError('CHANNELS_UNSUPPORTED', 'Update Harness to configure swarm collaboration.')
- return this.writeChannelSettings(enabled)
- },
- enabledChanged: enabled => { this.channelsEnabled = enabled; this.teamMailboxService?.pump() },
- forward: (machineId, payload) => teamRpc({ port: env.PORT, machineId, dataDir: env.ADAPTER_DATA_DIR }, 'team', payload),
- })
- }
- refreshChannels(): void { if (this.readChannelDesk) void this.channels().refresh(true).catch(() => {}) }
- teamDelivery(event: SessionInputDelivery): void { this.teamMailboxService?.observe(event) }
- teamCanWrite(deliveryId: string): boolean { return this.teamMailboxService?.canWrite(deliveryId) ?? false }
- private localTeamRuntime(agentId: string): MemberRuntime | null {
- const agent = registry.byAgent(agentId)
- return agent ? { name: projectDisplayName(agent), engine: agent.engine, cwd: agent.cwd ?? undefined,
- available: agent.active && registry.terminalAvailable(agentId),
- ...(!agent.active ? { reason: 'Session is paused or offline.' } : {}) } : null
- }
- private teamMailbox(): TeamMailbox {
- return this.teamMailboxService ??= new TeamMailbox({
- stateDir: join(this.teamStateDir, 'mailboxes'),
- channelsEnabled: () => this.channelsEnabled,
- runtime: id => this.localTeamRuntime(id),
- send: (id, text, deliveryId) => {
- if (!this.onMessage) throw new TeamError('UNAVAILABLE', 'Agent input is not ready.')
- this.onMessage(id, text, deliveryId)
- },
- cancel: id => this.onCancelOrchestratorMessage?.(id) ?? false,
- })
- }
- private teams(): TeamService {
- return this.teamService ??= new TeamService({
- stateDir: join(this.teamStateDir, 'ledgers'), machineId: this.machineId,
- taskScope: async address => {
- if (address.machineId === this.machineId) return this.swarmPromptScopes.current(address.agentId)
- const result = await teamRpc({ port: env.PORT, machineId: address.machineId, dataDir: env.ADAPTER_DATA_DIR },
- 'team_delivery', { action: 'prompt_scope', agentId: address.agentId })
- return typeof result.teamId === 'string' ? result.teamId : null
- },
- questionReplied: async (address, teamId, questionId) => {
- if (address.machineId === this.machineId) this.swarmPromptScopes.replied(address.agentId, teamId, questionId)
- else await teamRpc({ port: env.PORT, machineId: address.machineId, dataDir: env.ADAPTER_DATA_DIR },
- 'team_delivery', { action: 'prompt_replied', agentId: address.agentId, teamId, questionId })
- },
- command: address => address.machineId === this.machineId
- ? this.teamCommand ?? `${[process.execPath, ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} team --port ${env.PORT}`
- : 'harness team',
- runtime: async address => {
- Address.parse(address)
- if (address.machineId === this.machineId) return this.localTeamRuntime(address.agentId)
- const result = await teamRpc({ port: env.PORT, machineId: address.machineId, dataDir: env.ADAPTER_DATA_DIR }, 'team_delivery', { action: 'runtime', agentId: address.agentId })
- return result.runtime as MemberRuntime | null
- },
- delivery: async (address, action, delivery) => {
- if (address.machineId === this.machineId) {
- const mailbox = this.teamMailbox()
- return action === 'send' ? mailbox.accept(delivery) : action === 'status' ? mailbox.status(delivery.id)
- : action === 'hold' || action === 'release' ? mailbox.hold(delivery.id, action === 'hold') : mailbox.cancel(delivery.id, action === 'consume')
- }
- const result = await teamRpc({ port: env.PORT, machineId: address.machineId, dataDir: env.ADAPTER_DATA_DIR }, 'team_delivery', { action, delivery })
- return result.receipt == null ? null : Receipt.parse(result.receipt)
- },
- changed: (id, revision) => this.sendLocal({ type: 'team_changed', payload: { id, revision } }),
- })
- }
- /** Resume persisted queues after input wiring is ready, even with no UI attached. */
- startTeams(): void {
- if (this.readChannelDesk) this.channels().start()
- if (!existsSync(this.teamStateDir)) return
- try { this.teamMailbox().start(); this.teams().start() }
- catch { console.warn('[teams] preserved unreadable team state; inspect Team for recovery') }
- }
- /** The commander asks this for every turn that ends — see OrchestratorService.roleOf. */
- orchestratorRoleOf(agentId: string): ReturnType<OrchestratorService['roleOf']> {
- return this.orchestration().roleOf(agentId)
- }
- private orchestration(): OrchestratorService {
- return this.orchestratorService ??= new OrchestratorService({
- stateDir: join(env.ADAPTER_DATA_DIR, 'orchestrator'),
- workspaceDir: join(homedir(), 'harnesses', 'orchestrated'),
- command: this.orchestratorCommand ?? `${[process.execPath, ...process.execArgv, process.argv[1]].map(shellQuote).join(' ')} orchestrator --port ${env.PORT} --machine ${shellQuote(this.machineId)}`,
- catalog: () => listInstalledDsh().filter(d => d.manifest.kind !== 'viewer' && !isHiddenBuiltin(d) && !!d.manifest.engine && supportsFirstPrompt(d.manifest.engine)).map(d => ({
- id: d.id, name: d.manifest.name, description: d.manifest.description ?? '', engine: d.manifest.engine!, viewer: !!d.manifest.viewer,
- })),
- supportsEngine: engine => ENGINES.includes(engine as AgentEngine) && supportsFirstPrompt(engine as AgentEngine),
- create: async input => {
- if (!this.onCreateAgent) throw new OrchestratorError('UNSUPPORTED', 'This daemon cannot create agents.')
- const available = await this.engineProbeProvider([input.engine])
- if (!available.some(e => e.engine === input.engine && e.installed)) throw new OrchestratorError('ENGINE_NOT_INSTALLED', `${input.engine} must be installed before starting this specialist.`)
- const result = await this.onCreateAgent({ ...input, grid: null, codexHome: null, agent: null, permissionMode: null })
- if (!result.ok) throw new OrchestratorError(result.error, result.detail ?? result.error)
- return { agentId: result.session.agentId }
- },
- send: (id, text, deliveryId) => {
- if (!this.onMessage || !registry.resolve(id)) throw new OrchestratorError('AGENT_UNAVAILABLE', 'The agent is not available to receive a message.')
- this.onMessage(id, text, deliveryId)
- },
- cancelDelivery: id => this.onCancelOrchestratorMessage?.(id) ?? false,
- cancel: id => this.onCancel?.(id),
- agent: id => {
- const agent = registry.resolve(id)
- if (!agent) return null
- const context = this.dshFrameProvider?.(agent)
- return { viewerUrl: context?.viewerUrl, viewerName: context?.viewerName, error: agent.launch?.state === 'failed' ? agent.launch.detail ?? agent.launch.error : null }
- },
- changed: (id, revision) => this.sendLocal({ type: 'orchestrator_changed', payload: { id, revision } }),
- })
- }
+ /** Every frame sent to the apps, as it is sent: the orchestrator reads its Directors' turns from them
+ * (services/orchestrator.ts, through its port). One that throws costs it that frame, never the apps. */
+ onFrameSent: ((frame: Frame) => void) | null = null
+ /** The account's notices the backend announces (`desk_changed`, …), for the experiments that hear them
+ * (Tab collaboration reads its tab channels again), as well as the windows here. */
+ onAccountNotice: ((notice: BackendNotice) => void) | null = null
/**
* Called on `agent_retarget` — cli.ts re-execs an EXISTING agent's pane against a different grid,
* or, when `grid` is null, back onto its own login.
@@@ -1683,14 -722,13 +726,13 @@@
// ── down-frame dispatch (the hosted runtime-role RPC switch) ────────────────────────────────────────────
- /** Emit an RPC reply. For an E2EE-session requester whose result carries user content, the reply is
- * encrypted with that connection's session key and delivered ONLY to it. Content-bearing adapter data
- * is never returned plaintext: even legacy backend nodeRequest (`connId === ''`) gets only an error. */
+ /** Emit an RPC reply: in the clear to a window on this computer that asked; through the gateway to a
+ * remote client, which seals it to that client alone, or answers a bare E2EE_REQUIRED when it cannot
+ * (`GatewayPort.reply`). */
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = rpcResultType(type)
- if (connId && deviceDump.enabled && this.e2ee.sessionRole(connId) === 'device') deviceDump.record('out', 'legacy', connId, { type: resultType, payload: { requestId, ...payload } })
// Before the E2EE wrap: an RPC reply is only readable here.
- if (env.LOG_FRAMES && !TEAM_REQUEST_TYPES.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
- if (env.LOG_FRAMES && !TEAM_REQUESTS.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
++ if (env.LOG_FRAMES && !TEAM_REQUESTS.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })
if (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
@@@ -1741,83 -763,31 +767,31 @@@
// frames were then read as the BACKEND's. The transport half closes that, because it is stamped
// at enqueue by the caller that had just verified membership. Either one being true is local.
const local = transport === 'local' || this.localClients.has(connId)
- // ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.
- // `transport === 'relay'` rather than `!local`, so this keeps holding if the p2p allowlist
- // (`TERMINAL_P2P_DOWN_TYPES`) ever widens; "not local" would quietly start admitting p2p.
- //
- // Deliberately ABOVE the observer hand-off below. A genuine observer frame is `relay`, so this
- // never intercepts one; but placed after it, a forged `observer:` connId on a local or p2p frame
- // would be swallowed by `harnessSharing.receive` and returned without ever reaching this line —
- // silently, with no warning — and the invariant would then rest on three facts in other files
- // (the `local:` prefix rule, `registerLocalClient`'s check, the p2p-signal ordering) instead of
- // on this one. The grid-name incident was exactly a bypass nobody could see.
- if (transport !== 'relay' && BACKEND_ONLY_DOWN_TYPES.has(type)) {
- console.warn(`[backend] ignoring ${type} from ${transport} (${connId}) — only the backend may send it`)
- return
- }
- if (connId.startsWith('observer:')) {
- await this.harnessSharing?.receive(connId, type, (frame.payload ?? {}) as Record<string, unknown>)
- return
- }
- if (type.startsWith('observer_')) return
- // E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.
- if (type.startsWith('e2e_')) {
- if (local) {
- this.sendTo(connId, { type: 'local_protocol_error', payload: { error: 'LOCAL_E2EE_UNSUPPORTED' } })
+ if (local) {
+ // ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.
+ if (BACKEND_ONLY_DOWN_TYPES.has(type)) {
+ console.warn(`[backend] ignoring ${type} from ${transport} (${connId}) — only the backend may send it`)
return
}
- const deviceBefore = deviceDump.enabled && (this.isDeviceConn(connId) || (type === 'e2e_pair_intent' && (frame.payload as { role?: unknown } | undefined)?.role === 'device'))
- if (deviceBefore) deviceDump.record('in', 'wire', connId, frame)
- this.e2ee.handleFrame(connId, frame)
- // A reconnecting device is only known as one once its hello has been accepted.
- if (!deviceBefore && deviceDump.enabled && this.isDeviceConn(connId)) deviceDump.record('in', 'wire', connId, frame)
- return
- }
- if (type === 'autonomous_device_request') {
- if (!local) await this.autonomousDeviceRelay?.handle(connId, frame)
- return
- }
- // ⚠️ Default-deny: the relay is NOT trusted. A non-local frame is acted on only if it opens under
- // this connId's E2EE session — whatever its type — or is one of the backend's own plaintext frames.
- // A list of "sensitive" types to check instead fails open: every type missing from it, including
- // ones added later, would be taken in the clear.
- //
- // The backend's own control frames are the mirror image: only ever plaintext, because the backend
- // holds no key — so one that arrives SEALED was sealed by a paired client, and opening it would let
- // that client speak as the backend (`machine_meta` repoints this computer's grid).
- if (!local) {
- const from = `${transport} (${connId ? `conn:${sid(connId)}` : 'backend'})`
- const wrapped = isWrapped(frame.payload)
- if (type.startsWith('__') || BACKEND_ONLY_DOWN_TYPES.has(type)) {
- // And only on the backend's OWN address: it sends these with `connId: ''`, while every frame a
- // client sends arrives stamped with that client's connId — so a client-shaped one was relayed, not
- // written by the backend, whichever socket let it through. `__client_disconnected` is the one the
- // hub addresses to a client's own connId; it only tears down that connection's state.
- if (transport !== 'relay' || wrapped || (connId !== '' && type !== '__client_disconnected')) {
- console.warn(`[backend] ignoring ${logSafeType(type)} from ${from} — only the backend sends it, and only in the clear`)
- return
- }
- } else if (wrapped) {
- const dec = this.e2ee.unwrapDown(connId, frame)
- if (!dec) return
- frame = dec
- } else {
- console.warn(`[backend] refusing plaintext ${logSafeType(type)} from ${from} — E2EE required`)
- const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId
- if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })
+ // The backend hub's own control frames (`__clients`, `__client_disconnected`) are the gateway's to
+ // hear, from the backend: a process on this computer was able to set how many devices watch it.
+ if (type.startsWith('__')) {
+ console.warn(`[backend] ignoring ${logSafeType(type)} from ${transport} (${connId}) — only the backend sends it`)
return
}
+ // E2EE belongs to the relay: a window here speaks in the clear, and has no handshake to make.
+ if (type.startsWith('e2e_')) {
+ this.sendTo(connId, { type: 'local_protocol_error', payload: { error: 'LOCAL_E2EE_UNSUPPORTED' } })
+ return
+ }
+ if (type === 'autonomous_device_request') return
}
- if (!local && deviceDump.enabled && this.e2ee.sessionRole(connId) === 'device') deviceDump.record('in', 'legacy', connId, frame)
- if (!local && TERMINAL_P2P_SIGNAL_TYPES.has(type)) {
- await this.terminalP2p.handleSignal(connId, type, frame.payload)
- return
- }
- // Logged AFTER the unwrap above, so a down-frame reads as what the client actually asked for rather
- // than as an opaque __e2e envelope.
+ if (type.startsWith('observer_')) return
+ // Logged as opened (the gateway unwrapped a remote client's), so a down-frame reads as what the client
+ // actually asked for rather than as an opaque __e2e envelope.
// Terminal frames contain raw keystrokes, paste text and screen bytes after
// unwrap. Never pass them to the frame logger, even in diagnostic mode.
- if (env.LOG_FRAMES && !TEAM_REQUEST_TYPES.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
- if (env.LOG_FRAMES && !TEAM_REQUESTS.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
++ if (env.LOG_FRAMES && !TEAM_REQUESTS.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)
diff --cc cli/src/core/agents/create.ts
index 49481ab3e,999d117c9..f53b3525e
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@@ -125,10 -126,10 +127,11 @@@ export function createAgentCreator(
// Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
// retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
// before the grid block because a file-configured engine keys its config directory on it.
- // The `harness-` prefix is also discovery's whitelist (see `isHarnessSession` /
- // `TmuxBackend.inventory()`) — every pane outside it is invisible to the daemon.
+ // The `harness-` prefix is also discovery's whitelist for a pane nobody tagged (see `ownedHere` /
+ // `TmuxBackend.inventory()`): the panes this daemon creates carry its tag, which goes with them into
+ // any session the person moves them to.
const label = buildHarnessSessionLabel(engine)
+ await prepareInstructionWrites(cwd)
// Prepare the harness workspace, then bind its session context to the selected engine.
// Missing packages or invalid runtimes refuse the launch before the agent is started.
let dshEnv: Record<string, string> | undefined
diff --cc cli/src/core/agents/fork.ts
index 87f202e9f,34ee159b6..8d2fa958e
--- a/cli/src/core/agents/fork.ts
+++ b/cli/src/core/agents/fork.ts
@@@ -23,7 -23,7 +23,8 @@@ import { forkName, planFork } from '../
import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
import { projectDisplayName, type registry, type RegisteredSession } from '../../lib/registry.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
+import { prepareInstructionWrites, scmLaunchEnv } from '../../scm/scmProjects.js'
+ import type { createLaunchHelpers } from './launch.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { createPaneWatcher } from './newPane.js'
@@@ -125,11 -134,9 +136,12 @@@ export function createAgentForker(
cwd: source.cwd,
sessionLabel: label,
argv,
- env: mergedLaunchEnv(mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv), scmLaunchEnv(source.scmLaunch)),
- env: mergedLaunchEnv(Object.keys(built.overrides.env).length ? built.overrides.env : undefined, dshEnv),
++ // The SCM's environment last, after the harness context's, as at create and relaunch.
++ env: mergedLaunchEnv(mergedLaunchEnv(Object.keys(built.overrides.env).length ? built.overrides.env : undefined, dshEnv), scmLaunchEnv(source.scmLaunch)),
grid: null,
gridLaunchRecord: null,
+ // Same folder as the source, so the same workspace binding.
+ scmLaunchRecord: source.scmLaunch ?? null,
codexHome: source.codexHome ?? null,
dshRuntime: source.dsh ? label : null,
dsh: source.dsh ?? null,
diff --cc cli/src/core/agents/launches.spec.ts
index 000000000,a65379c68..d614779e4
mode 000000,100644..100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@@ -1,0 -1,534 +1,546 @@@
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+ import { homedir, tmpdir } from 'node:os'
+ import { join } from 'node:path'
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+ import { installedDsh } from '../../dsh/installed.js'
+ import { dshSupportedEngines } from '../../dsh/manifest.js'
+ import { opencodeMajorVersion } from '../../engines/opencode/version.js'
+ import { AgentCreationReceiptError, AgentCreationReceipts, type AgentCreationOutcome } from '../../lib/agentCreationReceipt.js'
+ import type { AgentFrame } from '../../lib/agentFrame.js'
+ import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'
+ import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from '../../lib/engineLaunch.js'
+ import { parseGridLaunchOverride } from '../../lib/gridLaunch.js'
+ import { parseNewAgentModel } from '../../lib/newAgentModel.js'
+ import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '../../lib/projectFolder.js'
+ import type { RegisteredSession } from '../../lib/registry.js'
+ import { createLaunchRequests, type CreateAgent, type ForkAgent, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from './launches.js'
+
+ /**
+ * The requests that start an agent's process, answered by the core: every refusal before a pane exists,
+ * what each launch is handed, the receipts that let a lost answer be asked for again, and the replies,
+ * field for field. Trust records, grid reads, project folders and installed harnesses are fakes here:
+ * they are tested with their own modules, and a test must never write the person's own engine config.
+ */
+ const root = vi.hoisted(() => ({ projects: '' }))
+ vi.mock('../../lib/claudeTrust.js', async (real) => ({
+ ...await real<object>(),
+ claudeTrusts: vi.fn(() => false), codexTrusts: vi.fn(() => false), preTrustClaudeProject: vi.fn(), preTrustCodexProject: vi.fn(),
+ }))
+ vi.mock('../../engines/opencode/version.js', async (real) => ({ ...await real<object>(), opencodeMajorVersion: vi.fn(() => 1) }))
+ vi.mock('../../lib/newAgentModel.js', async (real) => ({
+ ...await real<object>(), parseNewAgentModel: vi.fn(() => ({ state: 'absent' })),
+ }))
+ vi.mock('../../lib/gridLaunch.js', async (real) => ({ ...await real<object>(), parseGridLaunchOverride: vi.fn(() => ({ state: 'absent' })) }))
+ vi.mock('../../dsh/installed.js', async (real) => ({ ...await real<object>(), installedDsh: vi.fn(() => undefined) }))
+ vi.mock('../../dsh/manifest.js', async (real) => ({ ...await real<object>(), dshSupportedEngines: vi.fn(() => ['claude', 'codex']) }))
+ vi.mock('../../lib/engineLaunch.js', async (real) => ({
+ ...await real<object>(),
+ supportsFirstPrompt: vi.fn(() => true), supportsNamedAgent: vi.fn(() => true),
+ permissionModeFlags: vi.fn(() => ['--flag']), permissionModeApproves: vi.fn(() => false),
+ }))
+ vi.mock('../../lib/projectFolder.js', async (real) => {
+ const actual = await real<typeof import('../../lib/projectFolder.js')>()
+ return { ...actual, parseProjectFolder: vi.fn(actual.parseProjectFolder), prepareProjectFolder: vi.fn(async () => '/projects/prepared'), projectsRoot: vi.fn(() => root.projects) }
+ })
+
+ const CREATION = 'creation-0123456789abcdef'
+ /** Where the models service resolves a new agent's grid model (core/api.ts `ModelsPort.launchTarget`). */
+ const resolveNewAgentModel = vi.fn<LaunchRequestDeps['modelTarget']>()
+ const session = (agentId = 'a1', over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `${agentId}-session`, engine: 'claude', ...over }) as RegisteredSession
+ const frameOf = (s: RegisteredSession) => ({ id: s.agentId }) as unknown as AgentFrame
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
+
+ let dir: string
+ let stores = 0
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'launches-'))
+ root.projects = join(dir, 'harnesses')
+ mkdirSync(root.projects)
+ })
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ vi.restoreAllMocks()
+ vi.resetAllMocks()
+ })
+
+ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: CreateAgent | null; fork?: ForkAgent | null; resume?: ResumeAgent | null; restart?: RestartAgent | null } = {}) {
+ const create = launches.create === undefined ? vi.fn(async () => ({ ok: true as const, session: session('new-agent') })) : launches.create
+ const fork = launches.fork === undefined ? vi.fn(async () => ({ ok: true as const, session: session('forked'), level: 'native' as const })) : launches.fork
+ const resume = launches.resume === undefined ? vi.fn(async () => ({ ok: true as const, session: session('a1'), resumed: true })) : launches.resume
+ const restart = launches.restart === undefined ? vi.fn(async () => ({ ok: true as const, session: session('a1'), resumed: false })) : launches.restart
+ const known = new Map([['new-agent', session('new-agent')], ['forked', session('forked')], ['a1', session('a1')]])
+ const deps: LaunchRequestDeps = {
+ receipts: new AgentCreationReceipts(join(dir, `receipts-${++stores}`)),
+ createAgent: () => create, forkAgent: () => fork, resumeAgent: () => resume, restartAgent: () => restart,
+ byAgent: (id) => known.get(id), toProject: vi.fn(async (s: RegisteredSession) => frameOf(s)),
+ modelTarget: resolveNewAgentModel,
+ ...over,
+ }
+ const requests = createLaunchRequests(deps)
+ const replies: Array<Record<string, unknown>> = []
+ const reply = (result: Record<string, unknown>) => { replies.push(result) }
+ return {
+ deps, create, fork, resume, restart, replies, requests,
+ ask: async (payload: Record<string, unknown>, local = true) => { await requests.create(payload, { local }, reply); return replies.at(-1) },
+ status: async (payload: Record<string, unknown>) => { await requests.createStatus(payload, reply); return replies.at(-1) },
+ relaunch: async (type: string, payload: Record<string, unknown>) => { await requests.relaunch(type, payload, reply); return replies.at(-1) },
+ forkAsk: async (payload: Record<string, unknown>) => { await requests.fork(payload, reply); return replies.at(-1) },
+ }
+ }
+
+ describe('agent_create, refused before any pane exists', () => {
+ it('an engine it does not know, a folder it cannot read, or a cwd that is not an absolute path', async () => {
+ const { ask, create } = setup()
+ expect(await ask({ cwd: '/w' })).toStrictEqual({ error: 'INVALID_ENGINE' })
+ expect(await ask({ engine: 'gpt', cwd: '/w' })).toStrictEqual({ error: 'INVALID_ENGINE' })
+ expect(await ask({ engine: 'claude', projectSource: 'bogus' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE', detail: 'Choose a project.' })
+ vi.mocked(parseProjectFolder).mockImplementationOnce(() => { throw new Error('unexpected') })
+ expect(await ask({ engine: 'claude', projectSource: 'new' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE' })
+ expect(await ask({ engine: 'terminal', projectSource: 'new', creationId: CREATION }))
+ .toStrictEqual({ error: 'INVALID_PROJECT_SOURCE', detail: 'a terminal opens in a folder, it does not prepare one' })
+ expect(await ask({ engine: 'claude', cwd: 'relative/path' })).toStrictEqual({ error: 'INVALID_CWD' })
+ expect(await ask({ engine: 'claude' })).toStrictEqual({ error: 'INVALID_CWD' })
+ expect(await ask({ engine: 'terminal', cwd: 'relative' })).toStrictEqual({ error: 'INVALID_CWD' })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('on a machine that cannot launch, a creation id that is not one, and a folder asked for without a receipt or beside a cwd', async () => {
+ expect(await setup({}, { create: null }).ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })
+ const { ask } = setup()
+ expect(await ask({ engine: 'claude', cwd: '/w', creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })
+ expect(await ask({ engine: 'claude', projectSource: 'new' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE' })
+ expect(await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION, cwd: '/w' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE' })
+ })
+
+ it('a model or grid that is not one, a grid for a terminal, and a codexHome anywhere but on codex without a grid', async () => {
+ const { ask, create } = setup()
+ vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'invalid', detail: 'no such model' } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'INVALID_GRID', detail: 'no such model' })
+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'invalid', reason: 'no baseUrl' } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'INVALID_GRID', detail: 'no baseUrl' })
+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)
+ expect(await ask({ engine: 'terminal' })).toStrictEqual({ error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' })
+ const codexHomeRefused = { error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' }
+ expect(await ask({ engine: 'claude', cwd: '/w', codexHome: '/homes/codex' })).toStrictEqual(codexHomeRefused)
+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)
+ expect(await ask({ engine: 'codex', cwd: '/w', codexHome: '/homes/codex' })).toStrictEqual(codexHomeRefused)
+ expect(create).not.toHaveBeenCalled()
+ // One that is not a plain absolute path is not a codexHome at all, and is dropped rather than refused.
+ for (const codexHome of ['relative', '/with\nnewline', `/${'x'.repeat(4096)}`, 7]) await ask({ engine: 'claude', cwd: '/w', codexHome })
+ expect(vi.mocked(create!).mock.calls.map(([input]) => input.codexHome)).toEqual([null, null, null, null])
+ })
+
+ it('a harness that is not an id, not installed here, a viewer, or not for this engine', async () => {
+ const { ask, create } = setup()
+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'not an id' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' })
+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 7 })).toStrictEqual({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' })
+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/notes' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/notes is not installed on this machine' })
+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/viewer', manifest: { kind: 'viewer' } } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/viewer' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/viewer is a viewer package, not an agent' })
+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)
+ expect(await ask({ engine: 'pi', cwd: '/w', dsh: 'acme/notes' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/notes supports claude, codex; pi is not compatible' })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('a first prompt that is not text, too long, or for an engine that cannot take one', async () => {
+ const { ask, create } = setup()
+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' })
+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 'x'.repeat(MAX_FIRST_PROMPT_CHARS + 1) }))
+ .toStrictEqual({ error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` })
+ vi.mocked(supportsFirstPrompt).mockReturnValueOnce(false)
+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 'fix it' })).toMatchObject({ error: 'PROMPT_UNSUPPORTED' })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('a named agent that is not a name, or one its engine cannot open as (OpenCode v2 counts as cannot)', async () => {
+ const { ask, create } = setup()
+ expect(await ask({ engine: 'claude', cwd: '/w', agent: '../reviewer' })).toStrictEqual({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' })
+ expect(await ask({ engine: 'claude', cwd: '/w', agent: 7 })).toMatchObject({ error: 'INVALID_AGENT' })
+ vi.mocked(supportsNamedAgent).mockReturnValueOnce(false)
+ vi.mocked(opencodeMajorVersion).mockReturnValueOnce(2)
+ expect(await ask({ engine: 'opencode', cwd: '/w', agent: 'reviewer' })).toMatchObject({ error: 'AGENT_UNSUPPORTED' })
+ expect(supportsNamedAgent).toHaveBeenLastCalledWith('opencode', 2)
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('a permission mode the engine does not have, and a conversation to resume that is not one or comes with new-conversation choices', async () => {
+ const { ask, create } = setup()
+ vi.mocked(permissionModeFlags).mockReturnValueOnce(null as never)
+ expect(await ask({ engine: 'claude', cwd: '/w', permissionMode: 'yolo' })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE', detail: 'claude has no permission mode "yolo"' })
+ expect(await ask({ engine: 'claude', cwd: '/w', permissionMode: 7 })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE', detail: 'claude has no permission mode 7' })
+ const notASession = { error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }
+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: '../x' })).toStrictEqual(notASession)
+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 7 })).toStrictEqual(notASession)
+ const fresh = { error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }
+ expect(await ask({ engine: 'terminal', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ expect(await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION, resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'ok', selection: { model: 'm' } } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)
+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/notes', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 'go', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ expect(await ask({ engine: 'claude', cwd: '/w', agent: 'reviewer', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)
+ const takeOver = { error: 'INVALID_SESSION', detail: 'takeOver is idle, now or wait, with a resumeSessionId' }
+ expect(await ask({ engine: 'claude', cwd: '/w', takeOver: 'now' })).toStrictEqual(takeOver)
+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc', takeOver: 'later' })).toStrictEqual(takeOver)
+ expect(create).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('agent_create, launched', () => {
+ it('hands the creator every choice, as one input, and answers with the new agent\'s frame', async () => {
+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)
+ vi.mocked(permissionModeApproves).mockReturnValueOnce(true)
+ const { ask, create } = setup()
+ const reply = await ask({ engine: 'codex', cwd: '/w', codexHome: '/homes/codex', dsh: 'acme/notes', prompt: ' fix the build ', name: ' Builder ',
+ agent: 'reviewer', permissionMode: 'auto' })
+ expect(reply).toStrictEqual({ agent: { id: 'new-agent' } })
+ expect(create).toHaveBeenCalledWith({ engine: 'codex', cwd: '/w', bypassPermission: true, permissionMode: 'auto', grid: null, codexHome: '/homes/codex',
+ dsh: 'acme/notes', prompt: 'fix the build', name: 'Builder', agent: 'reviewer', resumeSessionId: null, takeOver: null })
+ expect(Object.keys(vi.mocked(create!).mock.calls[0][0])).toEqual(['engine', 'cwd', 'bypassPermission', 'permissionMode', 'grid', 'codexHome', 'dsh', 'prompt', 'name', 'agent', 'resumeSessionId', 'takeOver'])
+ })
+
+ it('opens a terminal in the home folder, bypasses permission unless told not to, and takes blank choices as none', async () => {
+ const { ask, create } = setup()
+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'absent' } as never).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)
+ await ask({ engine: 'terminal' })
+ await ask({ engine: 'claude', cwd: '/w', bypassPermission: false, prompt: ' ', name: ' ', dsh: null, agent: null, permissionMode: null, resumeSessionId: null, takeOver: null })
+ await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc', takeOver: 'idle' })
+ const inputs = vi.mocked(create!).mock.calls.map(([input]) => input)
+ expect(inputs[0]).toMatchObject({ engine: 'terminal', cwd: homedir(), bypassPermission: true })
+ expect(inputs[1]).toMatchObject({ cwd: '/w', bypassPermission: false, prompt: null, name: null, grid: { networkId: 'g' } })
+ expect(inputs[2]).toMatchObject({ resumeSessionId: 'ses_abc', takeOver: 'idle' })
+ })
+
+ it('points a model picked by name at its grid as read now, or says the model is unavailable', async () => {
+ const { ask, create } = setup()
+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)
+ resolveNewAgentModel.mockResolvedValueOnce({ networkId: 'resolved' } as never).mockResolvedValueOnce(null).mockRejectedValueOnce(new Error('offline'))
+ await ask({ engine: 'claude', cwd: '/w' })
+ expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })
+ const unavailable = { error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }
+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual(unavailable)
+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual(unavailable)
+ expect(create).toHaveBeenCalledOnce()
+ })
+
+ it('passes a refusal on with its cause when it has one', async () => {
+ const refused = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'SPAWN_FAILED', detail: 'tmux: no server' })) })
+ expect(await refused.ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'SPAWN_FAILED', detail: 'tmux: no server' })
+ const bare = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })
+ expect(await bare.ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'ENGINE_MISSING' })
+ })
+ })
+
+ describe('agent_create with a receipt', () => {
+ it('answers outside the connection\'s line, with the creation id and the new agent, and a retry is the same launch', async () => {
+ let finish!: (value: { ok: true; session: RegisteredSession }) => void
+ const create = vi.fn(() => new Promise<{ ok: true; session: RegisteredSession }>((resolve) => { finish = resolve }))
+ const { ask, replies, status } = setup({}, { create })
+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })
+ expect(replies).toEqual([])
+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'pending' })
+ finish({ ok: true, session: session('new-agent') })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
+ expect(replies[1]).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'new-agent' } })
+ expect(Object.keys(replies[1])).toEqual(['creationId', 'state', 'agent'])
+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })
+ await vi.waitFor(() => expect(replies).toHaveLength(3))
+ expect(create).toHaveBeenCalledOnce()
+ // The same id for another launch is a conflict, never a second process.
+ await ask({ engine: 'codex', cwd: '/w', creationId: CREATION })
+ expect(replies.at(-1)).toStrictEqual({ error: 'CREATION_CONFLICT' })
+ })
+
+ it('records a launch that may have started as unconfirmed, and any other refusal as failed, with its folder and its cause, cut short', async () => {
+ for (const [error, expected] of [['SPAWN_FAILED', 'unconfirmed'], ['REGISTRATION_FAILED', 'unconfirmed'], ['ENGINE_MISSING', 'failed']] as const) {
+ const { ask, replies } = setup({}, { create: vi.fn(async () => ({ ok: false as const, error, detail: 'd'.repeat(3000) })) })
+ await ask({ engine: 'claude', cwd: '/w', creationId: `${CREATION}-${error.toLowerCase()}`.slice(0, 64).replace(/_/g, '-') })
+ await vi.waitFor(() => expect(replies).toHaveLength(1))
+ expect(replies[0].state).toBe(expected)
+ if (expected === 'failed') expect(replies[0]).toStrictEqual({ creationId: expect.any(String), state: 'failed', failure: { code: 'ENGINE_MISSING', detail: 'd'.repeat(2000) } })
+ }
+ const bare = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })
+ await bare.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })
+ await vi.waitFor(() => expect(bare.replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'ENGINE_MISSING' } }]))
+ })
+
+ it('prepares the project folder it was asked for, named after the harness or the engine, and launches in it', async () => {
+ const { ask, create, replies } = setup()
+ vi.mocked(installedDsh).mockReturnValue({ id: 'acme/notes', manifest: { kind: 'agent', name: 'Notes' } } as never)
+ await ask({ engine: 'claude', projectSource: 'new', projectName: 'Docs', creationId: CREATION, dsh: 'acme/notes' })
+ await vi.waitFor(() => expect(replies).toHaveLength(1))
- expect(prepareProjectFolder).toHaveBeenCalledWith({ source: 'new', name: 'Docs' }, { label: 'Notes' })
++ expect(prepareProjectFolder).toHaveBeenCalledWith({ source: 'new', name: 'Docs' }, { label: 'Notes', onPrepared: expect.any(Function) })
+ expect(vi.mocked(create!).mock.calls[0][0].cwd).toBe('/projects/prepared')
+ vi.mocked(installedDsh).mockReturnValue(undefined)
+ await ask({ engine: 'pi', projectSource: 'new', creationId: `${CREATION}-pi` })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
- expect(prepareProjectFolder).toHaveBeenLastCalledWith({ source: 'new' }, { label: 'Pi' })
++ expect(prepareProjectFolder).toHaveBeenLastCalledWith({ source: 'new' }, { label: 'Pi', onPrepared: expect.any(Function) })
++ expect(vi.mocked(create!).mock.calls[1][0].scmLaunchRecord).toBeNull()
++ })
++
++ it('hands the launch the SCM record the prepared workspace reported (registry `scmLaunch`)', async () => {
++ const { ask, create, replies } = setup()
++ vi.mocked(prepareProjectFolder).mockImplementationOnce(async (_project, options) => {
++ options?.onPrepared?.({ cwd: '/projects/prepared', scmLaunchRecord: { kind: 'git' } })
++ return '/projects/prepared'
++ })
++ await ask({ engine: 'claude', projectSource: 'worktree', gitSource: '/work/repo', branchRef: 'refs/heads/main', creationId: CREATION })
++ await vi.waitFor(() => expect(replies).toHaveLength(1))
++ expect(vi.mocked(create!).mock.calls[0][0]).toMatchObject({ cwd: '/projects/prepared', scmLaunchRecord: { kind: 'git' } })
+ })
+
+ it('records a folder it could not prepare as failed, in the folder\'s own words when it has them', async () => {
+ const { ask, create, replies } = setup()
+ vi.mocked(prepareProjectFolder).mockRejectedValueOnce(new ProjectFolderError('CLONE_FAILED', 'Could not clone it.')).mockRejectedValueOnce(new Error('disk full'))
+ await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION })
+ await ask({ engine: 'claude', projectSource: 'new', creationId: `${CREATION}-2` })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
+ expect(replies.map((r) => r.failure)).toEqual([
+ { code: 'CLONE_FAILED', detail: 'Could not clone it.' }, { code: 'PROJECT_PREPARATION_FAILED', detail: 'Could not prepare the project folder.' },
+ ])
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('records the prepared folder of a launch that then failed, so the person can open it', async () => {
+ const { ask, replies } = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })
+ await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION })
+ await vi.waitFor(() => expect(replies).toStrictEqual([{ creationId: CREATION, state: 'failed', preparedFolder: '/projects/prepared', failure: { code: 'ENGINE_MISSING' } }]))
+ })
+
+ it('trusts only a folder it just made empty, or a worktree of a repository the engine already trusts', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { ask, replies } = setup()
+ const launch = async (payload: Record<string, unknown>, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }); await vi.waitFor(() => expect(replies).toHaveLength(n)) }
+ await launch({ engine: 'claude', projectSource: 'new' }, 1)
+ expect(preTrustClaudeProject).toHaveBeenCalledWith('/projects/prepared')
+ vi.mocked(codexTrusts).mockReturnValueOnce(true)
+ await launch({ engine: 'codex', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' }, 2)
+ expect(codexTrusts).toHaveBeenCalledWith('/repo', null)
+ expect(preTrustCodexProject).toHaveBeenCalledWith('/projects/prepared', null)
+ await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' }, 3)
+ await launch({ engine: 'claude', projectSource: 'branch', gitSource: '/repo', branchRef: 'refs/heads/main' }, 4)
+ await launch({ engine: 'pi', projectSource: 'new' }, 5)
+ expect(preTrustClaudeProject).toHaveBeenCalledOnce()
+ expect(preTrustCodexProject).toHaveBeenCalledOnce()
+ vi.mocked(preTrustClaudeProject).mockImplementationOnce(() => { throw new Error('config locked') }).mockImplementationOnce(() => { throw 'busy' })
+ await launch({ engine: 'claude', projectSource: 'new' }, 6)
+ await launch({ engine: 'claude', projectSource: 'new' }, 7)
+ expect(console.warn).toHaveBeenCalledWith('[agent] pre-trust /projects/prepared · config locked')
+ expect(console.warn).toHaveBeenCalledWith('[agent] pre-trust /projects/prepared · busy')
+ expect(claudeTrusts).toHaveBeenCalledWith('/repo')
+ })
+
+ // A Codex agent on its own profile reads its trust from THAT profile's config.toml: the trust was
+ // read and written in ~/.codex alone, so it got Codex's trust prompt in a folder Harness had just made.
+ it('asks and records a Codex agent\'s trust in its own profile', async () => {
+ const { ask, replies } = setup()
+ const empty = join(root.projects, 'fresh-profile')
+ mkdirSync(empty)
+ vi.mocked(codexTrusts).mockReturnValueOnce(true)
+ await ask({ creationId: `${CREATION}-1`, engine: 'codex', codexHome: '/profiles/work', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' })
+ await ask({ creationId: `${CREATION}-2`, engine: 'codex', codexHome: '/profiles/work', cwd: empty })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
+ expect(codexTrusts).toHaveBeenCalledWith('/repo', '/profiles/work')
+ expect(preTrustCodexProject).toHaveBeenNthCalledWith(1, '/projects/prepared', '/profiles/work')
+ expect(preTrustCodexProject).toHaveBeenNthCalledWith(2, empty, '/profiles/work')
+ })
+
+ it('trusts an empty workspace this machine\'s own window made in the projects folder, and nothing else', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { ask, replies } = setup()
+ const empty = join(root.projects, 'fresh')
+ const filled = join(root.projects, 'filled')
+ mkdirSync(empty)
+ mkdirSync(filled)
+ writeFileSync(join(filled, 'README.md'), 'mine')
+ const launch = async (payload: Record<string, unknown>, local: boolean, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }, local); await vi.waitFor(() => expect(replies).toHaveLength(n)) }
+ await launch({ engine: 'claude', cwd: empty }, true, 1)
+ await launch({ engine: 'codex', cwd: empty }, true, 2)
+ expect(preTrustClaudeProject).toHaveBeenCalledWith(empty)
+ expect(preTrustCodexProject).toHaveBeenCalledWith(empty, null)
+ await launch({ engine: 'claude', cwd: filled }, true, 3)
+ await launch({ engine: 'claude', cwd: join(root.projects, 'missing') }, true, 4)
+ await launch({ engine: 'claude', cwd: empty }, false, 5)
+ await launch({ engine: 'claude', cwd: dir }, true, 6)
+ await launch({ engine: 'pi', cwd: empty }, true, 7)
+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)
+ await launch({ engine: 'claude', cwd: empty, dsh: 'acme/notes' }, true, 8)
+ expect(preTrustClaudeProject).toHaveBeenCalledOnce()
+ expect(preTrustCodexProject).toHaveBeenCalledOnce()
+ vi.mocked(preTrustCodexProject).mockImplementationOnce(() => { throw new Error('config locked') }).mockImplementationOnce(() => { throw 'busy' })
+ await launch({ engine: 'codex', cwd: empty }, true, 9)
+ await launch({ engine: 'codex', cwd: empty }, true, 10)
+ expect(warn).toHaveBeenCalledWith(`[agent] pre-trust ${empty} · config locked`)
+ expect(warn).toHaveBeenCalledWith(`[agent] pre-trust ${empty} · busy`)
+ })
+
+ it('resolves a model picked by name inside the receipt, and records it unavailable when it cannot be read', async () => {
+ const { ask, create, replies } = setup()
+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)
+ resolveNewAgentModel.mockResolvedValueOnce({ networkId: 'resolved' } as never).mockRejectedValueOnce(new Error('offline'))
+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })
+ await ask({ engine: 'claude', cwd: '/w', creationId: `${CREATION}-2` })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
+ expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })
+ expect(replies[1]).toStrictEqual({ creationId: `${CREATION}-2`, state: 'failed',
+ failure: { code: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' } })
+ })
+
+ it('says why a receipt could not be kept, and answers INTERNAL when the answer cannot be put together', async () => {
+ const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
+ expect(await storage.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })
+ const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
+ expect(await broken.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
+ const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })
+ await frameless.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })
+ await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))
+ })
+ })
+
+ describe('agent_create_status', () => {
+ it('names a launch by a valid creation id, and says what became of it', async () => {
+ const { status, deps } = setup()
+ expect(await status({ creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })
+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'missing' })
+ const outcome = (value: AgentCreationOutcome | { state: 'pending' }) => { vi.spyOn(deps.receipts, 'status').mockReturnValueOnce(value as never) }
+ outcome({ state: 'created', agentId: 'forked', level: 'handoff', resumed: true })
+ const created = await status({ creationId: CREATION })
+ expect(created).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'forked' }, level: 'handoff', resumed: true })
+ expect(Object.keys(created!)).toEqual(['creationId', 'state', 'agent', 'level', 'resumed'])
+ outcome({ state: 'created', agentId: 'deleted-since' })
+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'unavailable' })
+ outcome({ state: 'failed', error: 'ENGINE_MISSING', detail: 'claude is not installed', preparedFolder: '/projects/prepared' })
+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'failed', preparedFolder: '/projects/prepared', failure: { code: 'ENGINE_MISSING', detail: 'claude is not installed' } })
+ outcome({ state: 'unconfirmed' })
+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'unconfirmed' })
+ })
+
+ it('says why a receipt could not be read', async () => {
+ const storage = setup({ receipts: { run: vi.fn(), status: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
+ expect(await storage.status({ creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })
+ const broken = setup({ receipts: { run: vi.fn(), status: vi.fn(() => { throw new Error('bug') }) } })
+ expect(await broken.status({ creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
+ })
+ })
+
+ describe('agent_resume and agent_restart', () => {
+ it('relaunch the agent named, resume taking a permission mode, and answer with its frame and whether it resumed', async () => {
+ const { relaunch, resume, restart } = setup()
+ expect(await relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ agent: { id: 'a1' }, resumed: false })
+ expect(await relaunch('agent_resume', { agentId: 'a1' })).toStrictEqual({ agent: { id: 'a1' }, resumed: true })
+ expect(await relaunch('agent_resume', { agentId: 'a1', permissionMode: 'plan' })).toMatchObject({ resumed: true })
+ expect(restart).toHaveBeenCalledWith('a1')
+ expect(vi.mocked(resume!).mock.calls).toEqual([['a1'], ['a1', 'plan']])
+ })
+
+ it('refuse a request with no agent, on a machine that cannot relaunch, and a permission mode a restart has no use for', async () => {
+ const { relaunch, restart } = setup()
+ expect(await relaunch('agent_restart', {})).toStrictEqual({ error: 'MISSING_AGENT_ID' })
+ expect(await setup({}, { restart: null }).relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })
+ expect(await setup({}, { resume: null }).relaunch('agent_resume', { agentId: 'a1' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })
+ for (const [type, permissionMode] of [['agent_restart', 'auto'], ['agent_resume', 7], ['agent_resume', 'allow']] as const) {
+ expect(await relaunch(type, { agentId: 'a1', permissionMode })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE' })
+ }
+ expect(restart).not.toHaveBeenCalled()
+ })
+
+ it('pass a refusal on with its cause when it has one', async () => {
+ const failed = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error: 'RESTART_FAILED', detail: 'claude did not come back up' })) })
+ expect(await failed.relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'RESTART_FAILED', detail: 'claude did not come back up' })
+ const bare = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error: 'AGENT_NOT_FOUND' })) })
+ expect(await bare.relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'AGENT_NOT_FOUND' })
+ })
+
+ it('keep a receipt: one relaunch per creation id, an unobserved one unconfirmed, a refusal failed and cut short', async () => {
+ const { relaunch, replies, resume } = setup()
+ await relaunch('agent_resume', { agentId: 'a1', creationId: CREATION, permissionMode: 'auto' })
+ await vi.waitFor(() => expect(replies).toHaveLength(1))
+ expect(replies[0]).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'a1' }, resumed: true })
+ await relaunch('agent_resume', { agentId: 'a1', creationId: CREATION, permissionMode: 'ask' })
+ expect(replies.at(-1)).toStrictEqual({ error: 'CREATION_CONFLICT' })
+ expect(resume).toHaveBeenCalledOnce()
+ expect(await relaunch('agent_restart', { agentId: 'a1', creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })
+ for (const [error, state] of [['RESTART_FAILED', 'unconfirmed'], ['RESUME_UNCONFIRMED', 'unconfirmed'], ['AGENT_BUSY', 'failed']] as const) {
+ const run = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error, detail: 'd'.repeat(3000) })) })
+ await run.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ expect(run.replies[0].state).toBe(state)
+ if (state === 'failed') expect(run.replies[0].failure).toStrictEqual({ code: 'AGENT_BUSY', detail: 'd'.repeat(2000) })
+ }
+ const bare = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error: 'AGENT_BUSY' })) })
+ await bare.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(bare.replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'AGENT_BUSY' } }]))
+ })
+
+ it('say why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {
+ const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })
+ expect(await storage.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })
+ const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
+ expect(await broken.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
+ const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })
+ await frameless.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))
+ })
+ })
+
+ describe('agent_fork', () => {
+ it('forks the agent named, with a name and a first message when given, and answers with the new one\'s frame and what it got', async () => {
+ const { forkAsk, fork } = setup()
+ expect(await forkAsk({ agentId: 'a1', name: ` ${'n'.repeat(130)} `, prompt: 'carry on' })).toStrictEqual({ agent: { id: 'forked' }, level: 'native' })
+ expect(fork).toHaveBeenCalledWith({ agentId: 'a1', name: 'n'.repeat(120), prompt: 'carry on' })
+ await forkAsk({ agentId: 'a1', name: ' ', prompt: ' ' })
+ await forkAsk({ agentId: 'a1', prompt: null })
+ expect(vi.mocked(fork!).mock.calls.slice(1).map(([input]) => input)).toEqual([{ agentId: 'a1', name: null, prompt: null }, { agentId: 'a1', name: null, prompt: null }])
+ })
+
+ it('refuses a request with no agent, on a machine that cannot fork, and a first message that is not text or too long', async () => {
+ const { forkAsk, fork } = setup()
+ expect(await forkAsk({})).toStrictEqual({ error: 'MISSING_AGENT_ID' })
+ expect(await setup({}, { fork: null }).forkAsk({ agentId: 'a1' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })
+ expect(await forkAsk({ agentId: 'a1', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT' })
+ expect(await forkAsk({ agentId: 'a1', prompt: 'x'.repeat(MAX_FIRST_PROMPT_CHARS + 1) })).toStrictEqual({ error: 'PROMPT_TOO_LONG' })
+ expect(await forkAsk({ agentId: 'a1', creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })
+ expect(fork).not.toHaveBeenCalled()
+ })
+
+ it('passes a refusal on with its cause when it has one', async () => {
+ const failed = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error: 'SPAWN_FAILED', detail: 'tmux: no server' })) })
+ expect(await failed.forkAsk({ agentId: 'a1' })).toStrictEqual({ error: 'SPAWN_FAILED', detail: 'tmux: no server' })
+ const bare = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error: 'NOT_FORKABLE' })) })
+ expect(await bare.forkAsk({ agentId: 'a1' })).toStrictEqual({ error: 'NOT_FORKABLE' })
+ })
+
+ it('keeps a receipt like agent_create: one fork per creation id, a spawn it cannot confirm unconfirmed, a refusal failed and cut short', async () => {
+ const { forkAsk, replies, fork } = setup()
+ await forkAsk({ agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(replies).toHaveLength(1))
+ expect(replies[0]).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'forked' }, level: 'native' })
+ await forkAsk({ agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(replies).toHaveLength(2))
+ expect(fork).toHaveBeenCalledOnce()
+ for (const [error, state] of [['SPAWN_FAILED', 'unconfirmed'], ['REGISTRATION_FAILED', 'unconfirmed'], ['NOT_FORKABLE', 'failed']] as const) {
+ const run = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error, detail: 'd'.repeat(3000) })) })
+ await run.forkAsk({ agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ expect(run.replies[0].state).toBe(state)
+ if (state === 'failed') expect(run.replies[0].failure).toStrictEqual({ code: 'NOT_FORKABLE', detail: 'd'.repeat(2000) })
+ }
+ const bare = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error: 'NOT_FORKABLE' })) })
+ await bare.forkAsk({ agentId: 'a1', creationId: CREATION })
+ await vi.waitFor(() => expect(bare.replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'NOT_FORKABLE' } }]))
+ })
+
+ it('says why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {
+ const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') }) } })
+ expect(await storage.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_CONFLICT' })
+ const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })
+ expect(await broken.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })
+ const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })
+ await frameless.forkAsk({ agentId: 'a1', creationId: CREATION })
+ await settle()
+ await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))
+ })
+ })
diff --cc cli/src/core/agents/launches.ts
index 000000000,a688928e3..35faa6a26
mode 000000,100644..100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@@ -1,0 -1,406 +1,411 @@@
+ /**
+ * The requests that start an agent's process: `agent_create`, `agent_fork`, `agent_resume` and
+ * `agent_restart`, and `agent_create_status`, which asks what became of one. A client that names its
+ * request with a `creationId` gets a durable receipt (lib/agentCreationReceipt.ts): a transport retry
+ * carrying the same id never starts a second process, and a lost answer can be asked for again. Such a
+ * request is answered outside the connection's line, so a status check can pass a slow launch.
+ *
+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md), with the
+ * receipts the socket used to hold.
+ */
+ import { readdir } from 'node:fs/promises'
+ import { homedir } from 'node:os'
+ import { dirname, isAbsolute } from 'node:path'
+ import type { BackendSocket } from '../../backendSocket.js'
+ import { installedDsh } from '../../dsh/installed.js'
+ import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'
+ import { opencodeMajorVersion } from '../../engines/opencode/version.js'
+ import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types.js'
+ import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationReceipts, type AgentCreationStatus } from '../../lib/agentCreationReceipt.js'
+ import type { AgentFrame } from '../../lib/agentFrame.js'
+ import { engineLabel } from '../../lib/agentNames.js'
+ import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'
+ import {
+ AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves,
+ permissionModeFlags, supportsFirstPrompt, supportsNamedAgent,
+ } from '../../lib/engineLaunch.js'
+ import { parseGridLaunchOverride, type GridLaunchOverride } from '../../lib/gridLaunch.js'
+ import { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.js'
+ import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from '../../lib/projectFolder.js'
++import type { ScmLaunchRecord } from '../../scm/types.js'
+ import type { RegisteredSession } from '../../lib/registry.js'
+
+ /** Creates an agent (core/agents/create.ts). The orchestrator creates through the same one. */
+ export type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>
+ /** Opens a NEW agent that starts with another one's whole history (core/agents/fork.ts); `level` says
+ * what it got: the engine's own fork, or a handoff message. */
+ export type ForkAgent = NonNullable<BackendSocket['onForkAgent']>
+ /** Stops an agent's live engine process and relaunches it in the SAME tmux pane, keeping the SAME
+ * agentId and (best-effort) resuming the same engine session. `resumed` says whether the relaunch
+ * actually resumed the prior conversation or had to fall back to a fresh one (core/agents/restart.ts). */
+ export type RestartAgent = (agentId: string) => Promise<
+ { ok: true; session: RegisteredSession; resumed: boolean }
+ | { ok: false; error: string; detail?: string }
+ >
+ /** Resumes stopped work directly, or attaches if it is already running. Never replaces a live process
+ * and never falls back to a fresh conversation (core/agents/lifecycle.ts). */
+ export type ResumeAgent = (agentId: string, permissionMode?: string) => ReturnType<RestartAgent>
+
+ export interface LaunchRequestDeps {
+ /** The receipts of launches asked for with a `creationId`. */
+ receipts: Pick<AgentCreationReceipts, 'run' | 'status'>
+ /** Each launch, read when a request comes in: null on a machine that cannot launch agents. */
+ createAgent: () => CreateAgent | null
+ forkAgent: () => ForkAgent | null
+ resumeAgent: () => ResumeAgent | null
+ restartAgent: () => RestartAgent | null
+ byAgent: (agentId: string) => RegisteredSession | undefined
+ /** An agent's frame, as the socket builds it for every reply. */
+ toProject: (s: RegisteredSession) => Promise<AgentFrame>
+ /** Where a new agent on a grid model sends its inference: the models service's to resolve, on this
+ * machine (core/api.ts `ModelsPort.launchTarget`). Null, or a rejection while models is down, refuses
+ * the create with GRID_UNAVAILABLE rather than start it anywhere else. */
+ modelTarget: (selection: NewAgentModel) => Promise<GridLaunchOverride | null>
+ }
+
+ type Reply = (result: Record<string, unknown>) => void
+
+ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {
+ /** Recover by stable runtime identity; a deleted agent must never become a fresh launch. */
+ const creationStatusPayload = async (status: AgentCreationStatus): Promise<Record<string, unknown>> => {
+ if (status.state === 'created') {
+ const session = byAgent(status.agentId)
+ return session
+ ? { state: 'created', agent: await toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}) }
+ : { state: 'unavailable' }
+ }
+ // A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors
+ // so clients can distinguish "safe to correct the choices" from "outcome still unknown".
+ if (status.state === 'failed') {
+ return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error, ...(status.detail ? { detail: status.detail } : {}) } }
+ }
+ return status
+ }
+
+ /** Answers `agent_create_status`: what became of the launch a `creationId` names. */
+ const createStatus = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {
+ const creationId = payload.creationId
+ if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }
+ try {
+ reply({ creationId, ...await creationStatusPayload(receipts.status(creationId)) })
+ } catch (error) {
+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
+ }
+ }
+
+ /** Answers `agent_create`. `asker.local` says the frame came from this machine. */
+ const create = async (payload: Record<string, unknown>, asker: { local: boolean }, reply: Reply): Promise<void> => {
+ const engine = payload.engine as AgentEngine | undefined
+ const cwd = payload.cwd
+ if (typeof engine !== 'string' || !ENGINES.includes(engine)) { reply({ error: 'INVALID_ENGINE' }); return }
+ let projectFolder
+ try { projectFolder = parseProjectFolder(payload) }
+ catch (error) {
+ reply(error instanceof ProjectFolderError
+ ? { error: error.code, detail: error.message }
+ : { error: 'INVALID_PROJECT_SOURCE' }); return
+ }
+ // A terminal opens where a terminal app would — the home directory — when the client names
+ // no folder; every other engine works IN a folder and must be told which.
+ const terminal = isTerminalEngine(engine)
+ if (terminal && projectFolder) { reply({ error: 'INVALID_PROJECT_SOURCE', detail: 'a terminal opens in a folder, it does not prepare one' }); return }
+ if (!projectFolder && !(terminal && cwd === undefined) && (typeof cwd !== 'string' || !isAbsolute(cwd))) { reply({ error: 'INVALID_CWD' }); return }
+ const onCreateAgent = createAgent()
+ if (!onCreateAgent) { reply({ error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const creationId = payload.creationId
+ if (creationId !== undefined && !validCreationId(creationId)) {
+ reply({ error: 'INVALID_CREATION_ID' }); return
+ }
+ if (projectFolder && (!validCreationId(creationId) || cwd !== undefined)) {
+ reply({ error: 'INVALID_PROJECT_SOURCE' }); return
+ }
+ // Absent is the ordinary case and stays indistinguishable from a client that predates grids;
+ // present-but-malformed is refused here rather than half-applied at launch, because an agent
+ // that quietly ran on the engine's own login would look like it worked.
+ const model = parseNewAgentModel(engine, payload)
+ if (model.state === 'invalid') { reply({ error: 'INVALID_GRID', detail: model.detail }); return }
+ const grid = parseGridLaunchOverride(payload.grid)
+ if (grid.state === 'invalid') { reply({ error: 'INVALID_GRID', detail: grid.reason }); return }
+ if (terminal && grid.state === 'ok') { reply({ error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' }); return }
+ // Same validation the desktop app already applies client-side (`Agent._safeCodexHome`) —
+ // repeated here because a client's own check is not a guarantee about what actually
+ // arrives on the wire.
+ const rawCodexHome = typeof payload.codexHome === 'string' ? payload.codexHome : null
+ const codexHome = rawCodexHome && rawCodexHome.startsWith('/') && rawCodexHome.length <= 4096
+ && !/[\x00-\x1f\x7f]/.test(rawCodexHome)
+ ? rawCodexHome
+ : null
+ if (codexHome && (engine !== 'codex' || grid.state === 'ok')) {
+ reply({ error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })
+ return
+ }
+ // A DSH is refused, never approximated: an agent created as its plain base engine would look
+ // like it worked and have none of the skills the user picked the tile for.
+ let dsh: string | null = null
+ if (payload.dsh !== undefined && payload.dsh !== null) {
+ if (typeof payload.dsh !== 'string' || !DSH_ID_RE.test(payload.dsh)) {
+ reply({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' }); return
+ }
+ const installed = installedDsh(payload.dsh)
+ if (!installed) {
+ reply({ error: 'INVALID_DSH', detail: `${payload.dsh} is not installed on this machine` }); return
+ }
+ if (installed.manifest.kind === 'viewer') {
+ reply({ error: 'INVALID_DSH', detail: `${payload.dsh} is a viewer package, not an agent` }); return
+ }
+ if (!dshSupportedEngines(installed.manifest).includes(engine)) {
+ reply({ error: 'INVALID_DSH', detail: `${payload.dsh} supports ${dshSupportedEngines(installed.manifest).join(', ')}; ${engine} is not compatible` }); return
+ }
+ dsh = installed.id
+ }
+ // A first prompt is refused BEFORE any pane exists: an engine with no way to take one would
+ // otherwise open on an empty input and look like the person's request had been heard. The
+ // length bound is a first message's, not a document's. The text itself is never logged.
+ let prompt: string | null = null
+ if (payload.prompt !== undefined && payload.prompt !== null) {
+ if (typeof payload.prompt !== 'string') { reply({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' }); return }
+ const trimmed = payload.prompt.trim()
+ if (trimmed.length > MAX_FIRST_PROMPT_CHARS) {
+ reply({ error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` }); return
+ }
+ if (trimmed && !supportsFirstPrompt(engine)) {
+ reply({ error: 'PROMPT_UNSUPPORTED', detail: new FirstPromptUnsupportedError(engine).message }); return
+ }
+ prompt = trimmed || null
+ }
+ // Blank is "number it", the same as absent — a client that sends an empty field is not
+ // asking for an agent with no name.
+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null
+ // The engine's named agent is refused BEFORE any pane exists, like the prompt: an engine with
+ // no way to open as one would otherwise come up as a general session under that agent's
+ // name. The shape is an identifier the engine looks a file up by — never a path.
+ let agent: string | null = null
+ if (payload.agent !== undefined && payload.agent !== null) {
+ if (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {
+ reply({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return
+ }
+ // OpenCode v2 counts as no way: its TUI exits 1 on `--agent` (engineLaunch.ts).
+ if (!supportsNamedAgent(engine, engine === 'opencode' ? opencodeMajorVersion() : null)) {
+ reply({ error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return
+ }
+ agent = payload.agent
+ }
+ // A permission mode picked in New Harness. A client that predates the choice sends only
+ // `bypassPermission`; one that sends a mode this engine does not have is refused rather than
+ // quietly launched in some other mode.
+ let permissionMode: string | null = null
+ if (payload.permissionMode !== undefined && payload.permissionMode !== null) {
+ if (typeof payload.permissionMode !== 'string' || !permissionModeFlags(engine, payload.permissionMode)) {
+ reply({ error: 'INVALID_PERMISSION_MODE', detail: `${engine} has no permission mode ${JSON.stringify(payload.permissionMode)}` }); return
+ }
+ permissionMode = payload.permissionMode
+ }
+ // Opening a conversation Harness did not start: the engine resumes it, as it was. Nothing a new
+ // conversation is created with applies to it.
+ let resumeSessionId: string | null = null
+ if (payload.resumeSessionId !== undefined && payload.resumeSessionId !== null) {
+ // Engines' ids: uuids, `ses_…` (OpenCode, Kilo), `20260927_101500_ab12cd` (Hermes), slugs
+ // (Devin), Pi's custom ids with dots. One word, never a path.
+ if (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{1,127}$/.test(payload.resumeSessionId)) {
+ reply({ error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return
+ }
+ if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || dsh || prompt || agent) {
+ reply({ error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }); return
+ }
+ resumeSessionId = payload.resumeSessionId
+ }
+ let takeOver: 'idle' | 'now' | 'wait' | null = null
+ if (payload.takeOver !== undefined && payload.takeOver !== null) {
+ if (!resumeSessionId || (payload.takeOver !== 'idle' && payload.takeOver !== 'now' && payload.takeOver !== 'wait')) {
+ reply({ error: 'INVALID_SESSION', detail: 'takeOver is idle, now or wait, with a resumeSessionId' }); return
+ }
+ takeOver = payload.takeOver
+ }
+ const input = {
+ engine,
+ cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',
+ // On unless a client says otherwise: a harness works without stopping to ask for each command.
+ bypassPermission: permissionMode ? permissionModeApproves(permissionMode) : payload.bypassPermission !== false,
+ permissionMode,
+ grid: grid.state === 'ok' ? grid.override : null,
+ codexHome,
+ dsh,
+ prompt,
+ name,
+ agent,
+ resumeSessionId,
+ takeOver,
+ }
+ const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : input
+ if (creationId !== undefined) {
+ // Reserve before spawning. A transport retry carries the SAME creationId; a deliberate
+ // New agent action carries a new one. Detach so a status check can pass a slow create
+ // on this connection, just as engines_probe is detached above.
+ const create = onCreateAgent
+ try {
+ void receipts.run(creationId, creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput), async () => {
+ if (model.state === 'ok') {
+ const target = await modelTarget(model.selection).catch(() => null)
+ if (!target) return { state: 'failed', error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }
+ input.grid = target
+ }
+ let preparedFolder: string | undefined
++ let scmLaunchRecord: ScmLaunchRecord | null = null
+ if (projectFolder) {
- try { preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine) }) }
++ try {
++ preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine),
++ onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord } })
++ }
+ catch (error) {
+ return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',
+ detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }
+ }
+ // Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or
+ // the person's own repo is theirs to answer for (lib/claudeTrust.ts); a worktree gets only
+ // the answer its source repo already has. `branch` IS the source folder: nothing to record.
+ try {
+ // A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.
+ const engineTrust = input.engine === 'claude' ? { trusts: (path: string) => claudeTrusts(path), record: (path: string) => preTrustClaudeProject(path) }
+ : input.engine === 'codex' ? { trusts: (path: string) => codexTrusts(path, input.codexHome), record: (path: string) => preTrustCodexProject(path, input.codexHome) } : null
+ if (engineTrust && (projectFolder.source === 'new'
+ || (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {
+ engineTrust.record(preparedFolder)
+ }
+ } catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }
+ } else if (!dsh && asker.local && dirname(input.cwd) === projectsRoot()) {
+ // On the LOCAL machine the desktop makes a new workspace ITSELF and sends the path as a plain
+ // cwd, so `projectFolder` above never sees it. Such a folder is empty and is trusted the way a
+ // `new` project is — but only on evidence, and only where those workspaces live:
+ //
+ // · directly inside the projects root, which is the one folder the app and this daemon
+ // create workspaces in. Trust INHERITS downward (claudeTrusts), so recording it for a
+ // folder the person merely browsed to — an empty `~/code`, or a home with nothing in it —
+ // would silently cover every repo cloned under it later: OH-14 again by another door.
+ // · empty as read from disk, never on the client's word. A clone, a worktree or the
+ // person's own repo has content, so it stays the engine's question (lib/claudeTrust.ts).
+ // · from a LOCAL frame. agent_create is not backend-only, so a relayed peer would otherwise
+ // name an empty path on this host and have it trusted.
+ //
+ // DSH trust is decided in cli.ts, where the template count is known; leave that to it.
+ try {
+ const empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)
+ if (empty) {
+ if (input.engine === 'claude') preTrustClaudeProject(input.cwd)
+ if (input.engine === 'codex') preTrustCodexProject(input.cwd, input.codexHome)
+ }
+ } catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }
+ }
- const result = await create(preparedFolder ? { ...input, cwd: preparedFolder } : input)
++ const result = await create(preparedFolder ? { ...input, cwd: preparedFolder, scmLaunchRecord } : input)
+ if (result.ok) return { state: 'created', agentId: result.session.agentId }
+ // tmux may have executed before a timeout; registration cleanup is best-effort.
+ // Neither can prove that no process started, so never encourage another launch.
+ if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }
+ return { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ }).then(async (status) => {
+ reply({ creationId, ...await creationStatusPayload(status) })
+ }).catch(() => reply({ error: 'INTERNAL' }))
+ } catch (error) {
+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
+ }
+ return
+ }
+ // Clients predating receipts retain their existing response shape.
+ if (model.state === 'ok') {
+ const target = await modelTarget(model.selection).catch(() => null)
+ if (!target) { reply({ error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }); return }
+ input.grid = target
+ }
+ const result = await onCreateAgent(input)
+ // `detail` carries the underlying cause (tmux's own message) so the person who clicked
+ // Create can read it, rather than having to open a log on the machine that failed.
+ if (!result.ok) {
+ reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
+ return
+ }
+ reply({ agent: await toProject(result.session) })
+ }
+
+ // Resume attaches or restores a saved conversation; restart replaces a live process in its
+ // existing pane. Both keep the agentId and use the same durable operation receipt protocol.
+ const relaunch = async (type: string, payload: Record<string, unknown>, reply: Reply): Promise<void> => {
+ const target = payload.agentId as string | undefined
+ if (!target) { reply({ error: 'MISSING_AGENT_ID' }); return }
+ const operation = type === 'agent_resume' ? 'resume' : 'restart'
+ const restart = operation === 'resume' ? resumeAgent() : restartAgent()
+ if (!restart) { reply({ error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const permissionMode = payload.permissionMode
+ if (permissionMode !== undefined && (operation !== 'resume' || typeof permissionMode !== 'string'
+ || !['ask', 'auto', 'plan', 'full'].includes(permissionMode))) {
+ reply({ error: 'INVALID_PERMISSION_MODE' }); return
+ }
+ const invoke = () => permissionMode === undefined ? restart(target) : resumeAgent()!(target, permissionMode)
+ const creationId = payload.creationId
+ if (creationId !== undefined) {
+ if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }
+ try {
+ void receipts.run(creationId, creationFingerprint({ operation, agentId: target,
+ ...(permissionMode === undefined ? {} : { permissionMode }) }), async () => {
+ const result = await invoke()
+ if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }
+ // RESTART_FAILED can follow an unobserved relaunch. Never silently
+ // replace that process again when a caller checks this intent.
+ if (result.error === 'RESTART_FAILED' || result.error === 'RESUME_UNCONFIRMED') return { state: 'unconfirmed' }
+ return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ }).then(async (status) => {
+ reply({ creationId, ...await creationStatusPayload(status) })
+ }).catch(() => reply({ error: 'INTERNAL' }))
+ } catch (error) {
+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
+ }
+ return
+ }
+ const result = await invoke()
+ if (!result.ok) {
+ reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
+ return
+ }
+ reply({ agent: await toProject(result.session), resumed: result.resumed })
+ }
+
+ // Fork an agent: a second one with the first one's history — see lib/forkAgent.ts. The reply
+ // is agent_create's shape plus `level`, so a client opens the pane the same way.
+ const fork = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {
+ const target = payload.agentId as string | undefined
+ if (!target) { reply({ error: 'MISSING_AGENT_ID' }); return }
+ const onForkAgent = forkAgent()
+ if (!onForkAgent) { reply({ error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim().slice(0, 120) : null
+ const rawPrompt = payload.prompt
+ if (rawPrompt !== undefined && rawPrompt !== null && typeof rawPrompt !== 'string') { reply({ error: 'INVALID_PROMPT' }); return }
+ const prompt = typeof rawPrompt === 'string' && rawPrompt.trim() ? rawPrompt : null
+ if (prompt && prompt.length > MAX_FIRST_PROMPT_CHARS) { reply({ error: 'PROMPT_TOO_LONG' }); return }
+ const creationId = payload.creationId
+ if (creationId !== undefined) {
+ if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }
+ // Forking starts a new process too. Reserve the same durable intent used
+ // by agent_create so a lost receipt can be checked without another fork.
+ const fork = onForkAgent
+ try {
+ void receipts.run(creationId, creationFingerprint({ operation: 'fork', agentId: target, name, prompt }), async () => {
+ const result = await fork({ agentId: target, name, prompt })
+ if (result.ok) return { state: 'created', agentId: result.session.agentId, level: result.level }
+ if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }
+ return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ }).then(async (status) => {
+ reply({ creationId, ...await creationStatusPayload(status) })
+ }).catch(() => reply({ error: 'INTERNAL' }))
+ } catch (error) {
+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
+ }
+ return
+ }
+ const result = await onForkAgent({ agentId: target, name, prompt })
+ if (!result.ok) {
+ reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
+ return
+ }
+ reply({ agent: await toProject(result.session), level: result.level })
+ }
+
+ return { createStatus, create, relaunch, fork }
+ }
diff --cc cli/src/core/api.ts
index 39302db78,fbcf1c867..baf626e34
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@@ -58,22 -228,414 +228,414 @@@ export interface CoreApi
clients: {
/** An agent's viewer moved: the windows' viewer panes forward to the new one. */
viewerChanged(agentId: string): void
+ /** A frame of a viewer stream for the one connection that opened it (`viewer_response`, `viewer_data`,
+ * `viewer_ack`, `viewer_end`, `viewer_close`): false when it cannot reach that connection. Only those
+ * types; the core drops any other. */
+ viewerFrame(connId: string, type: string, payload: Record<string, unknown>): boolean
/** The account's grid has a name: the models picker answers with it at once. */
gridNamed(name: string): void
+ /** What the models picker lists may have changed (a local model started or stopped, grid set up):
+ * the windows on this computer are pushed the list again (`grid_models_changed`). */
+ gridModelsChanged(): void
+ /** A harness being installed or updated moved on (`dsh_install_status`): the apps show it in the
+ * create dialog. */
+ dshInstallStatus(status: Record<string, unknown>): void
+ /** A frame for every window on this computer, as an experiment tells them it changed
+ * (`orchestrator_changed`, `team_changed`); never sent off this computer. */
+ windows(frame: { type: string; payload: Record<string, unknown> }): void
+ /** A frame for one of Share's observers, sealed by Share itself, to the relay through the gateway; false
+ * when it could not be handed over. */
+ observer(connId: string, type: string, payload: Record<string, unknown>): boolean
+ /** A frame from the devices for every window on this computer, never the cloud: what a hand at this
+ * desk did. Only `DEVICE_WINDOW_FRAMES`; the core drops any other. */
+ sendLocal(frame: DeviceWindowFrame): void
+ /** A window bridge's ask, to one window on this computer; false when it is gone. Only
+ * `DEVICE_BRIDGE_FRAMES`. */
+ sendToWindow(connId: string, frame: DeviceBridgeFrame): boolean
+ /** Whether a window on this computer is attached. */
+ hasWindow(): boolean
+ /** The devices on this computer changed (`harness_devices_changed`): the windows and the owner's apps
+ * show them. */
+ devicesChanged(payload: Record<string, unknown>): void
+ /** A dial on this computer is watching it, or no longer is: the core then makes the turn cards and
+ * recaps for it, as for a device watching through the backend. */
+ dialWatching(watching: boolean): void
+ /** A turn's card for the devices (`commander_event`): its progress, and its recap once it ends. */
+ turnCard(frame: TurnCardFrame): void
+ /** A turn's recap for the apps (`turn_summary`, or `turn_summary_pending` while one is being cut). */
+ turnSummary(frame: TurnSummaryFrame): void
}
+ /** How an agent's shell reaches this daemon: the command that runs this harness's CLI, the port the daemon
+ * serves and the machine it serves as. An experiment writes them into the prompts of the agents it runs
+ * (`… orchestrator --port 18473 --machine …`). */
+ daemon: DaemonAddress
+ /** The Wi-Fi device's doors into the core (services/wifi.ts): each one call it made when it ran here. */
+ wifi: {
+ /** What it lists and reads in line (`WifiView`), asked again before each request it answers. */
+ view(): Promise<WifiView>
+ /** A device's prompt into a live agent, through the pane's write lock, as delivery `deliveryId`. Settles
+ * once the lock has taken it: what it said of the prompt meanwhile is the reply's to carry. */
+ submit(agentId: string, text: string, deliveryId: string): Promise<void>
+ /** A queued delivery the device no longer stands behind (it was unpaired). */
+ cancel(deliveryId: string): void
+ /** The agent's transcript shows the device's prompt began its turn: the pane's lock moves on. */
+ started(agentId: string, text: string): void
+ /** Stop a live agent's turn; resolves whether it stopped. */
+ stop(agentId: string): Promise<boolean>
+ /** Answer a live agent's question, never a permission dialog; resolves whether the terminal took it. */
+ answer(agentId: string, requestId: string, answers: Record<string, string>): Promise<boolean>
+ /** Start an agent for an installed Store harness in `cwd`, with the device's fixed, safe launch
+ * arguments; refused when another agent works there. */
+ create(packageId: string, engine: string, cwd: string): Promise<ForkResult>
+ /** Move the window's focus one agent along the desk, the dial's way; 'no_app' without a window. */
+ stepFocus(direction: 'next' | 'previous', currentAgentId?: string): Promise<{ machineId: string; agentId: string } | 'no_agents' | 'no_app'>
+ /** A stroke on the device's glass for the window's terminal; false without a window. */
+ scroll(phase: 'down' | 'move' | 'up', dy: number, velocity: number): boolean
+ /** Ask the window to select an agent (`device_focus`); false without a window. */
+ focusApp(agentId: string, expiresAt: number, focusRevision: string): boolean
+ /** Ask the window to open the agent a Store preparation made (`device_prepare_open`). */
+ reveal(operationId: string, agentId: string): void
+ /** An answer or event for one device session, sealed to it by the gateway, if the session is still
+ * that identity's device. */
+ send(connId: string, identity: string, type: string, payload: Record<string, unknown>): void
+ /** Which identity's app said hello on a session (null: it left): the core counts it as watching. */
+ hello(connId: string, identity: string | null): void
+ /** A device said hello: what the agents are doing is sent again for it. */
+ joined(): void
+ /** It is built and serving: the gateway may connect the devices' direct links, which a service that
+ * could not be built would leave unanswered. */
+ ready(): void
+ /** A device asked to be unpaired, over its session: its pairing goes. */
+ unpaired(identity: string): void
+ /** The focus revision, as it changes: a window's stale selection is refused against it. */
+ focus(revision: string): void
+ /** It no longer reads this agent's transcript, as of the `seen`th prompt the core told it of. */
+ transcripts(agentId: string, seen: number): void
+ /** The agents whose transcripts it reads, said as it starts. */
+ watching(agentIds: string[]): void
+ /** The agents a device subscribed to: their tools' events are sent too, not only the answer's text. */
+ streams(agentIds: string[]): void
+ }
+ }
+
+ /** An agent to create, as an experiment asks for one (the orchestrator's Director and specialists). */
+ export interface AgentCreateRequest {
+ engine: AgentEngine
+ cwd: string
+ /** The harness to create it as, installed here; null for the engine alone. */
+ dsh: string | null
+ /** The message it opens with, already submitted. */
+ prompt: string
+ name: string
+ bypassPermission: boolean
+ }
+
+ /** See `CoreApi.daemon`. */
+ export interface DaemonAddress {
+ command: string
+ port: number
+ machineId(): string
+ /** The account's environment (`prod`, `staging`, …), as the links a feature makes name it. */
+ autonomousEnv: string
+ }
+
+ /**
+ * This machine's E2EE identity as Share's owner uses it (sharing/crypto.ts `OwnerKey`): its public half, and
+ * the signature on a welcome to one observer of one share. The private half is the gateway's alone; a Share in
+ * a process of its own asks for each welcome and holds no credential. Base64 throughout.
+ */
+ export interface ObserverKey {
+ publicKey(): Promise<string>
+ signWelcome(machineId: string, shareId: string, peer: string, ephemeral: string): Promise<string>
+ }
+ /** A process with no key of the core's: it signs nothing. */
+ export const OBSERVER_KEY_OFF: ObserverKey = {
+ publicKey: () => Promise.reject(new Error('no key: this process holds no E2EE identity')),
+ signWelcome: () => Promise.reject(new Error('no key: this process holds no E2EE identity')),
+ }
+
+ /** A service in its own process that acts on no agent: it creates none and reads no harness's frame. */
+ export const AGENT_ACTIONS_OFF: Pick<CoreApi['agents'], 'create' | 'dsh'> = {
+ create: async () => ({ ok: false, error: 'SERVICE_UNAVAILABLE' }),
+ dsh: () => null,
+ }
+
+ /** The account as a service that reads no backend, hears no notice and signs nothing has it. */
+ export const ACCOUNT_BACKEND_OFF: Pick<CoreApi['account'], 'backend' | 'onNotice' | 'observerKey'> = {
+ backend: async () => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }),
+ onNotice: () => () => {},
+ observerKey: OBSERVER_KEY_OFF,
+ }
+
+ /** Where a service that was never told runs this daemon from: the installed CLI, on no port it knows. */
+ export const DAEMON_UNKNOWN: DaemonAddress = { command: 'harness', port: 0, machineId: () => '', autonomousEnv: 'prod' }
+
+ /** What became of a delivered turn (`turns.deliver`), as the core's input says it: `queued`, written
+ * (`delivered`), its turn `started`, `rejected` with why, or `unknown`. `sessionId` is the agent it was
+ * delivered to, as the delivery named it. */
+ export type TurnDelivery = SessionInputDelivery
+
+ /** The delivery members of a core that delivers nothing for this service: nothing is written, nothing is
+ * taken back, and nothing is heard. */
+ export const DELIVERIES_OFF: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'> = {
+ deliver: () => {},
+ cancelDelivery: () => false,
+ onDelivery: () => () => {},
+ }
+
+ /** A turn's card for the devices: the dial's and the Wi-Fi device's tiles and their notifications. */
+ export type TurnCardFrame = {
+ type: 'commander_event'
+ agentId: string
+ dbSessionId: string
+ name?: string
+ payload: Record<string, unknown>
+ }
+ /** A turn's recap for the windows and the phone. */
+ export type TurnSummaryFrame = { type: 'turn_summary' | 'turn_summary_pending' } & Record<string, unknown>
+ /** The frame types `clients.turnCard` and `clients.turnSummary` carry: the core sends no other for them. */
+ export const TURN_CARD_TYPES: ReadonlySet<string> = new Set(['commander_event'])
+ export const TURN_SUMMARY_TYPES: ReadonlySet<string> = new Set(['turn_summary', 'turn_summary_pending'])
+
+ /** `agents.resolve` over a service process's own copy of the agents, as the registry answers it: by agent
+ * id, then by engine session id (an agent with none yet is never found by an empty one). */
+ export function resolveAgent(agents: readonly RegisteredSession[], id: string): RegisteredSession | undefined {
+ return agents.find((agent) => agent.agentId === id) ?? (id ? agents.find((agent) => agent.sessionId === id) : undefined)
+ }
+
+ /** Who sent a request, as the core established it. A service trusts this, never a field of the
+ * payload: a payload says whatever its sender wrote. */
+ export interface Asker {
+ /** A process on this machine (the desktop app, `hn`, a script), over the local socket. */
+ local: boolean
+ /** Whether it may act as this machine's owner: a local process, or the owner's paired app over the
+ * relay. A device or an observer may not. */
+ owner: boolean
+ /** The connection it came over (a window's, a remote client's), as the core names it, and the id it
+ * asked under: what a service keys work by that belongs to one connection (the Model Manager's grid
+ * commands, which a cancel on the same connection stops; a limit on how many at once per connection).
+ * The handler hears that connection close through `closed`. Absent when the core itself asks, and from
+ * a core from before it was given: then the request is its own connection. */
+ connection?: string
+ requestId?: string
+ }
+
+ /**
+ * A request a service answers for the apps: the reply, or a promise of it. A throw or a rejection is
+ * answered `SERVICE_FAILED` by the host and counted against the service.
+ *
+ * `closed` is aborted when the connection that asked closes (`Asker.connection`), or when the core that
+ * routed it goes: nobody is left to read the answer, so the work for it may stop. A handler that ignores
+ * it runs to the end, as every one did before it was given; one called without it (a spec, a wrapper)
+ * is never told.
+ */
+ export type ServiceRequest = (payload: Record<string, unknown>, asker: Asker, closed?: AbortSignal) => Record<string, unknown> | Promise<Record<string, unknown>>
+
+ /** The requests a service answers, by frame type: what its start returns. */
+ export type ServiceRequests = Readonly<Record<string, ServiceRequest>>
+
+ /*
+ * The requests each service answers for the apps, declared here rather than in the service's own module.
+ * The core routes them, and answers them SERVICE_UNAVAILABLE while their service is off, from these
+ * lists alone: a service that runs in its own process is never loaded into the core's to learn them
+ * (docs/design/2026-10-06-core-boundary-next.md, "The target, and its test"). Its module re-exports its own.
+ */
+
+ /** Session search (services/search.ts). */
+ export const SEARCH_REQUESTS = ['session_search', 'session_tail'] as const
+ /** The Harness Store (services/store.ts). */
+ export const STORE_REQUESTS = ['dsh_list', 'dsh_install', 'dsh_update', 'dsh_remove'] as const
+ /** Account usage (services/usage.ts). */
+ export const USAGE_REQUESTS = ['usage_read'] as const
+ /** The machine monitor (services/monitor.ts). */
+ export const MONITOR_REQUESTS = ['machine_resources'] as const
+ /** The command bar (services/commandBar.ts), an experiment: the socket's `command_bar`, and the hook server's
+ * `/api/command-bar/*`, which it asks as `command_bar_http`. */
+ export const COMMAND_BAR_REQUESTS = ['command_bar', 'command_bar_http'] as const
+ /** The project and folder readers (services/projects.ts). */
-export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const
++export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const
+ /** Change agent's handoff file, prepared in the edge host (services/handoff.ts). */
+ export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as const
+ /**
+ * Models (services/models.ts).
+ *
+ * The Model Manager's grid commands, `grid_fleet_run` and `grid_fleet_cancel`, are among them: a command
+ * is a job of the connection that started it, and a cancel stops only that connection's own
+ * (`lib/gridFleetRpc.ts`), keyed by the connection and request id the core gives every request
+ * (`Asker`). Their handshake, `grid_fleet_capabilities`, is still the socket's: the Grid harness runs a
+ * command only after it and reads an answer without its protocol as "update Harness", which a models
+ * service that is down must not make it say.
+ * The saved APIs and the Codex profiles came out of the socket's switch (launchTargetRequests).
+ */
+ export const MODELS_REQUESTS = [
+ 'grid_models_list', 'models_list',
+ 'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop',
+ 'grid_fleet_run', 'grid_fleet_cancel',
+ 'api_connections', 'codex_profiles_list', 'codex_profile_link',
+ ] as const
+
+ const MINUTE = 60_000
+
+ /**
+ * How long the core waits on a service in a process of its own for these answers before it answers
+ * SERVICE_UNAVAILABLE, where the half minute it gives any other would cut short what they do
+ * (core/serviceLinks.ts). By service, then by request or port call. A wait that runs out answers the
+ * asker; the work itself goes on in the service's process.
+ *
+ * - A grid command runs as long as its caller asked, up to half an hour (`GRID_FLEET_MAX_TIMEOUT_MS`).
+ * - Grid's set-up installs `grid` on first use (its installer is given ten minutes, `gridInstall.ts`),
+ * hands it this machine's sign-in and makes the account's grid: a Set up, a Get, a Use, `ensure` and
+ * a move onto a grid model (`moveTarget`) each wait for it.
+ * - A launch target, the private grid's name and the lists each run a few `grid` calls of up to 30 s.
+ * - The Store's install and update set up a harness's toolchain: minutes.
+ */
+ export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, number>>>> = {
+ models: {
+ grid_fleet_run: GRID_FLEET_MAX_TIMEOUT_MS + MINUTE,
+ grid_fleet_models_list: 15 * MINUTE, grid_fleet_model_download: 15 * MINUTE, grid_fleet_model_start: 15 * MINUTE,
+ ensure: 15 * MINUTE, moveTarget: 15 * MINUTE,
+ launchTarget: 3 * MINUTE, privateGridName: 2 * MINUTE, lists: 2 * MINUTE,
+ },
+ store: { dsh_install: 30 * MINUTE, dsh_update: 30 * MINUTE },
+ }
+
+ /** The orchestrator (services/orchestrator.ts): its projects, for the apps and for the agents it runs. */
+ export const ORCHESTRATOR_REQUESTS = ['orchestrator'] as const
+ /** Share (services/sharing.ts): an owner's shares of a harness, their links and their comments. */
+ export const SHARE_REQUESTS = [
+ 'harness_share_list', 'harness_share_invite', 'harness_share_remove', 'harness_share_link',
+ 'harness_share_comments', 'harness_share_comment_post', 'harness_share_comment_remove',
+ ] as const
+
+ /** Tab collaboration and teams (services/collaboration.ts): the teams' own requests, from the apps, from `harness team`
+ * in an agent's shell and from the other machines' teams. */
+ export const TEAMS_REQUESTS = ['team', 'team_delivery'] as const
+
+ /**
+ * The experiments: services that cost nothing until they are on (docs/design/2026-10-06-core-boundary-next.md,
+ * "Experimental features: move only"). Each runs in a process of its own that the master starts only once the
+ * core asks for it (harnessd/services.ts `onDemand`): when one of its `requests` arrives, or at start when its
+ * saved `state` is in the data folder (paths under it; `dir/*.ext` for a file of that kind in that folder).
+ * Off, it has no process and none of its code is loaded anywhere. Each may act on the core through the hooks
+ * an experiment has (core/experimentQueries.ts, core/deliveries.ts), and no other process may.
+ *
+ * Adding one: its service (`start<Name>(core, ports)`, returning its requests' handlers) and its process's
+ * runner (`SERVICE_RUNNERS`, src/serviceProcess.ts); its process (`SERVICE_HOSTS`, `onDemand: true`); its
+ * entry here; and its start for the core's own process (services/inline.ts `EXPERIMENT_STARTS`). Removing
+ * one is deleting those.
+ */
+ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[]; state: readonly string[] }>> = {
+ orchestrator: { requests: ORCHESTRATOR_REQUESTS, state: ['orchestrator/*.json'] },
+ // Tab collaboration and teams, beside the prompt scopes in the teams' process (harnessd/services.ts). Its
+ // ledgers and mailboxes: a team was made here, or another machine's team delivered to an agent here.
+ collaboration: { requests: TEAMS_REQUESTS, state: ['teams'] },
+ // Its invitations and links: a harness was shared from here.
+ sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json'] },
+ // Request-only: it keeps nothing, so it is on from its first request until the daemon stops.
+ commandBar: { requests: COMMAND_BAR_REQUESTS, state: [] },
+ }
+
+ /** The core's calls into Share: an observer's frame as the relay handed it over, the relay gone (every observer
+ * with it), and stopping it. */
+ export interface SharingPort {
+ observer(connId: string, type: string, payload: Record<string, unknown>): Promise<void> | void
+ linkDown(): void
+ stop(): Promise<void> | void
}
+ /** What the core gets when Share fails: an observer's frame goes unanswered, as it would to a daemon without
+ * Share, and a shutdown goes on. */
+ export const SHARING_FALLBACKS: PortFallbacks<SharingPort> = { observer: undefined, linkDown: undefined, stop: undefined }
+
+ /** What an agent is to the orchestrator's projects: a specialist (`worker`), or a project's Director, and
+ * whether work is still out under it. */
+ export type OrchestratorRole = { role: 'worker' } | { role: 'director'; busy: boolean }
+
+ /** The core's calls into the orchestrator: what an agent is to its projects, asked at every turn's end
+ * (core/turns/recaps.ts), the frames the apps are sent, which its projects read their Directors' turns
+ * from, and stopping it. */
+ export interface OrchestratorPort {
+ roleOf(agentId: string): OrchestratorRole | null
+ frame(frame: Record<string, unknown>): void
+ stop(): void
+ }
+
+ /** What the core gets when the orchestrator fails: no agent is a specialist or a Director, so every turn's
+ * end is announced; no project hears a frame; a shutdown goes on. */
+ export const ORCHESTRATOR_FALLBACKS: PortFallbacks<OrchestratorPort> = { roleOf: null, frame: undefined, stop: undefined }
+
/** The core's calls into session search: index a session at its turn boundaries, forget a purged
- * conversation, the title it indexed for one being adopted, the two requests it answers
- * (`session_search`, `session_tail`), and stopping its sweeps. */
- export type SearchPort = Pick<SessionSearchIndex, 'touch' | 'deleteHistory' | 'session' | 'search' | 'tail' | 'stop'>
+ * conversation, the title it indexed for one being adopted, and stopping its sweeps. The apps' own
+ * requests (`session_search`, `session_tail`) are its `ServiceRequests`, not the core's calls. */
+ export type SearchPort = Pick<SessionSearchIndex, 'touch' | 'deleteHistory' | 'session' | 'stop'>
- /** What the core gets when search fails: nothing indexed, no title, and the requests answered with
- * an error. */
+ /** What the core gets when search fails: nothing indexed and no title. */
export const SEARCH_FALLBACKS: PortFallbacks<SearchPort> = {
- touch: undefined, deleteHistory: undefined, session: undefined, search: FAIL, tail: later(FAIL), stop: undefined,
+ touch: undefined, deleteHistory: undefined, session: undefined, stop: undefined,
}
+ /*
+ * Recaps (services/recaps.ts): each turn's recap, the devices' turn cards and the notifications a finished
+ * turn rings, built from the turn's lifecycle. The core tells the recaps that lifecycle as it happens and
+ * never waits on them: a session runs the same without them, and a turn they miss simply has no recap.
+ */
+
+ /** A session as the core knows it when it tells the recaps something: what a card is addressed to. */
+ export interface RecapSession {
+ sessionId: string
+ /** The agent that owns it: a card is addressed to the agent, stable across a `/clear`. */
+ agentId: string
+ /** Its display name, which a summary card carries for a machine whose tile is not loaded. */
+ name?: string
+ /** Its transcript: a Claude sub-agent writes its own beside it, which a held turn end watches. */
+ transcriptPath?: string
+ /** An Orchestrator specialist's turn, or its director's while specialists are out: nobody's news. Said
+ * where a turn ends, a cancel or a forget (reading it reads the orchestrator); absent, the recaps keep
+ * what they were last told. */
+ subagent?: boolean
+ }
+
+ /** Who watches this machine's turn cards: a device at all (through the backend or on the cable), and one
+ * rendering this machine right now. */
+ export interface RecapWatchers { device: boolean; active: boolean }
+
+ /** The turn lifecycle, as the core tells the recaps. */
+ export type TurnLifecycle =
+ /** A session's events (a turn started, its text, its tools and sub-agents, its end), as one batch. */
+ | { kind: 'events'; session: RecapSession; events: LiveEvent[]; replay: boolean }
+ /** The core's five-second turn heartbeat, and whether the turn is verifiably working right now. */
+ | { kind: 'beat'; session: RecapSession; working: boolean }
+ /** The turn was cancelled: no turn end comes. */
+ | { kind: 'cancelled'; session: RecapSession }
+ /** The session was unbound, or its agent removed; what is stored for it is kept for a resume. */
+ | { kind: 'forgotten'; session: RecapSession }
+ /** The engine's Stop hook: it stopped writing. */
+ | { kind: 'stopped'; sessionId: string }
+ /** The agent's conversation moved to a new session (a `/clear`, a fork's first turn): its recaps follow. */
+ | { kind: 'rebound'; from: string; to: string }
+ /** The conversation was purged: everything stored for it goes. */
+ | { kind: 'purged'; sessionId: string }
+ /** A question was put to the person, or answered: a turn waiting on one is not announced as done. */
+ | { kind: 'asked' | 'answered'; sessionId: string; requestId: string }
+ /** A device joined: every session's card is said again. `working`: the sessions whose turn is
+ * verifiably working now, whose busy card is said with it. */
+ | { kind: 'rejoined'; working: string[] }
+
+ /** The core's calls into the recaps: the lifecycle, and what they hold of a session, read in line. */
+ export interface RecapsPort {
+ /** Something happened to a turn. A notice: the core never waits for it, and one the recaps miss costs
+ * that turn its recap, nothing else. */
+ lifecycle(event: TurnLifecycle, watchers: RecapWatchers): void
+ /** A session's last turns and asks, and whether its card is busy; null when they hold nothing. */
+ recaps(sessionId: string): SessionRecaps | null
+ /** The cards of every turn still working or being recapped, for a dial that just attached: asked when it
+ * attaches and sent when they come, never waited for in line. */
+ liveCards(): Promise<TurnCardFrame[]>
+ }
+
+ /** What the core gets when the recaps fail: nothing told, no recap, and no live card. */
+ export const RECAPS_FALLBACKS: PortFallbacks<RecapsPort> = { lifecycle: undefined, recaps: null, liveCards: later([]) }
+
/** The core's calls into the DSH viewers: each harness agent's viewer server and verdict watch. */
export interface ViewersPort {
/** Start the agent's viewer and verdict watch when it has a DSH. Idempotent: called on every
diff --cc cli/src/lib/agentFrame.spec.ts
index 34b454009,bfdc59731..9d3f7684c
--- a/cli/src/lib/agentFrame.spec.ts
+++ b/cli/src/lib/agentFrame.spec.ts
@@@ -1,9 -1,8 +1,9 @@@
import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
- import { describe, expect, it } from 'vitest'
+ import { describe, expect, it, vi } from 'vitest'
import { agentFrame } from './agentFrame.js'
+import { agentProject } from './agentProject.js'
import type { RegisteredSession } from './registry.js'
function session(grid: RegisteredSession['grid'], codexHome: RegisteredSession['codexHome'] = null): RegisteredSession {
diff --cc cli/src/lib/agentFrame.ts
index efd9d3ef0,03862800b..3373bfaf8
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@@ -189,11 -188,8 +192,11 @@@ const gitContexts = new SessionGitConte
export async function agentFrame(
s: RegisteredSession,
- { selectedModel, terminalAvailable, dsh, tokenUsage, activity: contextActivity }: AgentFrameContext,
+ { selectedModel, terminalAvailable, dsh, tokenUsage, activity: contextActivity, gridAnnotation }: AgentFrameContext,
): Promise<AgentFrame> {
+ // The git context is git's own display projection and keeps reading git directly; the frame's
+ // `project` goes through the SCM seam. Both resolve through agentProject's shared reader, so the
+ // seam adds no Git process.
const home = agentProject(s.cwd)
const context = gitContexts.read(JSON.stringify([s.agentId, s.sessionId, s.engine, s.codexHome, s.registeredAt]), async () => {
const saved = await sessionGitHistory.get(s)
diff --cc cli/src/lib/e2ee/applicationFrames.ts
index bbd7d2369,b4f4e86c9..1affae92e
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@@ -18,7 -23,7 +23,7 @@@ const FLEET_REQUESTS = new Set(['grid_f
'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.
- const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'scm_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare', ...OWNER_COMMAND_TYPES])
-const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare', ...OWNER_COMMAND_TYPES])
++const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'scm_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare', ...OWNER_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the
* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floor
diff --cc cli/src/services/projects.spec.ts
index 000000000,84b1d6b52..4ca8ca459
mode 000000,100644..100644
--- a/cli/src/services/projects.spec.ts
+++ b/cli/src/services/projects.spec.ts
@@@ -1,0 -1,104 +1,116 @@@
+ import { afterEach, describe, expect, it, vi } from 'vitest'
+ import { listDir } from '../lib/fsBrowse.js'
+ import { readGitProject } from '../lib/gitProject.js'
+ import { MediaPreviewError, readMediaPreviewChunk } from '../lib/mediaPreview.js'
+ import { projectPreview } from '../lib/projectPreview.js'
+ import type { RegisteredSession } from '../lib/registry.js'
+ import { readSessionGitPullRequest } from '../lib/sessionGitPullRequest.js'
++import { detectScmProject } from '../scm/scmProjects.js'
+ import { fakeCore } from '../testing/fakeCore.js'
+ import { PROJECTS_REQUESTS, startProjects } from './projects.js'
+
+ vi.mock('../lib/fsBrowse.js', () => ({ listDir: vi.fn(() => ({ path: '/home/me', entries: [], truncated: false })) }))
+ vi.mock('../lib/gitProject.js', () => ({ readGitProject: vi.fn(async () => ({ path: '/work/app', branch: 'main' })) }))
++vi.mock('../scm/scmProjects.js', () => ({ detectScmProject: vi.fn(async () => ({ kind: 'git', git: { isGit: true } })) }))
+ vi.mock('../lib/projectPreview.js', () => ({ projectPreview: vi.fn(async () => ({ path: '/work/app', readme: '# app' })) }))
+ vi.mock('../lib/sessionGitPullRequest.js', () => ({ readSessionGitPullRequest: vi.fn(async () => ({ status: 'found', number: 12 })) }))
+ vi.mock('../lib/mediaPreview.js', async (importOriginal) => ({
+ MediaPreviewError: (await importOriginal<typeof import('../lib/mediaPreview.js')>()).MediaPreviewError,
+ readMediaPreviewChunk: vi.fn(async () => ({ mime: 'image/png', data: 'AAAA', done: true })),
+ }))
+
+ const ASKER = { local: false, owner: false }
+ const row = (agentId: string, cwd: string | null) => ({ agentId, sessionId: `s-${agentId}`, cwd }) as RegisteredSession
+
+ function setup() {
+ const agents = [row('a1', '/work/app'), row('a2', null)]
+ const core = fakeCore({ agents: { live: vi.fn(() => agents), resolve: vi.fn((id: string) => agents.find((agent) => agent.agentId === id || agent.sessionId === id)) } })
+ const requests = startProjects(core)
+ return { core, ask: (type: string, payload: Record<string, unknown> = {}) => requests[type]!(payload, ASKER), requests }
+ }
+
+ describe('the project and folder readers', () => {
+ afterEach(() => { vi.clearAllMocks() })
+
+ it('answer exactly the requests they declare', () => {
+ expect(Object.keys(setup().requests).sort()).toEqual([...PROJECTS_REQUESTS].sort())
+ })
+
+ it('git_pull_request: an agent\'s branch and pull request, asked by either id, with the context it was shown', async () => {
+ const { ask } = setup()
+ expect(await ask('git_pull_request', { agentId: 's-a1', history: true, offset: 20 })).toEqual({ status: 'found', number: 12 })
+ expect(readSessionGitPullRequest).toHaveBeenLastCalledWith(row('a1', '/work/app'), { expected: undefined, history: true, offset: 20 })
+ const context = { cwd: '/work/app', branch: 'feature', remote: null }
+ await ask('git_pull_request', { agentId: 'a1', context, offset: 'later' })
+ expect(readSessionGitPullRequest).toHaveBeenLastCalledWith(row('a1', '/work/app'), { expected: context, history: false, offset: undefined })
+ await ask('git_pull_request', { agentId: 'a1', context: { cwd: '/w', branch: 'b', remote: 'origin' } })
+ expect(readSessionGitPullRequest).toHaveBeenCalledTimes(3)
+ })
+
+ it('git_pull_request: unavailable for an agent with no folder, a malformed context, or a read that fails', async () => {
+ const { ask } = setup()
+ for (const payload of [{}, { agentId: 7 }, { agentId: 'nobody' }, { agentId: 'a2' }]) {
+ expect(await ask('git_pull_request', payload)).toEqual({ status: 'unavailable' })
+ }
+ for (const context of [null, 'main', { cwd: 1, branch: 'b', remote: null }, { cwd: '/w', branch: 2, remote: null }, { cwd: '/w', branch: 'b', remote: 3 }]) {
+ expect(await ask('git_pull_request', { agentId: 'a1', context })).toEqual({ status: 'unavailable' })
+ }
+ expect(readSessionGitPullRequest).not.toHaveBeenCalled()
+ vi.mocked(readSessionGitPullRequest).mockRejectedValueOnce(new Error('gh missing'))
+ expect(await ask('git_pull_request', { agentId: 'a1' })).toEqual({ status: 'unavailable' })
+ })
+
+ it('git_project_info and project_preview: read within the home and the folders agents run in', async () => {
+ const { ask } = setup()
+ expect(await ask('git_project_info', { path: '/work/app', refresh: true })).toEqual({ path: '/work/app', branch: 'main' })
+ expect(readGitProject).toHaveBeenLastCalledWith('/work/app', { refresh: true, knownRoots: ['/work/app'] })
+ await ask('git_project_info', { path: 9 })
+ expect(readGitProject).toHaveBeenLastCalledWith('', { refresh: false, knownRoots: ['/work/app'] })
+ expect(await ask('project_preview', { path: '/work/app' })).toEqual({ path: '/work/app', readme: '# app' })
+ expect(projectPreview).toHaveBeenLastCalledWith('/work/app', ['/work/app'])
+ await ask('project_preview')
+ expect(projectPreview).toHaveBeenLastCalledWith('', ['/work/app'])
+ })
+
+ it('git_project_info and project_preview: a read that fails is UNAVAILABLE', async () => {
+ const { ask } = setup()
+ vi.mocked(readGitProject).mockRejectedValueOnce(new Error('git failed'))
+ expect(await ask('git_project_info', { path: '/work/app' })).toEqual({ error: 'UNAVAILABLE' })
+ vi.mocked(projectPreview).mockRejectedValueOnce(new Error('unreadable'))
+ expect(await ask('project_preview', { path: '/work/app' })).toEqual({ error: 'UNAVAILABLE' })
+ })
+
++ it('scm_project_info: the same probe through the SCM seam, with the same fence, and `none` when it fails', async () => {
++ const { ask } = setup()
++ expect(await ask('scm_project_info', { path: '/work/app', refresh: true })).toEqual({ kind: 'git', git: { isGit: true } })
++ expect(detectScmProject).toHaveBeenLastCalledWith('/work/app', { refresh: true, knownRoots: ['/work/app'] })
++ await ask('scm_project_info', { path: 9 })
++ expect(detectScmProject).toHaveBeenLastCalledWith('', { refresh: false, knownRoots: ['/work/app'] })
++ vi.mocked(detectScmProject).mockRejectedValueOnce(new Error('probe failed'))
++ expect(await ask('scm_project_info', { path: '/work/app' })).toEqual({ kind: 'none', error: 'UNAVAILABLE' })
++ })
++
+ it('fs_list_dir: one folder\'s subfolders, or why not', async () => {
+ const { ask } = setup()
+ expect(await ask('fs_list_dir', { path: '/home/me' })).toEqual({ path: '/home/me', entries: [], truncated: false })
+ expect(listDir).toHaveBeenLastCalledWith('/home/me')
+ vi.mocked(listDir).mockReturnValueOnce({ error: 'FORBIDDEN' })
+ expect(await ask('fs_list_dir')).toEqual({ error: 'FORBIDDEN' })
+ expect(listDir).toHaveBeenLastCalledWith('')
+ })
+
+ it('agent_read_file: a media chunk from the agent\'s project, or why not', async () => {
+ const { ask } = setup()
+ expect(await ask('agent_read_file', { agentId: 'a1', path: 'shot.png', media: true, offset: 0, revision: 'r1' }))
+ .toEqual({ mime: 'image/png', data: 'AAAA', done: true })
+ expect(readMediaPreviewChunk).toHaveBeenLastCalledWith('/work/app', 'shot.png', 0, 'r1')
+ expect(await ask('agent_read_file', { path: 'shot.png', media: true })).toEqual({ error: 'MISSING_AGENT_OR_PATH' })
+ expect(await ask('agent_read_file', { agentId: 'a1', media: true })).toEqual({ error: 'MISSING_AGENT_OR_PATH' })
+ expect(await ask('agent_read_file', { agentId: 'a1', path: 'notes.md' })).toEqual({ error: 'UNSUPPORTED', detail: 'agent_read_file serves media previews only' })
+ expect(await ask('agent_read_file', { agentId: 'a2', path: 'shot.png', media: true })).toEqual({ error: 'AGENT_NOT_FOUND' })
+ vi.mocked(readMediaPreviewChunk).mockRejectedValueOnce(new MediaPreviewError('OUTSIDE_PROJECT'))
+ expect(await ask('agent_read_file', { agentId: 'a1', path: '../x.png', media: true })).toEqual({ error: 'OUTSIDE_PROJECT' })
+ vi.mocked(readMediaPreviewChunk).mockRejectedValueOnce(new Error('EIO'))
+ expect(await ask('agent_read_file', { agentId: 'a1', path: 'shot.png', media: true })).toEqual({ error: 'MEDIA_READ_FAILED' })
+ })
+ })
diff --cc cli/src/services/projects.ts
index 000000000,b8ca4a84c..1d939f660
mode 000000,100644..100644
--- a/cli/src/services/projects.ts
+++ b/cli/src/services/projects.ts
@@@ -1,0 -1,76 +1,86 @@@
+ /**
+ * The project and folder readers: an agent's branch and pull request, a project's repository and preview,
+ * a folder's subfolders for the New Agent browser, and media from an agent's project. Each reads the disk
+ * or runs git, so it is answered when it settles, never in the connection's line. Moved out of the
+ * socket's switch as they were (docs/design/2026-10-06-core-boundary-next.md, step 4).
+ */
+ import type { CoreApi, ServiceRequests } from '../core/api.js'
+ import { listDir } from '../lib/fsBrowse.js'
+ import { readGitProject } from '../lib/gitProject.js'
+ import { MediaPreviewError, readMediaPreviewChunk } from '../lib/mediaPreview.js'
+ import { projectPreview } from '../lib/projectPreview.js'
+ import { readSessionGitPullRequest, type ExpectedGitContext } from '../lib/sessionGitPullRequest.js'
++import { detectScmProject } from '../scm/scmProjects.js'
+ import { internalOnThrow } from './requestErrors.js'
+
+ /** The requests the project readers answer for the apps, declared in core/api.ts for the core to route. */
+ export { PROJECTS_REQUESTS } from '../core/api.js'
+
+ export function startProjects(core: CoreApi): ServiceRequests {
+ /** The browsable home, widened by the folders agents are running in: a repository outside both is not
+ * somewhere this daemon runs git. */
+ const knownRoots = (): string[] => core.agents.live().flatMap((agent) => agent.cwd ? [agent.cwd] : [])
+ return {
+ git_pull_request: internalOnThrow('git_pull_request', (payload) => {
+ const id = payload.agentId
+ const agent = typeof id === 'string' ? core.agents.resolve(id) : undefined
+ if (!agent?.cwd) return { status: 'unavailable' }
+ const requested = payload.context
+ if (requested !== undefined && (!requested || typeof requested !== 'object'
+ || typeof (requested as Record<string, unknown>).cwd !== 'string'
+ || typeof (requested as Record<string, unknown>).branch !== 'string'
+ || (requested as Record<string, unknown>).remote !== null && typeof (requested as Record<string, unknown>).remote !== 'string')) {
+ return { status: 'unavailable' }
+ }
+ return readSessionGitPullRequest(agent, {
+ expected: requested as ExpectedGitContext | undefined,
+ history: payload.history === true, offset: typeof payload.offset === 'number' ? payload.offset : undefined,
+ }).then((result) => result, () => ({ status: 'unavailable' }))
+ }),
+
+ git_project_info: internalOnThrow('git_project_info', (payload) => {
+ const path = typeof payload.path === 'string' ? payload.path : ''
+ return readGitProject(path, { refresh: payload.refresh === true, knownRoots: knownRoots() })
+ .then((result) => result, () => ({ error: 'UNAVAILABLE' }))
+ }),
+
++ // The same probe through the SCM seam, answering `{kind, git?, error?}`. Beside `git_project_info`,
++ // not in its place: an older client keeps asking the old question and gets the old answer. Same
++ // fence and refresh as above.
++ scm_project_info: internalOnThrow('scm_project_info', (payload) => {
++ const path = typeof payload.path === 'string' ? payload.path : ''
++ return detectScmProject(path, { refresh: payload.refresh === true, knownRoots: knownRoots() })
++ .then((result) => result, () => ({ kind: 'none', error: 'UNAVAILABLE' }))
++ }),
++
+ project_preview: internalOnThrow('project_preview', (payload) => {
+ const path = typeof payload.path === 'string' ? payload.path : ''
+ return projectPreview(path, knownRoots()).then((result) => result, () => ({ error: 'UNAVAILABLE' }))
+ }),
+
+ // One-level remote directory listing for the New Agent folder browser.
+ fs_list_dir: internalOnThrow('fs_list_dir', (payload) => {
+ const path = typeof payload.path === 'string' ? payload.path : ''
+ const result = listDir(path)
+ if ('error' in result) return { error: result.error }
+ return { ...result }
+ }),
+
+ // Media previews, in bounded binary chunks. The text mode this request also used to serve was read by
+ // nothing — every client has always asked with `media: true` — so it is gone rather than carrying a
+ // second, laxer file reader (lib/mediaPreview.ts).
+ agent_read_file: internalOnThrow('agent_read_file', async (payload) => {
+ const projectId = payload.agentId as string | undefined
+ const path = payload.path as string | undefined
+ if (!projectId || !path) return { error: 'MISSING_AGENT_OR_PATH' }
+ if (payload.media !== true) return { error: 'UNSUPPORTED', detail: 'agent_read_file serves media previews only' }
+ const s = core.agents.resolve(projectId)
+ if (!s?.cwd) return { error: 'AGENT_NOT_FOUND' }
+ try {
+ return { ...await readMediaPreviewChunk(s.cwd, path, payload.offset, payload.revision) }
+ } catch (error) {
+ return { error: error instanceof MediaPreviewError ? error.message : 'MEDIA_READ_FAILED' }
+ }
+ }),
+ }
+ }
diff --cc cli/src/services/workspaces.ts
index 807a717d5,f0f3f6387..18d9cfbf6
--- a/cli/src/services/workspaces.ts
+++ b/cli/src/services/workspaces.ts
@@@ -35,12 -37,20 +35,20 @@@ export function startWorkspaces(core: C
// Worktrees Harness made that no live or stopped harness uses and nothing would miss
// (lib/worktreeSweep.ts). The core decides when: a few minutes after start, once restored agents
// are back in the registry, then twice a day.
+ //
+ // One sweep at a time: a sweep still going is never joined by a second over the same folders. In the
+ // core's process its timers are hours apart; in this service's own process, a core that restarted
+ // asks again on its own timer while a long sweep from the last core may still be running.
+ let sweeping = false
const sweepUnusedWorktrees = () => {
+ if (sweeping) return
let inUse: Array<string | null>
try { inUse = core.agents.all().map(s => s.cwd) } catch { return }
+ sweeping = true
- void sweepWorktrees({ root: join(homedir(), 'harnesses'), inUse })
+ void sweepScmProjects({ root: join(homedir(), 'harnesses'), inUse })
.then(removed => { if (removed.length) console.log(`[worktrees] removed ${removed.length} unused worktree(s)`) })
.catch(() => {})
+ .finally(() => { sweeping = false })
}
ports.workspaces = { nameBranches: nameSessionBranches, sweepUnused: sweepUnusedWorktrees }
}