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.

Tab collaboration is an experiment: the teams beside their prompt scopes, started only once on (#932)

Deecef0e042a7ba
diff --git a/cli/e2e/experiments.e2e.ts b/cli/e2e/experiments.e2e.ts
index f65934c67..bc771ff23 100644
--- a/cli/e2e/experiments.e2e.ts
+++ b/cli/e2e/experiments.e2e.ts
@@ -6,7 +6,7 @@
* costs that process alone: the core never restarts, every agent keeps working, and the window on this
* computer stays connected and hears every turn.
*/
-import { mkdirSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
@@ -40,6 +40,7 @@ async function turn(client: LocalClient, agentId: string, content: string): Prom
await ended
}
const projects = (client: LocalClient) => client.request('orchestrator', { action: 'list' }, 40_000)
+const teamsStarts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service teams started/g)].length
describe('the experiments, each in a process started only when it is on', () => {
let daemon: IsolatedDaemon | undefined
@@ -144,4 +145,41 @@ describe('the experiments, each in a process started only when it is on', () =>
expect(d.coresStarted()).toBe(1)
client.close()
})
+
+ it('Tab collaboration: off, the teams have no process; a team request starts it, the scopes and the teams beside them', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)
+ expect(teamsStarts(d), 'an experiment no one asked for').toBe(0)
+ expect(await client.request('team', { action: 'capabilities' }, 40_000)).toMatchObject({ protocol: expect.any(String) })
+ expect(teamsStarts(d)).toBe(1)
+ await until('the scopes and the teams to connect', () => (d.log().includes('[services] teams connected') && d.log().includes('[services] collaboration connected')) || null, 30_000, 200)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('a team in its own process introduces its members and delivers a question into the other agent, through the core', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const [alpha, beta] = [await create(d, client, 'team-alpha'), await create(d, client, 'team-beta', 'codex')]
+ const teamId = '1'.repeat(32), questionId = '2'.repeat(32)
+ const member = (agent: Record<string, any>, name: string) => ({ machineId: d.computerId, agentId: agent.id, name })
+ const created = await client.request('team', { action: 'create', id: teamId, name: 'End to end', members: [member(alpha, 'alpha'), member(beta, 'beta')] }, 40_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const team = async () => (await client.request('team', { action: 'get', teamId }, 40_000)).team as { members: Array<{ name: string; introduction: { state: string } }>; exchanges: Array<{ delivery: { state: string } }> }
+ // Each member is told it is in the team: written into its pane by the core, its turn heard back.
+ await until('both introductions to start their turns', async () => (await team()).members.every((m) => m.introduction.state === 'started') || null, 90_000, 500)
+ const keys = JSON.parse(readFileSync(join(d.dataDir, 'teams', 'ledgers', `${teamId}.json`), 'utf8')).members as Array<{ name: string; key: string }>
+ const asked = await client.request('team', { action: 'ask', teamId, id: questionId, memberKey: keys.find((m) => m.name === 'alpha')!.key, to: 'beta', text: 'Which port does the daemon serve?' }, 40_000)
+ expect(asked.error, JSON.stringify(asked)).toBeUndefined()
+ await until('the question to start beta\'s turn', async () => (await team()).exchanges[0]?.delivery.state === 'started' || null, 90_000, 500)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('a team\'s saved state turns Tab collaboration on as the daemon starts', async () => {
+ const d = await fresh({}, (daemon) => mkdirSync(join(daemon.dataDir, 'teams', 'ledgers'), { recursive: true }))
+ await until('the teams to start for their saved state', () => d.log().includes('[services] collaboration connected') || null, 30_000, 200)
+ expect(teamsStarts(d)).toBe(1)
+ })
})
diff --git a/cli/e2e/lean.e2e.ts b/cli/e2e/lean.e2e.ts
index d422de569..1aaa52095 100644
--- a/cli/e2e/lean.e2e.ts
+++ b/cli/e2e/lean.e2e.ts
@@ -19,9 +19,10 @@ import { withLean } from './harness/release.js'
import { readLeanBundle } from '../src/harnessd/leanBundle.js'
type Engine = 'claude' | 'codex'
-/** The processes the master runs the services in, and the services, each on its own link to the core. */
-const PROCESSES = ['search', 'viewers', 'edge', 'teams', 'models']
-const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'teams', 'models']
+/** The processes the master runs the services in, and the services, each on its own link to the core. The
+ * experiments' start only once they are on (e2e/experiments.e2e.ts, from the run's bundle). */
+const PROCESSES = ['search', 'viewers', 'edge', 'models']
+const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'models']
const commandOf = (pid: number): string => execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }).trim()
const rssMiB = (pid: number): number => Number(execFileSync('ps', ['-o', 'rss=', '-p', String(pid)], { encoding: 'utf8' }).trim()) / 1024
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.ts
index 2a42d6020..ceb2fdd5c 100644
--- a/cli/e2e/services.e2e.ts
+++ b/cli/e2e/services.e2e.ts
@@ -51,9 +51,10 @@ async function turn(client: LocalClient, agentId: string, content: string): Prom
const IN_THE_CORE = { HARNESSD_SERVICES: 'none' }
/** A master quick to give up on a service that keeps failing as it starts. */
const QUICK_TO_PARK = { HARNESSD_SERVICE_PARK_CRASHES: '3', HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000' }
-/** The processes the services run in by default, and what makes every one of them fail as it starts. */
-const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'teams', 'models'] as const
-const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,teams,models'
+/** The processes the services run in by default, and what makes every one of them fail as it starts. The
+ * experiments' (the teams', the orchestrator's) start only once they are on: e2e/experiments.e2e.ts. */
+const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'models'] as const
+const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,models'
describe('a failing service never takes the core down', () => {
let daemon: IsolatedDaemon | undefined
diff --git a/cli/e2e/signedIn.e2e.ts b/cli/e2e/signedIn.e2e.ts
index 6f2d72259..55eea1971 100644
--- a/cli/e2e/signedIn.e2e.ts
+++ b/cli/e2e/signedIn.e2e.ts
@@ -14,7 +14,8 @@ import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
type Engine = 'claude' | 'codex'
const MACHINE: FakeMachine = { machineId: 'c3'.repeat(16), computerId: 'e2e-computer-0000-0000-00000000000c', name: 'signed-in', token: 'e2e-token-signed-in' }
-const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects', 'teams'] as const
+/** Every service but the experiments, which start only once they are on (e2e/experiments.e2e.ts). */
+const SERVICES = ['search', 'viewers', 'store', 'workspaces', 'usage', 'monitor', 'projects'] as const
const row = async (client: LocalClient, agentId: string) =>
((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index c1a4ac7d4..24cedd533 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -232,7 +232,14 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
// started only once it is on (services/orchestratorProcess.ts); its 640 lines leave. What stays is what any
// experiment acts on the core through (core/experiments.ts, core/experimentQueries.ts) and what the core
// keeps of the orchestrator (core/orchestratorLink.ts): 290 lines.
-const CORE_CLOSURE_BUDGET = 89_540
+//
+// Then at 88,080 in 392, from 89,443 in 402: Tab collaboration and teams are an experiment, in the teams'
+// process beside the prompt scopes (services/collaborationProcess.ts), started only once on; the team
+// service, its mailbox, the tab channels and their wire (1,700 lines) leave. What stays: the team write hold
+// the core reads a pane with as it writes a team's turn, now lib/teamWriteHold.ts, and what the core keeps of
+// the teams' process (core/teamsLink.ts: which deliveries may be written, the scopes' own questions) and of
+// the account's notices (core/experiments.ts).
+const CORE_CLOSURE_BUDGET = 88_180
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
@@ -310,7 +317,6 @@ const CORE_MAY_REACH: Record<string, string> = {
'lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',
'lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder',
'lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',
- 'orchestrator/prompts.ts': 'step 8: the teams\' command line quotes with it (backendSocket.ts), until the teams leave',
'services/fleet.ts': 'step 9: the fleet, beside the dial',
'services/fleetRouter.ts': 'step 9: the fleet, beside the dial',
'services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',
@@ -320,16 +326,6 @@ const CORE_MAY_REACH: Record<string, string> = {
'sharing/owner.ts': 'step 8: the experimental host',
'sharing/protocol.ts': 'step 8: the experimental host',
'sharing/viewer.ts': 'step 8: the experimental host',
- 'teams/channels.ts': 'step 8: the experimental host',
- 'teams/client.ts': 'step 8: the experimental host',
- 'teams/mailbox.ts': 'step 8: the experimental host',
- 'teams/model.ts': 'step 8: the experimental host',
- 'teams/preflight.ts': 'step 8: the experimental host',
- 'teams/promptScope.ts': 'step 8: the experimental host',
- 'teams/prompts.ts': 'step 8: the experimental host',
- 'teams/service.ts': 'step 8: the experimental host',
- 'teams/store.ts': 'step 8: the experimental host',
- 'teams/wire.ts': 'step 8: the experimental host',
}
describe('the daemon\'s shape', () => {
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index f9a850369..68635e328 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,6 +1,5 @@
import type { PurgeAgentService } from './lib/purgeAgentService.js'
-import { baseNode } from './harnessd/baseNode.js'
-import type { Asker, BackendNotice, GatewayEvents, GatewayPort, ModelsPort, PromptScopes, RemoteClient, RemoteRole, RemoteTransport } from './core/api.js'
+import { 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 { ActivityFrame } from './lib/turnActivity.js'
import { MonitorCompletions } from './lib/harnessMonitor.js'
@@ -20,7 +19,6 @@ import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/auton
* the gateway, which seals it.
*/
-import { existsSync } from 'node:fs'
import { join } from 'path'
import { hostname } from 'os'
import { env } from './config/env.js'
@@ -37,15 +35,6 @@ import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harness
import { engineInstallRecipe } from './lib/engineInstall.js'
import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'
import { agentTokenUsage } from './lib/agentTokenUsage.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 { terminalHandoffRequest } from './lib/terminalHandoff.js'
import { ViewerForwarder } from './lib/viewerForwarder.js'
import { InteractiveViewers } from './lib/interactiveViewer.js'
@@ -61,6 +50,8 @@ 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
+/** The teams' requests, which the frame log leaves out: they carry what agents ask each other. */
+const TEAM_REQUESTS: ReadonlySet<string> = new Set(TEAMS_REQUESTS)
export type Frame = Record<string, unknown>
@@ -192,95 +183,14 @@ export class BackendSocket {
/** Injectable for queue-isolation tests; production uses the machine-local probe. */
engineProbeProvider: typeof probeEngines = probeEngines
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
/** 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
- /** 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
- swarmPromptScopes: PromptScopes = 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 ?? `${[baseNode(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 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.
@@ -477,7 +387,7 @@ export class BackendSocket {
this.onMachineMeta?.(meta.name ?? null)
},
notice: (notice: BackendNotice) => {
- if (notice.type === 'desk_changed') this.refreshChannels()
+ this.onAccountNotice?.(notice)
this.sendLocal(notice.type === 'machines_changed' ? { type: notice.type, payload: { reason: notice.reason } }
: notice.type === 'device_keys_changed' ? { type: notice.type, payload: {} }
: { type: notice.type, payload: { revision: notice.revision } })
@@ -554,9 +464,6 @@ export class BackendSocket {
async stop(): Promise<void> {
this.closed = true
this.closeAgentService?.dispose()
- this.teamService?.stop()
- this.teamMailboxService?.stop()
- this.channelDirectory?.stop()
this.viewerForwarder.closeAll()
this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()
await this.terminalStreams?.stop()
@@ -837,7 +744,7 @@ export class BackendSocket {
private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {
const resultType = rpcResultType(type)
// 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 !== '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 (this.localClients.has(connId)) {
this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })
return
@@ -896,7 +803,7 @@ export class BackendSocket {
// 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 !== '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')) {
logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)
}
const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)
@@ -918,34 +825,6 @@ export class BackendSocket {
const requestId = payload.requestId
const answer = (result: Record<string, unknown>): void => reply(type, requestId, result)
- if (TEAM_REQUEST_TYPES.has(type)) {
- // Observers were handled above; only the owner or a paired owner client reaches this route.
- if (!owner) {
- reply(type, requestId, { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' })
- return
- }
- void Promise.resolve().then(async () => {
- if (type === 'team') {
- if (payload.action === 'context') {
- const agentId = Id.parse(payload.agentId)
- return this.channels().taskContext(agentId, this.swarmPromptScopes.current(agentId))
- }
- if (String(payload.action).startsWith('channel_')) return this.channels().request(payload)
- if (typeof payload.teamId === 'string' && this.teams().isChannel(payload.teamId)
- && ['ask', 'get', 'members'].includes(String(payload.action))) await this.channels().refresh(payload.action === 'ask')
- return teamRequest(this.teams(), payload)
- }
- if (payload.action === 'runtime') return { runtime: this.localTeamRuntime(Id.parse(payload.agentId)) }
- if (payload.action === 'prompt_scope') return { teamId: this.swarmPromptScopes.current(Id.parse(payload.agentId)) }
- if (payload.action === 'prompt_replied') {
- this.swarmPromptScopes.replied(Id.parse(payload.agentId), OperationId.parse(payload.teamId), OperationId.parse(payload.questionId))
- return { ok: true }
- }
- return teamDeliveryRequest(this.teamMailbox(), payload)
- }).then(result => reply(type, requestId, result)).catch(error => reply(type, requestId, teamFailure(error)))
- return
- }
-
// A paired owner can run the machine's orchestrator; observers and device sessions cannot.
// Both requests and replies are encrypted, including project artifacts.
if (OWNER_COMMAND_TYPES.has(type)) {
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index 8595ee45b..43816f90a 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -39,7 +39,8 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
- `api.ts`: the contract with services, their ports, fallbacks and requests. `serviceHost.ts`: services
in this process. `serviceLinks.ts`: services in their own processes. `viewersLink.ts`: what the core
keeps of the viewers when they run in theirs. `workspacesLink.ts`: what the core tells workspaces in
- theirs. `teamsLink.ts`: every change to the teams' prompt scopes, kept until their process has it.
+ theirs. `teamsLink.ts`: every change to the teams' prompt scopes, kept until their process has it once Tab
+ collaboration is on, which of its deliveries may be written, and the scopes' own two questions.
`monitorLink.ts`: the monitor's port, asked of its process. `storeLink.ts`: what the Store in its
process tells the core. `modelsLink.ts`: what the core keeps of models in its process for frames and
keystrokes, and how it asks it the rest. `agentQueries.ts`: what a service in its own process may ask of the agents;
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index a69095504..9aa922762 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
-import { AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'
+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'
import { FAIL } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
@@ -54,6 +54,8 @@ describe('the core API services stand on', () => {
lane: LANE_OFF,
privateGridName: vi.fn(async () => 'grid-1'),
machineName: vi.fn(() => 'Studio'),
+ backend: vi.fn(async () => ({ status: 200, body: {} })),
+ onNotice: vi.fn(() => () => {}),
runtimeProfile: vi.fn(() => null),
setRuntime: vi.fn(),
fork: vi.fn(async () => ({ ok: true as const, agentId: 'fork' })),
@@ -92,6 +94,8 @@ describe('the core API services stand on', () => {
expect(core.account.lane).toBe(deps.lane)
expect(core.account.privateGridName).toBe(deps.privateGridName)
expect(core.account.machineName).toBe(deps.machineName)
+ expect(core.account.backend).toBe(deps.backend)
+ expect(core.account.onNotice).toBe(deps.onNotice)
// What a device or another machine asks of an agent here: the core's own handlers, as they are.
expect(core.agents.runtimeProfile).toBe(deps.runtimeProfile)
expect(core.agents.setRuntime).toBe(deps.setRuntime)
@@ -120,9 +124,10 @@ describe('the core API services stand on', () => {
}
})
- it('falls back, when the teams fail, to an undo that has nothing to undo', () => {
+ it('falls back, when the teams fail, to an undo that has nothing to undo, and holds no pane for a team', () => {
const undo = TEAMS_FALLBACKS.prepare as () => void
expect(undo()).toBeUndefined()
+ expect(TEAMS_FALLBACKS.canWrite).toBe(false)
})
it('starts with every port empty: a service fills its own when it starts', () => {
@@ -157,6 +162,11 @@ describe('the core API services stand on', () => {
expect(DAEMON_UNKNOWN.machineId()).toBe('')
})
+ it('gives a service that reads no backend an unavailable answer, and no notice to hear', async () => {
+ expect(await ACCOUNT_BACKEND_OFF.backend('GET', '/api/tab-channels')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
+ expect(ACCOUNT_BACKEND_OFF.onNotice(() => {})()).toBeUndefined()
+ })
+
it('answers no role and reads no frame while the orchestrator is off', () => {
expect(ORCHESTRATOR_FALLBACKS).toEqual({ roleOf: null, frame: undefined, stop: undefined })
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 13f1aa91e..5ef46ec3c 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -144,6 +144,11 @@ export interface CoreApi {
/** This machine's name as the account's Machines list shows it (the backend's `machine_meta`); null
* until the first one lands. */
machineName(): string | null
+ /** A read or write of the account's backend, signed in by the core (`proxyBackend`): an experiment's
+ * account-wide settings (Tab collaboration's tab channels). A failure is an answer: 502, 504, 401. */
+ backend(method: string, path: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> }>
+ /** Hear the account's changes the backend announces (`desk_changed`, …). Returns how to stop hearing. */
+ onNotice(listener: (notice: BackendNotice) => void): () => void
}
clients: {
/** An agent's viewer moved: the windows' viewer panes forward to the new one. */
@@ -191,6 +196,12 @@ export const AGENT_ACTIONS_OFF: Pick<CoreApi['agents'], 'create' | 'dsh'> = {
dsh: () => null,
}
+/** The account as a service that reads no backend and hears no notice has it. */
+export const ACCOUNT_BACKEND_OFF: Pick<CoreApi['account'], 'backend' | 'onNotice'> = {
+ backend: async () => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }),
+ onNotice: () => () => {},
+}
+
/** 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: () => '' }
@@ -297,6 +308,9 @@ export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, numbe
/** The orchestrator (services/orchestrator.ts): its projects, for the apps and for the agents it runs. */
export const ORCHESTRATOR_REQUESTS = ['orchestrator'] 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,
@@ -313,6 +327,9 @@ export const ORCHESTRATOR_REQUESTS = ['orchestrator'] as const
*/
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'] },
}
/** What an agent is to the orchestrator's projects: a specialist (`worker`), or a project's Director, and
@@ -451,18 +468,23 @@ export interface WorkspacesPort {
/** What the core gets when workspaces fails: branches keep their names and nothing is swept. */
export const WORKSPACES_FALLBACKS: PortFallbacks<WorkspacesPort> = { nameBranches: undefined, sweepUnused: undefined }
-/** The core's calls into the teams: which team a prompt belongs to, recorded as a message is written,
- * as a turn starts (from its hook or its transcript), as it is typed into a scoped terminal, and
- * forgotten with its agent. */
-export type TeamsPort = Pick<SwarmPromptScopes, 'prepare' | 'started' | 'raw' | 'forget'>
+/** The prompt scopes whole: the core's calls, which team a prompt belongs to, recorded as a message is
+ * written, as a turn starts (from its hook or its transcript), as it is typed into a scoped terminal, and
+ * forgotten with its agent; and the team a prompt came from (`current`), which an agent's answer to a
+ * team's question moves back (`replied`). In the core's process the teams service's own; in their own,
+ * core/teamsLink.ts. */
+export type PromptScopes = Pick<SwarmPromptScopes, 'prepare' | 'started' | 'raw' | 'forget' | 'current' | 'replied'>
+
+/** The core's calls into the teams: the prompt scopes' records, and whether a team's delivery still holds
+ * the agent's pane, asked in line as its turn is written (core/input.ts). */
+export type TeamsPort = Pick<PromptScopes, 'prepare' | 'started' | 'raw' | 'forget'> & {
+ canWrite(deliveryId: string): boolean
+}
-/** What the core gets when the teams fail: the prompt is written with no team recorded for it. */
-export const TEAMS_FALLBACKS: PortFallbacks<TeamsPort> = { prepare: () => {}, started: undefined, raw: undefined, forget: undefined }
+/** What the core gets when the teams fail: the prompt is written with no team recorded for it, and a team's
+ * delivery holds no pane (it waits, unwritten). */
+export const TEAMS_FALLBACKS: PortFallbacks<TeamsPort> = { prepare: () => {}, started: undefined, raw: undefined, forget: undefined, canWrite: false }
-/** The prompt scopes whole, as the socket's team features hold them: the core's calls (`TeamsPort`),
- * and the team a prompt came from (`current`), which an agent's answer to a team's question moves
- * back (`replied`). In the core's process the socket's own; in their own, core/teamsLink.ts. */
-export type PromptScopes = TeamsPort & Pick<SwarmPromptScopes, 'current' | 'replied'>
/** A change to the prompt scopes, as the core tells the teams' own process (core/teamsLink.ts,
* services/teamsProcess.ts): numbered within one core's life, stamped with when it happened, and
@@ -845,6 +867,8 @@ export interface CoreApiDeps {
lane: CoreApi['account']['lane']
privateGridName: CoreApi['account']['privateGridName']
machineName: CoreApi['account']['machineName']
+ backend: CoreApi['account']['backend']
+ onNotice: CoreApi['account']['onNotice']
create: CoreApi['agents']['create']
dsh: CoreApi['agents']['dsh']
windows: CoreApi['clients']['windows']
@@ -858,7 +882,7 @@ export interface CoreApiDeps {
export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,
- gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, privateGridName, machineName,
+ gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, privateGridName, machineName, backend, onNotice,
runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF,
}: CoreApiDeps): CoreApi {
return {
@@ -884,7 +908,7 @@ export function createCoreApi({
questions,
transcripts: { databaseHistory },
external: { sessions: externalSessions, open: openSessions },
- account: { mintGridName, accessToken, lane, privateGridName, machineName },
+ account: { mintGridName, accessToken, lane, privateGridName, machineName, backend, onNotice },
clients: { viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows },
daemon,
}
diff --git a/cli/src/core/deliveries.spec.ts b/cli/src/core/deliveries.spec.ts
index 23a188885..9458afabf 100644
--- a/cli/src/core/deliveries.spec.ts
+++ b/cli/src/core/deliveries.spec.ts
@@ -1,8 +1,8 @@
import { describe, expect, it, vi } from 'vitest'
import type { TurnDelivery } from './api.js'
-import { createDeliveries, KEPT_DELIVERERS, type DeliveriesDeps } from './deliveries.js'
+import { createDeliveries, HELD_DELIVERIES, KEPT_DELIVERERS, type DeliveriesDeps } from './deliveries.js'
-const setup = (over: Partial<Pick<DeliveriesDeps, 'submit' | 'cancel' | 'deliverers'>> = {}) => {
+const setup = (over: Partial<Pick<DeliveriesDeps, 'submit' | 'cancel' | 'deliverers'>> = {}, ready = true) => {
const deps = {
submit: over.submit ?? vi.fn(),
cancel: over.cancel ?? vi.fn(() => true),
@@ -10,7 +10,9 @@ const setup = (over: Partial<Pick<DeliveriesDeps, 'submit' | 'cancel' | 'deliver
deliverers: over.deliverers ?? new Set(['orchestrator']),
log: vi.fn(),
}
- return { deps, deliveries: createDeliveries(deps) }
+ const deliveries = createDeliveries(deps)
+ if (ready) deliveries.ready()
+ return { deps, deliveries }
}
const event = (deliveryId: string, state: TurnDelivery['state'] = 'queued'): TurnDelivery => ({ deliveryId, sessionId: 'agent-1', state })
@@ -90,6 +92,45 @@ describe('delivered turns', () => {
expect(deps.tell.mock.calls).toEqual([['teams', event('first')]])
})
+ it('holds what is delivered before the core\'s input is wired, writes it in order once it is, and the rest as it comes', () => {
+ const { deps, deliveries } = setup({}, false)
+ deliveries.turns.deliver('agent-1', 'first', 'd1')
+ expect(deliveries.answer('orchestrator', 'deliver', { agentId: 'agent-2', text: 'second', deliveryId: 'd2' })).toEqual({})
+ expect(deps.submit).not.toHaveBeenCalled()
+ deliveries.ready()
+ deliveries.turns.deliver('agent-1', 'third', 'd3')
+ expect(vi.mocked(deps.submit).mock.calls).toEqual([['agent-1', 'first', 'd1'], ['agent-2', 'second', 'd2'], ['agent-1', 'third', 'd3']])
+ // Ready twice holds nothing back and writes nothing twice.
+ deliveries.ready()
+ expect(deps.submit).toHaveBeenCalledTimes(3)
+ })
+
+ it('takes back one still held as the input would a queued one, and asks the input of any other', () => {
+ const { deps, deliveries } = setup({ cancel: vi.fn(() => false) }, false)
+ const heard: TurnDelivery[] = []
+ deliveries.turns.onDelivery((event) => heard.push(event))
+ deliveries.answer('orchestrator', 'deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd1' })
+ expect(deliveries.turns.cancelDelivery('d1')).toBe(true)
+ expect(heard).toEqual([{ deliveryId: 'd1', sessionId: 'agent-1', state: 'rejected', reason: 'cancelled' }])
+ expect(deps.tell).toHaveBeenCalledWith('orchestrator', heard[0])
+ expect(deliveries.answer('orchestrator', 'cancel_delivery', { deliveryId: 'd2' })).toEqual({ cancelled: false })
+ expect(deps.cancel).toHaveBeenCalledWith('d2')
+ deliveries.ready()
+ expect(deps.submit).not.toHaveBeenCalled()
+ expect(deliveries.turns.cancelDelivery('d1')).toBe(false)
+ })
+
+ it('refuses the oldest held when too many wait, as a full queue does', () => {
+ const { deps, deliveries } = setup({}, false)
+ const heard: TurnDelivery[] = []
+ deliveries.turns.onDelivery((event) => heard.push(event))
+ for (let i = 0; i <= HELD_DELIVERIES; i++) deliveries.turns.deliver('agent-1', `turn ${i}`, `d${i}`)
+ expect(heard).toEqual([{ deliveryId: 'd0', sessionId: 'agent-1', state: 'rejected', reason: 'queue_full' }])
+ deliveries.ready()
+ expect(deps.submit).toHaveBeenCalledTimes(HELD_DELIVERIES)
+ expect(vi.mocked(deps.submit).mock.calls[0]).toEqual(['agent-1', 'turn 1', 'd1'])
+ })
+
it('logs to the console when given no log of its own', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
diff --git a/cli/src/core/deliveries.ts b/cli/src/core/deliveries.ts
index 4a23fe5c3..2529dafba 100644
--- a/cli/src/core/deliveries.ts
+++ b/cli/src/core/deliveries.ts
@@ -15,6 +15,9 @@ import type { CoreApi, TurnDelivery } from './api.js'
type Payload = Record<string, unknown>
+/** The most deliveries held while the core starts: a teams' mailbox resumes a few at most. */
+export const HELD_DELIVERIES = 1_000
+
/** The most deliveries whose maker is remembered: past it the oldest is forgotten, and what becomes of it
* is told to no process. A delivery settles within minutes (its queue item lives five), and a process
* makes a few a minute. */
@@ -39,10 +42,41 @@ export function createDeliveries(deps: DeliveriesDeps) {
const listeners = new Set<(event: TurnDelivery) => void>()
/** Which process made each delivery, oldest first. */
const makers = new Map<string, string>()
+ /**
+ * What was delivered before the core's input was wired (`ready`), in order. A teams' mailbox resumes its
+ * queue on a timer as soon as it starts, in the core's process or in its own, and the socket held such a
+ * turn back with "Agent input is not ready" until then; dropped, it would read as written and never be.
+ */
+ let held: Array<{ agentId: string; text: string; deliveryId: string }> | null = []
+ const submit = (agentId: string, content: string, deliveryId: string): void => {
+ if (!held) { deps.submit(agentId, content, deliveryId); return }
+ held.push({ agentId, text: content, deliveryId })
+ if (held.length > HELD_DELIVERIES) {
+ const dropped = held.shift()!
+ settled({ deliveryId: dropped.deliveryId, sessionId: dropped.agentId, state: 'rejected', reason: 'queue_full' })
+ }
+ }
+ /** Take back a delivery still held, as the input would one still queued, or ask the input. */
+ const cancel = (deliveryId: string): boolean => {
+ const at = held?.findIndex((delivery) => delivery.deliveryId === deliveryId) ?? -1
+ if (at < 0) return deps.cancel(deliveryId)
+ const [taken] = held!.splice(at, 1)
+ settled({ deliveryId, sessionId: taken.agentId, state: 'rejected', reason: 'cancelled' })
+ return true
+ }
+ const settled = (event: TurnDelivery): void => {
+ for (const listener of listeners) {
+ try { listener(event) } catch (error) {
+ log(`[deliveries] a listener failed on ${event.deliveryId.slice(0, 40)} · ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
+ const maker = makers.get(event.deliveryId)
+ if (maker) deps.tell(maker, event)
+ }
const turns: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'> = {
- deliver: (agentId, content, deliveryId) => deps.submit(agentId, content, deliveryId),
- cancelDelivery: (deliveryId) => deps.cancel(deliveryId),
+ deliver: (agentId, content, deliveryId) => submit(agentId, content, deliveryId),
+ cancelDelivery: (deliveryId) => cancel(deliveryId),
onDelivery: (listener) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
@@ -56,14 +90,13 @@ export function createDeliveries(deps: DeliveriesDeps) {
/** The core's input says what became of a delivery: every listener here hears it, each guarded, and the
* process that made it is told. A listener that throws costs that listener the event, never the input
* that said it or another listener. */
- settled(event: TurnDelivery): void {
- for (const listener of listeners) {
- try { listener(event) } catch (error) {
- log(`[deliveries] a listener failed on ${event.deliveryId.slice(0, 40)} · ${error instanceof Error ? error.message : String(error)}`)
- }
- }
- const maker = makers.get(event.deliveryId)
- if (maker) deps.tell(maker, event)
+ settled,
+
+ /** The core's input is wired: what was held is written, in order, and the rest as it comes. */
+ ready(): void {
+ const waiting = held ?? []
+ held = null
+ for (const delivery of waiting) deps.submit(delivery.agentId, delivery.text, delivery.deliveryId)
},
/** A service in its own process delivering a turn, or taking one back (`service_query`): null when the
@@ -73,14 +106,14 @@ export function createDeliveries(deps: DeliveriesDeps) {
if (!deps.deliverers.has(service)) return { error: 'NOT_A_DELIVERER' }
const deliveryId = text(payload.deliveryId)
if (!deliveryId) return { error: 'INVALID_DELIVERY' }
- if (query === 'cancel_delivery') return { cancelled: deps.cancel(deliveryId) }
+ if (query === 'cancel_delivery') return { cancelled: cancel(deliveryId) }
const agentId = text(payload.agentId)
if (!agentId || typeof payload.text !== 'string') return { error: 'INVALID_DELIVERY' }
// Known before it is written: the input says `queued` as it takes it, and that is the maker's to hear.
makers.delete(deliveryId)
makers.set(deliveryId, service)
if (makers.size > KEPT_DELIVERERS) makers.delete(makers.keys().next().value!)
- deps.submit(agentId, payload.text, deliveryId)
+ submit(agentId, payload.text, deliveryId)
return {}
},
}
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index f9053e744..9030cc1b3 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -58,6 +58,18 @@ describe('what an experiment in its own process may ask of the core', () => {
expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'daemon', {})).toEqual({ command: `'node' 'cli.js'`, port: 18473, machineId: 'machine-7' })
})
+ it('reads and writes the account\'s backend under /api/, signed in by the core, and nothing else', async () => {
+ const backend = vi.fn(async () => ({ status: 200, body: { success: true, data: { tabs: [] } } }))
+ const core = fakeCore({ account: { backend } })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'backend', { method: 'PATCH', path: '/api/tab-channels/settings', body: { enabled: true } }))
+ .toEqual({ status: 200, body: { success: true, data: { tabs: [] } } })
+ expect(backend).toHaveBeenCalledWith('PATCH', '/api/tab-channels/settings', { enabled: true })
+ for (const bad of [{ method: 'TRACE', path: '/api/x' }, { method: 'GET', path: '/auth/token' }, { method: 'GET' }]) {
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'backend', bad)).toEqual({ error: 'INVALID_REQUEST' })
+ }
+ expect(backend).toHaveBeenCalledOnce()
+ })
+
it('answers none of these for a process that is not an experiment, and leaves other queries to whoever answers them', async () => {
const core = fakeCore()
expect(await answerExperimentQuery(core, experiments, 'gateway', 'create', {})).toEqual({ error: 'NOT_AN_EXPERIMENT' })
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index 399851dbf..bae77f73a 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -8,7 +8,9 @@
* - `create`: create an agent, as the window's `agent_create` does;
* - `stop_turn`: stop an agent's turn;
* - `windows`: a change notice for every window on this computer (`orchestrator_changed`);
- * - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes.
+ * - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes;
+ * - `backend`: a read or write of the account's backend under `/api/`, signed in by the core, which holds the
+ * sign-in (Tab collaboration's tab channels).
* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or
* telling the windows something is no other process's to ask. The process's side is
* services/processCoreApi.ts.
@@ -17,9 +19,10 @@ import type { BackendSocket } from '../backendSocket.js'
import type { AgentCreateRequest, CoreApi } from './api.js'
type Payload = Record<string, unknown>
-type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon'>
+type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon', 'backend'])
+const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
/** The answer to an experiment's query, or null when it is not one of these. */
@@ -58,6 +61,11 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
core.clients.windows({ type: text(frame.type), payload: frame.payload as Payload })
return {}
}
+ case 'backend': {
+ const method = text(payload.method), path = text(payload.path)
+ if (!METHODS.has(method) || !path.startsWith('/api/')) return { error: 'INVALID_REQUEST' }
+ return { ...await core.account.backend(method, path, payload.body) }
+ }
default:
return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId() }
}
diff --git a/cli/src/core/experiments.spec.ts b/cli/src/core/experiments.spec.ts
index 46db330ec..41da18ae1 100644
--- a/cli/src/core/experiments.spec.ts
+++ b/cli/src/core/experiments.spec.ts
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { stateIsThere, wakeExperiments } from './experiments.js'
+import { createAccountNotices, createExperimentHooks, stateIsThere, wakeExperiments } from './experiments.js'
describe('the experiments on as the core starts', () => {
let dataDir: string
@@ -38,4 +38,51 @@ describe('the experiments on as the core starts', () => {
expect(woken).toEqual(['orchestrator'])
expect(want.mock.calls).toEqual([['orchestrator']])
})
+
+ it('hands the account\'s notices to each listener here, guarded, and to the experiments\' processes', () => {
+ const tell = vi.fn()
+ const log = vi.fn()
+ const notices = createAccountNotices(tell, log)
+ const heard = vi.fn()
+ const stop = notices.onNotice(heard)
+ notices.onNotice(() => { throw new Error('boom') })
+ notices.onNotice(() => { throw 'odd' })
+ notices.notice({ type: 'desk_changed', revision: 3 })
+ stop()
+ notices.notice({ type: 'desk_changed', revision: 4 })
+ expect(heard.mock.calls).toEqual([[{ type: 'desk_changed', revision: 3 }]])
+ expect(tell).toHaveBeenCalledTimes(2)
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('boom'))
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('odd'))
+ })
+
+ it('logs to the console when given no log of its own', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ const notices = createAccountNotices(() => {})
+ notices.onNotice(() => { throw new Error('boom') })
+ notices.notice({ type: 'desk_changed', revision: 1 })
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('boom'))
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('asks for an experiment after doing what it must not miss, and tells each experiment in its own process the account\'s notices', () => {
+ const order: string[] = []
+ const notify = vi.fn(() => true)
+ const hooks = createExperimentHooks({
+ want: (service) => order.push(`want ${service}`), notify, outOfProcess: new Set(['collaboration']), experiments: ['orchestrator', 'collaboration'],
+ onWant: { collaboration: () => order.push('keep the scopes') },
+ })
+ hooks.want('collaboration')
+ hooks.want('orchestrator')
+ expect(order).toEqual(['keep the scopes', 'want collaboration', 'want orchestrator'])
+ const heard = vi.fn()
+ hooks.onNotice(heard)
+ hooks.notice({ type: 'desk_changed', revision: 5 })
+ expect(heard).toHaveBeenCalledWith({ type: 'desk_changed', revision: 5 })
+ expect(notify.mock.calls).toEqual([['collaboration', { type: 'service_event', payload: { kind: 'notice', notice: { type: 'desk_changed', revision: 5 } } }]])
+ createExperimentHooks({ want: vi.fn(), notify, outOfProcess: new Set(), experiments: [] }).want('x')
+ })
})
diff --git a/cli/src/core/experiments.ts b/cli/src/core/experiments.ts
index 5dcdaa9ef..73b186497 100644
--- a/cli/src/core/experiments.ts
+++ b/cli/src/core/experiments.ts
@@ -7,6 +7,7 @@
*/
import { readdirSync, existsSync } from 'node:fs'
import { join } from 'node:path'
+import type { BackendNotice } from './api.js'
/** Whether any of `state` is in `dataDir`: a path under it, or `dir/*.ext` for a file of that kind in that folder. */
export function stateIsThere(dataDir: string, state: readonly string[]): boolean {
@@ -35,3 +36,50 @@ export function wakeExperiments(options: {
for (const name of woken) options.want(name)
return woken
}
+
+/**
+ * The account's notices the backend announces (`desk_changed`, …), for the experiments that hear them: each
+ * listener in this process (`core.account.onNotice`), guarded, and each experiment's process (`tell`). Tab
+ * collaboration reads its tab channels again at `desk_changed`, as the socket did before it left.
+ */
+export function createAccountNotices(tell: (notice: BackendNotice) => void, log: (line: string) => void = (line) => console.warn(line)) {
+ const listeners = new Set<(notice: BackendNotice) => void>()
+ return {
+ onNotice(listener: (notice: BackendNotice) => void): () => void {
+ listeners.add(listener)
+ return () => { listeners.delete(listener) }
+ },
+ notice(notice: BackendNotice): void {
+ for (const listener of listeners) {
+ try { listener(notice) } catch (error) { log(`[experiments] a notice's listener failed · ${error instanceof Error ? error.message : String(error)}`) }
+ }
+ tell(notice)
+ },
+ }
+}
+
+/**
+ * What the core does for the experiments as a whole: ask the master for one (`want`), first doing what that
+ * experiment must not miss from then on (`onWant`: the teams' scopes kept from the moment teams is on), and
+ * hand the account's notices to the listeners here and to each experiment in its own process.
+ */
+export function createExperimentHooks(deps: {
+ want: (service: string) => void
+ notify: (service: string, frame: { type: string; payload: Record<string, unknown> }) => boolean
+ outOfProcess: ReadonlySet<string>
+ experiments: Iterable<string>
+ onWant?: Readonly<Record<string, () => void>>
+ log?: (line: string) => void
+}) {
+ const notices = createAccountNotices((notice) => {
+ for (const name of deps.experiments) if (deps.outOfProcess.has(name)) deps.notify(name, { type: 'service_event', payload: { kind: 'notice', notice } })
+ }, deps.log)
+ return {
+ want(service: string): void {
+ if (deps.onWant && Object.hasOwn(deps.onWant, service)) deps.onWant[service]()
+ deps.want(service)
+ },
+ onNotice: notices.onNotice,
+ notice: notices.notice,
+ }
+}
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index f597b74f9..04a13691d 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -20,8 +20,7 @@ import type { RegisteredSession } from '../lib/registry.js'
import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'
import { messageHold, passingHold } from '../lib/messageHold.js'
import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'
-import { Id } from '../teams/model.js'
-import { teamWriteHold } from '../teams/preflight.js'
+import { teamWriteHold } from '../lib/teamWriteHold.js'
import type { TerminalControl } from './terminals/control.js'
type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }
@@ -32,7 +31,7 @@ export interface InputDeps {
terminal: Pick<TerminalControl, 'captureTerminal' | 'validateTerminal' | 'submitTerminalAction' | 'keyTerminalAction' | 'pinTerminalControl'>
/** The teams and orchestrator features. */
teams: {
- /** Before a paste: record where the prompt came from (BackendSocket.swarmPromptScopes.prepare). */
+ /** Before a paste: record where the prompt came from (the teams' prompt scopes, `ports.teams`). */
prepare: (agentId: string, content: string, tabId?: string, deliveryId?: string) => () => void
/** A delivery settled: the orchestrator hears of it, then the team. */
delivery: (event: SessionInputDelivery) => void
@@ -219,6 +218,9 @@ export function createInput(deps: InputDeps) {
*
* Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).
*/
+/** A tab's id as Tab collaboration takes it (teams/model.ts `Id`): a message from a tab is in its swarm's scope. */
+const TAB_ID = /^[A-Za-z0-9_-]{1,128}$/
+
export function createMessageRequest(submit: (id: string, content: string, deliveryId?: string, tabId?: string) => void) {
return (payload: Record<string, unknown>): void => {
const content = payload.content as string | undefined
@@ -226,8 +228,7 @@ export function createMessageRequest(submit: (id: string, content: string, deliv
if (!content || !target) return
// From the relay this is only reached sealed: text typed into an agent is never taken from the relay
// in the clear.
- const tabId = Id.safeParse(payload.tabId)
- if (tabId.success) submit(target, content, undefined, tabId.data)
+ if (typeof payload.tabId === 'string' && TAB_ID.test(payload.tabId)) submit(target, content, undefined, payload.tabId)
else submit(target, content)
}
}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index a11bf4415..b4de95b3d 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -128,7 +128,7 @@ import { createAgentUpdate } from './agents/update.js'
import { createEngineHooks, installEngineHooks } from './engines/hooks.js'
import { createCursorTaskHooks } from './engines/cursorTasks.js'
import { databaseHistory } from './transcripts/databaseHistory.js'
-import { createCoreApi, emptyPorts, EXPERIMENTS, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'
+import { createCoreApi, emptyPorts, EXPERIMENTS, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
@@ -139,12 +139,12 @@ import { createStoreLink } from './storeLink.js'
import { createModelsLink } from './modelsLink.js'
import { answerAgentQuery } from './agentQueries.js'
import { createDeliveries } from './deliveries.js'
-import { wakeExperiments } from './experiments.js'
+import { createExperimentHooks, wakeExperiments } from './experiments.js'
import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
import { createOrchestratorLink } from './orchestratorLink.js'
import { daemonCommand } from '../lib/daemonCommand.js'
import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'
-import { createTeamsLink } from './teamsLink.js'
+import { createTeamsLink, teamsOutOfProcess } from './teamsLink.js'
import { startFleet } from '../services/fleet.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND, PROBE_TIMEOUT_MS } from '../harnessd/protocol.js'
import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'
@@ -161,7 +161,6 @@ import { WindowSelection } from '../cable/windowSelection.js'
import { WindowVisit } from '../cable/windowVisit.js'
import { WindowForm } from '../cable/windowForm.js'
import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'
-import { TeamError } from '../teams/model.js'
import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'
import { E2eeStore } from '../lib/e2ee/store.js'
import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'
@@ -652,6 +651,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
gridModelsChanged: () => { void backendRef?.pushGridModels() },
privateGridName: async () => backendRef?.gridName() ?? null,
machineName: () => backendRef?.machineName() ?? null,
+ // An experiment's account-wide settings (Tab collaboration's tab channels), signed in by this core.
+ backend: (method, path, body) => proxyBackend(method, path, body),
+ onNotice: (listener) => experimentHooks.onNotice(listener),
dshInstallStatus: (status) => backendRef?.send({ type: 'dsh_install_status', payload: status }),
// The backend mints and remembers the account's grid name; this CLI holds neither the account's
// email nor its id. An older backend (no route) answers nothing, which the grid reconcile treats as
@@ -793,6 +795,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
started: (...args) => ports.teams?.started(...args),
raw: (...args) => ports.teams?.raw(...args),
forget: (agentId) => ports.teams?.forget(agentId),
+ canWrite: (deliveryId) => ports.teams?.canWrite(deliveryId) ?? false,
}
backend.viewerTargetProvider = (agentId) => ports.viewers?.forwardingUrl(agentId) ?? null
@@ -986,10 +989,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
teams: {
prepare: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),
delivery: (event) => {
- backend.teamDelivery(event)
deliveries.settled(event)
},
- canWrite: (deliveryId) => backend.teamCanWrite(deliveryId),
+ canWrite: (deliveryId) => teams.canWrite(deliveryId),
},
device: () => autonomousDeviceService,
clients: backend,
@@ -1104,8 +1106,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const viewersLink = createViewersLink(coreApi, (frame, opts) => serviceLinks.notify('viewers', frame, opts))
// How the core tells workspaces in their own process what to do, and answers them (core/workspacesLink.ts).
const workspacesLink = createWorkspacesLink(coreApi, (frame) => serviceLinks.notify('workspaces', frame), forgetAgentProject)
- // Every change to the prompt scopes, kept until their own process has it, and each agent's scope (core/teamsLink.ts).
- const teamsLink = createTeamsLink({ notify: (frame) => serviceLinks.notify('teams', frame) })
+ // Tab collaboration and teams, an experiment: the prompt scopes and the teams beside them, both in its process
+ // or both in this one (core/teamsLink.ts), which keeps the scopes' changes from the moment it is on.
+ const teamsOut = teamsOutOfProcess(outOfProcess)
+ const teamsLink = createTeamsLink({ notify: (frame) => serviceLinks.notify('teams', frame), off: true })
+ // An experiment asked for, and the account's notices for those that hear them (core/experiments.ts).
+ const experimentHooks = createExperimentHooks({ want: (service) => coreLink.want(service), notify: (service, frame) => serviceLinks.notify(service, frame),
+ outOfProcess, experiments, onWant: { collaboration: () => teamsLink.on() } })
+ backend.onAccountNotice = (notice) => experimentHooks.notice(notice)
// What the Store in its own process tells the core: an install's progress, and that what is installed changed (core/storeLink.ts).
const storeLink = createStoreLink(coreApi, invalidateInstalledDsh)
// What the core keeps of models in its own process for frames and keystrokes, and how it asks it the rest (core/modelsLink.ts).
@@ -1116,7 +1124,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
waits: LONG_ANSWERS,
// An experiment's process runs only once it is on: a request for one that is off asks the master for it.
onDemand: experiments,
- want: (service) => coreLink.want(service),
+ want: (service) => experimentHooks.want(service),
answer: async (service, query, payload) => deliveries.answer(service, query, payload)
?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)
@@ -1124,18 +1132,21 @@ async function runForeground(session: AuthSession | null): Promise<void> {
: service === 'workspaces' ? workspacesLink.answer(query, payload)
: service === 'store' ? storeLink.answer(query, payload)
: service === 'models' ? modelsLink.answer(query, payload)
- : service === 'teams' ? teamsLink.answer(query, payload)
+ : service === 'teams' || service === 'collaboration' ? teamsLink.answer(query, payload)
: service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query)),
// The gateway's own traffic: its remote clients and what they sent, and its comings and goings.
notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload) },
binary: (service, bytes) => { if (service === 'gateway') gatewayLink?.binary(bytes) },
- connected: (service) => { if (service === 'gateway') gatewayLink?.connected() },
+ connected: (service) => {
+ if (service === 'gateway') gatewayLink?.connected()
+ if (service === 'teams') teamsLink.on()
+ },
disconnected: (service) => { if (service === 'gateway') gatewayLink?.disconnected() },
})
serviceLinksRef = serviceLinks
// A request a service declared goes to it: in its own process, or in this one (core/serviceHost.ts).
- backend.serviceRouter = (type, payload, asker, reply) =>
- serviceLinks.route(type, payload, asker, reply) || serviceHost.route(type, payload, asker, reply)
+ backend.serviceRouter = (type, payload, asker, reply) => (teamsOut && teamsLink.route(type, payload, asker, reply))
+ || serviceLinks.route(type, payload, asker, reply) || serviceHost.route(type, payload, asker, reply)
// Session search (services/search.ts): in this process, or in its own (services/searchProcess.ts),
// where the core tells it what changed. A purge's forgetting waits for it if it is down.
if (outOfProcess.has('search')) {
@@ -1161,9 +1172,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (outOfProcess.has('orchestrator')) ports.orchestrator = orchestratorLink.port
else serviceHost.start('orchestrator', inline!.startOrchestrator, coreApi, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS)
backend.onFrameSent = (frame) => ports.orchestrator?.frame(frame)
- // The prompt scopes, behind the service host's guard (a fault there costs no message its write) or in their own process.
- if (outOfProcess.has('teams')) ports.teams = backend.swarmPromptScopes = teamsLink.scopes
- else serviceHost.start('teams', (_core, started) => { started.teams = backend.swarmPromptScopes }, coreApi, TEAMS_FALLBACKS)
+ // Tab collaboration and teams (services/collaboration.ts): in their own process, or in this one behind the
+ // service host's guard (a fault there costs no message its write), the prompt scopes the service's own.
+ if (teamsOut) ports.teams = teamsLink.scopes
+ else serviceHost.start('teams', inline!.startTeamsInCore, coreApi, TEAMS_FALLBACKS, TEAMS_REQUESTS)
// The harnesses installed here, and installing, updating and removing one (services/store.ts): in this
// process, or beside the viewers in theirs (services/storeProcess.ts).
if (!outOfProcess.has('store')) serviceHost.serve('store', inline!.startStore, coreApi, STORE_REQUESTS)
@@ -1710,7 +1722,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
coreLink.startHeartbeat()
// The experiments with saved state are on: their processes are asked for now, the master heeding a
// bound core alone (core/experiments.ts). The others wait for their first request.
- wakeExperiments({ dataDir: env.ADAPTER_DATA_DIR, experiments: EXPERIMENTS, outOfProcess, want: (service) => coreLink.want(service) })
+ wakeExperiments({ dataDir: env.ADAPTER_DATA_DIR, experiments: EXPERIMENTS, outOfProcess, want: (service) => experimentHooks.want(service) })
} else {
try { writeFileSync(PID_FILE, String(process.pid) + '\n') } catch { /* best effort */ }
}
@@ -2396,19 +2408,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.onMessage = (id, content, deliveryId, tabId) => submitAgent(id, content, deliveryId, tabId)
backend.messageProvider = inputs.messageRequest
backend.onCancelOrchestratorMessage = id => input.cancelDelivery(id)
- backend.readChannelDesk = async () => {
- const response = await proxyBackend('GET', '/api/tab-channels')
- if (response.status === 404) throw new TeamError('CHANNELS_UNSUPPORTED', 'Tab channels are not enabled on this Harness server.')
- if (response.status !== 200 || response.body.success !== true) throw new Error('The saved channel directory is unavailable.')
- return response.body.data
- }
- backend.writeChannelSettings = async enabled => {
- const response = await proxyBackend('PATCH', '/api/tab-channels/settings', { enabled })
- if (response.status === 404) throw new TeamError('CHANNELS_UNSUPPORTED', 'Update the Harness server to configure swarm collaboration.')
- if (response.status !== 200 || response.body.success !== true) throw new TeamError('CHANNEL_SETTINGS_FAILED', 'The swarm setting could not be saved. Refresh Settings to check its state.')
- return response.body.data
- }
- backend.startTeams()
+ deliveries.ready() // The input is wired: what was delivered meanwhile (a teams' queue resuming) is written now.
// Keep the log file under its cap. This daemon writes it through an inherited stdout fd, so a size
// check on a timer is the only place that can see it grow — `prepareLogFile` at spawn time alone
diff --git a/cli/src/core/teamsLink.spec.ts b/cli/src/core/teamsLink.spec.ts
index d56a04c70..7daf20219 100644
--- a/cli/src/core/teamsLink.spec.ts
+++ b/cli/src/core/teamsLink.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { TeamsEvent } from './api.js'
-import { createTeamsLink, KEPT_BYTES, KEPT_EVENTS } from './teamsLink.js'
+import { createTeamsLink, KEPT_BYTES, KEPT_EVENTS, teamsOutOfProcess } from './teamsLink.js'
const TEAM_A = 'a'.repeat(32)
const TEAM_B = 'b'.repeat(32)
@@ -167,6 +167,63 @@ describe('the teams\' prompt scopes in their own process, as the core keeps them
expect(hello({ core: 'core-1', applied: 2 })).toMatchObject({ reset: false, events: [] })
})
+ it('keeps nothing for a process no one asked for, and everything from the moment teams is on', () => {
+ const { link, scopes, sent, hello } = setup({ off: true })
+ const undo = scopes.prepare('agent-1', 'typed while teams was off', 'tab-1')
+ undo()
+ scopes.started('agent-1', 'typed while teams was off', 'hook')
+ expect(sent).toEqual([])
+ expect(hello({ core: null }).events).toEqual([])
+ link.on()
+ scopes.forget('agent-1')
+ expect(sent.map((event) => [event.seq, event.kind])).toEqual([[1, 'forget']])
+ })
+
+ it('says a team\'s delivery may be written only while the process last said so, and not past when it said', () => {
+ const { link, scopes, tick } = setup()
+ expect(scopes.canWrite('team:d1')).toBe(false)
+ expect(link.answer('writable', { deliveries: { 'team:d1': 1_000 + 3_000, 'team:d2': 'soon' } })).toEqual({})
+ expect(scopes.canWrite('team:d1')).toBe(true)
+ expect(scopes.canWrite('team:d2')).toBe(false)
+ tick(3_000)
+ expect(scopes.canWrite('team:d1')).toBe(false)
+ link.answer('writable', { deliveries: { 'team:d1': 99_999 } })
+ expect(scopes.canWrite('team:d1')).toBe(true)
+ // A report replaces the last whole.
+ link.answer('writable', {})
+ expect(scopes.canWrite('team:d1')).toBe(false)
+ })
+
+ it('answers the scopes\' own questions, from the apps and from the teams beside them, as it did while they were away', () => {
+ const { link, scopes, ack, sent } = setup()
+ scopes.prepare('agent-1', 'hello team', 'tab-1')
+ scopes.started('agent-1', 'hello team', 'hook')
+ ack(2, { 'agent-1': TEAM_A })
+ const replies: Array<Record<string, unknown>> = []
+ const owner = { owner: true }
+ expect(link.route('team_delivery', { action: 'prompt_scope', agentId: 'agent-1' }, owner, (r) => replies.push(r))).toBe(true)
+ expect(link.route('team_delivery', { action: 'prompt_replied', agentId: 'agent-1', teamId: TEAM_A, questionId: TEAM_B }, owner, (r) => replies.push(r))).toBe(true)
+ expect(link.route('team_delivery', { action: 'prompt_scope', agentId: 'agent-1' }, { owner: false }, (r) => replies.push(r))).toBe(true)
+ expect(link.route('team_delivery', { action: 'prompt_scope', agentId: '../x' }, owner, (r) => replies.push(r))).toBe(true)
+ expect(link.route('team_delivery', { action: 'prompt_replied', agentId: 'agent-1', teamId: 'nope', questionId: TEAM_B }, owner, (r) => replies.push(r))).toBe(true)
+ expect(link.route('team_delivery', { action: 'prompt_replied', agentId: 'agent-1', teamId: TEAM_A }, owner, (r) => replies.push(r))).toBe(true)
+ expect(replies).toEqual([
+ { teamId: TEAM_A },
+ { ok: true },
+ { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' },
+ { error: 'INVALID_REQUEST', detail: 'agentId: Invalid' },
+ { error: 'INVALID_REQUEST', detail: 'teamId: Invalid' },
+ { error: 'INVALID_REQUEST', detail: 'questionId: Invalid' },
+ ])
+ expect(sent.at(-1)).toMatchObject({ kind: 'replied', teamId: TEAM_A, questionId: TEAM_B })
+ // Every other request goes on to the teams.
+ expect(link.route('team_delivery', { action: 'send' }, owner, (r) => replies.push(r))).toBe(false)
+ expect(link.route('team', { action: 'prompt_scope' }, owner, (r) => replies.push(r))).toBe(false)
+ // The same two, asked by the teams beside the scopes.
+ expect(link.answer('team_scope', { agentId: 'agent-2' })).toEqual({ teamId: null })
+ expect(link.answer('team_replied', { agentId: 'agent-1', teamId: TEAM_A, questionId: TEAM_B })).toEqual({ ok: true })
+ })
+
it('refuses a question it does not know', () => {
expect(setup().link.answer('agents', {})).toEqual({ error: 'UNKNOWN_QUERY' })
})
@@ -183,4 +240,18 @@ describe('the teams\' prompt scopes in their own process, as the core keeps them
expect(KEPT_EVENTS).toBe(10_000)
expect(KEPT_BYTES).toBe(16 * 1024 * 1024)
})
+
+ it('runs the scopes and the teams beside them in one process or both in the core\'s, and says so when named apart', () => {
+ const log = vi.fn()
+ expect(teamsOutOfProcess(new Set(['search', 'teams', 'collaboration']), log)).toBe(true)
+ expect(teamsOutOfProcess(new Set(['search']), log)).toBe(false)
+ expect(log).not.toHaveBeenCalled()
+ const apart = new Set(['search', 'collaboration'])
+ expect(teamsOutOfProcess(apart, log)).toBe(false)
+ expect([...apart]).toEqual(['search'])
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('one process or none'))
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ expect(teamsOutOfProcess(new Set(['teams']))).toBe(false)
+ expect(warn).toHaveBeenCalledOnce()
+ })
})
diff --git a/cli/src/core/teamsLink.ts b/cli/src/core/teamsLink.ts
index a86a33fc5..72363c98a 100644
--- a/cli/src/core/teamsLink.ts
+++ b/cli/src/core/teamsLink.ts
@@ -21,6 +21,15 @@
* scope as it acknowledges events (`ack`), and the core answers from that report. While a change to an
* agent's scope is on its way to the process, or after the process started over, the answer is null:
* no team, never a wrong one. That is the fallback while the process is down, too.
+ *
+ * Teams is an experiment (core/api.ts `EXPERIMENTS`): its process runs only once it is on. Until then
+ * (`off`), nothing is kept for it, and nothing it would read is said: the core keeps no journal for a process
+ * no one asked for (`on`, once it is asked for or connects). The rest of what the core keeps of it:
+ * - which of its deliveries may be written now (`canWrite`, asked in line as a team's turn is written,
+ * core/input.ts), as the process last reported them (`writable`); none before, so a team's turn waits;
+ * - the two `team_delivery` questions about the scopes themselves (`prompt_scope`, `prompt_replied`), which
+ * the core answered while the scopes' process was down and still does (`route`), and the same two asked
+ * by the process itself for its teams (`team_scope`, `team_replied`).
*/
import { randomUUID } from 'node:crypto'
import type { PromptScopes, TeamsEvent } from './api.js'
@@ -39,6 +48,8 @@ export interface TeamsLinkOptions {
log?: (line: string) => void
keptEvents?: number
keptBytes?: number
+ /** Teams is not on yet: nothing is kept for its process until `on`. */
+ off?: boolean
}
type Change = TeamsEvent extends infer E ? E extends TeamsEvent ? Omit<E, 'seq' | 'core' | 'at'> : never : never
@@ -61,8 +72,13 @@ export function createTeamsLink(options: TeamsLinkOptions) {
const reported = new Map<string, string>()
/** The last event that could move an agent's team: until the process has it, the team is unknown. */
const moved = new Map<string, number>()
+ /** Whether teams is on: its process asked for, or connected. */
+ let active = options.off !== true
+ /** Each delivery the process says may be written now, and until when. */
+ let writable = new Map<string, number>()
const record = (change: Change, movesScope: boolean): number => {
+ if (!active) return 0
const event = { ...change, seq: ++seq, core, at: now() } as TeamsEvent
const size = 256 + ('text' in event ? event.text.length : 0) + ('bytes' in event ? event.bytes.length : 0)
journal.push({ event, size })
@@ -77,10 +93,10 @@ export function createTeamsLink(options: TeamsLinkOptions) {
return event.seq
}
- const scopes: PromptScopes = {
+ const scopes: PromptScopes & { canWrite(deliveryId: string): boolean } = {
prepare: (agentId, text, tabId, deliveryId) => {
const of = record({ kind: 'prepare', agentId, text, tabId, deliveryId }, false)
- return () => { record({ kind: 'unprepare', agentId, of }, false) }
+ return () => { if (of) record({ kind: 'unprepare', agentId, of }, false) }
},
started: (agentId, text, source = 'transcript', engine) => { record({ kind: 'started', agentId, text, source, engine }, true) },
raw: (agentId, bytes, tabId, pasted = false) => {
@@ -89,6 +105,20 @@ export function createTeamsLink(options: TeamsLinkOptions) {
forget: (agentId) => { record({ kind: 'forget', agentId }, true) },
replied: (agentId, teamId, questionId) => { record({ kind: 'replied', agentId, teamId, questionId }, true) },
current: (agentId) => ((moved.get(agentId) ?? 0) > acked ? null : reported.get(agentId) ?? null),
+ canWrite: (deliveryId) => (writable.get(deliveryId) ?? 0) > now(),
+ }
+
+ const agentOf = (value: unknown): string | null => (typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : null)
+ const operationOf = (value: unknown): string | null => (typeof value === 'string' && /^[a-f0-9]{32}$/.test(value) ? value : null)
+ /** A scope's own question, answered here: `{ teamId }` for `prompt_scope`, the reply taken for `prompt_replied`. */
+ const scopeAnswer = (action: unknown, payload: Record<string, unknown>): Record<string, unknown> => {
+ const agentId = agentOf(payload.agentId)
+ if (!agentId) return { error: 'INVALID_REQUEST', detail: 'agentId: Invalid' }
+ if (action === 'prompt_scope') return { teamId: scopes.current(agentId) }
+ const teamId = operationOf(payload.teamId), questionId = operationOf(payload.questionId)
+ if (!teamId || !questionId) return { error: 'INVALID_REQUEST', detail: `${teamId ? 'questionId' : 'teamId'}: Invalid` }
+ scopes.replied(agentId, teamId, questionId)
+ return { ok: true }
}
/** The process connected: the events it lacks, or everything this side holds and a fresh start. */
@@ -120,13 +150,43 @@ export function createTeamsLink(options: TeamsLinkOptions) {
return {
scopes,
+ /** Teams is on: keep everything for its process from now on. */
+ on(): void { active = true },
/** The core's answers to the teams' questions (core/serviceLinks.ts `answer`, for `teams`). */
answer(query: string, payload: Record<string, unknown>): Record<string, unknown> {
if (query === 'hello') return hello(payload)
if (query === 'ack') return ack(payload)
+ if (query === 'team_scope') return scopeAnswer('prompt_scope', payload)
+ if (query === 'team_replied') return scopeAnswer('prompt_replied', payload)
+ if (query === 'writable') {
+ const reported = payload.deliveries && typeof payload.deliveries === 'object' ? payload.deliveries as Record<string, unknown> : {}
+ writable = new Map(Object.entries(reported).flatMap(([id, until]) => (typeof until === 'number' ? [[id, until] as const] : [])))
+ return {}
+ }
return { error: 'UNKNOWN_QUERY' }
},
+ /** A `team_delivery` question about the scopes themselves, answered here as it was while the scopes'
+ * process was down: false for every other request, which goes to the teams' process. */
+ route(type: string, payload: Record<string, unknown>, asker: { owner: boolean }, reply: (result: Record<string, unknown>) => void): boolean {
+ if (type !== 'team_delivery' || (payload.action !== 'prompt_scope' && payload.action !== 'prompt_replied')) return false
+ reply(asker.owner ? scopeAnswer(payload.action, payload) : { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' })
+ return true
+ },
}
}
export type TeamsLink = ReturnType<typeof createTeamsLink>
+
+/**
+ * Whether Tab collaboration runs in its own process: the prompt scopes (`teams`) and the teams beside them
+ * (`collaboration`) both, or both in the core's. Named apart (`HARNESSD_SERVICES=collaboration`), they would
+ * be two mailboxes on one folder: both run in the core's process then, and it says so.
+ */
+export function teamsOutOfProcess(outOfProcess: Set<string>, log: (line: string) => void = (line) => console.warn(line)): boolean {
+ if (outOfProcess.has('teams') !== outOfProcess.has('collaboration')) {
+ log('[services] the prompt scopes and the teams run in one process or none: both run in this one')
+ outOfProcess.delete('teams')
+ outOfProcess.delete('collaboration')
+ }
+ return outOfProcess.has('teams')
+}
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index bc4436109..b14f49264 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -339,8 +339,10 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their
// Directors; the agents it runs are the core's.
orchestrator: { services: ['orchestrator'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
- // The prompt scopes hold a few drafts and fingerprints per agent: small, bounded state.
- teams: { services: ['teams'], heapLimitMiB: 256, rssLimitMiB: 512 },
+ // Tab collaboration and teams, an experiment: the prompt scopes, a few drafts and fingerprints per agent, and
+ // beside them the teams, their mailbox and the tab channels (services/collaborationProcess.ts), each on its
+ // own link to the core. Started only once it is on (core/api.ts `EXPERIMENTS`).
+ teams: { services: ['teams', 'collaboration'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },
// The relay and its E2EE (gateway/gatewayProcess.ts): the backend link, every remote client's session,
// the terminals' WebRTC channels and their queues. Network, crypto and pure-JS WebRTC, the attack surface,
// where a fault costs the remote clients and nothing else (docs/design/2026-10-06-core-boundary-next.md).
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index 8245762a1..d72f68fd9 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -1,7 +1,7 @@
/** User Close is a disk-backed lifecycle operation. Hiding/switching a tab never calls this. */
import { stripVTControlCharacters } from 'node:util'
import { randomUUID } from 'node:crypto'
-import { teamWriteHold } from '../teams/preflight.js'
+import { teamWriteHold } from './teamWriteHold.js'
import { terminalActivity } from '../cable/terminalActivity.js'
import type { RegisteredSession, registry as liveRegistry } from './registry.js'
import { terminalRouteKey } from './terminalRuntime.js'
diff --git a/cli/src/lib/teamWriteHold.ts b/cli/src/lib/teamWriteHold.ts
new file mode 100644
index 000000000..d649d4719
--- /dev/null
+++ b/cli/src/lib/teamWriteHold.ts
@@ -0,0 +1,38 @@
+import { stripVTControlCharacters } from 'node:util'
+import type { RegisteredSession } from './registry.js'
+import { inspectRuntimePane } from './runtimeProfileController.js'
+import { parseEngineQuestionPane } from './askQuestion.js'
+
+/**
+ * Conservative, read-only inspection at the serialized input write boundary. The core's: it writes a team's
+ * turn only into a ready composer (core/input.ts), and closes an agent only from one (lib/closeAgentService.ts).
+ * Here rather than in teams/ since Tab collaboration left the core's process (step 8); teams/preflight.ts says
+ * it as it always did.
+ */
+export function teamWriteHold(engine: RegisteredSession['engine'], capture: string | null): string | null {
+ if (!capture) return 'team_waiting_unavailable'
+ const pane = inspectRuntimePane(engine, capture)
+ if (pane.dialog || parseEngineQuestionPane(engine, capture)) return 'team_waiting_user'
+ if (pane.draft) return 'team_waiting_draft'
+ if (!pane.idle) return 'team_waiting_idle'
+ const lines = capture.split('\n').map(stripVTControlCharacters)
+ if (/esc(?:ape)? to (?:interrupt|cancel|stop)/i.test(lines.slice(-15).join('\n'))) return 'team_waiting_idle'
+ // These composers permit an empty first line followed by a multiline human draft.
+ // The general profile inspector only needs the first line; team delivery needs every line.
+ if (['claude', 'codex', 'cursor', 'hermes'].includes(engine)) {
+ const index = lines.findLastIndex(line => /^\s*[›❯→]/u.test(line))
+ if (index < 0) return 'team_waiting_idle'
+ // Codex shows its styled placeholder only when the whole composer is empty.
+ // Its configurable model/cwd/task footer below that placeholder is not draft
+ // text. The profile inspector has already proved this visible prompt text is
+ // a placeholder; a bare first line still needs the multiline-draft check.
+ if (engine === 'codex' && lines[index].replace(/^\s*[›❯→]\s*/u, '').trim()) return null
+ for (const line of lines.slice(index + 1)) {
+ if (/[─━―]{8,}/u.test(line)) break
+ const text = line.trim()
+ if (!text || /^(?:\? for shortcuts|\d+% context|context:|ctrl\+|shift\+|tab to|plan mode|accept edits|bypass permissions)/i.test(text)) continue
+ return 'team_waiting_draft'
+ }
+ }
+ return null
+}
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index c7cba9d87..469068a08 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -33,6 +33,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['projects', async () => (await import('./services/projectsProcess.js')).runProjectsService],
['store', async () => (await import('./services/storeProcess.js')).runStoreService],
['teams', async () => (await import('./services/teamsProcess.js')).runTeamsService],
+ ['collaboration', async () => (await import('./services/collaborationProcess.js')).runCollaborationService],
['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],
['models', async () => (await import('./services/modelsProcess.js')).runModelsService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index dd8b6de39..a41fa9fb7 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -43,7 +43,7 @@ let several people build features at once without touching the core or each othe
A service that can crash natively, hang or leak should run in a process of its own, where it costs only
that process. A process per risk, not per feature: search (native `node:sqlite`), the viewers (their
-servers) with the Store (its minutes-long installs), the teams' prompt scopes, models (grid's installs,
+servers) with the Store (its minutes-long installs), each experiment (below), models (grid's installs,
downloads and commands), and the edge host, one process for the light services that only answer requests
(workspaces, usage, the monitor, the project readers). A fault in one of the edge host's services can
cost the others in it, never the core. Every service in `KNOWN_SERVICES` runs out of the core's process
@@ -122,7 +122,7 @@ way back).
## Experiments
-An experiment (the orchestrator; Tab collaboration and Share next) is a service that costs nothing until it is
+An experiment (the orchestrator, Tab collaboration; Share next) is a service that costs nothing until it is
on: its own process, which the master starts only when the core asks for it (`want`), when one of its
requests arrives or, as the core starts, when its saved state is in the data folder. Off, nothing of it runs or
is loaded anywhere; one failing costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it:
@@ -143,7 +143,12 @@ To add one:
it there when `HARNESSD_SERVICES` keeps it in (`serviceHost.serve`, or `start` with a port).
Removing one is deleting those. A port the core calls in line (the orchestrator's `roleOf`) is answered
-from what the process last reported (`src/core/orchestratorLink.ts`), as the viewers' are.
+from what the process last reported (`src/core/orchestratorLink.ts`), as the viewers' are. Tab collaboration
+(`src/services/collaboration.ts`, beside the prompt scopes in the teams' process) shows the rest: whether a
+team's turn may still be written, which the core asks as it writes it, is reported for a few seconds at a
+time, so a process that stops reporting leaves none writable (`collaborationProcess.ts`, `core/teamsLink.ts`);
+a cancel its mailbox reads in line is asked of the core first (`takingBack`); and the core keeps nothing for
+the scopes until the experiment is on.
## Do not
diff --git a/cli/src/services/collaboration.spec.ts b/cli/src/services/collaboration.spec.ts
new file mode 100644
index 000000000..d346d4c48
--- /dev/null
+++ b/cli/src/services/collaboration.spec.ts
@@ -0,0 +1,306 @@
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { emptyPorts, type BackendNotice, type TurnDelivery } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { ChannelDependencies } from '../teams/channels.js'
+import type { MailboxDependencies } from '../teams/mailbox.js'
+import { TeamError } from '../teams/model.js'
+import type { TeamDependencies } from '../teams/service.js'
+import { fakeCore } from '../testing/fakeCore.js'
+
+/**
+ * The teams' own classes are the teams' specs' to prove (src/teams); here, what the service gives them and
+ * how it answers for them, each moved out of the socket as it was.
+ */
+const made = vi.hoisted(() => ({
+ teams: [] as Array<{ deps: TeamDependencies; calls: string[]; channel: boolean; startThrows: boolean }>,
+ mailboxes: [] as Array<{ deps: MailboxDependencies; calls: string[]; writable: Set<string> }>,
+ channels: [] as Array<{ deps: ChannelDependencies; calls: string[] }>,
+ answered: [] as string[],
+ startThrows: false,
+ refreshFails: false,
+}))
+vi.mock('../teams/service.js', async (original) => ({
+ ...await original<typeof import('../teams/service.js')>(),
+ TeamService: class {
+ record: (typeof made.teams)[number]
+ constructor(deps: TeamDependencies) { this.record = { deps, calls: [], channel: false, startThrows: made.startThrows }; made.teams.push(this.record) }
+ start() { this.record.calls.push('start'); if (this.record.startThrows) throw new Error('unreadable') }
+ stop() { this.record.calls.push('stop') }
+ isChannel() { return this.record.channel }
+ },
+}))
+vi.mock('../teams/mailbox.js', () => ({
+ TeamMailbox: class {
+ record: (typeof made.mailboxes)[number]
+ constructor(deps: MailboxDependencies) { this.record = { deps, calls: [], writable: new Set() }; made.mailboxes.push(this.record) }
+ start() { this.record.calls.push('start') }
+ stop() { this.record.calls.push('stop') }
+ pump() { this.record.calls.push('pump') }
+ observe(event: TurnDelivery) { this.record.calls.push(`observe ${event.deliveryId}`) }
+ canWrite(id: string) { return this.record.writable.has(id) }
+ accept(delivery: { id: string }) { this.record.calls.push(`accept ${delivery.id}`); return { id: delivery.id, state: 'queued' } }
+ status(id: string) { this.record.calls.push(`status ${id}`); return null }
+ hold(id: string, held: boolean) { this.record.calls.push(`hold ${id} ${held}`); return null }
+ cancel(id: string, received: boolean) { this.record.calls.push(`cancel ${id} ${received}`); return { id, state: 'cancelled' } }
+ },
+}))
+vi.mock('../teams/channels.js', () => ({
+ ChannelDirectory: class {
+ record: (typeof made.channels)[number]
+ constructor(deps: ChannelDependencies) { this.record = { deps, calls: [] }; made.channels.push(this.record) }
+ start() { this.record.calls.push('start') }
+ stop() { this.record.calls.push('stop') }
+ refresh(force: boolean) { this.record.calls.push(`refresh ${force}`); return made.refreshFails ? Promise.reject(new Error('offline')) : Promise.resolve({}) }
+ taskContext(agentId: string, teamId: string | null) { return Promise.resolve({ context: agentId, teamId }) }
+ request(payload: { action: string }) { return Promise.resolve({ channel: payload.action }) }
+ },
+}))
+vi.mock('../teams/wire.js', async (original) => ({
+ ...await original<typeof import('../teams/wire.js')>(),
+ teamRequest: async (_service: unknown, payload: { action: string }) => { made.answered.push(`team ${payload.action}`); return { team: payload.action } },
+ teamDeliveryRequest: (_mailbox: unknown, payload: { action: string }) => { made.answered.push(`delivery ${payload.action}`); return { receipt: payload.action } },
+}))
+const { startCollaboration, startTeamsInCore, TEAMS_REQUESTS } = await import('./collaboration.js')
+
+const OWNER = { local: true, owner: true }
+const TEAM = 'a'.repeat(32), QUESTION = 'b'.repeat(32), RECEIPT = `team:${'c'.repeat(32)}:${'d'.repeat(32)}:question`
+const agent = (agentId: string, active = true) => ({ agentId, sessionId: `s-${agentId}`, engine: 'codex', cwd: '/w', active }) as RegisteredSession
+
+describe('Tab collaboration and teams, as a service', () => {
+ let dataDir: string
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'collaboration-'))
+ made.teams.length = 0; made.mailboxes.length = 0; made.channels.length = 0; made.answered.length = 0
+ made.startThrows = false
+ made.refreshFails = false
+ })
+ afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+
+ const setup = (over: { scope?: string | null; backend?: (method: string, path: string, body?: unknown) => Promise<{ status: number; body: Record<string, unknown> }> } = {}, options: Record<string, unknown> = {}) => {
+ const listeners: Array<(event: TurnDelivery) => void> = []
+ const notices: Array<(notice: BackendNotice) => void> = []
+ const stopHearing = vi.fn(), stopNotices = vi.fn()
+ const deliver = vi.fn(), cancelDelivery = vi.fn(() => true), windows = vi.fn()
+ const live = new Map([['a1', agent('a1')], ['a2', agent('a2', false)], ['a3', { ...agent('a3'), cwd: null } as unknown as RegisteredSession]])
+ const core = fakeCore({
+ dataDir,
+ agents: { byAgent: (id) => live.get(id), displayName: (session) => `name ${session.agentId}`, terminalAvailable: (id) => id === 'a1' },
+ turns: { deliver, cancelDelivery, onDelivery: (listener) => { listeners.push(listener); return stopHearing } },
+ account: {
+ backend: over.backend ?? (async () => ({ status: 200, body: { success: true, data: { tabs: [] } } })),
+ onNotice: (listener) => { notices.push(listener); return stopNotices },
+ },
+ clients: { windows },
+ daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: () => 'm1' },
+ })
+ const replied = vi.fn()
+ const rpc = vi.fn(async (_at: unknown, _type: string, payload: Record<string, unknown>) => ({ teamId: payload.action === 'prompt_scope' ? 'remote-team' : undefined, runtime: { name: 'far' }, receipt: payload.action === 'status' ? null : { id: RECEIPT, state: 'queued', updatedAt: 1 } }))
+ const teams = startCollaboration(core, { scopes: { current: () => over.scope ?? null, replied }, rpc: rpc as never, ...options })
+ return { core, teams, listeners, notices, stopHearing, stopNotices, deliver, cancelDelivery, windows, replied, rpc }
+ }
+
+ it('declares the teams\' two requests', () => {
+ expect(TEAMS_REQUESTS).toEqual(['team', 'team_delivery'])
+ })
+
+ it('answers an owner alone, and says why a request it cannot read failed', async () => {
+ const { teams } = setup()
+ expect(await teams.requests.team({ action: 'list' }, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' })
+ expect(await teams.requests.team({ action: 'list' }, OWNER)).toEqual({ team: 'list' })
+ expect(await teams.requests.team({ action: 'context', agentId: '../bad' }, OWNER)).toMatchObject({ error: 'INVALID_REQUEST' })
+ })
+
+ it('answers a task\'s context from the scope its prompt came from, and a channel\'s own requests from the channels', async () => {
+ const { teams } = setup({ scope: TEAM })
+ expect(await teams.requests.team({ action: 'context', agentId: 'a1' }, OWNER)).toEqual({ context: 'a1', teamId: TEAM })
+ expect(await teams.requests.team({ action: 'channel_list' }, OWNER)).toEqual({ channel: 'channel_list' })
+ // A channel's team is read fresh before its members are asked of, or a question asked in it.
+ await teams.requests.team({ action: 'get', teamId: TEAM }, OWNER)
+ made.teams[0].channel = true
+ await teams.requests.team({ action: 'ask', teamId: TEAM }, OWNER)
+ await teams.requests.team({ action: 'members', teamId: TEAM }, OWNER)
+ await teams.requests.team({ action: 'archive', teamId: TEAM }, OWNER)
+ expect(made.channels[0].calls).toEqual(['refresh true', 'refresh false'])
+ })
+
+ it('answers a delivery\'s own questions: an agent\'s runtime, its prompt\'s scope, a reply moving it back, and the mailbox', async () => {
+ const { teams, replied } = setup({ scope: TEAM })
+ expect(await teams.requests.team_delivery({ action: 'runtime', agentId: 'a1' }, OWNER)).toEqual({ runtime: { name: 'name a1', engine: 'codex', cwd: '/w', available: true } })
+ expect(await teams.requests.team_delivery({ action: 'runtime', agentId: 'a2' }, OWNER)).toEqual({ runtime: { name: 'name a2', engine: 'codex', cwd: '/w', available: false, reason: 'Session is paused or offline.' } })
+ expect(await teams.requests.team_delivery({ action: 'runtime', agentId: 'nobody' }, OWNER)).toEqual({ runtime: null })
+ expect(await teams.requests.team_delivery({ action: 'runtime', agentId: 'a3' }, OWNER)).toEqual({ runtime: { name: 'name a3', engine: 'codex', cwd: undefined, available: false } })
+ expect(await teams.requests.team_delivery({ action: 'prompt_scope', agentId: 'a1' }, OWNER)).toEqual({ teamId: TEAM })
+ expect(await teams.requests.team_delivery({ action: 'prompt_replied', agentId: 'a1', teamId: TEAM, questionId: QUESTION }, OWNER)).toEqual({ ok: true })
+ expect(replied).toHaveBeenCalledWith('a1', TEAM, QUESTION)
+ expect(await teams.requests.team_delivery({ action: 'send', delivery: { id: 'd1' } }, OWNER)).toEqual({ receipt: 'send' })
+ expect(await teams.requests.team_delivery({ action: 'cancel' }, OWNER)).toEqual({ receipt: 'cancel' })
+ })
+
+ it('in the teams\' own process, asks the core before the mailbox takes a delivery back, and says what may be written changed', async () => {
+ const order: string[] = []
+ const takingBack = vi.fn(async (id: string) => { order.push(`ask ${id}`); return () => order.push(`release ${id}`) })
+ const changed = vi.fn(() => order.push('changed'))
+ const { teams } = setup({}, { takingBack, changed })
+ for (const action of ['cancel', 'consume', 'hold']) await teams.requests.team_delivery({ action, delivery: { id: `d-${action}` } }, OWNER)
+ await teams.requests.team_delivery({ action: 'release', delivery: { id: 'd-release' } }, OWNER)
+ await teams.requests.team_delivery({ action: 'cancel', delivery: {} }, OWNER)
+ expect(takingBack.mock.calls.map(([id]) => id)).toEqual(['d-cancel', 'd-consume', 'd-hold'])
+ expect(order.slice(0, 3)).toEqual(['ask d-cancel', 'release d-cancel', 'changed'])
+ expect(changed).toHaveBeenCalledTimes(5)
+ })
+
+ it('gives the teams what the socket gave them, from the core\'s API', async () => {
+ const { teams, deliver, cancelDelivery, windows, rpc, replied } = setup({ scope: TEAM })
+ await teams.requests.team({ action: 'list' }, OWNER)
+ const deps = made.teams[0].deps
+ expect(deps.stateDir).toBe(join(dataDir, 'teams', 'ledgers'))
+ expect(deps.machineId).toBe('m1')
+ const here = { machineId: 'm1', agentId: 'a1' }, there = { machineId: 'm2', agentId: 'b1' }
+ expect(deps.command(here)).toBe(`'node' 'cli.js' team --port 18473`)
+ expect(deps.command(there)).toBe('harness team')
+ expect(await deps.taskScope!(here)).toBe(TEAM)
+ expect(await deps.taskScope!(there)).toBe('remote-team')
+ rpc.mockResolvedValueOnce({} as never)
+ expect(await deps.taskScope!(there)).toBeNull()
+ await deps.questionReplied!(here, TEAM, QUESTION)
+ expect(replied).toHaveBeenCalledWith('a1', TEAM, QUESTION)
+ await deps.questionReplied!(there, TEAM, QUESTION)
+ expect(rpc).toHaveBeenCalledWith({ port: 18473, machineId: 'm2', dataDir }, 'team_delivery', { action: 'prompt_replied', agentId: 'b1', teamId: TEAM, questionId: QUESTION })
+ expect(await deps.runtime(here)).toMatchObject({ name: 'name a1', available: true })
+ expect(await deps.runtime(there)).toEqual({ name: 'far' })
+ // The mailbox here, for a member here.
+ expect(await deps.delivery(here, 'send', { id: 'd1' } as never)).toEqual({ id: 'd1', state: 'queued' })
+ await deps.delivery(here, 'status', { id: 'd1' })
+ await deps.delivery(here, 'hold', { id: 'd1' })
+ await deps.delivery(here, 'release', { id: 'd1' })
+ await deps.delivery(here, 'cancel', { id: 'd1' })
+ await deps.delivery(here, 'consume', { id: 'd1' })
+ expect(made.mailboxes[0].calls).toEqual(['accept d1', 'status d1', 'hold d1 true', 'hold d1 false', 'cancel d1 false', 'cancel d1 true'])
+ // Another machine's, through its own daemon.
+ expect(await deps.delivery(there, 'send', { id: 'd2' } as never)).toEqual({ id: RECEIPT, state: 'queued', updatedAt: 1 })
+ expect(await deps.delivery(there, 'status', { id: 'd2' })).toBeNull()
+ deps.changed!('t1', 3)
+ expect(windows).toHaveBeenCalledWith({ type: 'team_changed', payload: { id: 't1', revision: 3 } })
+ // The mailbox writes and takes back through the core's delivered turns.
+ const mailbox = made.mailboxes[0].deps
+ expect(mailbox.stateDir).toBe(join(dataDir, 'teams', 'mailboxes'))
+ mailbox.send('a1', 'a question', 'team:d1')
+ expect(deliver).toHaveBeenCalledWith('a1', 'a question', 'team:d1')
+ expect(mailbox.cancel('team:d1')).toBe(true)
+ expect(cancelDelivery).toHaveBeenCalledWith('team:d1')
+ expect(mailbox.runtime('a1')).toMatchObject({ available: true })
+ expect(mailbox.channelsEnabled!()).toBe(false)
+ })
+
+ it('reads and sets the tab channels through the account, says why it could not, and reaches other machines through its daemon', async () => {
+ const answers = [
+ { status: 200, body: { success: true, data: { tabs: ['t'] } } },
+ { status: 404, body: {} },
+ { status: 500, body: {} },
+ { status: 200, body: { success: true, data: { enabled: true } } },
+ { status: 404, body: {} },
+ { status: 200, body: { success: false } },
+ ]
+ const backend = vi.fn(async () => answers.shift()!)
+ const changed = vi.fn()
+ const { teams, rpc } = setup({ backend }, { changed })
+ teams.refreshChannels()
+ const deps = made.channels[0].deps
+ expect(deps.machineId).toBe('m1')
+ expect(await deps.readDesk()).toEqual({ tabs: ['t'] })
+ await expect(deps.readDesk()).rejects.toMatchObject({ code: 'CHANNELS_UNSUPPORTED' })
+ await expect(deps.readDesk()).rejects.toThrow('The saved channel directory is unavailable.')
+ expect(await deps.writeSettings!(true)).toEqual({ enabled: true })
+ expect(backend).toHaveBeenLastCalledWith('PATCH', '/api/tab-channels/settings', { enabled: true })
+ await expect(deps.writeSettings!(false)).rejects.toMatchObject({ code: 'CHANNELS_UNSUPPORTED' })
+ await expect(deps.writeSettings!(false)).rejects.toMatchObject({ code: 'CHANNEL_SETTINGS_FAILED' })
+ // Switched on: the mailbox delivers what waited for it, and what may be written changed.
+ deps.enabledChanged!(true)
+ expect(changed).toHaveBeenCalledOnce()
+ await teams.requests.team_delivery({ action: 'send', delivery: { id: 'd1' } }, OWNER)
+ deps.enabledChanged!(true)
+ expect(made.mailboxes[0].calls).toContain('pump')
+ expect(made.mailboxes[0].deps.channelsEnabled!()).toBe(true)
+ await deps.forward('m2', { action: 'channel_get' })
+ expect(rpc).toHaveBeenLastCalledWith({ port: 18473, machineId: 'm2', dataDir }, 'team', { action: 'channel_get' })
+ expect(made.channels[0].calls).toEqual(['refresh true'])
+ expect(TeamError).toBeTypeOf('function')
+ })
+
+ it('hears what became of its deliveries once its mailbox is up, and the account\'s desk changing', async () => {
+ const { teams, listeners, notices } = setup()
+ const event: TurnDelivery = { deliveryId: 'team:d1', sessionId: 'a1', state: 'started' }
+ listeners[0](event)
+ expect(teams.canWrite('team:d1')).toBe(false)
+ await teams.requests.team_delivery({ action: 'send', delivery: { id: 'team:d1' } }, OWNER)
+ listeners[0](event)
+ expect(made.mailboxes[0].calls).toContain('observe team:d1')
+ made.mailboxes[0].writable.add('team:d1')
+ expect(teams.canWrite('team:d1')).toBe(true)
+ notices[0]({ type: 'zoo_changed', revision: 1 })
+ expect(made.channels).toHaveLength(0)
+ notices[0]({ type: 'desk_changed', revision: 2 })
+ expect(made.channels[0].calls).toEqual(['refresh true'])
+ // A desk that cannot be read now is read at the next poll: nothing is thrown.
+ made.refreshFails = true
+ notices[0]({ type: 'desk_changed', revision: 3 })
+ teams.refreshChannels()
+ await new Promise((settle) => setTimeout(settle, 0))
+ expect(made.channels[0].calls).toEqual(['refresh true', 'refresh true', 'refresh true'])
+ })
+
+ it('starts the channels at once, and the teams and their mailbox when they keep state here', () => {
+ const quiet = setup()
+ quiet.teams.start()
+ expect(made.channels[0].calls).toEqual(['start'])
+ // The channels hold the teams; nothing of theirs is started without state here.
+ expect(made.teams[0].calls).toEqual([])
+ expect(made.mailboxes).toHaveLength(0)
+ mkdirSync(join(dataDir, 'teams'))
+ const kept = setup()
+ kept.teams.start()
+ expect(made.mailboxes[0].calls).toEqual(['start'])
+ expect(made.teams[1].calls).toEqual(['start'])
+ kept.teams.stop()
+ expect(kept.stopHearing).toHaveBeenCalledOnce()
+ expect(kept.stopNotices).toHaveBeenCalledOnce()
+ expect(made.teams[1].calls.at(-1)).toBe('stop')
+ expect(made.mailboxes[0].calls.at(-1)).toBe('stop')
+ expect(made.channels[1].calls.at(-1)).toBe('stop')
+ // Nothing built: nothing to stop but the hearing.
+ quiet.teams.stop()
+ })
+
+ it('keeps unreadable team state for recovery and starts all the same', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ mkdirSync(join(dataDir, 'teams'))
+ made.startThrows = true
+ const { teams } = setup()
+ teams.start()
+ expect(warn).toHaveBeenCalledWith('[teams] preserved unreadable team state; inspect Team for recovery')
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
+ it('in the core\'s process, keeps its own prompt scopes, which the core records into, and starts at once', async () => {
+ const ports = emptyPorts()
+ const core = fakeCore({ dataDir, daemon: { command: 'harness', port: 1, machineId: () => 'm1' } })
+ const requests = startTeamsInCore(core, ports, { stateDir: join(dataDir, 'teams') })
+ expect(made.channels[0].calls).toEqual(['start'])
+ const port = ports.teams!
+ const undo = port.prepare('a1', 'hello team', 'tab-1')
+ port.started('a1', 'hello team', 'hook')
+ expect(await requests.team_delivery({ action: 'prompt_scope', agentId: 'a1' }, OWNER)).toEqual({ teamId: expect.stringMatching(/^[a-f0-9]{32}$/) })
+ undo()
+ port.raw('a1', new Uint8Array([104]))
+ port.forget('a1')
+ expect(port.canWrite('team:d1')).toBe(false)
+ ;(port as unknown as { stop(): void }).stop()
+ expect(made.channels[0].calls.at(-1)).toBe('stop')
+ })
+})
diff --git a/cli/src/services/collaboration.ts b/cli/src/services/collaboration.ts
new file mode 100644
index 000000000..09816e06f
--- /dev/null
+++ b/cli/src/services/collaboration.ts
@@ -0,0 +1,223 @@
+/**
+ * Tab collaboration and teams (`collaboration`), an experiment: agents on this machine and the owner's others asking each other
+ * questions in a team or a tab's swarm (teams/service.ts), the mailbox that writes those turns into this
+ * machine's agents and keeps their receipts (teams/mailbox.ts), and the tab channels read from the account
+ * (teams/channels.ts). Moved out of the socket as it was (docs/design/2026-10-06-core-boundary-next.md, step
+ * 8, move only): what the socket gave them, they now get from the core's API, in the core's process
+ * (`HARNESSD_SERVICES=none`) or in the teams' own (services/collaborationProcess.ts), beside the prompt
+ * scopes (services/teamsProcess.ts), as a service of its own there.
+ * - The `team` and `team_delivery` requests, for an owner alone, as the socket answered them.
+ * - A team's turns, delivered through the core (`core.turns.deliver`), what became of each, and whether one
+ * still holds its agent's pane (`canWrite`), which the core asks in line as it writes it.
+ * - The prompt scopes it reads (`scopes`): the service's own in the core's process; in the teams' process,
+ * the core's word on them (core/teamsLink.ts), where a change on its way reads as no team.
+ * - The tab channels, read and set through the account (`core.account.backend`), polled while it runs and
+ * read again at the account's `desk_changed`.
+ */
+import { existsSync } from 'node:fs'
+import { join } from 'node:path'
+import type { CoreApi, CorePorts, ServiceRequests, TurnDelivery } from '../core/api.js'
+import { ChannelDirectory } from '../teams/channels.js'
+import { teamRpc } from '../teams/client.js'
+import { TeamMailbox } from '../teams/mailbox.js'
+import { Address, Id, OperationId, Receipt, TeamError, type MemberRuntime } from '../teams/model.js'
+import { SwarmPromptScopes } from '../teams/promptScope.js'
+import { TeamService } from '../teams/service.js'
+import { teamDeliveryRequest, teamFailure, teamRequest } from '../teams/wire.js'
+
+/** The requests the teams answer, declared in core/api.ts for the core to route. */
+export { TEAMS_REQUESTS } from '../core/api.js'
+
+/** The prompt scopes as the teams read them: the team an agent's current prompt came from, and an answer to a
+ * team's question moving it back. */
+export interface TeamScopes {
+ current(agentId: string): string | null | Promise<string | null>
+ replied(agentId: string, teamId: string, questionId: string): void | Promise<unknown>
+}
+
+export interface TeamsOptions {
+ scopes: TeamScopes
+ /** Where the teams keep their ledgers and mailboxes; an isolated fixture's own. */
+ stateDir?: string
+ /** The command a member on this machine runs `team` with; an isolated fixture's own. */
+ command?: string | null
+ /** How a request reaches another of the owner's machines: through this daemon's own local socket. */
+ rpc?: typeof teamRpc
+ /** The local socket's folder (`ADAPTER_DATA_DIR`) the other machines are reached through. */
+ dataDir?: string
+ /**
+ * Before the mailbox takes a delivery back (a cancel, a hold, read through the inbox): the teams' own
+ * process asks the core whether the turn could still be taken back, since the mailbox reads that answer in
+ * line (`core.turns.cancelDelivery`) and the core's cannot wait. Released once the mailbox has read it.
+ */
+ takingBack?: (deliveryId: string) => Promise<() => void>
+ /** Something that decides whether a delivery may be written changed: the teams' process tells the core. */
+ changed?: () => void
+}
+
+/** The mailbox's actions that may take a delivery the core holds back. */
+const TAKES_BACK: ReadonlySet<string> = new Set(['cancel', 'consume', 'hold'])
+
+export interface Teams {
+ requests: ServiceRequests
+ /** Whether a team's delivery still holds its agent's pane: the mailbox's word, in line. */
+ canWrite(deliveryId: string): boolean
+ /** The account's tab channels changed (`desk_changed`): read them again. */
+ refreshChannels(): void
+ /** Resume persisted queues after input wiring is ready, even with no UI attached. */
+ start(): void
+ stop(): void
+}
+
+export function startCollaboration(core: CoreApi, options: TeamsOptions): Teams {
+ const stateDir = options.stateDir ?? join(core.dataDir, 'teams')
+ const rpc = options.rpc ?? teamRpc
+ // Read as each is used: in the teams' own process the core says them once it is connected, after this starts.
+ const machineId = (): string => core.daemon.machineId()
+ const at = (to: string) => ({ port: core.daemon.port, machineId: to, dataDir: options.dataDir ?? core.dataDir })
+ const scopes = options.scopes
+ let channelsEnabled = false
+ let channelDirectory: ChannelDirectory | null = null
+ let teamService: TeamService | null = null
+ let teamMailboxService: TeamMailbox | null = null
+
+ const readDesk = async (): Promise<unknown> => {
+ const response = await core.account.backend('GET', '/api/tab-channels')
+ if (response.status === 404) throw new TeamError('CHANNELS_UNSUPPORTED', 'Tab channels are not enabled on this Harness server.')
+ if (response.status !== 200 || response.body.success !== true) throw new Error('The saved channel directory is unavailable.')
+ return response.body.data
+ }
+ const writeSettings = async (enabled: boolean): Promise<unknown> => {
+ const response = await core.account.backend('PATCH', '/api/tab-channels/settings', { enabled })
+ if (response.status === 404) throw new TeamError('CHANNELS_UNSUPPORTED', 'Update the Harness server to configure swarm collaboration.')
+ if (response.status !== 200 || response.body.success !== true) throw new TeamError('CHANNEL_SETTINGS_FAILED', 'The swarm setting could not be saved. Refresh Settings to check its state.')
+ return response.body.data
+ }
+ const channels = (): ChannelDirectory => channelDirectory ??= new ChannelDirectory({
+ machineId: machineId(), service: teams(), readDesk,
+ writeSettings,
+ enabledChanged: enabled => { channelsEnabled = enabled; teamMailboxService?.pump(); options.changed?.() },
+ forward: (to, payload) => rpc(at(to), 'team', payload),
+ })
+ const localTeamRuntime = (agentId: string): MemberRuntime | null => {
+ const agent = core.agents.byAgent(agentId)
+ return agent ? { name: core.agents.displayName(agent), engine: agent.engine, cwd: agent.cwd ?? undefined,
+ available: agent.active && core.agents.terminalAvailable(agentId),
+ ...(!agent.active ? { reason: 'Session is paused or offline.' } : {}) } : null
+ }
+ const teamMailbox = (): TeamMailbox => teamMailboxService ??= new TeamMailbox({
+ stateDir: join(stateDir, 'mailboxes'),
+ channelsEnabled: () => channelsEnabled,
+ runtime: id => localTeamRuntime(id),
+ send: (id, text, deliveryId) => core.turns.deliver(id, text, deliveryId),
+ cancel: id => core.turns.cancelDelivery(id),
+ })
+ const teams = (): TeamService => teamService ??= new TeamService({
+ stateDir: join(stateDir, 'ledgers'), machineId: machineId(),
+ taskScope: async address => {
+ if (address.machineId === machineId()) return scopes.current(address.agentId)
+ const result = await rpc(at(address.machineId),
+ 'team_delivery', { action: 'prompt_scope', agentId: address.agentId })
+ return typeof result.teamId === 'string' ? result.teamId : null
+ },
+ questionReplied: async (address, teamId, questionId) => {
+ if (address.machineId === machineId()) await scopes.replied(address.agentId, teamId, questionId)
+ else await rpc(at(address.machineId),
+ 'team_delivery', { action: 'prompt_replied', agentId: address.agentId, teamId, questionId })
+ },
+ command: address => address.machineId === machineId()
+ ? options.command ?? `${core.daemon.command} team --port ${core.daemon.port}`
+ : 'harness team',
+ runtime: async address => {
+ Address.parse(address)
+ if (address.machineId === machineId()) return localTeamRuntime(address.agentId)
+ const result = await rpc(at(address.machineId), 'team_delivery', { action: 'runtime', agentId: address.agentId })
+ return result.runtime as MemberRuntime | null
+ },
+ delivery: async (address, action, delivery) => {
+ if (address.machineId === machineId()) {
+ const mailbox = teamMailbox()
+ return takeBack(TAKES_BACK.has(action) ? delivery.id : null, () => 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 rpc(at(address.machineId), 'team_delivery', { action, delivery })
+ return result.receipt == null ? null : Receipt.parse(result.receipt)
+ },
+ changed: (id, revision) => core.clients.windows({ type: 'team_changed', payload: { id, revision } }),
+ })
+ const stopHearing = core.turns.onDelivery((event: TurnDelivery) => teamMailboxService?.observe(event))
+ const stopNotices = core.account.onNotice((notice) => { if (notice.type === 'desk_changed') void channels().refresh(true).catch(() => {}) })
+
+ return {
+ requests: {
+ team: (payload, asker) => answer('team', payload, asker),
+ team_delivery: (payload, asker) => answer('team_delivery', payload, asker),
+ },
+ canWrite: (deliveryId) => teamMailboxService?.canWrite(deliveryId) ?? false,
+ refreshChannels: () => { void channels().refresh(true).catch(() => {}) },
+ start: () => {
+ channels().start()
+ if (!existsSync(stateDir)) return
+ try { teamMailbox().start(); teams().start() }
+ catch { console.warn('[teams] preserved unreadable team state; inspect Team for recovery') }
+ },
+ stop: () => {
+ stopHearing()
+ stopNotices()
+ teamService?.stop()
+ teamMailboxService?.stop()
+ channelDirectory?.stop()
+ },
+ }
+
+ function answer(type: 'team' | 'team_delivery', payload: Record<string, unknown>, asker: { owner: boolean }): Promise<Record<string, unknown>> | Record<string, unknown> {
+ // Observers never reach a service's request; only the owner or a paired owner client does.
+ if (!asker.owner) return { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' }
+ return Promise.resolve().then(async () => {
+ if (type === 'team') {
+ if (payload.action === 'context') {
+ const agentId = Id.parse(payload.agentId)
+ return channels().taskContext(agentId, await scopes.current(agentId))
+ }
+ if (String(payload.action).startsWith('channel_')) return channels().request(payload)
+ if (typeof payload.teamId === 'string' && teams().isChannel(payload.teamId)
+ && ['ask', 'get', 'members'].includes(String(payload.action))) await channels().refresh(payload.action === 'ask')
+ return teamRequest(teams(), payload)
+ }
+ if (payload.action === 'runtime') return { runtime: localTeamRuntime(Id.parse(payload.agentId)) }
+ if (payload.action === 'prompt_scope') return { teamId: await scopes.current(Id.parse(payload.agentId)) }
+ if (payload.action === 'prompt_replied') {
+ await scopes.replied(Id.parse(payload.agentId), OperationId.parse(payload.teamId), OperationId.parse(payload.questionId))
+ return { ok: true }
+ }
+ const delivery = payload.delivery as { id?: unknown } | undefined
+ return takeBack(TAKES_BACK.has(String(payload.action)) && typeof delivery?.id === 'string' ? delivery.id : null,
+ () => teamDeliveryRequest(teamMailbox(), payload))
+ }).catch(error => teamFailure(error))
+ }
+
+ /** Run a mailbox action, taking a delivery back as the teams' process must (`takingBack`), and say that
+ * what may be written may have changed. */
+ async function takeBack<T>(deliveryId: string | null, act: () => T): Promise<T> {
+ const release = deliveryId && options.takingBack ? await options.takingBack(deliveryId) : null
+ try { return act() } finally {
+ release?.()
+ options.changed?.()
+ }
+ }
+}
+
+/**
+ * The teams in the core's process (`HARNESSD_SERVICES=none`), as the socket ran them: the prompt scopes the
+ * core records into are the service's own, read in line, and the service starts at once.
+ */
+export function startTeamsInCore(core: CoreApi, ports: CorePorts, options: Omit<TeamsOptions, 'scopes'> = {}): ServiceRequests {
+ const scopes = new SwarmPromptScopes()
+ const teams = startCollaboration(core, { ...options, scopes })
+ ports.teams = Object.assign({
+ prepare: scopes.prepare.bind(scopes), started: scopes.started.bind(scopes), raw: scopes.raw.bind(scopes), forget: scopes.forget.bind(scopes),
+ canWrite: (deliveryId: string) => teams.canWrite(deliveryId),
+ }, { stop: () => teams.stop() })
+ teams.start()
+ return teams.requests
+}
diff --git a/cli/src/services/collaborationProcess.spec.ts b/cli/src/services/collaborationProcess.spec.ts
new file mode 100644
index 000000000..1fd4889df
--- /dev/null
+++ b/cli/src/services/collaborationProcess.spec.ts
@@ -0,0 +1,256 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CoreApi } from '../core/api.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { TeamsOptions, Teams } from './collaboration.js'
+import { AGENTS_FRESH_MS, runCollaborationService, WATCHED, WRITABLE_EVERY_MS, WRITABLE_FOR_MS } from './collaborationProcess.js'
+import type { CoreConnection, ServiceProcessOptions } from './process.js'
+
+// The real default reaches a real socket: never in a test.
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+
+const OWNER = { local: true, owner: true }
+const flush = async () => { for (let i = 0; i < 5; i++) await new Promise((settle) => setTimeout(settle, 0)) }
+const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w', displayName: agentId, terminalAvailable: true }) as unknown as RegisteredSession
+
+describe('Tab collaboration and teams in the teams\' own process', () => {
+ afterEach(() => vi.clearAllMocks())
+
+ const setup = () => {
+ let options: ServiceProcessOptions | null = null
+ let api: CoreApi | null = null
+ let given: TeamsOptions | null = null
+ let clock = 10_000
+ const timers: Array<{ run: () => void; ms: number; cleared: boolean }> = []
+ const writable = new Set<string>()
+ const calls: string[] = []
+ const stop = vi.fn()
+ const service = runCollaborationService({
+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',
+ run: (o) => { options = o; return { stop } },
+ now: () => clock,
+ setTimer: (run, ms) => { const timer = { run, ms, cleared: false }; timers.push(timer); return timer },
+ clearTimer: (timer) => { (timer as { cleared: boolean }).cleared = true },
+ start: (core, opts) => {
+ api = core
+ given = opts
+ return {
+ requests: {
+ team: async (payload) => ({ team: payload.action, agents: core.agents.live().map((a) => a.agentId), command: core.daemon.command }),
+ team_delivery: async (payload) => ({ delivery: payload.action }),
+ },
+ canWrite: (id) => writable.has(id),
+ refreshChannels: () => calls.push('refresh'),
+ start: () => calls.push('start'),
+ stop: () => calls.push('stop'),
+ } satisfies Teams
+ },
+ })
+ return { options: options!, api: () => api!, given: () => given!, writable, timers, calls, service, stop, tick: (ms: number) => { clock += ms }, now: () => clock }
+ }
+ const core = (answers: Record<string, unknown> = {}) => {
+ const asked: Array<[string, Record<string, unknown> | undefined]> = []
+ const query = vi.fn(async (name: string, payload?: Record<string, unknown>) => {
+ asked.push([name, payload])
+ const answer = answers[name]
+ if (answer instanceof Error) throw answer
+ return (answer ?? {}) as Record<string, unknown>
+ })
+ return { connection: { query } satisfies CoreConnection, asked, query }
+ }
+
+ it('starts once it knows the agents and the daemon, and answers on the agents as each request starts', async () => {
+ const { options, calls } = setup()
+ expect(options).toMatchObject({ name: 'collaboration', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })
+ const link = core({ shown: { agents: [agent('a1')] }, daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: 'm' } })
+ options.onConnected!(link.connection)
+ await flush()
+ expect(calls).toEqual(['start'])
+ expect(await options.requests.team!({ action: 'list' }, OWNER)).toEqual({ team: 'list', agents: ['a1'], command: `'node' 'cli.js'` })
+ expect(await options.requests.team_delivery!({ action: 'status' }, OWNER)).toEqual({ delivery: 'status' })
+ // Connected again (a new core, the same machine): asked how the daemon runs again, not started twice.
+ const again = core({ shown: { agents: [agent('a1')] }, daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: 'm' } })
+ options.onConnected!(again.connection)
+ await flush()
+ expect(calls).toEqual(['start'])
+ expect(link.asked.filter(([name]) => name === 'daemon')).toHaveLength(1)
+ expect(again.asked.filter(([name]) => name === 'daemon')).toHaveLength(1)
+ // A core under another machine (signed in since): the teams under the old one go, new ones start.
+ options.onConnected!(core({ shown: { agents: [] }, daemon: { command: 'x', port: 1, machineId: 'account-machine' } }).connection)
+ await flush()
+ expect(calls).toEqual(['start', 'stop', 'start'])
+ })
+
+ it('keeps the daemon it knew when a new core cannot say', async () => {
+ const { options, calls } = setup()
+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm' } }).connection)
+ await flush()
+ options.onConnected!(core({ daemon: new Error('gone') }).connection)
+ await flush()
+ expect(await options.requests.team!({ action: 'list' }, OWNER)).toMatchObject({ command: 'x' })
+ expect(calls).toEqual(['start'])
+ })
+
+ it('starts nothing while it does not know which machine it serves', async () => {
+ const { options, calls } = setup()
+ options.onConnected!(core({ daemon: { error: 'NOT_AN_EXPERIMENT' } }).connection)
+ await flush()
+ expect(calls).toEqual([])
+ expect(await options.requests.team!({ action: 'list' }, OWNER)).toMatchObject({ team: 'list' })
+ expect(calls).toEqual([])
+ })
+
+ it('reads the scopes as the core says them, and their reply moving back through the core', async () => {
+ const { options, given } = setup()
+ const link = core({ team_scope: { teamId: 'a'.repeat(32) } })
+ options.onConnected!(link.connection)
+ expect(await given().scopes.current('a1')).toBe('a'.repeat(32))
+ link.query.mockResolvedValueOnce({ teamId: null })
+ expect(await given().scopes.current('a1')).toBeNull()
+ link.query.mockRejectedValueOnce(new Error('gone'))
+ expect(await given().scopes.current('a1')).toBeNull()
+ await given().scopes.replied('a1', 'a'.repeat(32), 'b'.repeat(32))
+ link.query.mockRejectedValueOnce(new Error('gone'))
+ expect(await given().scopes.replied('a1', 't', 'q')).toEqual({})
+ expect(link.asked).toContainEqual(['team_replied', { agentId: 'a1', teamId: 'a'.repeat(32), questionId: 'b'.repeat(32) }])
+ })
+
+ it('tells the core a delivery may be written before handing it over, and keeps telling while any may', async () => {
+ const { options, api, writable, timers, tick } = setup()
+ const link = core()
+ options.onConnected!(link.connection)
+ await flush()
+ link.asked.length = 0
+ writable.add('team:d1')
+ api().turns.deliver('a1', 'a question', 'team:d1')
+ expect(link.asked.map(([name]) => name)).toEqual(['writable', 'deliver'])
+ expect(link.asked[0][1]).toEqual({ deliveries: { 'team:d1': 10_000 + WRITABLE_FOR_MS } })
+ expect(timers).toHaveLength(1)
+ expect(timers[0].ms).toBe(WRITABLE_EVERY_MS)
+ tick(WRITABLE_EVERY_MS)
+ timers[0].run()
+ expect(link.asked.at(-1)).toEqual(['writable', { deliveries: { 'team:d1': 11_000 + WRITABLE_FOR_MS } }])
+ // Taken back: told once that none may, and the telling stops.
+ writable.delete('team:d1')
+ timers[0].run()
+ expect(link.asked.at(-1)).toEqual(['writable', { deliveries: {} }])
+ expect(timers[0].cleared).toBe(true)
+ const count = link.asked.length
+ // Nothing changed and none may: nothing more to say.
+ options.onEvent!({ kind: 'delivery', event: { deliveryId: 'team:d1', sessionId: 'a1', state: 'started' } })
+ expect(link.asked).toHaveLength(count)
+ })
+
+ it('watches the last deliveries only, and one handed over again as the newest', async () => {
+ const { options, api, writable } = setup()
+ const link = core()
+ options.onConnected!(link.connection)
+ for (let i = 0; i <= WATCHED; i++) api().turns.deliver('a1', 'q', `team:d${i}`)
+ api().turns.deliver('a1', 'q', 'team:d5')
+ writable.add('team:d0')
+ writable.add('team:d5')
+ api().turns.deliver('a1', 'q', 'team:dX')
+ expect(link.asked.filter(([name]) => name === 'writable').at(-1)![1]).toEqual({ deliveries: { 'team:d5': expect.any(Number) } })
+ })
+
+ it('asks the core to take a delivery back before its mailbox reads the answer in line, and forgets it after', async () => {
+ const { options, api, given } = setup()
+ const link = core({ cancel_delivery: { cancelled: true } })
+ options.onConnected!(link.connection)
+ expect(api().turns.cancelDelivery('team:d1')).toBe(false)
+ const release = await given().takingBack!('team:d1')
+ expect(api().turns.cancelDelivery('team:d1')).toBe(true)
+ release()
+ expect(api().turns.cancelDelivery('team:d1')).toBe(false)
+ given().changed!()
+ })
+
+ it('hears the account\'s notices once it runs, and its deliveries\' progress; anything else is not its', async () => {
+ const { options, api } = setup()
+ const heard = vi.fn(), noticed = vi.fn()
+ api().turns.onDelivery(heard)
+ const stop = api().account.onNotice(noticed)
+ // Not running yet: a notice is the next service's to read when it starts.
+ options.onEvent!({ kind: 'notice', notice: { type: 'desk_changed', revision: 1 } })
+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm' } }).connection)
+ await flush()
+ options.onEvent!({ kind: 'delivery', event: { deliveryId: 'team:d1', sessionId: 'a1', state: 'queued' } })
+ options.onEvent!({ kind: 'notice', notice: { type: 'desk_changed', revision: 2 } })
+ options.onEvent!({ kind: 'notice' })
+ options.onEvent!({ kind: 'other' })
+ stop()
+ options.onEvent!({ kind: 'notice', notice: { type: 'desk_changed', revision: 3 } })
+ expect(heard).toHaveBeenCalledOnce()
+ expect(noticed.mock.calls).toEqual([[{ type: 'desk_changed', revision: 2 }]])
+ })
+
+ it('reads the agents again, for its mailbox\'s next look, once they are a second old; once at a time', async () => {
+ const { options, api, tick } = setup()
+ const link = core({ shown: { agents: [agent('a1')] } })
+ options.onConnected!(link.connection)
+ await flush()
+ const reads = () => link.asked.filter(([name]) => name === 'shown').length
+ const before = reads()
+ expect(api().agents.live().map((a) => a.agentId)).toEqual(['a1'])
+ expect(reads()).toBe(before)
+ tick(AGENTS_FRESH_MS + 1)
+ api().agents.live()
+ api().agents.live()
+ expect(reads()).toBe(before + 1)
+ // A core that cannot say keeps the agents it said.
+ link.query.mockRejectedValueOnce(new Error('gone'))
+ tick(AGENTS_FRESH_MS + 1)
+ await flush()
+ api().agents.live()
+ await flush()
+ expect(api().agents.live().map((a) => a.agentId)).toEqual(['a1'])
+ })
+
+ it('acts on nothing before it connects, or after the core is gone, and stops what it runs with the process', async () => {
+ const { options, api, service, stop, calls, writable, timers } = setup()
+ api().turns.deliver('a1', 'q', 'team:d1')
+ await flush()
+ expect(await options.requests.team!({ action: 'list' }, OWNER)).toMatchObject({ agents: [], command: 'harness' })
+ options.onConnected!(core().connection)
+ writable.add('team:d2')
+ api().turns.deliver('a1', 'q', 'team:d2')
+ options.onDisconnected!()
+ await service.stop()
+ expect(timers[0].cleared).toBe(true)
+ expect(calls).toContain('stop')
+ expect(stop).toHaveBeenCalledOnce()
+ // Stopped with nothing being told: nothing to clear.
+ const quiet = setup()
+ await quiet.service.stop()
+ })
+
+ it('runs the real process, on the real clock and timers, when given none', async () => {
+ vi.useFakeTimers()
+ try {
+ const { runServiceProcess } = await import('./process.js')
+ const writable = new Set(['team:d1'])
+ let api: CoreApi | null = null
+ const process = runCollaborationService({
+ dataDir: '/data', socketPath: '/s', machineId: 'm', token: 't',
+ start: (given) => {
+ api = given
+ return { requests: { team: async () => ({}), team_delivery: async () => ({}) }, canWrite: (id) => writable.has(id), refreshChannels: () => {}, start: () => {}, stop: () => {} }
+ },
+ })
+ const options = vi.mocked(runServiceProcess).mock.calls.at(-1)![0]
+ const link = core()
+ options.onConnected!(link.connection)
+ api!.turns.deliver('a1', 'q', 'team:d1')
+ await vi.advanceTimersByTimeAsync(WRITABLE_EVERY_MS)
+ expect(link.asked.filter(([name]) => name === 'writable').length).toBeGreaterThanOrEqual(2)
+ process.stop()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('starts the real service when given none', async () => {
+ const { runServiceProcess } = await import('./process.js')
+ runCollaborationService({ dataDir: '/data-that-is-not-there', socketPath: '/s', machineId: 'm', token: 't' }).stop()
+ expect(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests.team_delivery).toBeTypeOf('function')
+ })
+})
diff --git a/cli/src/services/collaborationProcess.ts b/cli/src/services/collaborationProcess.ts
new file mode 100644
index 000000000..8f7187d3a
--- /dev/null
+++ b/cli/src/services/collaborationProcess.ts
@@ -0,0 +1,192 @@
+/**
+ * Tab collaboration and teams in the teams' own process (`harness __service teams,collaboration`), beside the
+ * prompt scopes (services/teamsProcess.ts): an experiment, started only once it is on (core/api.ts
+ * `EXPERIMENTS`). The same service as in the core's process (services/collaboration.ts), on the core's API as
+ * a process reaches it (services/processCoreApi.ts), and what a mailbox in another process needs besides:
+ * - The prompt scopes it reads are the core's word on them (`team_scope`, `team_replied`, core/teamsLink.ts),
+ * never the scopes beside it, which may not yet have a change the core already made: no team, never a wrong
+ * one, as when they answered in the core's process.
+ * - The core asks in line, as it writes a team's turn, whether that turn may still be written. This process
+ * tells the core which may (`writable`), before each is handed over and whenever that can change, each for a
+ * few seconds at a time: a process that stops telling, hung or gone, leaves none writable, and a team's turn
+ * waits rather than being written against its mailbox's word.
+ * - Its mailbox reads in line whether a turn was taken back. Before a cancel or a hold this process asks the
+ * core, which takes it back if it can (`takingBack`), and the mailbox reads that answer; one it takes back on
+ * its own (as the channels are switched off) is not taken back here, and waits unwritten instead.
+ * - The agents it reads as the apps are shown them, asked again as each request starts and whenever its
+ * mailbox reads them and they are a second old.
+ */
+import type { BackendNotice, DaemonAddress } from '../core/api.js'
+import { startCollaboration } from './collaboration.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+import { agentsIn, daemonIn, processCoreApi, type ShownAgent } from './processCoreApi.js'
+import { turnsLink } from './turnsLink.js'
+
+type Payload = Record<string, unknown>
+
+/** How long a delivery the core is told may be written stays so without being told again. */
+export const WRITABLE_FOR_MS = 3_000
+/** How often what may be written is told again while any may: within this, a deadline passing is heard. */
+export const WRITABLE_EVERY_MS = 1_000
+/** The most deliveries this process watches the writing of. */
+export const WATCHED = 1_000
+/** How old the agents it read may be before its mailbox's next look asks again. */
+export const AGENTS_FRESH_MS = 1_000
+
+export interface CollaborationServiceOptions {
+ dataDir: string
+ socketPath: string
+ machineId: string
+ token: string
+ /** Swapped in tests for one that does not touch the real socket or process. */
+ run?: typeof runServiceProcess
+ /** Swapped in tests for a service that keeps nothing on disk and polls no account. */
+ start?: typeof startCollaboration
+ now?: () => number
+ setTimer?: (run: () => void, ms: number) => unknown
+ clearTimer?: (timer: unknown) => void
+}
+
+export function runCollaborationService(options: CollaborationServiceOptions): ServiceProcess {
+ const now = options.now ?? Date.now
+ const setTimer = options.setTimer ?? ((run, ms) => { const timer = setInterval(run, ms); timer.unref?.(); return timer })
+ const clearTimer = options.clearTimer ?? ((timer) => clearInterval(timer as ReturnType<typeof setInterval>))
+ let core: CoreConnection | null = null
+ let live: ShownAgent[] = []
+ let readAt = -Infinity
+ let daemon: DaemonAddress | null = null
+ let reading: Promise<void> | null = null
+ const ask = (query: string, payload: Payload): Promise<Payload> =>
+ core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))
+ const deliveries = turnsLink(ask)
+ /** The agents as the core shows them now; once at a time. */
+ const readAgents = (): Promise<void> => reading ??= ask('shown', {}).then((answer) => {
+ live = (agentsIn(answer) as ShownAgent[] | null) ?? live
+ readAt = now()
+ }, () => {}).finally(() => { reading = null })
+ /** The connection the daemon's address was last asked on. */
+ let askedOn: CoreConnection | null = null
+ /** What a request reads: the agents now, and how this daemon is run, asked once per connection. A core that
+ * cannot say leaves what the last one said. */
+ const ready = async (): Promise<void> => {
+ await readAgents()
+ if (daemon && askedOn === core) return
+ const on = core
+ daemon = daemonIn(await ask('daemon', {}).catch(() => null)) ?? daemon
+ askedOn = on
+ }
+
+ const noticeListeners = new Set<(notice: BackendNotice) => void>()
+ /** What the core said each delivery taken back came to, for the mailbox to read in line. */
+ const takenBack = new Map<string, boolean>()
+ /** The deliveries handed to the core, newest last: those whose writing this process watches. */
+ const handed = new Set<string>()
+ let told = ''
+ let ticking: unknown = null
+
+ const base = processCoreApi(options.dataDir, 'collaboration', {
+ // Read in line by its mailbox's timer too: a copy a second old is asked for again, for its next look.
+ live: () => { if (now() - readAt > AGENTS_FRESH_MS) void readAgents(); return live },
+ ask, deliveries, daemon: () => daemon,
+ onNotice: (listener) => { noticeListeners.add(listener); return () => { noticeListeners.delete(listener) } },
+ })
+ const api = {
+ ...base,
+ turns: {
+ ...base.turns,
+ deliver: (agentId: string, text: string, deliveryId: string) => {
+ // The core hears that it may write it before it is handed it, on the same link.
+ handed.delete(deliveryId)
+ handed.add(deliveryId)
+ if (handed.size > WATCHED) handed.delete(handed.values().next().value!)
+ tell()
+ base.turns.deliver(agentId, text, deliveryId)
+ },
+ cancelDelivery: (deliveryId: string) => takenBack.get(deliveryId) ?? false,
+ },
+ }
+ const build = () => (options.start ?? startCollaboration)(api, {
+ scopes: {
+ current: (agentId) => ask('team_scope', { agentId }).then((answer) => (typeof answer.teamId === 'string' ? answer.teamId : null), () => null),
+ replied: (agentId, teamId, questionId) => ask('team_replied', { agentId, teamId, questionId }).catch(() => ({})),
+ },
+ takingBack: async (deliveryId) => {
+ takenBack.set(deliveryId, await deliveries.cancel(deliveryId))
+ return () => { takenBack.delete(deliveryId) }
+ },
+ changed: () => tell(),
+ })
+ let collaboration = build()
+ /** The machine the running service was started under, and whether it was. */
+ let builtFor: string | null = null
+ let started = false
+ /**
+ * The service, started, for the machine this daemon serves as now. One started under another machine goes
+ * and a new one starts: a sign-in starts a new core under the account's machine, and the teams it ran
+ * inside used to go with the core they ran in, which this process outlives.
+ */
+ const current = () => {
+ const machine = daemon?.machineId() ?? null
+ if (machine === null) return collaboration
+ if (started && builtFor !== machine) {
+ collaboration.stop()
+ collaboration = build()
+ started = false
+ }
+ if (!started) {
+ started = true
+ builtFor = machine
+ collaboration.start()
+ }
+ return collaboration
+ }
+
+ /** Tell the core which deliveries may be written now, when that changed or is due again; keep telling while any may. */
+ function tell(): void {
+ const until = now() + WRITABLE_FOR_MS
+ const writable = [...handed].filter((id) => collaboration.canWrite(id))
+ const said = JSON.stringify(writable)
+ if (said !== told || writable.length) {
+ told = said
+ void ask('writable', { deliveries: Object.fromEntries(writable.map((id) => [id, until])) }).catch(() => {})
+ }
+ if (writable.length && !ticking) ticking = setTimer(tell, WRITABLE_EVERY_MS)
+ if (!writable.length && ticking) { clearTimer(ticking); ticking = null }
+ }
+
+ const service = (options.run ?? runServiceProcess)({
+ name: 'collaboration',
+ socketPath: options.socketPath,
+ machineId: options.machineId,
+ token: options.token,
+ requests: {
+ team: async (payload, asker) => { await ready(); return current().requests.team(payload, asker) },
+ team_delivery: async (payload, asker) => { await ready(); return current().requests.team_delivery(payload, asker) },
+ },
+ onEvent: (payload) => {
+ if (deliveries.heard(payload)) { tell(); return }
+ // Heard once the service runs for a known machine: the channels it would read are that machine's.
+ if (started && payload.kind === 'notice' && payload.notice && typeof payload.notice === 'object') {
+ for (const listener of noticeListeners) listener(payload.notice as BackendNotice)
+ }
+ },
+ onConnected: (connection) => {
+ core = connection
+ told = ''
+ // Its queues resume once it knows the agents and the daemon, and the core hears what may be written.
+ void ready().then(() => {
+ current()
+ tell()
+ })
+ },
+ onDisconnected: () => { core = null },
+ })
+ return {
+ stop: () => {
+ if (ticking) clearTimer(ticking)
+ ticking = null
+ collaboration.stop()
+ return service.stop()
+ },
+ }
+}
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index 9ab9c5280..062682ffe 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import { startGateway } from '../gateway/start.js'
import * as inline from './inline.js'
import { startModels } from './models.js'
+import { startTeamsInCore } from './collaboration.js'
import { startMonitor } from './monitor.js'
import { startOrchestrator } from './orchestrator.js'
import { startProjects } from './projects.js'
@@ -13,6 +14,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startStore, startUsage, startViewers, startWorkspaces })
+ expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startStore, startTeamsInCore, startUsage, startViewers, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 7e2646f7c..e680e9021 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -14,6 +14,7 @@
*/
export { startGateway } from '../gateway/start.js'
export { startModels } from './models.js'
+export { startTeamsInCore } from './collaboration.js'
export { startMonitor } from './monitor.js'
export { startOrchestrator } from './orchestrator.js'
export { startProjects } from './projects.js'
diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.ts
index a32a1a4b6..448765cda 100644
--- a/cli/src/services/modelsProcess.ts
+++ b/cli/src/services/modelsProcess.ts
@@ -15,7 +15,7 @@
* it asks for (`service_query`), each time it needs it: a service keeps no credential.
*/
import type { CoreApi, ServiceRequests } from '../core/api.js'
-import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'
+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, TERMINALS_OFF } from '../core/api.js'
import type { AgentGridTarget, GridGlance } from '../lib/gridAnnotation.js'
import { parseGridLaunchOverride } from '../lib/gridLaunch.js'
import { gridGlances, onGridModelsChanged } from '../lib/gridModels.js'
@@ -103,6 +103,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa
machineName: () => machineName,
// Models never reaches another machine: the fleet's lane is not its to seal.
lane: LANE_OFF,
+ ...ACCOUNT_BACKEND_OFF,
},
clients: {
viewerChanged: () => {},
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index e622a5000..235e3ca39 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -61,6 +61,27 @@ describe('the core API a light service runs on in its own process', () => {
expect(api.turns.cancelDelivery('d1')).toBe(false)
expect(api.daemon).toMatchObject({ command: 'harness', port: 0 })
expect(api.daemon.machineId()).toBe('')
+ expect(await api.account.backend('GET', '/api/tab-channels')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
+ expect(api.account.onNotice(() => {})()).toBeUndefined()
+ })
+
+ it('reads the account\'s backend through the core for an experiment, and hears the notices it is told', async () => {
+ let answer: Record<string, unknown> | Error = { status: 200, body: { success: true } }
+ const ask = vi.fn(async () => { if (answer instanceof Error) throw answer; return answer })
+ const listeners: Array<(notice: never) => void> = []
+ const api = processCoreApi('/data', 'collaboration', { ask, onNotice: (listener) => { listeners.push(listener as never); return () => {} } })
+ expect(await api.account.backend('PATCH', '/api/tab-channels/settings', { enabled: true })).toEqual({ status: 200, body: { success: true } })
+ expect(ask).toHaveBeenLastCalledWith('backend', { method: 'PATCH', path: '/api/tab-channels/settings', body: { enabled: true } })
+ await api.account.backend('GET', '/api/tab-channels')
+ expect(ask).toHaveBeenLastCalledWith('backend', { method: 'GET', path: '/api/tab-channels' })
+ answer = { error: 'INVALID_REQUEST' }
+ expect(await api.account.backend('GET', '/nope')).toEqual({ status: 502, body: { error: 'INVALID_REQUEST' } })
+ answer = { status: 200 }
+ expect(await api.account.backend('GET', '/api/x')).toEqual({ status: 502, body: { error: 'BACKEND_UNREACHABLE' } })
+ answer = new Error('the link went')
+ expect(await api.account.backend('GET', '/api/x')).toEqual({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } })
+ api.account.onNotice(() => {})
+ expect(listeners).toHaveLength(1)
})
it('acts on the core for an experiment: agents made, turns stopped and delivered, windows told, each asked', async () => {
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index eae826987..a0ca90b11 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -8,8 +8,8 @@
* credential is refused: a service holds none (services/AGENTS.md).
*
* An experiment acts on the core as well (core/experimentQueries.ts): it creates agents, stops a turn,
- * delivers turns (services/turnsLink.ts) and tells the windows it changed, each asked of the core over its
- * link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its
+ * delivers turns (services/turnsLink.ts), reads and writes the account's backend and tells the windows it
+ * changed, each asked of the core over its link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its
* name, whether its terminal is there and its harness's viewer.
*/
import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, resolveAgent, TERMINALS_OFF, type CoreApi, type DaemonAddress } from '../core/api.js'
@@ -33,6 +33,8 @@ export interface AgentsView {
deliveries?: ReturnType<typeof turnsLink>
/** Where this daemon runs, as the core last said (`service_query daemon`). */
daemon?: () => DaemonAddress | null
+ /** The account's notices the core tells it (`service_event` kind `notice`), for whoever listens. */
+ onNotice?: CoreApi['account']['onNotice']
}
/** Whether what the core sent is an agent. */
@@ -101,6 +103,14 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
lane: LANE_OFF,
privateGridName: async () => null,
machineName: () => null,
+ backend: async (method, path, body) => {
+ const answer = await (ask?.('backend', { method, path, ...(body === undefined ? {} : { body }) }) ?? Promise.reject(new Error('no core to ask')))
+ .catch((): Payload => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }))
+ return typeof answer.status === 'number' && answer.body && typeof answer.body === 'object'
+ ? { status: answer.status, body: answer.body as Payload }
+ : { status: 502, body: { error: typeof answer.error === 'string' ? answer.error : 'BACKEND_UNREACHABLE' } }
+ },
+ onNotice: (listener) => view.onNotice?.(listener) ?? (() => {}),
},
clients: {
viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},
diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.ts
index 9e96cd8f3..51ad451ab 100644
--- a/cli/src/services/searchProcess.ts
+++ b/cli/src/services/searchProcess.ts
@@ -8,7 +8,7 @@
* process's alone: a crash or a leak in search costs search, and the master starts it again.
*/
import type { CoreApi } from '../core/api.js'
-import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import { databaseHistory } from '../core/transcripts/databaseHistory.js'
import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'
import { externalProviders } from '../lib/sessionSearch/externals/index.js'
@@ -71,6 +71,7 @@ export function searchCoreApi(
lane: LANE_OFF,
privateGridName: async () => null,
machineName: () => null,
+ ...ACCOUNT_BACKEND_OFF,
},
clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },
daemon: DAEMON_UNKNOWN,
diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.ts
index 50ce761cf..d9091ab82 100644
--- a/cli/src/services/viewersProcess.ts
+++ b/cli/src/services/viewersProcess.ts
@@ -18,7 +18,7 @@
* no longer restarts every viewer: they stay up here, and the new core hears their URLs at once.
*/
import type { CoreApi } from '../core/api.js'
-import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { startViewers } from './viewers.js'
@@ -77,6 +77,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re
lane: LANE_OFF,
privateGridName: async () => null,
machineName: () => null,
+ ...ACCOUNT_BACKEND_OFF,
},
clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },
daemon: DAEMON_UNKNOWN,
diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.ts
index ba1c7123c..86ae50856 100644
--- a/cli/src/services/workspacesProcess.ts
+++ b/cli/src/services/workspacesProcess.ts
@@ -13,7 +13,7 @@
* alone: a hang or a crash in it costs workspaces, and the master starts them again.
*/
import type { CoreApi } from '../core/api.js'
-import { AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
import { startWorkspaces } from './workspaces.js'
@@ -79,6 +79,7 @@ export function workspacesCoreApi(
lane: LANE_OFF,
privateGridName: async () => null,
machineName: () => null,
+ ...ACCOUNT_BACKEND_OFF,
},
clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },
daemon: DAEMON_UNKNOWN,
diff --git a/cli/src/socketBindings.spec.ts b/cli/src/socketBindings.spec.ts
index 156595f4e..134eacb18 100644
--- a/cli/src/socketBindings.spec.ts
+++ b/cli/src/socketBindings.spec.ts
@@ -14,7 +14,6 @@ const SRC = join(__dirname)
/** Slots left unbound on purpose, and why. */
const NOT_BOUND_ON_PURPOSE: Record<string, string> = {
- teamCommand: 'a test override: null runs the daemon\'s own `team` command',
onLocalClient: 'declared and never wired (the design doc\'s "Found while mapping")',
}
diff --git a/cli/src/teams/preflight.ts b/cli/src/teams/preflight.ts
index ec8ffa793..dd3e16e59 100644
--- a/cli/src/teams/preflight.ts
+++ b/cli/src/teams/preflight.ts
@@ -1,33 +1,2 @@
-import { stripVTControlCharacters } from 'node:util'
-import type { RegisteredSession } from '../lib/registry.js'
-import { inspectRuntimePane } from '../lib/runtimeProfileController.js'
-import { parseEngineQuestionPane } from '../lib/askQuestion.js'
-
-/** Conservative, read-only inspection at the serialized input write boundary. */
-export function teamWriteHold(engine: RegisteredSession['engine'], capture: string | null): string | null {
- if (!capture) return 'team_waiting_unavailable'
- const pane = inspectRuntimePane(engine, capture)
- if (pane.dialog || parseEngineQuestionPane(engine, capture)) return 'team_waiting_user'
- if (pane.draft) return 'team_waiting_draft'
- if (!pane.idle) return 'team_waiting_idle'
- const lines = capture.split('\n').map(stripVTControlCharacters)
- if (/esc(?:ape)? to (?:interrupt|cancel|stop)/i.test(lines.slice(-15).join('\n'))) return 'team_waiting_idle'
- // These composers permit an empty first line followed by a multiline human draft.
- // The general profile inspector only needs the first line; team delivery needs every line.
- if (['claude', 'codex', 'cursor', 'hermes'].includes(engine)) {
- const index = lines.findLastIndex(line => /^\s*[›❯→]/u.test(line))
- if (index < 0) return 'team_waiting_idle'
- // Codex shows its styled placeholder only when the whole composer is empty.
- // Its configurable model/cwd/task footer below that placeholder is not draft
- // text. The profile inspector has already proved this visible prompt text is
- // a placeholder; a bare first line still needs the multiline-draft check.
- if (engine === 'codex' && lines[index].replace(/^\s*[›❯→]\s*/u, '').trim()) return null
- for (const line of lines.slice(index + 1)) {
- if (/[─━―]{8,}/u.test(line)) break
- const text = line.trim()
- if (!text || /^(?:\? for shortcuts|\d+% context|context:|ctrl\+|shift\+|tab to|plan mode|accept edits|bypass permissions)/i.test(text)) continue
- return 'team_waiting_draft'
- }
- }
- return null
-}
+/** The team write hold, which the core reads panes with as it writes a team's turn: lib/teamWriteHold.ts. */
+export { teamWriteHold } from '../lib/teamWriteHold.js'
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index bc1d65049..18033f4cc 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -54,6 +54,8 @@ export function fakeCore(over: Overrides = {}): CoreApi {
},
privateGridName: vi.fn(async () => null),
machineName: vi.fn(() => null),
+ backend: vi.fn(async () => ({ status: 200, body: {} })),
+ onNotice: vi.fn(() => () => {}),
...over.account,
},
clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), ...over.clients },
diff --git a/cli/src/testing/relaySocket.ts b/cli/src/testing/relaySocket.ts
index 938c95737..7c066bb4b 100644
--- a/cli/src/testing/relaySocket.ts
+++ b/cli/src/testing/relaySocket.ts
@@ -2,10 +2,12 @@
* The socket and its gateway in one process, as the daemon builds them (core/main.ts), for the specs that
* drive the relay through the socket. It takes the arguments the socket took when it held the backend link
* itself, so a spec written against that reads as it did; `gatewayOf` is the gateway it was built with.
+ * The teams ride on it as they did when they were the socket's (testing/teamFixture.ts).
*/
import { BackendSocket } from '../backendSocket.js'
import { RelayGateway } from '../gateway/gateway.js'
import type { AuthSessionManager } from '../lib/authSession.js'
+import { attachTeams, type TeamFixture } from './teamFixture.js'
export function relaySocket(
machineId: string,
@@ -13,10 +15,10 @@ export function relaySocket(
onStatus?: (connected: boolean) => void,
computerId = '',
autonomousEnv = 'prod',
-): BackendSocket {
+): BackendSocket & TeamFixture {
const socket = new BackendSocket(machineId, onStatus)
socket.useGateway(new RelayGateway({ machineId, auth, computerId, autonomousEnv, core: socket.fromGateway }))
- return socket
+ return attachTeams(socket)
}
/** The gateway a socket from `relaySocket` was built with. */
diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.ts
new file mode 100644
index 000000000..ed4c844a5
--- /dev/null
+++ b/cli/src/testing/teamFixture.ts
@@ -0,0 +1,98 @@
+/**
+ * The teams on a socket, for the teams' own specs written against it (teams/remote.spec.ts,
+ * teams/transport.spec.ts) when the team features were the socket's: its state folder and command
+ * (`teamStateDir`, `teamCommand`), its prompt scopes (`swarmPromptScopes`), what became of a delivery
+ * (`teamDelivery`), the account's tab channels (`readChannelDesk`) and their start (`startTeams`).
+ *
+ * Tab collaboration is now a service (services/collaboration.ts), routed by the socket like any other. This
+ * starts it on the socket in its own process, as `HARNESSD_SERVICES=none` does, from the core's API as those
+ * specs knew it: the real registry's agents, the turns the socket's `onMessage` writes, and the frames the
+ * socket sends its windows. So the specs run as they were written, and say the same of the moved service.
+ */
+import type { BackendSocket } from '../backendSocket.js'
+import { env } from '../config/env.js'
+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DELIVERIES_OFF, LANE_OFF, TERMINALS_OFF, type CoreApi, type TurnDelivery } from '../core/api.js'
+import { projectDisplayName, registry } from '../lib/registry.js'
+import type { SessionInputDelivery } from '../lib/sessionInput.js'
+import { startCollaboration, type Teams } from '../services/collaboration.js'
+import { SwarmPromptScopes } from '../teams/promptScope.js'
+
+export interface TeamFixture {
+ /** Where the teams keep their ledgers and mailboxes. */
+ teamStateDir: string
+ /** The command a member on this machine runs `team` with. */
+ teamCommand: string | null
+ /** The prompt scopes the teams read. */
+ swarmPromptScopes: SwarmPromptScopes
+ /** The account's tab channels, as the backend would answer them; none: no channels. */
+ readChannelDesk: (() => Promise<unknown>) | null
+ /** What became of a delivery, as the core's input says it. */
+ teamDelivery(event: SessionInputDelivery): void
+ /** Resume persisted queues and poll the channels, as the daemon does once its input is wired. */
+ startTeams(): void
+}
+
+export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixture {
+ const listeners = new Set<(event: TurnDelivery) => void>()
+ let teams: Teams | null = null
+ const fixture = socket as T & TeamFixture
+ const core = (): CoreApi => ({
+ dataDir: env.ADAPTER_DATA_DIR,
+ terminals: TERMINALS_OFF,
+ agents: {
+ all: () => registry.list(), live: () => registry.list(), displayName: projectDisplayName,
+ byAgent: (agentId) => registry.byAgent(agentId), resolve: (id) => registry.resolve(id), advertised: () => registry.advertised(),
+ terminalAvailable: (agentId) => registry.terminalAvailable(agentId), sync: () => {},
+ runtimeModels: async () => [], runtimeProfile: () => null, setRuntime: () => {}, fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
+ ...AGENT_ACTIONS_OFF,
+ },
+ turns: {
+ send: () => {}, stop: () => {}, recent: () => [], asks: () => [],
+ ...DELIVERIES_OFF,
+ deliver: (agentId, text, deliveryId) => socket.onMessage?.(agentId, text, deliveryId),
+ cancelDelivery: (deliveryId) => socket.onCancelOrchestratorMessage?.(deliveryId) ?? false,
+ onDelivery: (listener) => { listeners.add(listener); return () => { listeners.delete(listener) } },
+ },
+ questions: { answer: () => {}, answerReviewed: async () => false },
+ transcripts: { databaseHistory: () => undefined },
+ external: { sessions: { list: () => [], scan: async () => [] }, open: { known: () => new Map(), fresh: async () => new Map() } },
+ account: {
+ mintGridName: async () => null, accessToken: () => Promise.reject(new Error('no credential')), lane: LANE_OFF,
+ privateGridName: async () => null, machineName: () => null,
+ ...ACCOUNT_BACKEND_OFF,
+ // The tab channels as the spec says the account has them; a backend without them answers 404.
+ backend: async (method, path) => {
+ if (method !== 'GET' || path !== '/api/tab-channels' || !fixture.readChannelDesk) return { status: 404, body: {} }
+ return { status: 200, body: { success: true, data: await fixture.readChannelDesk() } }
+ },
+ },
+ clients: {
+ viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},
+ windows: (frame) => socket.sendLocal(frame),
+ },
+ daemon: { command: 'harness', port: env.PORT, machineId: () => socket.machineId },
+ })
+ /** Built at its first use, from what the spec set by then. */
+ const collaboration = (): Teams => teams ??= startCollaboration(core(), {
+ scopes: fixture.swarmPromptScopes, stateDir: fixture.teamStateDir, command: fixture.teamCommand, dataDir: env.ADAPTER_DATA_DIR,
+ })
+ Object.assign(fixture, {
+ teamStateDir: `${env.ADAPTER_DATA_DIR}/teams`,
+ teamCommand: null,
+ swarmPromptScopes: new SwarmPromptScopes(),
+ readChannelDesk: null,
+ teamDelivery: (event: SessionInputDelivery) => { for (const listener of listeners) listener(event) },
+ startTeams: () => collaboration().start(),
+ })
+ socket.serviceRouter = (type, payload, asker, reply) => {
+ if (type !== 'team' && type !== 'team_delivery') return false
+ void Promise.resolve(collaboration().requests[type](payload, asker)).then(reply)
+ return true
+ }
+ const stop = socket.stop.bind(socket)
+ socket.stop = async () => {
+ teams?.stop()
+ await stop()
+ }
+ return fixture
+}