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.

Swarm v3: Regular or PM agents, and join by bringing your own agent (#4116) (#3447)

harness-for-autonomous[bot]075d4ddda372
diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.ts
index d1d4c98f3..39abf0d88 100644
--- a/backend/integration/superTabSwarmBuddy.test.ts
+++ b/backend/integration/superTabSwarmBuddy.test.ts
@@ -874,3 +874,99 @@ describe('several Buddies through the store (#3818)', () => {
expect((await f.store.read(peer, f.tab)).state.buddyCap).toBe(2)
})
})
+
+// Task #4116 (Swarm v3, anh Dee 11-07): + New agent makes a Regular or a PM agent on the person's own computer, through the store:
+// its grant is the store's reading of the machine's account row, never the request's.
+describe('+ New agent through the store', () => {
+ const capable = async (f: Swarm) => f.store.observeMachine(peer, f.tab, 'peer-mac', { generation: f.generation, resources: { cpuPercent: 10,
+ memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture',
+ os: 'macOS', gpuPercent: null }, quotas: [], tools: {}, runningHarnessIds: [...f.running], stoppedHarnessIds: [],
+ capabilities: ['buddySessions', 'swarmBuddy', 'leadStart', 'regularAgent'] })
+
+ it('starts a Regular agent on the person\'s own computer, in a chat only they and it read', async () => {
+ const f = await swarm()
+ await capable(f)
+ const made = await f.execute({ type: 'agent.new', kind: 'regular', name: 'Ada', engine: 'claude', machineId: 'peer-mac' }, peer)
+ const chat = String(made.result.conversationId)
+ const ada = await f.launch(String(made.result.startId))
+ await capable(f)
+ await expect(send(f, chat, 'Hello Ada')).resolves.toBeTruthy()
+ await expect(send(f, chat, 'Hello', {}, peer, ada)).resolves.toBeTruthy()
+ await expect(f.store.messages(owner, f.tab, chat, {})).rejects.toThrow(UNAVAILABLE)
+ await expect(send(f, chat, 'Peeking', {}, owner)).rejects.toThrow(UNAVAILABLE)
+ const read = await f.store.read(peer, f.tab)
+ expect(read.state.agents.find(a => a.id === ada)).toMatchObject({ regular: true })
+ })
+
+ it('starts a PM that names its new project, on the person\'s own computer', async () => {
+ const f = await swarm()
+ await capable(f)
+ const made = await f.execute({ type: 'agent.new', kind: 'pm', projectName: 'Docs', engine: 'claude', machineId: 'peer-mac' }, peer)
+ const read = await f.store.read(peer, f.tab)
+ expect(read.state.projects!.find(p => p.id === made.result.projectId)).toMatchObject({ name: 'Docs', ownerId: peer.sub })
+ expect(read.state.starts!.find(s => s.id === made.result.startId)?.request).toMatchObject({ machineId: 'peer-mac', conversationId: made.result.conversationId })
+ })
+
+ it('is refused on a computer that is not the person\'s own', async () => {
+ const f = await swarm()
+ await expect(f.execute({ type: 'agent.new', kind: 'regular', name: 'Ada', engine: 'claude', machineId: 'owner-mac' }, peer)).rejects.toMatchObject({ code: 'AGENT_OWN_MACHINE' })
+ })
+
+ it('gives a Regular agent a task in a project its person reads, and never in one they do not', async () => {
+ const f = await swarm()
+ await capable(f)
+ const made = await f.execute({ type: 'agent.new', kind: 'regular', name: 'Ada', engine: 'claude', machineId: 'peer-mac' }, peer)
+ const ada = await f.launch(String(made.result.startId))
+ const hidden = (await f.execute({ type: 'project.create', name: 'Hidden', visibility: 'private', brief: '' })).result as { projectId: string; conversationId: string }
+ const hiddenPm = String((await f.execute({ type: 'agent.add', conversationId: hidden.conversationId, machineId: 'owner-mac', harnessId: randomUUID(),
+ name: 'PM hidden', configuration: config, lead: true })).result.agentId)
+ const task = async (projectId: string) => String((await f.execute({ type: 'conversation.create', projectId, title: 'A task', brief: 'Do it.', checks: [] })).result.conversationId)
+ const hiddenTask = await task(hidden.projectId)
+ await expect(f.execute({ type: 'work.assign', conversationId: hiddenTask, agentId: ada }, owner, hiddenPm)).rejects.toBeTruthy()
+ const webTask = await task(f.web.projectId)
+ await f.execute({ type: 'work.assign', conversationId: webTask, agentId: ada }, owner, f.pms.web)
+ const read = await f.store.read(owner, f.tab)
+ expect(read.state.conversations.find(c => c.id === webTask)?.assignment).toMatchObject({ agentId: ada })
+ })
+
+ // Security review 2 of #4116 (Rowan): its next task takes it out of the earlier project's chats, loaded or quiet.
+ it('takes a Regular agent out of an earlier project\'s chats when it takes a task elsewhere', async () => {
+ const f = await swarm()
+ await capable(f)
+ const made = await f.execute({ type: 'agent.new', kind: 'regular', name: 'Ada', engine: 'claude', machineId: 'peer-mac' }, peer)
+ const ada = await f.launch(String(made.result.startId))
+ const task = async (projectId: string) => String((await f.execute({ type: 'conversation.create', projectId, title: 'A task', brief: 'Do it.', checks: [] })).result.conversationId)
+ const webTask = await task(f.web.projectId)
+ const first = await f.execute({ type: 'work.assign', conversationId: webTask, agentId: ada }, owner, f.pms.web)
+ await f.execute({ type: 'work.status', conversationId: webTask, assignmentId: String(first.result.assignmentId), status: 'done', result: 'Done.' }, peer, ada)
+ // Long enough for the web task to go quiet, so no read loads it by activity.
+ f.clock.now += 3 * 86_400_000
+ const secretTask = await task(f.secret.projectId)
+ await f.execute({ type: 'work.assign', conversationId: secretTask, agentId: ada }, owner, f.pms.secret)
+ // Read straight from its stored part: a quiet group is in no first load.
+ const stored = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: webTask } } })
+ expect((stored.data as { agentIds: string[] }).agentIds).not.toContain(ada)
+ })
+
+ // Security review 1 of #4116 (SecAlder): a dormant chat is in no first load. Its Regular agent leaves it even so, and a message
+ // that wakes it reaches the agent nowhere while it works in another project.
+ it('takes a Regular agent out of a dormant chat of an earlier project, and a message that wakes it never reaches the agent', async () => {
+ const f = await swarm()
+ await capable(f)
+ const made = await f.execute({ type: 'agent.new', kind: 'regular', name: 'Ada', engine: 'claude', machineId: 'peer-mac' }, peer)
+ const ada = await f.launch(String(made.result.startId))
+ const task = async (projectId: string) => String((await f.execute({ type: 'conversation.create', projectId, title: 'A task', brief: 'Do it.', checks: [] })).result.conversationId)
+ const webTask = await task(f.web.projectId)
+ const first = await f.execute({ type: 'work.assign', conversationId: webTask, agentId: ada }, owner, f.pms.web)
+ await f.execute({ type: 'work.status', conversationId: webTask, assignmentId: String(first.result.assignmentId), status: 'done', result: 'Done.' }, peer, ada)
+ // Dormant, as the sweep leaves a finished task a day quiet (sweeps.ts).
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: webTask }, data: { dormant: true } })
+ const secretTask = await task(f.secret.projectId)
+ await f.execute({ type: 'work.assign', conversationId: secretTask, agentId: ada }, owner, f.pms.secret)
+ const stored = await db.swarmGroup.findUniqueOrThrow({ where: { tabId_key: { tabId: f.tab, key: webTask } } })
+ expect(stored.agentIds).not.toContain(ada)
+ const woke = await send(f, webTask, 'What is Ada on now?', { recipientIds: [] }, owner)
+ const queued = await f.store.deliveries(peer, f.tab, ada)
+ expect(queued.map(d => d.messageId)).not.toContain(String(woke.result.messageId))
+ })
+})
diff --git a/backend/src/superTabs/agentKind.test.ts b/backend/src/superTabs/agentKind.test.ts
new file mode 100644
index 000000000..5b8d81fde
--- /dev/null
+++ b/backend/src/superTabs/agentKind.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest'
+import { createSuperTab, type Agent, type Person } from './model.js'
+import { agentChatId, agentKind } from './agentKind.js'
+import { openSwarmBuddyChat } from './buddies.js'
+
+// Task #4116 (Swarm v3, anh Dee 11-07): the left pane lists "My agents": the person's Buddy first, then their other agents,
+// a crown beside a PM, bold for an agent whose chat has news. Each agent says what it is and the chat its person talks to it in.
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+
+function setup() {
+ const state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ const peer: Person = { id: 'peer', email: '[email protected]', role: 'collaborator', generation: 'second' }
+ state.people.push(peer)
+ const agent = (id: string, extra: Partial<Agent> = {}): Agent => {
+ const made = { id, machineId: 'machine', harnessId: `${id}-harness`, machineOwnerId: 'peer', contributorId: 'peer', membershipGeneration: 'second',
+ name: id, configuration, ...extra } as Agent
+ state.agents.push(made)
+ return made
+ }
+ return { state, peer, agent }
+}
+
+describe('an agent\'s kind and chat', () => {
+ it('is a Buddy in its Buddy chat', () => {
+ const { state, peer, agent } = setup()
+ const buddy = agent('buddy', { buddyOf: { personId: 'peer', generation: 'second' }, buddyScope: 'swarm' })
+ const chat = openSwarmBuddyChat(state, peer)
+ chat.agentIds.push(buddy.id)
+ expect(agentKind(state, buddy)).toBe('buddy')
+ expect(agentChatId(state, buddy)).toBe(chat.id)
+ })
+
+ it('is a PM in its project\'s Lead chat', () => {
+ const { state, agent } = setup()
+ const pm = agent('pm')
+ const lead = state.conversations.find(c => c.id === 'lead')!
+ lead.leadId = pm.id
+ lead.agentIds.push(pm.id)
+ expect(agentKind(state, pm)).toBe('pm')
+ expect(agentChatId(state, pm)).toBe('lead')
+ })
+
+ it('is Regular otherwise, with no chat of its own yet', () => {
+ const { state, agent } = setup()
+ const worker = agent('worker')
+ state.conversations.find(c => c.id === 'lead')!.agentIds.push(worker.id)
+ expect(agentKind(state, worker)).toBe('regular')
+ expect(agentChatId(state, worker)).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/agentKind.ts b/backend/src/superTabs/agentKind.ts
new file mode 100644
index 000000000..86aecc0f7
--- /dev/null
+++ b/backend/src/superTabs/agentKind.ts
@@ -0,0 +1,24 @@
+/**
+ * What an agent is to the person who brought it (Swarm v3, task #4116; anh Dee 11-07): their Buddy, a PM that leads a project,
+ * or a Regular agent, which no project holds and whose task decides where it works. The left pane's "My agents" lists the
+ * reader's own by this, a crown beside a PM, each bold while its chat has news the reader has not read (their read marks).
+ */
+import { isBuddy, isBuddyChat } from './buddies.js'
+import type { Agent, SuperTabState } from './model.js'
+import { isAgentChat, ledProject } from './projects.js'
+
+export type AgentKind = 'buddy' | 'pm' | 'regular'
+
+export function agentKind(state: SuperTabState, target: Agent): AgentKind {
+ if (isBuddy(target)) return 'buddy'
+ return ledProject(state, target.id) ? 'pm' : 'regular'
+}
+
+/** The chat [target]'s person talks to it in: a Buddy's own chat, a PM's project chat, a Regular agent's own chat (agent.new);
+ * none for an agent started before chats of their own. */
+export function agentChatId(state: SuperTabState, target: Agent): string | null {
+ if (isBuddy(target)) return state.conversations.find(c => isBuddyChat(c) && c.agentIds.includes(target.id))?.id ?? null
+ const led = ledProject(state, target.id)
+ if (led) return led.leadConversationId
+ return state.conversations.find(c => isAgentChat(c) && c.agentIds.includes(target.id))?.id ?? null
+}
diff --git a/backend/src/superTabs/agentNew.test.ts b/backend/src/superTabs/agentNew.test.ts
new file mode 100644
index 000000000..b56c26e30
--- /dev/null
+++ b/backend/src/superTabs/agentNew.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import type { ContributedMachine } from './machines.js'
+import { createSuperTab, SuperTabError, type Actor, type SuperTabState } from './model.js'
+import { agentKind } from './agentKind.js'
+import { hostTab } from './read/hostRows.js'
+
+// Task #4116 (Swarm v3, anh Dee 11-07): "+ New agent" makes a Regular or a PM agent on the person's own computer and account.
+// A PM names and starts a project; a Regular agent is in no project, and the task it is given decides where it works.
+const NOW = 50_000_000
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const mate: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'mate', email: '[email protected]' }
+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,
+ deviceType: null, chip: null, os: null, gpuPercent: null }
+const reading = { generation: 'g1', receivedAt: NOW, sessionKind: 'computer' as const, resources, tools: {}, quotas: [], runningHarnessIds: [],
+ stoppedHarnessIds: [], capabilities: ['leadStart', 'regularAgent'] }
+const own = (userId: string) => ({ contribution: { machineOwnerId: userId, contributorId: userId } })
+const code = (body: () => unknown): string | null => {
+ // A schema refusal (a missing field) has no code of its own.
+ try { body(); return null } catch (error) { return error instanceof SuperTabError ? error.code : 'INVALID' }
+}
+
+function swarm() {
+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = mate, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invited = run({ type: 'invite.create', email: mate.email, role: 'collaborator', conversationId: 'lead' }, owner)
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, mate)
+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation
+ const pool = (machineId: string, contributorId: string, extra: Partial<ContributedMachine> = {}): ContributedMachine => ({
+ machineId, name: machineId, contributorId, membershipGeneration: generation(contributorId), generation: 'g1', cwd: '/swarm', scope: 'swarm',
+ engines: ['claude', 'codex'], maxAgents: 4, paused: false, observation: reading, ...extra })
+ state.machines = [pool('owner-mac', 'owner'), pool('mate-mac', 'mate'), pool('mate-buddy', 'mate', { buddyOnly: true, maxAgents: 1 })]
+ const add = (extra: Record<string, unknown>, actor: Actor = mate, context: Partial<CommandContext> = own(actor.kind === 'person' ? actor.userId : 'x')) =>
+ run({ type: 'agent.new', engine: 'claude', machineId: 'mate-mac', ...extra } as Command, actor, context)
+ return { run, add, get state() { return state } }
+}
+
+describe('+ New agent, PM', () => {
+ it('names a new project of the person and starts its PM on their own computer, with no repository needed', () => {
+ const f = swarm()
+ const made = f.add({ kind: 'pm', projectName: 'Docs site' })
+ const project = f.state.projects!.find(p => p.id === made.result.projectId)!
+ expect(project).toMatchObject({ name: 'Docs site', ownerId: 'mate' })
+ expect(made.result.conversationId).toBe(project.leadConversationId)
+ const start = f.state.starts!.find(s => s.id === made.result.startId)!
+ expect(start.request).toMatchObject({ machineId: 'mate-mac', conversationId: project.leadConversationId, engine: 'claude' })
+ expect(start).toMatchObject({ contributorId: 'mate', machineOwnerId: 'mate' })
+ })
+
+ it('needs a project name', () => {
+ const f = swarm()
+ expect(code(() => f.add({ kind: 'pm' }))).not.toBeNull()
+ expect((f.state.projects ?? []).filter(p => p.id !== 'lead')).toHaveLength(0)
+ })
+})
+
+describe('+ New agent, Regular', () => {
+ it('starts on the person\'s own computer in a chat of its own, in no project', () => {
+ const f = swarm()
+ const made = f.add({ kind: 'regular', name: 'Ada' })
+ const chat = f.state.conversations.find(c => c.id === made.result.conversationId)!
+ expect(chat).toMatchObject({ title: 'Ada', audience: { people: [{ id: 'mate' }] } })
+ const start = f.state.starts!.find(s => s.id === made.result.startId)!
+ expect(start.request).toMatchObject({ machineId: 'mate-mac', conversationId: chat.id, engine: 'claude', name: 'Ada', regular: true })
+ expect(start).toMatchObject({ contributorId: 'mate', machineOwnerId: 'mate' })
+ expect((f.state.projects ?? []).filter(p => p.id !== 'lead')).toHaveLength(0)
+ })
+
+ it('once started, is a Regular agent in its own chat', () => {
+ const f = swarm()
+ const made = f.add({ kind: 'regular', name: 'Ada' })
+ const startId = made.result.startId as string
+ f.run({ type: 'agent.startDispatch', startId }, mate, own('mate'))
+ const agentId = f.run({ type: 'agent.started', startId, harnessId: 'h-ada',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, mate, own('mate')).result.agentId as string
+ const agent = f.state.agents.find(a => a.id === agentId)!
+ expect(agentKind(f.state, agent)).toBe('regular')
+ expect(f.state.conversations.find(c => c.id === made.result.conversationId)!.agentIds).toContain(agentId)
+ })
+})
+
+describe('+ New agent, on whose computer', () => {
+ it('runs only on the person\'s own listed computer, never another person\'s, a Buddy-only one or one not listed', () => {
+ const f = swarm()
+ for (const kind of ['pm', 'regular']) {
+ const extra = { kind, projectName: 'P', name: 'A' }
+ expect(code(() => f.add({ ...extra, machineId: 'owner-mac' }, mate, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }))).toBe('AGENT_OWN_MACHINE')
+ expect(code(() => f.add({ ...extra, machineId: 'mate-buddy' }))).toBe('MACHINE_NOT_LISTED')
+ expect(code(() => f.add({ ...extra, machineId: 'nowhere' }))).toBe('MACHINE_NOT_LISTED')
+ expect(code(() => f.add(extra, { kind: 'agent', agentId: 'x', machineOwnerId: 'mate' }))).not.toBeNull()
+ }
+ expect((f.state.projects ?? []).filter(p => p.id !== 'lead')).toHaveLength(0)
+ expect(f.state.starts ?? []).toHaveLength(0)
+ })
+})
+
+describe('a Regular agent\'s chat', () => {
+ /** Mate's Regular agent Ada, started and running in its chat. */
+ function running() {
+ const f = swarm()
+ const made = f.add({ kind: 'regular', name: 'Ada' })
+ const startId = made.result.startId as string
+ f.run({ type: 'agent.startDispatch', startId }, mate, own('mate'))
+ const agentId = f.run({ type: 'agent.started', startId, harnessId: 'h-ada',
+ configuration: { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null } }, mate, own('mate')).result.agentId as string
+ return { ...f, chat: made.result.conversationId as string, agentId }
+ }
+ const say = (chat: string, text: string) => ({ type: 'message.send', conversationId: chat, text, replyTo: null, recipientIds: [] }) as Command
+
+ it('takes its person\'s messages and the agent\'s replies', () => {
+ const f = running()
+ expect(code(() => f.run(say(f.chat, 'Hello Ada'), mate))).toBeNull()
+ f.run(say(f.chat, 'Hello'), { kind: 'agent', agentId: f.agentId, machineOwnerId: 'mate' })
+ })
+
+ it('is read and written by nobody else: not the Swarm\'s owner, nor another agent', () => {
+ const f = running()
+ expect(code(() => f.run(say(f.chat, 'Peeking'), owner))).toBe('NOT_FOUND')
+ const lead = f.state.agents.find(a => a.id !== f.agentId)
+ if (lead) expect(code(() => f.run(say(f.chat, 'Peeking'), { kind: 'agent', agentId: lead.id, machineOwnerId: lead.machineOwnerId }))).not.toBeNull()
+ // Its agent carried to another owner's machine (a stale grant) is not its person's agent there.
+ expect(code(() => f.run(say(f.chat, 'Hi'), { kind: 'agent', agentId: f.agentId, machineOwnerId: 'owner' }))).not.toBeNull()
+ })
+})
+
+// Swarm v3 FLOW (anh Dee 11-07): join the org, bring your agent on the computer you are on, and it becomes your Buddy. The
+// computer registers as part of it: no add-machine step.
+describe('joining by bringing your own agent', () => {
+ it('makes a new member\'s agent their Buddy on the computer they are on, which the Swarm did not list', () => {
+ const f = swarm()
+ expect(f.state.machines!.some(m => m.machineId === 'mate-laptop')).toBe(false)
+ const made = f.run({ type: 'buddy.create', machineId: 'mate-laptop', engine: 'codex',
+ setup: { name: 'Mate laptop', cwd: '/home/mate/swarm', engines: ['codex'] } } as Command, mate, own('mate'))
+ const start = f.state.starts!.find(s => s.id === made.result.startId)!
+ expect(start.request).toMatchObject({ machineId: 'mate-laptop', engine: 'codex', buddyOf: { personId: 'mate' }, buddyScope: 'swarm' })
+ expect(f.state.machines!.find(m => m.machineId === 'mate-laptop')).toMatchObject({ contributorId: 'mate', buddyOnly: true })
+ expect(f.state.conversations.find(c => c.id === made.result.conversationId)).toMatchObject({ kind: 'swarm-buddy' })
+ // Its computer is its own: nobody else's agent starts there.
+ expect(code(() => f.run({ type: 'buddy.create', machineId: 'mate-laptop', engine: 'codex',
+ setup: { name: 'Mate laptop', cwd: '/home/mate/swarm', engines: ['codex'] } } as Command, owner, { contribution: { machineOwnerId: 'mate', contributorId: 'mate' } }))).not.toBeNull()
+ })
+})
+
+// A host from before Regular agents would launch one as a project's agent, in a project folder it does not have: the start is
+// listed apart, and a computer whose host cannot run one is told to update instead.
+describe('a Regular agent\'s start on its computer', () => {
+ const lookups = { people: [], confidential: new Set<string>(), agentGrant: async () => {}, teams: [], githubApp: false }
+ const user = { sub: 'mate', email: mate.email, role: 'user', autonomousEnv: 'test' } as never
+
+ it('is listed to its host apart from other starts, in no project\'s folder', async () => {
+ const f = swarm()
+ const made = f.add({ kind: 'regular', name: 'Ada' })
+ const pool = (await hostTab('tab', f.state, 'mate-mac', user, null, lookups)).pool!
+ expect(pool.starts).toEqual([])
+ expect(pool.regularStarts!.map(s => s.id)).toEqual([made.result.startId])
+ expect((pool.projects ?? []).flatMap(p => p.conversationIds)).not.toContain(made.result.conversationId)
+ })
+
+ it('is refused on a computer whose Harness cannot run one yet, saying to update it', () => {
+ const f = swarm()
+ f.state.machines!.find(m => m.machineId === 'mate-mac')!.observation!.capabilities = ['leadStart']
+ expect(code(() => f.add({ kind: 'regular', name: 'Ada' }))).toBe('HOST_OUTDATED')
+ expect(f.state.starts ?? []).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 623714fd7..d6423f22b 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -68,7 +68,7 @@ import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged }
import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, setTimeZone, statusSchema, type AvatarUpload } from './profile.js'
import { cancelledTags, cancelReason, switchExpired, unfinishedWork } from './tidy.js'
import { namedDefault } from './catalog.js'
-import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deletableProject, deleteProject, markConfidential, onTeamAccount, ownsProject, admitPerson, dismissPeople, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
+import { BUILT_IN_ROLE_DEFAULTS, NO_PROJECT, isAgentChat, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deletableProject, deleteProject, markConfidential, onTeamAccount, ownsProject, admitPerson, dismissPeople, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
import { recordClosing, sessionClosed } from './closedAgents.js'
import { declinedWith, declinedWithout } from './sharing.js'
import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRows.js'
@@ -403,6 +403,11 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('buddy.create'), projectId: id.optional(), machineId: id, engine: swarmEngine, model: z.string().trim().min(1).max(200).optional(),
setup: z.object({ name: title, cwd: path, engines: z.array(swarmEngine).min(1).max(2) }).strict().optional(),
name: z.string().max(200).optional(), conversationId: id.optional() }).strict(),
+ // + New agent (Swarm v3, task #4116): a Regular agent in a chat of its own, or a PM that names and starts a project, on the
+ // person's own listed computer and account.
+ z.object({ type: z.literal('agent.new'), kind: z.enum(['regular', 'pm']), machineId: id, engine: swarmEngine,
+ model: z.string().trim().min(1).max(200).optional(), name: z.string().trim().min(1).max(80).optional(), projectName: title.optional(),
+ repositoryUrl: repositoryUrl.optional() }).strict(),
z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration,
startedSession: z.object({ sessionId: id, createdAt: z.iso.datetime() }).strict().optional() }).strict(),
@@ -1027,6 +1032,9 @@ function open(state: SuperTabState, conversationId: string) {
return group
}
+/** What a host says once it launches a Regular agent's start (cli superTabs/machines.ts CAPABILITIES, task #4116). */
+export const REGULAR_AGENT_CAPABILITY = 'regularAgent'
+
/** Pure policy/state transition. The store commits its state, messages and delivery records in one transaction. */
/** One command, then each task's line brought up to date (taskLine.ts), whichever way the command returned. */
/** Whether [assignment]'s builder can no longer close it: its attempt already ended (stopped or lost), or its agent is gone
@@ -1702,6 +1710,25 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
/** Records [me]'s own machine [machineId], prepared by the app ([setup]), as Buddy-only (machines.ts buddyOnly): its host
* then reads the Swarm, starts the Buddy and reports it, and nothing else of the Swarm runs there or reads it. */
+ /** A new project of [ownerId]'s named [name], with its Lead chat: project.create's, and + New agent's for a PM (task #4116). */
+ const createProject = (ownerId: string, name: string, visibility: 'public' | 'private', brief: string): SwarmProject => {
+ const projects = mutableProjects(state)
+ if (projects.length >= 100) fail('PROJECTS_FULL', 'A swarm can have up to 100 projects.')
+ const leadConversationId = `project-${operationId}`
+ // It starts on a copy of the built-in instructions as revision 1, the team's own to change (design, The built-in template).
+ // In a Swarm whose projects moved onto the base (#3600), on the base, marked: one way to start a project (review of #3300).
+ const onBase = projects.some(p => (p.instructionsBase ?? 0) >= BASE_VERSION)
+ const first = onBase ? { instructionsRevision: 1, instructionsHash: instructionsHash(BASE_DOCUMENT), instructionsBase: BASE_VERSION } : FIRST_INSTRUCTIONS
+ const project: SwarmProject = { id: operationId, name, ownerId, ownerGeneration: person(state, ownerId).generation, leadConversationId,
+ visibility, members: [], updateMinutes: 5, skillMode: 'default', ...first }
+ projects.push(project)
+ effects.instructions = { projectId: operationId, revision: 1, hash: first.instructionsHash, text: onBase ? BASE_DOCUMENT : INSTRUCTIONS_TEMPLATE,
+ summary: FIRST_SUMMARY, writtenBy: { kind: 'person', id: ownerId }, askedBy: ownerId, at: context.now }
+ state.conversations.push({ id: leadConversationId, projectId: operationId, title: 'Lead', leadId: null,
+ agentIds: [], archived: false, brief, checks: [], assignment: null, lastMessageSequence: 0 })
+ return project
+ }
+
const addBuddyMachine = (machineId: string, setup: NonNullable<Extract<Command, { type: 'buddy.create' }>['setup']>, me: { id: string; generation: string }) => {
// Its last Buddy's folders are still being deleted there: a new one would lose its own (machine.contribute does the same).
if (state.machineCleanups?.some(c => c.machineId === machineId)) {
@@ -1831,7 +1858,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
projectChatJoin(group, worker.id, worker.displayName ?? worker.name)
assignable(worker)
- sameProject(state, group, worker)
+ sameProject(state, group, worker, true)
const home = groupProject(state, group)
// A teammate's agent on a personal machine keeps what it has; it takes no new task for another person's project.
requireTeamWork(state, worker.machineId, worker.contributorId, home, context.now, context.teamMachines, context.otherWorkspaceMachines, taskAccess(group))
@@ -1849,6 +1876,18 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
/** [worker] takes [group]'s work as assignment [assignmentId], after assignRefusal let it: what work.assign writes, and its
* brief to the worker. */
const assignTo = (group: Conversation, worker: Agent, assignmentId: string) => {
+ // A Regular agent's conversation keeps a private project's content: from its first task there, it works only there. And it
+ // leaves every other project's conversations, which a finished task does not take it out of, so it neither hears nor posts
+ // in them while it works here; its own chat stays (security review 2 of #4116).
+ if (worker.regular) {
+ const home = groupProject(state, group)
+ if (home.visibility === 'private' && !worker.privateProjectId) worker.privateProjectId = home.id
+ for (const other of state.conversations) {
+ if (other.agentIds.includes(worker.id) && !isAgentChat(other) && groupProject(state, other).id !== home.id) {
+ other.agentIds = other.agentIds.filter(id => id !== worker.id)
+ }
+ }
+ }
// The PR ref is fetchable on another machine; a local worktree path is not. The previous agent's free-text result stays
// in its own status message, where deliveries retain its attribution and cross-account warning.
const recovery = group.assignment?.status === 'lost' ? [
@@ -2032,21 +2071,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
case 'project.create': {
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person creates a project and chooses its lead.', 403)
if (state.paused) fail('PAUSED', 'New work is paused in this swarm.')
- const projects = mutableProjects(state)
- if (projects.length >= 100) fail('PROJECTS_FULL', 'A swarm can have up to 100 projects.')
- const leadConversationId = `project-${operationId}`
- // It starts on a copy of the built-in instructions as revision 1, the team's own to change (design, The built-in template).
- // In a Swarm whose projects moved onto the base (#3600), on the base, marked: one way to start a project (review of #3300).
- const onBase = projects.some(p => (p.instructionsBase ?? 0) >= BASE_VERSION)
- const first = onBase ? { instructionsRevision: 1, instructionsHash: instructionsHash(BASE_DOCUMENT), instructionsBase: BASE_VERSION } : FIRST_INSTRUCTIONS
- projects.push({ id: operationId, name: command.name, ownerId: actor.userId, ownerGeneration: person(state, actor.userId).generation, leadConversationId,
- visibility: command.visibility, members: [], updateMinutes: 5, skillMode: 'default', ...first })
- effects.instructions = { projectId: operationId, revision: 1, hash: first.instructionsHash, text: onBase ? BASE_DOCUMENT : INSTRUCTIONS_TEMPLATE,
- summary: FIRST_SUMMARY, writtenBy: { kind: 'person', id: actor.userId }, askedBy: actor.userId, at: context.now }
- state.conversations.push({ id: leadConversationId, projectId: operationId, title: 'Lead', leadId: null,
- agentIds: [], archived: false, brief: command.brief, checks: [], assignment: null, lastMessageSequence: 0 })
- result.projectId = operationId
- result.conversationId = leadConversationId
+ const project = createProject(actor.userId, command.name, command.visibility, command.brief)
+ result.projectId = project.id
+ result.conversationId = project.leadConversationId
break
}
case 'lead.start': {
@@ -2194,6 +2221,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const project = manageProject(state, actor, command.projectId)
project.members = projectMembers(state, command.memberIds)
project.visibility = command.visibility
+ // Made private: a Regular agent already in its conversations holds what it heard there, so it is this project's from now
+ // on, as one assigned here would be (assignTo; security review 2 of #4116).
+ if (project.visibility === 'private') {
+ for (const target of state.agents.filter(a => a.regular && !a.privateProjectId)) {
+ if (state.conversations.some(c => c.agentIds.includes(target.id) && !isAgentChat(c) && groupProject(state, c).id === project.id)) target.privateProjectId = project.id
+ }
+ }
// Whoever no longer reads it loses it from their Buddy in this same write (spec: Access): its sessions in their one Buddy
// chat end, and its threads and PM lines there hide (buddies.ts hiddenProjectRow).
endLostProjectSessions(project)
@@ -3556,6 +3590,47 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
result.conversationId = chatId
break
}
+ case 'agent.new': {
+ // + New agent (Swarm v3, task #4116; anh Dee 11-07): the person's own agent, on their own listed computer and account, as
+ // a Buddy is (Ken's ruling, 10-28): never a machine shared with them, and never a Harness Team account.
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person makes their own agent.', 403)
+ if (state.paused) fail('PAUSED', 'New work is paused in this Swarm.')
+ const me = person(state, actor.userId)
+ if (me.role === 'viewer') fail('READ_ONLY', 'A viewer cannot start agents.', 403)
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'Choose your own computer.', 403)
+ if (grant.machineOwnerId !== me.id || grant.contributorId !== me.id || grant.hostGrant || grant.hostMachineId || grant.teamSession) {
+ fail('AGENT_OWN_MACHINE', 'A new agent runs only on your own computer, in your own account.', 403)
+ }
+ // A Buddy-only record is not the computer in the Swarm: its person adds it first (Desktop does, with no screen).
+ const pool = state.machines?.find(m => m.machineId === command.machineId && m.contributorId === me.id && !m.buddyOnly && !m.removal)
+ ?? fail('MACHINE_NOT_LISTED', 'Add this computer to the Swarm first.', 403)
+ if (command.kind === 'pm') {
+ const projectName = command.projectName ?? fail('PROJECT_NAME_REQUIRED', 'Name the project its PM starts.', 400)
+ const project = createProject(me.id, projectName, 'public', '')
+ const asked = leadEffort(withRoleDefaults({ engine: command.engine, ...(command.model ? { model: command.model } : {}),
+ ...(command.repositoryUrl ? { repositoryUrl: command.repositoryUrl } : {}) }, BUILT_IN_ROLE_DEFAULTS.lead), coordinatorNameOf(project))
+ const start = placeLead(state, project, me, pool.machineId, asked, operationId, context)
+ Object.assign(result, { projectId: project.id, conversationId: project.leadConversationId, startId: start.id })
+ break
+ }
+ // A Regular agent: in no project, in a chat of its own with its person, which nobody else reads (projects.ts readsAgentChat).
+ const name = command.name ?? fail('AGENT_NAME_REQUIRED', 'Name your agent.', 400)
+ // Only a host that says it runs one gets its start (read/hostRows.ts regularStarts): an older one would leave it waiting.
+ if (!pool.observation?.capabilities?.includes(REGULAR_AGENT_CAPABILITY)) fail('HOST_OUTDATED', `Update Harness on ${pool.name ?? 'your computer'} to start this agent there.`, 409)
+ const chatId = stableId('agent-chat', me.id, me.generation, operationId)
+ state.conversations.push({ id: chatId, kind: 'agent-chat', title: name, leadId: null, agentIds: [], archived: false, brief: '', checks: [],
+ assignment: null, lastMessageSequence: 0, audience: { people: [{ id: me.id, generation: me.generation }] } })
+ const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,
+ ...(command.model ? { model: command.model } : {}), name, cwd: buddyHomeFolder(pool, me), worktree: false, requirements: BUDDY_REQUIREMENTS, regular: true }
+ const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!
+ state.starts ??= []
+ if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')
+ state.starts.push({ poolGeneration: admitted.generation, id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),
+ contributorId: me.id, membershipGeneration: me.generation, machineOwnerId: grant.machineOwnerId, hostGrant: null, request,
+ harnessId: null, dispatched: false, error: null, requestedAt: context.now })
+ Object.assign(result, { conversationId: chatId, startId: operationId })
+ break
+ }
case 'agent.startDispatch':
case 'agent.started':
case 'agent.startSettled':
@@ -3715,6 +3790,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...(isSwarmBuddyChat(group) ? start.request.buddySession?.projectId ? { projectId: start.request.buddySession.projectId } : {}
: state.projects ? { projectId: groupProject(state, group).id } : {}),
...(start.request.buddyScope ? { buddyScope: start.request.buddyScope } : {}),
+ ...(start.request.regular ? { regular: true as const } : {}),
...(start.request.buddyNarrow ? { buddyNarrow: true as const } : {}),
machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,
hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,
@@ -3849,9 +3925,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const target = agent(state, command.agentId)
// A Buddy is its owner's to stop (buddies.ts), and a Swarm-wide one has no project to look up.
if (isBuddy(target)) fail('BUDDY_NOT_RELEASED', 'A Buddy is stopped by its owner, or by turning Buddies off, never released.')
- const project = projectOf(state, agentProjectId(state, target))
+ // A Regular agent between tasks is in no project: its person, or the Swarm's owner, releases it (task #4116).
+ if (agentProjectId(state, target) === NO_PROJECT && !(actor.kind === 'person' && [state.ownerId, target.contributorId].includes(actor.userId))) {
+ fail('FORBIDDEN', 'Only its person or the tab owner can release this agent.', 403)
+ }
+ const project = agentProjectId(state, target) === NO_PROJECT ? undefined : projectOf(state, agentProjectId(state, target))
const isOwner = actor.kind === 'person' && [state.ownerId, target.contributorId].includes(actor.userId)
- if (!projectAgent(state, actor, project.id) && !isOwner) fail('FORBIDDEN', 'Only an agent of this project, the contributor or tab owner can release a worker.', 403)
+ if (project && !projectAgent(state, actor, project.id) && !isOwner) fail('FORBIDDEN', 'Only an agent of this project, the contributor or tab owner can release a worker.', 403)
protectLead(state, target.id, actor)
// Only its own active work holds a decision back, not the active work of a task it sits in.
if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id)) fail('WORK_ACTIVE', 'Finish active work before releasing this worker.')
@@ -3860,7 +3940,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A session a person shared by hand is its host's to close on a stop: of the other agents, only the coordinator releases
// it. Any agent of the project releases one the Swarm started, which alone records its session (security review L5;
// tidy.ts reads the same mark).
- if (actor.kind === 'agent' && actor.agentId !== target.id && !target.startedSession && ledProject(state, actor.agentId)?.id !== project.id) {
+ if (actor.kind === 'agent' && actor.agentId !== target.id && !target.startedSession && ledProject(state, actor.agentId)?.id !== project?.id) {
fail('COORDINATOR_REQUIRED', 'A person added this session, so of its project\'s agents only the coordinator releases it.', 403)
}
// Any other agent is kept or stopped on request, finished work or not, whatever its role (project instructions, phase 4):
@@ -4037,7 +4117,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (isBuddyChat(group)) fail('BUDDY_CHAT_FIXED', 'A Buddy chat stays its owner\'s and their Buddy\'s: nobody else is added to it.', 403)
const member = agent(state, command.agentId)
if (isBuddy(member)) fail('BUDDY_CHAT_ONLY', 'A Buddy stays in its own chat: its owner\'s alone.', 403)
- sameProject(state, group, member)
+ sameProject(state, group, member, !command.present)
// Any agent may lead a task or be added to one, a linked one included, whatever its role (project instructions, phase 4).
if (member.workDecision === 'stop' && (command.lead || command.present)) fail('STOP_REQUESTED', 'This agent is stopping. Wait for its execution host.')
if (!command.present) {
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index b3772ab9d..718efec25 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -6,7 +6,7 @@ import { MAX_HARNESSES, tokensByModelSchema } from './costs/tokens.js'
import { activeWork, occupiesAgent, fail, person, stableId, type Actor, type Agent, type AgentStart, type AgentStartRequest, type MessageDraft, type SuperTabState } from './model.js'
import { WORKSPACE_LABEL } from './workspaces.js'
import { startFinished } from './parts/write.js'
-import { agentProjectId, canReadAgent, canReadProject, groupProject, ledProject, ownsProject, projectOf, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'
+import { agentProjectId, isAgentChat, canReadAgent, canReadProject, groupProject, ledProject, ownsProject, projectOf, projectsOf, teamAccountPool, type SwarmProject } from './projects.js'
import { isSwarmBuddyChat } from './buddies.js'
export { teamAccountPool } from './projects.js'
import { conversation } from './model.js'
@@ -884,7 +884,8 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
// A person's one Buddy chat has no project (Dee, 10-31): its project session works in the one it names, and its main Buddy
// and plain sessions in none, in their own folder (buddyHomeFolder).
const group = forProject ? undefined : conversation(state, request.conversationId)
- const project = forProject ?? (!isSwarmBuddyChat(group!) ? groupProject(state, group!)
+ // A Regular agent's own chat has none either (agent.new, task #4116): it starts in its person's home folder.
+ const project = forProject ?? (isAgentChat(group!) ? undefined : !isSwarmBuddyChat(group!) ? groupProject(state, group!)
: request.buddySession?.projectId ? projectOf(state, request.buddySession.projectId) : undefined)
if (project && !pool.scope && project.id !== 'lead') fail('PROJECT_CONTRIBUTION', 'Ask its owner to add this machine to the swarm again to support other projects.')
// Kept by its owner for other projects: a Product Manager too. A Buddy is its owner's own (commands.ts buddy.create).
@@ -899,11 +900,11 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
// a Product Manager outside a Team account: any machine of the Swarm takes it (leadStart.ts, Ken 10-29).
// What the task needs to reach, checked here for every start whatever the route sent (an older CLI drops needs.access):
// a Buddy and a Product Manager need none (design section 3).
- const needed = !request.buddyOf && !request.leadFor ? taskAccess(group) : []
- if (!request.buddyOf && !(request.leadFor && !teamAccountPool(pool))) requireTeamWork(state, pool.machineId, pool.contributorId, project!, now, teamMachines, otherWorkspaceMachines, needed)
+ const needed = !request.buddyOf && !request.leadFor && !request.regular ? taskAccess(group) : []
+ if (!request.buddyOf && !request.regular && !(request.leadFor && !teamAccountPool(pool))) requireTeamWork(state, pool.machineId, pool.contributorId, project!, now, teamMachines, otherWorkspaceMachines, needed)
const missing = project ? accessRefusal(state, pool.machineId, project, needed) : null
if (missing) failTeamWork(missing)
- const cwd = project ? projectFolder(pool, project) : buddyHomeFolder(pool, { id: request.buddyOf!.personId })
+ const cwd = project ? projectFolder(pool, project) : buddyHomeFolder(pool, { id: request.buddyOf?.personId ?? pool.contributorId })
// Every refused field is named, with what the machine does accept. Values the caller sent are not echoed: an account
// setting can be a path or a name of the caller's own.
const refused: string[] = []
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index d1b85d8c4..b1974ac7a 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -147,6 +147,11 @@ export interface Agent {
/** A Buddy that reads every project its person reads (buddies.ts; Dee, 10-31): the main Buddy of a Swarm Buddy chat, or a
* plain session there. It has no project and writes nowhere but its own chat. A project session has its project instead. */
buddyScope?: 'swarm'
+ /** A Regular agent (agent.new, task #4116): in no project but its active task's (projects.ts agentProjectId). */
+ regular?: true
+ /** The private project a Regular agent first worked in: its one conversation holds that project's content, so it takes tasks
+ * only there from then on (projects.ts regularMayWorkIn; security review 2 of #4116). Set at its assignment, never cleared. */
+ privateProjectId?: string
/** A Buddy that reads one project and writes into it (Dee, 10-31): a project session, or the one Buddy's session in an older
* project chat. Its host never widens its reads beyond its folder (cli buddyGuard wide mode), which could hold another
* project's clone. */
@@ -199,6 +204,8 @@ export interface AgentStartRequest {
buddyOf?: { personId: string; generation: string }
/** A Swarm-wide Buddy's start (Agent.buddyScope), written by buddy.create or message.send alone. */
buddyScope?: 'swarm'
+ /** A Regular agent's start (agent.new, task #4116): in its person's own chat, in no project's folder. Written by the server alone. */
+ regular?: true
/** A one-project Buddy's start (Agent.buddyNarrow), written by message.send alone. */
buddyNarrow?: true
/** The person's messages in an older project chat its start waits on, delivered when it joins (ids only). */
@@ -394,7 +401,7 @@ export interface Conversation {
* project (buddies.ts), or their one Buddy chat for the whole Swarm, with no project (`swarm-buddy`, buddies.ts
* openSwarmBuddyChat; Dee, 10-31): a kind of its own, so an older release parks it unread (parkLaterConversations) instead
* of reading it as a project's. Absent on every other conversation. */
- kind?: 'leads' | 'buddy' | 'swarm-buddy'
+ kind?: 'leads' | 'buddy' | 'swarm-buddy' | 'agent-chat'
projectId?: string
/** Stable, tab-local workgroup reference. Lead has no number. */
number?: number
@@ -1030,7 +1037,7 @@ export function conversation(state: SuperTabState, id: string): Conversation {
export const isLeads = (group: Conversation): boolean => group.kind === 'leads'
-const KNOWN_KINDS: Record<NonNullable<Conversation['kind']>, true> = { leads: true, buddy: true, 'swarm-buddy': true }
+const KNOWN_KINDS: Record<NonNullable<Conversation['kind']>, true> = { leads: true, buddy: true, 'swarm-buddy': true, 'agent-chat': true }
/** Conversation kinds this release knows; one of another kind is kept aside unchanged (parkLaterConversations, parts/shape.ts). */
export const knownKind = (group: Pick<Conversation, 'kind'>): boolean => group.kind == null || Object.hasOwn(KNOWN_KINDS, group.kind)
/** During a rolling deploy the previous release reads what the next one wrote. A conversation kind it does not know
diff --git a/backend/src/superTabs/projectUpdates.ts b/backend/src/superTabs/projectUpdates.ts
index 0792d8edb..1a8fca6bc 100644
--- a/backend/src/superTabs/projectUpdates.ts
+++ b/backend/src/superTabs/projectUpdates.ts
@@ -1,5 +1,5 @@
import { author, conversation, isLeads, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
-import { agentProjectId, groupProject, projectOf, type SwarmProject } from './projects.js'
+import { agentProjectId, groupProject, NO_PROJECT, projectOf, type SwarmProject } from './projects.js'
import type { ProgressData } from './parts/types.js'
/** A project with no report progress yet starts clean at the start of every conversation's numbering. */
@@ -70,6 +70,8 @@ export function projectUpdateRequest(state: SuperTabState, target: Agent, now: n
// An older Swarm without stored projects is one synthesized project. It keeps no report progress (noteWorkChanges),
// so its Lead is woken only for lost work (liveness.ts), which replaced the wake-up for workers down two hours.
if (state.paused) return null
+ // An agent in no project (a Regular one between tasks, task #4116) leads none.
+ if (agentProjectId(state, target) === NO_PROJECT) return null
const project = projectOf(state, agentProjectId(state, target))
const group = conversation(state, project.leadConversationId), progress = project.progress
if (group.leadId !== target.id || group.archived) return null
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 7600024a8..0a095f79e 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -189,6 +189,11 @@ export function startProject(state: SuperTabState, request: Pick<AgentStartReque
export function agentProjectId(state: SuperTabState, target: Agent): string {
// A Swarm-wide Buddy has no project (Dee, 10-31): never the project 'lead' by default, so it matches none.
if (isSwarmBuddy(target)) return NO_PROJECT
+ // A Regular agent (task #4116: "the task decides where it works") is its active task's project's while it works, else none.
+ if (target.regular) {
+ const work = state.conversations.find(c => c.assignment?.agentId === target.id && activeWork(c))
+ return work ? groupProject(state, work).id : NO_PROJECT
+ }
return target.projectId ?? state.conversations.find(c => c.agentIds.includes(target.id))?.projectId ?? 'lead'
}
/** The project id of an agent in no project: no project has it, so a comparison with one is false and projectOf refuses it. */
@@ -311,6 +316,12 @@ export function readConversation(state: SuperTabState, actor: Actor, conversatio
if (!readsSwarmBuddyChat(state, actor, group)) fail('NOT_FOUND', 'This conversation is unavailable.', 404)
return group
}
+ // A person's chat with a Regular agent of theirs has no project either (agent.new, task #4116): its person and that agent.
+ if (isAgentChat(group)) {
+ author(state, actor)
+ if (!readsAgentChat(state, actor, group)) fail('NOT_FOUND', 'This conversation is unavailable.', 404)
+ return group
+ }
// A chat of a project the reader does not read is refused in the same words as one that does not exist: "project
// unavailable" told another project's chat apart from a made-up id (security review 2 of #2435).
author(state, actor)
@@ -338,6 +349,7 @@ export function canReadGroup(state: SuperTabState, actor: Actor, group: Conversa
export function readsRecordsIn(state: SuperTabState, actor: Actor, group: Conversation): boolean {
if (isLeads(group)) return false
if (isSwarmBuddyChat(group)) return readsSwarmBuddyChat(state, actor, group)
+ if (isAgentChat(group)) return readsAgentChat(state, actor, group)
const project = groupProject(state, group)
if (!canReadProject(state, actor, project)) return false
const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
@@ -350,6 +362,20 @@ export function readsRecordsIn(state: SuperTabState, actor: Actor, group: Conver
|| (PRIVATE_VISIBLE_TO_OWNERS && (member.id === project.ownerId || member.id === state.ownerId)))
}
+/** A person's chat with a Regular agent of theirs (agent.new, task #4116). */
+export const isAgentChat = (group: Pick<Conversation, 'kind'>): boolean => group.kind === 'agent-chat'
+
+/** Whether [actor] reads agent chat [group]: its person at the membership it was opened in, and an agent in it that runs on that
+ * person's own account. Nobody else: not the Swarm's owner, a project's owner or PM, or another agent, as a Swarm Buddy chat. */
+function readsAgentChat(state: SuperTabState, actor: Actor, group: Conversation): boolean {
+ const owner = group.audience?.people[0]
+ if (!owner || !state.people.some(p => p.id === owner.id && p.generation === owner.generation)) return false
+ if (actor.kind === 'person') return actor.userId === owner.id
+ const target = state.agents.find(a => a.id === actor.agentId)
+ return !!target && target.machineOwnerId === actor.machineOwnerId && group.agentIds.includes(target.id)
+ && target.contributorId === owner.id && target.machineOwnerId === owner.id
+}
+
/** Whether [actor] reads Swarm Buddy chat [group] (Dee, 10-31): its person at the membership it was opened in, and a Buddy in it
* of that person and membership. Nobody else: not the Swarm's owner, a project's PM or another agent. */
function readsSwarmBuddyChat(state: SuperTabState, actor: Actor, group: Conversation): boolean {
@@ -394,6 +420,13 @@ export function audienceOf(state: SuperTabState, project: SwarmProject, personId
export function canReadAgent(state: SuperTabState, actor: Actor, target: Agent): boolean {
// A Swarm-wide Buddy belongs to no project and writes only in its person's chat: its person reads it, and so does it.
if (isSwarmBuddy(target)) return actor.kind === 'person' ? actor.userId === target.buddyOf!.personId : actor.agentId === target.id
+ // An idle Regular agent (task #4116): its person, itself, and the PM of a project its person reads, which may give it a task.
+ if (target.regular && agentProjectId(state, target) === NO_PROJECT) {
+ if (actor.kind === 'person') return actor.userId === target.contributorId
+ if (actor.agentId === target.id) return true
+ const led = ledProject(state, actor.agentId)
+ return !!led && regularMayWorkIn(state, target, led)
+ }
return canReadProject(state, actor, projectOf(state, agentProjectId(state, target)))
}
@@ -572,8 +605,26 @@ export function readAgent(state: SuperTabState, actor: Actor, agentId: string):
/** A terminal contains its session's entire history. Joining another project's
* chat must never expose that history to a different audience. */
-export function sameProject(state: SuperTabState, group: Conversation, target: Agent): void {
- if (agentProjectId(state, target) !== groupProject(state, group).id) {
+/** Whether Regular agent [target] may take a task in [project]: its person reads it (it works only where they could read it
+ * themselves), and, once it has worked in a private project, it is that one: its one conversation holds that project's
+ * content, which no other project's members may hear from it (security review 2 of #4116). Public work moves on freely. */
+function regularMayWorkIn(state: SuperTabState, target: Agent, project: SwarmProject): boolean {
+ const member = state.people.find(p => p.id === target.contributorId)
+ return !!member && canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project)
+ && (!target.privateProjectId || target.privateProjectId === project.id)
+}
+
+/** [admitsIdleRegular]: an assignment, the one way an idle Regular agent comes into a project (task #4116), which records its
+ * private mark (commands.ts assignTo), or taking an agent out, which admits nobody. A chat join admits none: added while idle,
+ * it would hear a private project with nothing recorded, or sit in several projects at once (security review 2 of #4116). */
+export function sameProject(state: SuperTabState, group: Conversation, target: Agent, admitsIdleRegular = false): void {
+ const project = groupProject(state, group)
+ // An idle Regular agent takes its task's project, if it may work there; a busy one stays in its task's.
+ if (target.regular && agentProjectId(state, target) === NO_PROJECT) {
+ if (!admitsIdleRegular) fail('REGULAR_TASK_ONLY', 'A Regular agent joins a project through a task there: give it one.', 403)
+ if (regularMayWorkIn(state, target, project)) return
+ }
+ if (agentProjectId(state, target) !== project.id) {
fail('PROJECT_SESSION', 'Start a separate agent for another project. This terminal belongs to its original project.')
}
}
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 4dd2fd044..cb349cf04 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -79,7 +79,10 @@ export interface Derived {
releaseTimes?: Record<string, import('../releases.js').ReleaseLedger['nextAt'] & object>
/** Every agent the reader can see. `workDecision` is null when the stored value stands; `roleId` null outside Custom. */
/** `roleName`: the role it goes by (instructions.ts roleNameOf), its stored one or what it is. */
- agents: Record<string, { downSince: string | null; limitedUntil: string | null; workDecision: 'awaiting' | null; roleId: string | null; roleName: string }>
+ /** `kind`: the reader's Buddy, a PM leading a project, or a Regular agent; `chatId`: the chat its person talks to it in, or null
+ * (agentKind.ts, task #4116). Absent from an older backend. */
+ agents: Record<string, { downSince: string | null; limitedUntil: string | null; workDecision: 'awaiting' | null; roleId: string | null; roleName: string;
+ kind: import('../agentKind.js').AgentKind; chatId: string | null }>
/** Every contributed machine the reader can see. */
/** `clientVersion`: the CLI version its daemon last connected with (routing reads a machine updated since its failed starts). */
machines: Record<string, { availableSlots: number; teamWork: { allowed: true } | { allowed: false; reason: string; [key: string]: unknown }; clientVersion?: string
@@ -354,6 +357,8 @@ export interface HostPool {
buddyStarts?: AgentStart[]
/** Product Managers' starts (leadStart.ts), apart from `starts` for the same reason. */
leadStarts?: AgentStart[]
+ /** Regular agents' starts (commands.ts agent.new, task #4116), apart for the same reason. */
+ regularStarts?: AgentStart[]
projects?: Array<{ id: string; leadConversationId: string; repository?: unknown; conversationIds: string[] }>
localGrid?: string
reservations: Array<{ harnessId: string; generation: string }>
diff --git a/backend/src/superTabs/read/derivedEtag.test.ts b/backend/src/superTabs/read/derivedEtag.test.ts
index 27983e6cb..dbc2538bc 100644
--- a/backend/src/superTabs/read/derivedEtag.test.ts
+++ b/backend/src/superTabs/read/derivedEtag.test.ts
@@ -3,7 +3,7 @@ import type { Derived } from './contract.js'
import { derivedEtag, MARK_FIELDS } from './derivedEtag.js'
const summary = (): Derived => ({
- agents: { a1: { downSince: null, limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer' } },
+ agents: { a1: { downSince: null, limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer', kind: 'regular', chatId: null } },
machines: { m1: { availableSlots: 2, teamWork: { allowed: true } } },
mentionsWaiting: 1, mentionsDigest: 'd1', avatars: { 'person:p1': 'https://example.test/a?sig=1' },
})
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index 1bdf737d7..2d7451426 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -134,12 +134,15 @@ function pool(tabId: string, state: SuperTabState, machineId: string, user: Auth
&& (!s.harnessId || !s.poolSettled) && !s.error)
// A host from before Buddies reads only `starts`, and would launch a Buddy as a Builder: it never sees one. Nor a Product
// Manager (leadStart.ts), which goes only to a host that said it starts one.
- const starts = pending.filter(s => !s.request.buddyOf && !s.request.leadFor), buddyStarts = pending.filter(s => s.request.buddyOf)
+ // Nor a Regular agent (commands.ts agent.new, task #4116), which an older host would launch in a project folder it lacks.
+ const starts = pending.filter(s => !s.request.buddyOf && !s.request.leadFor && !s.request.regular), buddyStarts = pending.filter(s => s.request.buddyOf)
+ const regularStarts = pending.filter(s => s.request.regular)
const leadStarts = pending.filter(s => s.request.leadFor)
const buddyChats = new Set(buddyStarts.map(s => s.request.conversationId))
const reservations = (state.harnessReservations ?? []).filter(r => r.machineId === machineId)
const removedHere = (state.removedSessions ?? []).filter(r => r.machineId === machineId).map(r => r.harnessId)
return { tabId, paused: state.paused, machine: contribution, starts, ...(buddyStarts.length ? { buddyStarts } : {}), ...(leadStarts.length ? { leadStarts } : {}),
+ ...(regularStarts.length ? { regularStarts } : {}),
...(contribution.scope === 'swarm' ? { projects: projectsOf(state).filter(p => pending.some(s => startProject(state, s.request)?.id === p.id))
.map(p => ({ id: p.id, leadConversationId: p.leadConversationId, repository: p.repository,
// A private conversation is chat only and never runs work here, so its id stays with its audience; a Buddy chat whose
diff --git a/backend/src/superTabs/read/views.test.ts b/backend/src/superTabs/read/views.test.ts
index 311116274..e9084def4 100644
--- a/backend/src/superTabs/read/views.test.ts
+++ b/backend/src/superTabs/read/views.test.ts
@@ -126,10 +126,18 @@ describe('reader view of the parts (design 4.1, 4.3)', () => {
const view = readerView(parts, peer, NOW, { teamMachines: [] })
const worker = view.parts.agents.find(a => a.key === s.worker)!
for (const hidden of ['downNamed', 'downSince', 'limitedUntil', 'roleId']) expect(worker.data).not.toHaveProperty(hidden)
- expect(view.derived.agents[s.worker]).toEqual({ downSince: new Date(NOW - 5 * MINUTE).toISOString(), limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer' })
+ expect(view.derived.agents[s.worker]).toEqual({ downSince: new Date(NOW - 5 * MINUTE).toISOString(), limitedUntil: null, workDecision: null, roleId: null, roleName: 'Engineer', kind: 'regular', chatId: null })
expect(Object.keys(view.derived.agents).sort()).toEqual([s.lead, s.worker].sort())
})
+ // Task #4116 (Swarm v3): the left pane's "My agents" reads each agent's kind and its chat from the derived summary.
+ it('says each agent\'s kind and the chat its person talks to it in', () => {
+ const { parts, s } = scene()
+ const view = readerView(parts, owner, NOW, { teamMachines: [] })
+ expect(view.derived.agents[s.lead]).toMatchObject({ kind: 'pm', chatId: 'lead' })
+ expect(view.derived.agents[s.worker]).toMatchObject({ kind: 'regular', chatId: null })
+ })
+
// Free slots count every session the machine runs, as today, even ones this reader cannot see.
it('derives a machine\'s free slots and team work, and cuts its harness ids to what the reader can see', () => {
const { parts } = scene()
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 574b4a0f9..9c817a733 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -16,6 +16,7 @@ import { canReadGroup } from '../projects.js'
import { promptWaits } from '../promptWaits.js'
import { storedPulse, type Pulse } from '../pulse.js'
import { coordinatorNameOf, roleNameOf } from '../instructions.js'
+import { agentChatId, agentKind } from '../agentKind.js'
import { withAvatarView } from '../profile.js'
import { swarmUsernames } from '../usernames.js'
import type { AgentView, Derived, GroupView, HeadView, LivePart, MachineView, MemberView, ProgressView, StartView } from './contract.js'
@@ -208,7 +209,9 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
workDecision: seen.workDecision === 'awaiting' && state.agents.find(a => a.id === seen.id)!.workDecision !== 'awaiting' ? 'awaiting' as const : null,
roleId: seen.roleId ?? null,
// Derived on every read: who leads a project, and its role set, live outside the agent's own part.
- roleName: roleNameOf(state, state.agents.find(a => a.id === seen.id)!) }])),
+ roleName: roleNameOf(state, state.agents.find(a => a.id === seen.id)!),
+ // What it is and where its person talks to it, for the left pane's "My agents" (agentKind.ts, task #4116).
+ kind: agentKind(state, state.agents.find(a => a.id === seen.id)!), chatId: agentChatId(state, state.agents.find(a => a.id === seen.id)!) }])),
machines: Object.fromEntries((visible.machines ?? []).map(machine)),
...(visible.otherProjectsWork ? { otherProjectsWork: visible.otherProjectsWork } : {}),
...(visible.pmAccounts ? { pmAccounts: visible.pmAccounts } : {}),
diff --git a/backend/src/superTabs/regularAssign.test.ts b/backend/src/superTabs/regularAssign.test.ts
new file mode 100644
index 000000000..9010f6435
--- /dev/null
+++ b/backend/src/superTabs/regularAssign.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
+import type { ContributedMachine } from './machines.js'
+import { agentProjectId, canReadAgent, canReadGroup, NO_PROJECT } from './projects.js'
+
+// Task #4116 (Swarm v3, anh Dee 11-07): "A Regular agent isn't tied to a project; the task decides where it works." Its PM gives
+// it a task only in a project its person can read, so nothing reaches its person that they could not read anyway; while it
+// works there it is that project's, and it is in none again once the task ends.
+const NOW = 50_000_000
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const mate: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'mate', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+const own = (userId: string) => ({ contribution: { machineOwnerId: userId, contributorId: userId } })
+const resources = { cpuPercent: 1, memoryTotalBytes: 8, memoryUsedBytes: 1, diskFreeBytes: 8, diskTotalBytes: 8, projectDiskFreeBytes: 8,
+ deviceType: null, chip: null, os: null, gpuPercent: null }
+const code = (body: () => unknown): string | null => {
+ try { body(); return null } catch (error) { return error instanceof SuperTabError ? error.code : 'INVALID' }
+}
+
+function swarm() {
+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invited = run({ type: 'invite.create', email: mate.email, role: 'collaborator', conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, mate)
+ const generation = (userId: string) => state.people.find(p => p.id === userId)!.generation
+ state.machines = [{ machineId: 'mate-mac', name: 'mate-mac', contributorId: 'mate', membershipGeneration: generation('mate'), generation: 'g1',
+ cwd: '/swarm', scope: 'swarm', engines: ['claude'], maxAgents: 4, paused: false,
+ observation: { generation: 'g1', receivedAt: NOW, sessionKind: 'computer', resources, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [], capabilities: ['regularAgent'] } } as ContributedMachine]
+ // Mate's Regular agent Ada, running in its chat.
+ const made = run({ type: 'agent.new', kind: 'regular', name: 'Ada', engine: 'claude', machineId: 'mate-mac' } as Command, mate, own('mate'))
+ const startId = made.result.startId as string
+ run({ type: 'agent.startDispatch', startId }, mate, own('mate'))
+ const ada = run({ type: 'agent.started', startId, harnessId: 'h-ada', configuration: config }, mate, own('mate')).result.agentId as string
+ run({ type: 'agent.startSettled', startId, warning: null } as Command, mate, own('mate'))
+ /** A project of the owner's, [visibility], with its PM and one task. */
+ const project = (name: string, visibility: 'public' | 'private') => {
+ const created = run({ type: 'project.create', name, visibility, brief: '' }).result as { projectId: string; conversationId: string }
+ const pm = run({ type: 'agent.add', conversationId: created.conversationId, machineId: `${name}-mac`, harnessId: `h-pm-${name}`, name: `PM ${name}`,
+ configuration: config, lead: true }, owner, own('owner')).result.agentId as string
+ const task = run({ type: 'conversation.create', projectId: created.projectId, title: `${name} task`, brief: 'Do it.', checks: [] } as Command)
+ .result.conversationId as string
+ return { ...created, pm, task, asPm: { kind: 'agent', agentId: pm, machineOwnerId: 'owner' } as Actor }
+ }
+ const agent = (id: string) => state.agents.find(a => a.id === id)!
+ const group = (id: string) => state.conversations.find(c => c.id === id)!
+ return { run, ada, project, agent, group, get state() { return state } }
+}
+
+describe('a Regular agent and its task', () => {
+ it('is in no project until its PM gives it a task in a project its person reads; then it works there, and is in none again after', () => {
+ const f = swarm()
+ expect(agentProjectId(f.state, f.agent(f.ada))).toBe(NO_PROJECT)
+ const app = f.project('app', 'public')
+ // That project's PM sees it to give it work; its person reads the project.
+ expect(canReadAgent(f.state, app.asPm, f.agent(f.ada))).toBe(true)
+ const assigned = f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ expect(f.group(app.task).assignment).toMatchObject({ agentId: f.ada })
+ expect(agentProjectId(f.state, f.agent(f.ada))).toBe(app.projectId)
+ const asAda: Actor = { kind: 'agent', agentId: f.ada, machineOwnerId: 'mate' }
+ expect(canReadGroup(f.state, asAda, f.group(app.task))).toBe(true)
+ f.run({ type: 'work.status', conversationId: app.task, assignmentId: assigned.result.assignmentId as string, status: 'done', result: 'Done.' } as Command, asAda)
+ expect(agentProjectId(f.state, f.agent(f.ada))).toBe(NO_PROJECT)
+ })
+
+ it('takes no task in a project its person cannot read, whose PM never sees it', () => {
+ const f = swarm()
+ const secret = f.project('secret', 'private')
+ expect(canReadAgent(f.state, secret.asPm, f.agent(f.ada))).toBe(false)
+ expect(code(() => f.run({ type: 'work.assign', conversationId: secret.task, agentId: f.ada }, secret.asPm))).not.toBeNull()
+ expect(f.group(secret.task).assignment).toBeNull()
+ })
+
+ it('works in one project at a time', () => {
+ const f = swarm()
+ const app = f.project('app', 'public'), web = f.project('web', 'public')
+ f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ expect(code(() => f.run({ type: 'work.assign', conversationId: web.task, agentId: f.ada }, web.asPm))).not.toBeNull()
+ })
+
+ // Security review of #4116 (Layoutfix): its one terminal carries every project it worked in and its person's private chat, so
+ // only its person reads or types in it, whichever project's task it holds now.
+ it('keeps its terminal its person\'s alone, even from the PM whose task it holds, and from the Swarm\'s owner', () => {
+ const f = swarm()
+ const app = f.project('app', 'public'), web = f.project('web', 'public')
+ f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ for (const type of ['agent.screen', 'agent.input'] as const) {
+ const command = (type === 'agent.screen' ? { type, agentId: f.ada } : { type, agentId: f.ada, text: 'ls' }) as Command
+ expect(code(() => f.run(command, app.asPm))).toBe('TERMINAL_PRIVATE')
+ expect(code(() => f.run(command, web.asPm))).not.toBeNull()
+ expect(code(() => f.run(command, owner))).not.toBeNull()
+ expect(code(() => f.run(command, mate))).not.toBe('TERMINAL_PRIVATE')
+ }
+ })
+
+ it('keeps its terminal its person\'s alone even once it is out of its own chat', () => {
+ const f = swarm()
+ const app = f.project('app', 'public')
+ f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ for (const chat of f.state.conversations.filter(c => c.kind === 'agent-chat')) chat.agentIds = chat.agentIds.filter(id => id !== f.ada)
+ expect(code(() => f.run({ type: 'agent.screen', agentId: f.ada } as Command, app.asPm))).toBe('TERMINAL_PRIVATE')
+ })
+
+ // Security review 2 of #4116 (Rowan): the agent keeps one conversation, so what it learned in a private project would reach
+ // the members of the next project it works in. Once it has worked in a private project it takes tasks only there; work in
+ // public projects, which every member reads, moves on freely.
+ it('after a task in a private project, takes tasks only in that project, and no other project\'s PM sees it', () => {
+ const f = swarm()
+ const secret = f.project('secret', 'private'), web = f.project('web', 'public')
+ f.run({ type: 'project.sharing', projectId: secret.projectId, visibility: 'private', memberIds: ['owner', 'mate'] } as Command)
+ const done = (task: string, assignmentId: string) => f.run({ type: 'work.status', conversationId: task, assignmentId, status: 'done', result: 'Done.' } as Command,
+ { kind: 'agent', agentId: f.ada, machineOwnerId: 'mate' })
+ const first = f.run({ type: 'work.assign', conversationId: secret.task, agentId: f.ada }, secret.asPm)
+ done(secret.task, first.result.assignmentId as string)
+ expect(canReadAgent(f.state, web.asPm, f.agent(f.ada))).toBe(false)
+ expect(code(() => f.run({ type: 'work.assign', conversationId: web.task, agentId: f.ada }, web.asPm))).not.toBeNull()
+ const again = f.run({ type: 'conversation.create', projectId: secret.projectId, title: 'secret again', brief: 'Do it.', checks: [] } as Command).result.conversationId as string
+ expect(code(() => f.run({ type: 'work.assign', conversationId: again, agentId: f.ada }, secret.asPm))).toBeNull()
+ })
+
+ it('after tasks in public projects only, takes a task in any project its person reads', () => {
+ const f = swarm()
+ const app = f.project('app', 'public'), secret = f.project('secret', 'private')
+ f.run({ type: 'project.sharing', projectId: secret.projectId, visibility: 'private', memberIds: ['owner', 'mate'] } as Command)
+ const first = f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ f.run({ type: 'work.status', conversationId: app.task, assignmentId: first.result.assignmentId as string, status: 'done', result: 'Done.' } as Command,
+ { kind: 'agent', agentId: f.ada, machineOwnerId: 'mate' })
+ expect(code(() => f.run({ type: 'work.assign', conversationId: secret.task, agentId: f.ada }, secret.asPm))).toBeNull()
+ })
+
+ // Security review 2 of #4116, second read (Rowan): a Regular agent comes into a project only through a task, which is where its
+ // private mark is recorded. Added to a chat while idle, it would hear a private project with nothing recorded, or sit in
+ // several projects' chats at once.
+ it('is never added to a project\'s chat while it has no task there', () => {
+ const f = swarm()
+ const secret = f.project('secret', 'private'), web = f.project('web', 'public')
+ f.run({ type: 'project.sharing', projectId: secret.projectId, visibility: 'private', memberIds: ['owner', 'mate'] } as Command)
+ expect(code(() => f.run({ type: 'conversation.agent', conversationId: secret.task, agentId: f.ada, present: true, lead: false } as Command, secret.asPm))).toBe('REGULAR_TASK_ONLY')
+ // A person who cannot see it is refused sooner: it is no agent of theirs to add.
+ expect(code(() => f.run({ type: 'conversation.agent', conversationId: secret.conversationId, agentId: f.ada, present: true, lead: false } as Command))).not.toBeNull()
+ // Working in one project, it joins none of another's.
+ f.run({ type: 'work.assign', conversationId: web.task, agentId: f.ada }, web.asPm)
+ expect(code(() => f.run({ type: 'conversation.agent', conversationId: secret.task, agentId: f.ada, present: true, lead: false } as Command, secret.asPm))).not.toBeNull()
+ expect(f.group(secret.task).agentIds).not.toContain(f.ada)
+ })
+
+ it('once in a project that is then made private, takes tasks only there', () => {
+ const f = swarm()
+ const app = f.project('app', 'public'), web = f.project('web', 'public')
+ const first = f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ f.run({ type: 'work.status', conversationId: app.task, assignmentId: first.result.assignmentId as string, status: 'done', result: 'Done.' } as Command,
+ { kind: 'agent', agentId: f.ada, machineOwnerId: 'mate' })
+ f.run({ type: 'project.sharing', projectId: app.projectId, visibility: 'private', memberIds: ['owner', 'mate'] } as Command)
+ expect(code(() => f.run({ type: 'work.assign', conversationId: web.task, agentId: f.ada }, web.asPm))).not.toBeNull()
+ })
+
+ // Security review 2 of #4116, third read (Rowan): a finished task leaves its agent in that task's chat, so the agent would keep
+ // hearing and posting in an earlier project's chats while it works in a private one. Taking a task takes it out of them.
+ it('leaves every other project\'s chats when it takes a task, and neither hears nor posts there', () => {
+ const f = swarm()
+ const app = f.project('app', 'public'), secret = f.project('secret', 'private')
+ f.run({ type: 'project.sharing', projectId: secret.projectId, visibility: 'private', memberIds: ['owner', 'mate'] } as Command)
+ const asAda: Actor = { kind: 'agent', agentId: f.ada, machineOwnerId: 'mate' }
+ const first = f.run({ type: 'work.assign', conversationId: app.task, agentId: f.ada }, app.asPm)
+ f.run({ type: 'work.status', conversationId: app.task, assignmentId: first.result.assignmentId as string, status: 'done', result: 'Done.' } as Command, asAda)
+ expect(f.group(app.task).agentIds).toContain(f.ada)
+ f.run({ type: 'work.assign', conversationId: secret.task, agentId: f.ada }, secret.asPm)
+ expect(f.group(app.task).agentIds).not.toContain(f.ada)
+ const own = f.state.conversations.find(c => c.kind === 'agent-chat')!
+ expect(own.agentIds).toContain(f.ada)
+ const say = (conversationId: string, actor: Actor) => f.run({ type: 'message.send', conversationId, text: 'What are you on?', replyTo: null, recipientIds: [] } as Command, actor)
+ const heard = say(app.task, owner)
+ expect(heard.messages.flatMap(m => m.recipients ?? [])).not.toContain(f.ada)
+ expect(code(() => say(app.task, asAda))).not.toBeNull()
+ })
+
+ it('is seen idle by its person and itself, and by no other person', () => {
+ const f = swarm()
+ expect(canReadAgent(f.state, mate, f.agent(f.ada))).toBe(true)
+ expect(canReadAgent(f.state, { kind: 'agent', agentId: f.ada, machineOwnerId: 'mate' }, f.agent(f.ada))).toBe(true)
+ expect(canReadAgent(f.state, owner, f.agent(f.ada))).toBe(false)
+ })
+})
diff --git a/backend/src/superTabs/sessionScope.ts b/backend/src/superTabs/sessionScope.ts
index d5d001ed3..d398a41e8 100644
--- a/backend/src/superTabs/sessionScope.ts
+++ b/backend/src/superTabs/sessionScope.ts
@@ -6,13 +6,16 @@ import { isSwarmBuddy } from './buddies.js'
const scopeId = (state: SuperTabState, projectId: string) => stableId(state.id, projectId)
/** The scope of a Swarm-wide Buddy's session: no project's id. */
const SWARM_BUDDY_SCOPE = 'swarm-buddy'
+const REGULAR_SCOPE = 'regular-agent'
/** The record every Swarm registering one native session writes. */
export const sessionRecordId = (state: SuperTabState, target: Agent) => stableId('swarm-session', state.environment, target.machineOwnerId, target.id)
export async function bindSession(tx: Prisma.TransactionClient, state: SuperTabState, target: Agent, now = Date.now()) {
// A Swarm-wide Buddy is in no project (Dee, 10-31): its session is bound to the Swarm's Buddy scope, which no project shares.
- const project = isSwarmBuddy(target) ? { id: SWARM_BUDDY_SCOPE, visibility: 'public' as const } : projectOf(state, agentProjectId(state, target))
+ // So is a Regular agent, whose task decides its project (task #4116): its session keeps one scope of its own whatever task it holds.
+ const project = isSwarmBuddy(target) ? { id: SWARM_BUDDY_SCOPE, visibility: 'public' as const }
+ : target.regular ? { id: REGULAR_SCOPE, visibility: 'public' as const } : projectOf(state, agentProjectId(state, target))
const scope = scopeId(state, project.id)
const id = sessionRecordId(state, target)
const prior = await tx.superTabSessionScope.findUnique({ where: { id } })
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 53bf29cec..fe04649fd 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -384,7 +384,7 @@ const WIDE_WINDOW = 5 * LIST_SIZE
export const ABANDONED_START_MS = 15 * 60_000
/** The commands that start, assign or route work, which read which of the tab's machines are Team machines. */
-const TEAM_WORK_COMMANDS = new Set<Command['type']>(['agent.start', 'lead.start', 'agent.startDispatch', 'work.assign', 'conversation.agent', 'route.record', 'route.override'])
+const TEAM_WORK_COMMANDS = new Set<Command['type']>(['agent.start', 'agent.new', 'lead.start', 'agent.startDispatch', 'work.assign', 'conversation.agent', 'route.record', 'route.override'])
/** Whether an agent's command adds an agent to a task by opening it, by posting into it or by naming one there: those joins
* check team access as conversation.agent does (commands.ts teamJoin). An ordinary post reads no machine rows. */
const addsAgent = (state: SuperTabState, actor: Actor, command: Command): boolean => {
@@ -1158,6 +1158,9 @@ export class SuperTabStore {
if (delivery) groupIds.push(delivery.conversationId)
}
if (command.type === 'agent.remove') agentIds.push(command.agentId)
+ // A Regular agent's task takes it out of every other project's conversations (commands.ts assignTo), dormant ones too, which
+ // no first load holds (security review 1 of #4116).
+ if (command.type === 'work.assign' && state.agents.find(a => a.id === command.agentId)?.regular) agentIds.push(command.agentId)
// These only ask about the agent. A coordinator's project chat, always loaded, answers them, and every group it was ever in is
// what a read by agent gave: 1,668 on prod, growing with every task (Ken's profile, 2026-11-02, up to 1.66 s a read). Filtering
// that read by dormant would not do: its index has no dormant, so it examines them all, and removals need them (design D8).
@@ -2000,6 +2003,11 @@ export class SuperTabStore {
throw error
})
if (command.type === 'buddy.rename' || command.type === 'buddy.create') context.buddyNames = await buddyNames(tx, tabId, original)
+ // + New agent (task #4116): the person's own computer, by the store's reading of its account row, as a Buddy's.
+ if (command.type === 'agent.new') context.contribution = await this.contribution(tx, original, actor, command, true).catch(error => {
+ if (error instanceof SuperTabError && ['HOST_UNAVAILABLE', 'HOST_REQUIRED'].includes(error.code)) fail('AGENT_OWN_MACHINE', 'A new agent runs only on your own computer, in your own account.', 403)
+ throw error
+ })
if (command.type === 'agent.started' || command.type === 'agent.startDispatch') {
const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
context.contribution = await this.contribution(tx, original, actor, start.request, true)
diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.ts
index 07ec9849d..19e8ce194 100644
--- a/backend/src/superTabs/terminal.ts
+++ b/backend/src/superTabs/terminal.ts
@@ -4,7 +4,7 @@ import { ensureIndex } from '../lib/db/indexes.js'
import { activeWork, occupiesAgent, actorKey, agent, author, conversation, fail, isLeads, stableId, SuperTabError, type Actor, type Agent, type Author, type Conversation, type MessageDraft,
type SuperTabState } from './model.js'
import { downSince, productManagerOn } from './machines.js'
-import { agentProjectId, isConfidential, ledProject, onTeamAccount, ownSession, projectAgent, projectOf, readAgent, teamSessionAccess } from './projects.js'
+import { agentProjectId, isAgentChat, NO_PROJECT, isConfidential, ledProject, onTeamAccount, ownSession, projectAgent, projectOf, readAgent, teamSessionAccess } from './projects.js'
import { redactCredentials } from './credentials.js'
/** Any agent of an agent's project, or a person with write access, reads and types in its terminal through the host of its
@@ -101,6 +101,8 @@ export function currentGroup(state: SuperTabState, target: Agent): Conversation
return state.conversations.find(c => occupiesAgent(c) && c.assignment!.agentId === target.id)
?? state.conversations.find(c => activeWork(c) && c.assignment!.agentId === target.id)
?? state.conversations.findLast(c => !c.archived && !isLeads(c) && !c.audience && c.agentIds.includes(target.id) && c.leadId !== target.id)
+ // A Regular agent between tasks is in its own chat (agent.new, task #4116).
+ ?? (target.regular ? state.conversations.find(c => isAgentChat(c) && c.agentIds.includes(target.id)) : undefined)
?? conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId)
}
@@ -198,6 +200,8 @@ export function terminalAlert(state: SuperTabState, actor: Actor, sender: Author
export function leadOf(state: SuperTabState, target: Agent): Agent | undefined {
// A Buddy answers to its person alone, never to a PM; a Swarm-wide one has no project (Dee, 10-31).
if (target.buddyOf) return undefined
+ // Nor does an agent in no project: a Regular one between tasks (task #4116).
+ if (agentProjectId(state, target) === NO_PROJECT) return undefined
const lead = conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId).leadId
return lead && lead !== target.id ? state.agents.find(a => a.id === lead) : undefined
}
@@ -205,6 +209,7 @@ export function leadOf(state: SuperTabState, target: Agent): Agent | undefined {
/** A row about an agent, delivered to its project Lead: in the row's group when the Lead is there, else by a second row in
* the Lead's chat. */
export function toLead(state: SuperTabState, target: Agent, row: MessageDraft): MessageDraft[] {
+ if (agentProjectId(state, target) === NO_PROJECT) return [{ ...row, recipients: [] }]
const chat = conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId)
const lead = leadOf(state, target)?.id
const here = !!lead && conversation(state, row.conversationId).agentIds.includes(lead)
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index c8e0ffa11..82f927f09 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -355,7 +355,7 @@ describe('contributed machine executor', () => {
Object.assign(f.pool, { capabilitiesWanted: true })
await f.machine.tick()
const posted = (g: typeof f) => g.backend.mock.calls.filter(c => c[1] === 'POST').map(c => c[3] as Record<string, unknown>)
- expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'leadSwitch', 'buddyModel', 'buddyEngine', 'turnInbox'] })
+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'regularAgent', 'leadSwitch', 'buddyModel', 'buddyEngine', 'turnInbox'] })
// A backend from before them does not ask, and would refuse the field.
const older = fixture()
await older.machine.tick()
@@ -3130,3 +3130,16 @@ describe('fresh Buddy idle proof (#3824)', () => {
expect(f.core.agents.activity).toHaveBeenCalledTimes(1)
})
})
+
+// Task #4116 (Swarm v3): a Regular agent's start comes apart from `starts` (backend read/hostRows.ts), so a host from before
+// never launches it as a project's agent; this host launches it, and says it can.
+describe('a Regular agent\'s start', () => {
+ it('is launched from its own list', async () => {
+ const f = fixture()
+ const pool = f.pool as Record<string, unknown>
+ pool.regularStarts = pool.starts
+ pool.starts = []
+ await f.machine.tick()
+ expect(f.start).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 65dfe6a0b..9ea06f5b7 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -186,13 +186,14 @@ interface Reading { tab: string; observation: Record<string, unknown>; localMode
/** A host's starts: its workers', and its Buddies' and Product Managers', which the backend lists apart so that a host from
* before them never launches one as a worker. */
-const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts), ...list(row.leadStarts)]
+const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts), ...list(row.leadStarts), ...list(row.regularStarts)]
/** What this host launches beyond workers, said in its reading (backend leadStart.ts): a project's Product Manager, a
* Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions), and a person's one Buddy for the Swarm in its folder of
* project worktrees (spec 2026-10-31-one-buddy-per-swarm), which the backend offers only on a host that says so. */
// windowsBuddy: this CLI proves a command's pane from its parents on Windows too (callerPane.ts `windowsRunningPane`), so a
// Buddy there refuses no other agent's Swarm command. The backend starts no Buddy on a Windows machine without it.
-const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy']
+// `regularAgent`: it launches a Regular agent's start, sent apart as `regularStarts` (backend agent.new, task #4116).
+const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'regularAgent']
/** What this host does for a Product Manager's switch to another engine or account (spec 2026-11-02-pm-switch-engine-account),
* said beside the others: the backend refuses a switch to a host that does not. */
CAPABILITIES.push('leadSwitch')
diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.ts
index cd9133ee8..cfb8a7da7 100644
--- a/cli/src/superTabs/projectFolder.spec.ts
+++ b/cli/src/superTabs/projectFolder.spec.ts
@@ -207,6 +207,16 @@ describe('preparing another person\'s start with the Harness GitHub App', () =>
expect(app.prepare).not.toHaveBeenCalled()
})
+ // Task #4116 (Swarm v3): a Regular agent is in no project when it starts; its task decides where it works.
+ it('prepares nothing for a Regular agent, which starts in no project: no token, no clone, no fetch', async () => {
+ const app = hosted(new SuperTabHostError('NOT_FOUND', 'This start has no project folder to prepare.', 404))
+ Object.assign(app.start.request, { regular: true })
+ expect(await app.ready()).toBeNull()
+ expect(app.backend).not.toHaveBeenCalled()
+ expect(app.prepare).not.toHaveBeenCalled()
+ expect(app.fetch).not.toHaveBeenCalled()
+ })
+
it('in a team account, always asks for a token, and fails without one rather than using any other login', async () => {
const team = hosted()
expect(await team.ready(true)).toEqual({ requester: '[email protected]' })
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
index ef82ed3b4..9cc76d37a 100644
--- a/cli/src/superTabs/projectFolder.ts
+++ b/cli/src/superTabs/projectFolder.ts
@@ -83,6 +83,8 @@ export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,
// A person's one Buddy has no project: its launch makes its folder from the checkouts already here and fetches nothing
// (buddyHome.ts). Asking for a token anyway was refused with a 404, which failed every such start (2026-11-02).
if (request.buddyScope === 'swarm') return null
+ // Nor does a Regular agent (backend agent.new, task #4116): it starts in no project, in a folder of its own (start.ts).
+ if (request.regular === true) return null
// Nor does a project with no repository address (task #3211): there is nothing to clone, and the server refuses a token
// for it. Its work starts in a folder of its own, made without any login (prepareSwarmProject).
const project = startProject(row, request)
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index cd36a3ba3..4499816d6 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -846,6 +846,14 @@ describe('which branch a worktree starts from', () => {
expect(payload).toMatchObject({ cwd: folder })
expect(existsSync(join(folder, AGENT_FOLDER_MARK))).toBe(true)
})
+ // Task #4116 (Swarm v3): a Regular agent starts in no project, in a permanent folder of its own Harness makes and marks.
+ it('is a permanent folder of its own for a Regular agent, never the folder the request names', async () => {
+ const [payload] = await created(request => { request.worktree = false; request.regular = true })
+ const folder = agentFolderFor(projectsRoot(), 'start')
+ expect(payload).toMatchObject({ cwd: folder })
+ expect(payload).not.toHaveProperty('projectSource')
+ expect(existsSync(join(folder, AGENT_FOLDER_MARK))).toBe(true)
+ })
it('is not asked for when the agent works in the folder itself', async () => {
const [payload] = await created(request => { request.worktree = false })
expect(payload).toMatchObject({ cwd: '/repo' })
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index dd4271036..e0e1034b8 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -445,7 +445,8 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
// A start that works in the folder it names, when that folder is a temporary one: a scratchpad, which Claude Code asks
// about on every run and nobody answers (computer's Dee, Scholes 11-06, #3713). The agent gets a permanent folder of its
// own, made, marked and trusted here, and removed when it stops (agentFolder.ts, machines.ts).
- const agentFolder = !homeFolder && request.worktree !== true && typeof request.cwd === 'string' && temporaryFolder(request.cwd)
+ // So does a Regular agent (backend agent.new, task #4116), which starts in no project: the backend's folder only admits it.
+ const agentFolder = !homeFolder && request.worktree !== true && (request.regular === true || (typeof request.cwd === 'string' && temporaryFolder(request.cwd)))
? agentFolderFor(projectsRoot(), startId) : null
// A folder there Harness did not make is refused, and so is the start: it never runs, or trusts, in someone else's folder.
if (agentFolder) {
diff --git a/docs/plans/2026-11-07-regular-or-pm-agents-plan.md b/docs/plans/2026-11-07-regular-or-pm-agents-plan.md
new file mode 100644
index 000000000..b03dceba3
--- /dev/null
+++ b/docs/plans/2026-11-07-regular-or-pm-agents-plan.md
@@ -0,0 +1,79 @@
+# Regular or PM agents, and joining by bringing your own agent: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** Swarm v3's agent model on the server and the CLI host (task #4116, requested by Dee through Harness; spec
+docs/specs/2026-11-07-swarm-v3.md, written by #4115): a new member joins and brings their own agent, which becomes their Buddy
+with no add-machine step; "+ New agent" makes a Regular or a PM agent on the person's own computer and account; a PM names and
+starts a project; a Regular agent is in no project, and the task it is given decides where it works. The Desktop screens are
+#4118 and #4121.
+
+**Architecture:**
+
+- **Join and bring your agent:** unchanged. `buddy.create` with `setup` already records the computer as Buddy-only and starts
+ the Buddy there (commands.ts addBuddyMachine). A test now pins it for a brand-new member.
+- **Kind and chat** (agentKind.ts): each agent in the Swarm read says `kind` (`buddy` | `pm` | `regular`) and `chatId`, the chat
+ its person talks to it in (`derived.agents`). Bold for unread is the client's: that chat's last message against its read mark.
+- **`agent.new`** (commands.ts): a person's own agent on their own listed computer and account, the grant read from the
+ machine's account row as a Buddy's is (store.ts contribution). A Buddy-only record does not count: Desktop adds the computer
+ first, with no screen.
+ - `kind: 'pm'`: a new project named `projectName`, made by the same helper as `project.create`, and its PM placed by
+ placeLead, with no repository needed.
+ - `kind: 'regular'`: a chat of kind `agent-chat` with its person alone, and a start marked `regular`. It starts in its
+ person's home folder, as a Swarm Buddy does.
+- **A Regular agent's project** (projects.ts): `agentProjectId` is its active task's project, else none. While idle it is seen
+ only by its person, itself, and the PM of a project its person reads; such a PM may give it a task there (sameProject). It
+ works in one project at a time. Its one conversation keeps what it learned, so once it has worked in a private project it
+ takes tasks only there (`privateProjectId`, set at that assignment; security review 2). Public work moves on freely.
+- **An agent chat** is read and written by its person, at the membership it was opened in, and by their own agent in it.
+ Nobody else reads it: not the Swarm's owner, a project's owner or PM, or another agent (projects.ts readsAgentChat).
+- **The host:** a Regular start is listed apart (`regularStarts`, read/hostRows.ts), so an older host never launches it as a
+ project's agent. `agent.new` is refused with "Update Harness" on a computer whose host does not say `regularAgent`. The CLI host
+ launches it in a permanent folder of its own (agentFolder.ts) and prepares no project, token or clone for it.
+
+**Tech Stack:** TypeScript backend and CLI, vitest.
+
+## Global Constraints
+
+- No code path reads a Claude or ChatGPT login. Identity is always the person's own, never the machine owner's.
+- Who can read what stays as today; a Regular agent reaches only projects its person can read.
+- Swarm code stays out of cli/src/core. Temp files only in `mktemp -d` folders.
+
+## Design
+
+- growth: one chat per Regular agent (capped by the Swarm's starts and its 100-project limit for PMs); a removed agent's chat
+ stays as a conversation, read by its person.
+- concurrency: the Swarm's usual write. A new chat and its start, or a project and its PM, land in one command.
+- read cost: `kind` and `chatId` come from the loaded state (ledProject and one scan of the conversations), on the reads that
+ already build `derived.agents`. A Regular agent's project is one scan for its active task.
+- scale: 10x agents means 10x rows in `derived.agents`, inside the existing per-agent cost. The first warning would be the
+ Swarm read's p95.
+- compatibility: the backend ships first. An older app ignores `kind` and `chatId`. An older backend refuses `agent.new` as an
+ invalid command type, and Desktop says "Update Harness". An older host never sees `regularStarts`. An older release reading
+ an `agent-chat` parks it unchanged (model.ts KNOWN_KINDS) once it knows the kind; one from before parks it as unknown.
+- migration and rollback: none. Rolled back, Regular agents and their chats stay as data. Their starts wait, and their chats are
+ kept aside by the older release.
+- audience: the server enforces it (readsAgentChat, canReadAgent, sameProject). Two security reviews.
+- identity: the person's own account on their own computer (`grant.machineOwnerId === person`), never a share and never a Team
+ account.
+- failure: every refusal names what to do: add the computer, update Harness, name the project or the agent.
+- platforms: backend; the CLI host on macOS, Linux and Windows (folder paths through agentFolder.ts).
+
+## Review Focus
+
+- Nobody but its person and their agent reads an agent chat.
+- A Regular agent never takes a task in a project its person cannot read, and never two projects at once.
+- A Regular agent that worked in a private project never takes another project's task.
+- `agent.new` never runs on another person's computer, a shared machine or a Team account.
+
+## Tasks (all test first)
+
+- [x] Kind and chat in the Swarm read.
+- [x] Join and bring your agent, pinned for a new member.
+- [x] `agent.new`: PM and Regular, own computer only, through the store.
+- [x] A Regular agent's chat: its person and its agent only.
+- [x] A Regular agent's task: only a project its person reads, one at a time.
+- [x] The host: `regularStarts`, the `regularAgent` capability, a folder of its own.
+- [ ] Left for after 09:00 if time runs out: a Regular agent working in the task's repository folder on its computer. Today it
+ takes the task and works from its own folder.