The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Backend: custom role sets per project (#1652)
0xken154598d762a4a5
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 5a7335c76..79683cbc2 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -1,4 +1,4 @@-import { randomUUID } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'import { execFile } from 'node:child_process'import { promisify } from 'node:util'import { join } from 'node:path'@@ -1358,6 +1358,59 @@ describe('Super Tabs on a real Mongo replica set', () => {await db.superTab.update({ where: { id: tab }, data: { state } })expect(await modes()).toEqual({ [lead]: 'default', [legacyLead]: 'orchestration' })})+ it('keeps custom role texts out of the tab and the host rows, and serves a text only to the project owner, its Lead and its agents\' hosts', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),+ name: 'Worker', configuration: config, lead: false })).result.agentId as string+ const version = (text: string) => createHash('sha256').update(text).digest('hex').slice(0, 16)+ const roles = [{ id: 'lead', name: 'Product Manager', kind: 'lead' as const, text: 'LEAD-TEXT' },+ { id: 'dev', name: 'Engineer', kind: 'builder' as const, text: 'DEV-TEXT' }, { id: 'review', name: 'Reviewer', kind: 'reviewer' as const, text: 'REVIEW-TEXT' }]+ await run(tab, { type: 'project.roles.create', projectId: 'lead', roles })+ const rows = async () => (await store.hostTabs(host, 'test-host')).filter(r => r.tabId === tab)+ const rowOf = async (id: string) => (await rows()).find(r => r.agent.id === id)!+ expect(await rowOf(worker)).not.toHaveProperty('role')+ await run(tab, { type: 'project.skills', projectId: 'lead', mode: 'custom' })+ expect(await rowOf(lead)).toMatchObject({ skillMode: 'default', role: { id: 'lead', name: 'Product Manager', kind: 'lead', version: version('LEAD-TEXT') } })+ expect(await rowOf(worker)).toMatchObject({ skillMode: 'default', role: { id: 'dev', name: 'Engineer', kind: 'builder', version: version('DEV-TEXT') } })+ const stored = JSON.stringify((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state)+ for (const text of [JSON.stringify(await rows()), stored, JSON.stringify((await store.read(owner, tab)).state)]) expect(text).not.toMatch(/LEAD-TEXT|DEV-TEXT/)++ const text = (user: AuthUser, roleId: string, asAgentId?: string) => app.inject({ method: 'GET',+ url: `/api/super-tabs/${tab}/projects/lead/roles/${roleId}${asAgentId ? `?asAgentId=${asAgentId}` : ''}`, headers: { authorization: `Bearer ${user.sub}` } })+ for (const [user, as] of [[owner], [host], [host, lead]] as Array<[AuthUser, string?]>) {+ const answer = await text(user, 'dev', as)+ expect(answer.statusCode, answer.body).toBe(200)+ expect(answer.json().data).toEqual({ version: version('DEV-TEXT'), text: 'DEV-TEXT' })+ }+ for (const [user, as] of [[peer], [host, worker]] as Array<[AuthUser, string?]>) expect((await text(user, 'dev', as)).statusCode).toBe(404)+ expect((await text(owner, 'aaaaaaaaaaaa')).statusCode).toBe(404)+ // A host reads a text only while it could host the agent now: its machine active and the contributor's share grant live.+ const share = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [] } })+ try { expect((await text(host, 'dev')).statusCode).toBe(404) } finally {+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: share.emails } })+ }+ await db.machine.update({ where: { machineId: 'test-host' }, data: { deletedAt: new Date() } })+ try { expect((await text(host, 'dev')).statusCode).toBe(404) } finally {+ await db.machine.update({ where: { machineId: 'test-host' }, data: { deletedAt: null } })+ }+ expect((await text(host, 'dev')).statusCode).toBe(200)++ await run(tab, { type: 'project.role.set', projectId: 'lead', role: { ...roles[1]!, text: 'DEV-TEXT v2' } })+ expect((await rowOf(worker)).role).toMatchObject({ id: 'dev', version: version('DEV-TEXT v2') })+ expect((await text(owner, 'dev')).json().data).toEqual({ version: version('DEV-TEXT v2'), text: 'DEV-TEXT v2' })+ await run(tab, { type: 'project.role.remove', projectId: 'lead', roleId: 'review' })+ expect((await text(owner, 'review')).statusCode).toBe(404)+ expect(await db.superTabRoleText.count({ where: { tabId: tab } })).toBe(2)+ await run(tab, { type: 'project.roles.reset', projectId: 'lead', roles: roles.slice(0, 2) })+ expect((await text(owner, 'dev')).json().data.text).toBe('DEV-TEXT')++ const other = (await run(tab, { type: 'project.create', name: 'Other', visibility: 'public', brief: '' })).result.projectId as string+ await run(tab, { type: 'project.roles.create', projectId: other, roles })+ await run(tab, { type: 'project.delete', projectId: other })+ expect(await db.superTabRoleText.count({ where: { tabId: tab, projectId: other } })).toBe(0)+ })it('closes the replying agent\'s own deliveries of a message as answered, and nobody else\'s', async () => {const { tab, lead } = await fixture()const helper = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex cf5ce414a..c05a86b2d 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1171,6 +1171,19 @@ model SuperTabStopReceipt {@@unique([tabId, assignmentId])}+// A custom role's skill text (superTabs/projects.ts ProjectRole), outside the tab snapshot: the snapshot keeps only+// its version, so tab reads and host rosters stay small. Hosts fetch the text when the version changes.+model SuperTabRoleText {+ id String @id @map("_id")+ tabId String+ projectId String+ roleId String+ version String+ text String++ @@index([tabId, projectId])+}+// Configuration observations stay outside the tab snapshot so a long-running// assignment keeps its complete history without making every tab read grow.model SuperTabConfiguration {diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 2b118c6b6..9d6dc2625 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -28,6 +28,7 @@ const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegatbefore: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional() }).refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')const decisionParams = tabParams.extend({ decisionId: id })+const roleParams = tabParams.extend({ projectId: id, roleId: id })const terminalParams = tabParams.extend({ requestId: id })const hostParams = z.object({ machineId: id })const hostStartParams = hostParams.extend({ tabId: id, startId: id })@@ -159,6 +160,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/route-decisions',{ preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },(req, reply) => respond(reply, () => store.routeDecisions(req.user!, req.params.tabId, req.query.asAgentId)))+ app.get<{ Params: z.infer<typeof roleParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/projects/:projectId/roles/:roleId',+ { preHandler: [validateParams(roleParams), validateQuery(agentQuery)] },+ (req, reply) => respond(reply, () => store.roleText(req.user!, req.params.tabId, req.params.projectId, req.params.roleId, req.query.asAgentId)))app.get<{ Params: z.infer<typeof decisionParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/route-decisions/:decisionId',{ preHandler: [validateParams(decisionParams), validateQuery(agentQuery)] },(req, reply) => respond(reply, () => store.routeDecision(req.user!, req.params.tabId, req.params.decisionId, req.query.asAgentId)))diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 616db44cf..9032387cf 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -11,7 +11,7 @@ import { routingOverrideSchema } from './routingPolicy.js'import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, type RunTarget } from './rules.js'import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, type TerminalRequest } from './terminal.js'-import { agentProjectId, deleteProject, groupProject, inviteLanding, ledProject, manageProject, mutableProjects, placeRules, projectMembers, projectOf, projectRules, readAgent, readConversation, readProject, sameProject, sharedWithLeads, SKILL_MODE_NAMES, skillModeOf, type SwarmProject } from './projects.js'+import { agentKind, agentProjectId, agentSetRole, deleteProject, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const title = z.string().trim().min(1).max(160)@@ -37,8 +37,13 @@ const repositoryUrl = z.string().max(4096).refine(value => {} catch { return false }}, 'Share a repository URL without credentials.')const project = z.object({ cwd: path, repositoryUrl: repositoryUrl.nullable() }).strict()+// Copied Default roles keep the ids lead, dev and review; a role the owner adds gets 12 random hex characters from the client.+const roleId = z.string().regex(/^([0-9a-f]{12}|lead|dev|review)$/)+const role = z.object({ id: roleId, name: z.string().trim().min(1).max(40), kind: z.enum(['lead', 'builder', 'reviewer']),+ text: z.string().min(1).refine(value => Buffer.byteLength(value) <= 65_536, 'A role\'s skill text is at most 64 KB.') }).strict()+const roleSet = z.array(role).min(1).max(MAX_ROLES)export const startRequestSchema = z.object({- conversationId: id, machineId: id, engine: swarmEngine, name: title, cwd: path, role: z.enum(['builder', 'reviewer']).optional(),+ conversationId: id, machineId: id, engine: swarmEngine, name: title, cwd: path, role: z.enum(['builder', 'reviewer']).optional(), roleId: roleId.optional(),worktree: z.boolean(), branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(),model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),permissionMode: z.string().min(1).max(80).optional(), codexHome: path.optional(),@@ -71,7 +76,11 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('project.cadence'), projectId: id, minutes: z.union([z.literal(1), z.literal(5), z.literal(15), z.literal(30)]) }).strict(),z.object({ type: z.literal('project.report'), projectId: id, throughRevision: z.number().int().nonnegative().safe(), text: text.nullable() }).strict(),z.object({ type: z.literal('project.repository'), projectId: id, repositoryUrl }).strict(),- z.object({ type: z.literal('project.skills'), projectId: id, mode: z.enum(['default', 'orchestration']), askedIn: askedInSchema.optional() }).strict(),+ z.object({ type: z.literal('project.skills'), projectId: id, mode: z.enum(['default', 'orchestration', 'custom']), askedIn: askedInSchema.optional() }).strict(),+ z.object({ type: z.literal('project.roles.create'), projectId: id, roles: roleSet }).strict(),+ z.object({ type: z.literal('project.role.set'), projectId: id, role }).strict(),+ z.object({ type: z.literal('project.role.remove'), projectId: id, roleId }).strict(),+ z.object({ type: z.literal('project.roles.reset'), projectId: id, roles: roleSet }).strict(),z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(), checks: z.array(check).max(40) }).strict().refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.').refine(c => !c.task || renderWorkTask(c.task).length <= 8000, 'Keep the rendered task within 8,000 characters.'),@@ -104,7 +113,7 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('work.define'), conversationId: id, brief: text.optional(), task: task.optional(), checks: z.array(check).min(1).max(40) }).strict().refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.').refine(c => !c.task || renderWorkTask(c.task).length <= 32_000, 'Keep the rendered task within 32,000 characters.'),- z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),+ z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, roleId: roleId.optional(), routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),z.object({ type: z.literal('work.status'), conversationId: id, assignmentId: id,status: z.enum(['working', 'needs_human', 'blocked', 'review', 'done', 'stopped']), result: text.nullable() }).strict(),z.object({ type: z.literal('work.cancel'), conversationId: id, assignmentId: id, reason }).strict(),@@ -174,6 +183,45 @@ function assignable(group: Conversation, worker: Agent): void {if (!reviewer && group.reviewOf) fail('REVIEW_GROUP', 'A review group is assigned only to a Reviewer.')}+/** A whole custom set: one lead role (always id lead, so its Lead never loses it), ids and names unique, names ignoring case. */+function roleSetOf(roles: ProjectRole[]): ProjectRole[] {+ const leads = roles.filter(r => r.kind === 'lead')+ if (leads.length !== 1) fail('ROLE_LEAD', 'A role set has exactly one lead role.', 400)+ if (leads[0]!.id !== 'lead') fail('ROLE_LEAD', 'The lead role keeps the id lead.', 400)+ if (new Set(roles.map(r => r.id)).size !== roles.length || new Set(roles.map(r => r.name.toLowerCase())).size !== roles.length) {+ fail('ROLE_NAME', 'Role names and ids are unique in the set.', 400)+ }+ return roles+}+const projectRole = (r: z.infer<typeof role>): ProjectRole => ({ id: r.id, name: r.name, kind: r.kind, version: roleVersion(r.text) })++/** The custom set's role an agent of this kind is started or assigned with. */+function chosenRole(project: SwarmProject, id: string, kind: RoleKind): ProjectRole {+ const chosen = project.roles?.find(r => r.id === id) ?? fail('ROLE_UNAVAILABLE', 'This role is not in this project\'s custom roles.', 400)+ if (chosen.kind !== kind) fail('ROLE_KIND', `${chosen.name} is a role of another kind: ${chosen.kind}, not ${kind}.`, 400)+ return chosen+}++/** Removing roles, or changing one's kind, never leaves a project's agent without the role it runs. */+function keepUsedRoles(state: SuperTabState, project: SwarmProject, next: ProjectRole[]): void {+ const dropped = new Set<string>()+ const users = state.agents.filter(a => {+ if (agentProjectId(state, a) !== project.id) return false+ const used = agentSetRole(state, project, a)+ if (!used || next.some(r => r.id === used.id && r.kind === used.kind)) return false+ dropped.add(used.id)+ return true+ })+ if (users.length) fail('ROLE_IN_USE', `Stop or reassign the ${users.length} agent${users.length === 1 ? '' : 's'} with ${dropped.size === 1 ? 'this role' : 'these roles'} first.`)+}++/** On Custom, an agent whose kind has no role there takes no new work, and the project has no review groups without a reviewer role. */+function requireCustomRole(project: SwarmProject, kind: RoleKind): void {+ if (skillSetOf(project) === 'custom' && !project.roles!.some(r => r.kind === kind)) {+ fail('ROLE_GONE', `This project's Custom skills have no ${kind} role.`)+ }+}+function controls(state: SuperTabState, actor: Actor, conversationId = 'lead'): void {const group = readConversation(state, actor, conversationId)if (actor.kind === 'agent' && group.leadId !== actor.agentId) {@@ -487,10 +535,56 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('OWNER_MESSAGE_REQUIRED', 'Only the project owner changes its skills; quote a chat message the project owner wrote in the last day asking for this change.', 403)}}- if (skillModeOf(project) === command.mode) break+ if (command.mode === 'custom' && !project.roles) fail('ROLES_MISSING', 'Create the project\'s custom roles first.')+ if (skillSetOf(project) === command.mode) breakmutableProjects(state)- projectOf(state, project.id).skillMode = command.mode- message(project.leadConversationId, `Skills: ${SKILL_MODE_NAMES[command.mode]}`, [], null, SYSTEM_ROW)+ const changed = projectOf(state, project.id)+ changed.skillSet = command.mode+ // Older clients know only skillMode: on Custom they run the Default text, the closest to the copied set.+ changed.skillMode = command.mode === 'custom' ? 'default' : command.mode+ message(project.leadConversationId, `Skills: ${SKILL_SET_NAMES[command.mode]}`, [], null, SYSTEM_ROW)+ if (command.mode !== 'custom') break+ for (const target of state.agents.filter(a => agentProjectId(state, a) === project.id && !agentSetRole(state, changed, a))) {+ const group = state.conversations.find(c => !c.archived && !isLeads(c) && c.agentIds.includes(target.id)) ?? conversation(state, project.leadConversationId)+ effects.messages.push({ id: stableId(operationId, 'role-gone', target.id), conversationId: group.id, author: sender, recipients: [target.id], replyTo: null,+ text: `Custom has no ${agentKind(state, target) === 'reviewer' ? 'Reviewer' : 'Engineer'} role for ${target.displayName ?? target.name}. `+ + 'Finish your current work; you take no new work.', source: SYSTEM_ROW })+ }+ break+ }+ case 'project.roles.create': {+ const project = manageProject(state, actor, command.projectId)+ if (project.roles) fail('ROLES_EXIST', 'This project already has custom roles.')+ project.roles = roleSetOf(command.roles.map(projectRole))+ break+ }+ case 'project.role.set': {+ const project = manageProject(state, actor, command.projectId)+ const roles = project.roles ?? fail('ROLES_MISSING', 'Create the project\'s custom roles first.')+ const existing = roles.find(r => r.id === command.role.id)+ if (existing?.kind === 'lead' && command.role.kind !== 'lead') fail('ROLE_LEAD', 'The lead role stays a lead role.', 400)+ if (!existing && roles.length >= MAX_ROLES) fail('ROLES_FULL', `A project has at most ${MAX_ROLES} roles.`)+ const next = roleSetOf(existing ? roles.map(r => r === existing ? projectRole(command.role) : r) : [...roles, projectRole(command.role)])+ keepUsedRoles(state, project, next)+ project.roles = next+ break+ }+ case 'project.role.remove': {+ const project = manageProject(state, actor, command.projectId)+ const roles = project.roles ?? fail('ROLES_MISSING', 'Create the project\'s custom roles first.')+ const removed = roles.find(r => r.id === command.roleId) ?? fail('NOT_FOUND', 'This role is unavailable.', 404)+ if (removed.kind === 'lead') fail('ROLE_LEAD', 'The lead role cannot be removed.', 400)+ const next = roles.filter(r => r !== removed)+ keepUsedRoles(state, project, next)+ project.roles = next+ break+ }+ case 'project.roles.reset': {+ const project = manageProject(state, actor, command.projectId)+ if (!project.roles) fail('ROLES_MISSING', 'Create the project\'s custom roles first.')+ const next = roleSetOf(command.roles.map(projectRole))+ keepUsedRoles(state, project, next)+ project.roles = nextbreak}case 'project.rename': {@@ -660,6 +754,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (reviewed.id === project.leadConversationId || reviewed.reviewOf || groupProject(state, reviewed).id !== project.id) {fail('REVIEW_TARGET', 'A review group reviews one build group of the same project.', 400)}+ requireCustomRole(project, 'reviewer')}const number = nextConversationNumber(state)state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),@@ -742,6 +837,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (!['claude', 'codex'].includes(command.request.engine)) {fail('SWARM_ENGINE', 'A Swarm agent runs only Claude Code or Codex.', 400)}+ const home = groupProject(state, conversation(state, command.request.conversationId))+ if (command.request.roleId) chosenRole(home, command.request.roleId, command.request.role ?? 'builder')+ else requireCustomRole(home, command.request.role ?? 'builder')// The Lead's account has machines the Swarm never prepared (no clone of the project), so a Lead may start only where the// Swarm already lists a machine: a contributed one, or one an agent of the Swarm runs on. A person's start may name any// machine of theirs, because the first Lead is created before anything is listed.@@ -826,7 +924,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma...(state.projects ? { projectId: groupProject(state, group).id } : {}),machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId,- ...(start.request.role ? { role: start.request.role } : {}),+ ...(start.request.role ? { role: start.request.role } : {}), ...(start.request.roleId ? { roleId: start.request.roleId } : {}),...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })group.agentIds.push(agentId)start.harnessId = command.harnessId@@ -1132,6 +1230,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst worker = agent(state, command.agentId)assignable(group, worker)sameProject(state, group, worker)+ const home = groupProject(state, group)+ if (command.roleId) worker.roleId = chosenRole(home, command.roleId, agentKind(state, worker)).id+ else requireCustomRole(home, agentKind(state, worker))requireWorkerDecisions(state, actor, group, worker.id)if (worker.workDecision === 'stop') fail('STOP_REQUESTED', 'This worker is stopping. Wait for its execution host.')if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 724c53c60..70b271638 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto'import type { RouteDecisionEffect } from './routeRecord.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'import { downSince } from './machines.js'-import { canReadAgent, canReadProject, groupProject, ledProject, placeRules, projectsOf, sharedWithLeads, type ProjectVisibility, type SwarmProject } from './projects.js'+import { agentProjectId, agentSetRole, canReadAgent, canReadProject, groupProject, ledProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'export type Role = 'owner' | 'collaborator' | 'viewer'export interface Person { id: string; email: string; role: Role; generation: string }@@ -27,6 +27,8 @@ export interface Agent {displayName?: string/** Chosen at start and kept for the session. Absent reads as builder (agentRole); the Lead is derived from leadId. */role?: AgentRole+ /** The project's custom role it runs, chosen at start or assignment (projects.ts agentSetRole). */+ roleId?: string | null/** A finished worker stays undecided even when its group receives a new brief. */workDecision?: 'awaiting' | 'keep' | 'stop'releaseId?: string@@ -51,6 +53,7 @@ export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?export interface AgentStartRequest {conversationId: stringrole?: AgentRole+ roleId?: stringmachineId: stringengine: stringmodel?: string@@ -407,6 +410,13 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(visible.invitations = visible.invitations.filter(i => visible.conversations.some(c => c.id === i.conversationId))}for (const project of projectsOf(visible)) for (const target of awaitingWorkers(visible, project.id)) target.workDecision = 'awaiting'+ for (const project of visible.projects ?? []) project.skillSet = skillSetOf(project)+ // On Custom every agent shows the role it runs, null when its kind has none; elsewhere a role id means nothing yet.+ for (const target of visible.agents) {+ const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))+ if (home && skillSetOf(home) === 'custom') target.roleId = agentSetRole(state, home, target)?.id ?? null+ else delete target.roleId+ }if (actor.kind !== 'person' || actor.userId !== state.ownerId) visible.invitations = []return visible}diff --git a/backend/src/superTabs/projects.test.ts b/backend/src/superTabs/projects.test.tsindex 2a6acf770..6d47963db 100644--- a/backend/src/superTabs/projects.test.ts+++ b/backend/src/superTabs/projects.test.ts@@ -1,7 +1,8 @@+import { createHash } from 'node:crypto'import { describe, expect, it } from 'vitest'import { applyCommand, type Command, type CommandContext } from './commands.js'import { createSuperTab, visibleState, type Actor, type MessageDraft } from './model.js'-import { canReadAgent, projectOf, projectsOf, readConversation, skillModeOf } from './projects.js'+import { canReadAgent, projectOf, projectsOf, readConversation, skillModeOf, skillSetOf } from './projects.js'const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }const peer: Actor = { kind: 'person', userId: 'peer', email: '[email protected]' }@@ -313,3 +314,180 @@ describe('project skill modes', () => {expect([modeOf(f, p.projectId), modeOf(f, other.projectId)]).toEqual(['default', 'default'])})})++describe('custom role sets', () => {+ type Kind = 'lead' | 'builder' | 'reviewer'+ const role = (id: string, name: string, kind: Kind, text = `# ${name}`) => ({ id, name, kind, text })+ const defaults = () => [role('lead', 'Product Manager', 'lead'), role('dev', 'Engineer', 'builder'), role('review', 'Reviewer', 'reviewer')]+ const version = (text: string) => createHash('sha256').update(text).digest('hex').slice(0, 16)+ const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host' })+ const request = (conversationId: string, extra: Record<string, unknown> = {}) => ({ conversationId, machineId: 'machine', engine: 'codex',+ name: 'Builder', cwd: '/work', worktree: true, ...extra,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } })+ /** A public project owned by peer (not the Swarm owner), with its custom set created from the Default copy. */+ function custom(roles = defaults()) {+ const f = setup(), p = f.project('public', peer)+ f.run({ type: 'project.roles.create', projectId: p.projectId, roles }, peer)+ return { f, p, roles: () => projectOf(f.state, p.projectId).roles }+ }++ it('creates the set once from the uploaded texts and keeps only each role\'s version in the tab state', () => {+ const { f, p, roles } = custom()+ expect(roles()).toEqual([{ id: 'lead', name: 'Product Manager', kind: 'lead', version: version('# Product Manager') },+ { id: 'dev', name: 'Engineer', kind: 'builder', version: version('# Engineer') },+ { id: 'review', name: 'Reviewer', kind: 'reviewer', version: version('# Reviewer') }])+ expect(JSON.stringify(f.state)).not.toContain('# Engineer')+ expect(() => f.run({ type: 'project.roles.create', projectId: p.projectId, roles: defaults() }, peer)).toThrow('already has custom roles')+ })++ it('refuses a set without exactly one lead, duplicate names or ids, and roles past the limits', () => {+ const f = setup(), p = f.project('public', peer)+ const create = (roles: unknown) => () => f.run({ type: 'project.roles.create', projectId: p.projectId, roles } as Command, peer)+ expect(create([role('dev', 'Engineer', 'builder')])).toThrow('exactly one lead')+ expect(create([...defaults(), role('aaaaaaaaaaaa', 'Second lead', 'lead')])).toThrow('exactly one lead')+ expect(create([role('aaaaaaaaaaaa', 'Product Manager', 'lead'), role('dev', 'Engineer', 'builder')])).toThrow('keeps the id lead')+ expect(create([...defaults(), role('aaaaaaaaaaaa', ' engineer ', 'builder')])).toThrow('unique')+ expect(create([...defaults(), role('dev', 'Other', 'builder')])).toThrow('unique')+ expect(create([...defaults(), role('not-hex', 'Other', 'builder')])).toThrow()+ expect(create([...defaults(), role('aaaaaaaaaaaa', 'x'.repeat(41), 'builder')])).toThrow()+ expect(create([...defaults(), role('aaaaaaaaaaaa', 'Big', 'builder', 'x'.repeat(65_537))])).toThrow('64 KB')+ expect(create([role('lead', 'PM', 'lead'), ...Array.from({ length: 20 }, (_, i) => role(i.toString(16).padStart(12, '0'), `B${i}`, 'builder'))])).toThrow()+ expect(projectOf(f.state, p.projectId).roles).toBeUndefined()+ })++ it('lets only the project owner manage the set: not the Swarm owner, a member or the project\'s Lead', () => {+ const { f, p } = custom(), lead = agentActor(f.add(p.conversationId, 'app-lead'))+ const commands: Command[] = [+ { type: 'project.roles.create', projectId: p.projectId, roles: defaults() },+ { type: 'project.role.set', projectId: p.projectId, role: role('dev', 'Coder', 'builder') },+ { type: 'project.role.remove', projectId: p.projectId, roleId: 'review' },+ { type: 'project.roles.reset', projectId: p.projectId, roles: defaults() }]+ for (const command of commands) for (const actor of [owner, lead]) expect(() => f.run(command, actor)).toThrow('Only the project owner')+ const fresh = setup(), mine = fresh.project('public', peer)+ expect(() => fresh.run({ type: 'project.roles.create', projectId: mine.projectId, roles: defaults() }, owner)).toThrow('Only the project owner')+ })++ it('keeps the lead role: renamed and rewritten, never removed, changed in kind or doubled', () => {+ const { f, p, roles } = custom()+ const set = (r: ReturnType<typeof role>) => () => f.run({ type: 'project.role.set', projectId: p.projectId, role: r }, peer)+ expect(() => f.run({ type: 'project.role.remove', projectId: p.projectId, roleId: 'lead' }, peer)).toThrow('lead role')+ expect(set(role('lead', 'Product Manager', 'builder'))).toThrow('lead role')+ expect(set(role('dev', 'Engineer', 'lead'))).toThrow('exactly one lead')+ expect(set(role('abcdefabcdef', 'Second lead', 'lead'))).toThrow('exactly one lead')+ expect(() => f.run({ type: 'project.roles.reset', projectId: p.projectId, roles: [role('dev', 'Engineer', 'builder')] }, peer)).toThrow('exactly one lead')+ set(role('lead', 'Coordinator', 'lead', '# New lead text'))()+ expect(roles()![0]).toEqual({ id: 'lead', name: 'Coordinator', kind: 'lead', version: version('# New lead text') })+ })++ it('adds and edits roles up to 20, with names unique in the set', () => {+ const { f, p, roles } = custom()+ const set = (r: ReturnType<typeof role>) => f.run({ type: 'project.role.set', projectId: p.projectId, role: r }, peer)+ set(role('abcdefabcdef', 'Docs writer', 'builder'))+ expect(() => set(role('bbbbbbbbbbbb', 'docs WRITER', 'reviewer'))).toThrow('unique')+ set(role('dev', 'Engineer', 'builder', '# Edited'))+ expect(roles()!.map(r => [r.id, r.version])).toEqual([['lead', version('# Product Manager')], ['dev', version('# Edited')],+ ['review', version('# Reviewer')], ['abcdefabcdef', version('# Docs writer')]])+ for (let i = 0; i < 16; i++) set(role(i.toString(16).padStart(12, '0'), `Extra ${i}`, 'builder'))+ expect(roles()).toHaveLength(20)+ expect(() => set(role('cccccccccccc', 'One too many', 'builder'))).toThrow('20 roles')+ expect(() => f.run({ type: 'project.role.set', projectId: f.project('public', peer).projectId, role: role('dev', 'Engineer', 'builder') }, peer)).toThrow('custom roles first')+ })++ it('refuses removing, resetting away or changing the kind of a role active agents use, and allows it once they are gone', () => {+ const { f, p, roles } = custom(), other = f.project('public', peer)+ f.add(p.conversationId, 'app-lead')+ const workers = [f.add(p.conversationId, 'w1', false), f.add(p.conversationId, 'w2', false)]+ f.add(other.conversationId, 'other-worker', false)+ const remove = (roleId: string) => () => f.run({ type: 'project.role.remove', projectId: p.projectId, roleId }, peer)+ expect(remove('dev')).toThrow('Stop or reassign the 2 agents with this role first')+ expect(() => f.run({ type: 'project.roles.reset', projectId: p.projectId, roles: [role('lead', 'PM', 'lead'), role('review', 'Reviewer', 'reviewer')] }, peer))+ .toThrow('Stop or reassign the 2 agents')+ expect(() => f.run({ type: 'project.role.set', projectId: p.projectId, role: role('dev', 'Engineer', 'reviewer') }, peer)).toThrow('Stop or reassign the 2 agents')+ f.run({ type: 'project.roles.reset', projectId: p.projectId, roles: defaults().map(r => ({ ...r, text: `${r.text} v2` })) }, peer)+ expect(roles()!.map(r => r.version)).toEqual(defaults().map(r => version(`${r.text} v2`)))+ remove('review')()+ for (const id of workers) f.run({ type: 'agent.remove', agentId: id })+ remove('dev')()+ expect(roles()!.map(r => r.id)).toEqual(['lead'])+ expect(remove('dev')).toThrow('unavailable')+ })++ it('switches to Custom only once the set exists, keeping skillMode Default for older clients and the set after leaving it', () => {+ const f = setup(), p = f.project('public', peer)+ const skills = (mode: 'default' | 'orchestration' | 'custom') => f.run({ type: 'project.skills', projectId: p.projectId, mode }, peer)+ expect(() => skills('custom')).toThrow('custom roles first')+ skills('orchestration')+ f.run({ type: 'project.roles.create', projectId: p.projectId, roles: defaults() }, peer)+ skills('custom')+ expect(projectOf(f.state, p.projectId)).toMatchObject({ skillSet: 'custom', skillMode: 'default' })+ expect(skillSetOf(projectOf(f.state, p.projectId))).toBe('custom')+ expect(f.messages).toEqual([expect.objectContaining({ conversationId: p.conversationId, text: 'Skills: Custom' })])+ skills('orchestration')+ expect(projectOf(f.state, p.projectId)).toMatchObject({ skillSet: 'orchestration', skillMode: 'orchestration' })+ expect(projectOf(f.state, p.projectId).roles).toHaveLength(3)+ skills('custom')+ skills('default')+ expect(skillSetOf(projectOf(f.state, p.projectId))).toBe('default')+ expect(f.messages).toEqual([expect.objectContaining({ text: 'Skills: Default' })])+ })++ it('reads Custom only while the stored mode is still Default, so an older release switching modes is followed', () => {+ const { f, p } = custom()+ f.run({ type: 'project.skills', projectId: p.projectId, mode: 'custom' }, peer)+ // What today's release writes when it switches this project: skillMode only.+ projectOf(f.state, p.projectId).skillMode = 'orchestration'+ expect(skillSetOf(projectOf(f.state, p.projectId))).toBe('orchestration')+ expect(skillSetOf({ ...projectOf(f.state, p.projectId), skillMode: undefined })).toBe('orchestration')+ })++ it('starts and assigns by a role id that exists in the custom set and matches the agent\'s kind', () => {+ const { f, p } = custom()+ f.run({ type: 'project.role.set', projectId: p.projectId, role: role('abcdefabcdef', 'Docs writer', 'builder') }, peer)+ const start = (extra: Record<string, unknown>) => String(f.run({ type: 'agent.start', request: request(p.conversationId, extra) } as Command).startId)+ expect(() => start({ roleId: 'review' })).toThrow('kind')+ expect(() => start({ roleId: 'lead' })).toThrow('kind')+ expect(() => start({ roleId: 'eeeeeeeeeeee' })).toThrow('not in this project')+ expect(() => start({ role: 'reviewer', roleId: 'dev' })).toThrow('kind')+ const startId = start({ roleId: 'abcdefabcdef' })+ const worker = String(f.run({ type: 'agent.started', startId, harnessId: 'native', configuration }).agentId)+ expect(f.state.agents.find(a => a.id === worker)!.roleId).toBe('abcdefabcdef')+ const group = String(f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Work', brief: 'Do it', checks: [{ description: 'Done', independent: false }] }, peer).conversationId)+ expect(() => f.run({ type: 'work.assign', conversationId: group, agentId: worker, roleId: 'review' }, peer)).toThrow('kind')+ expect(() => f.run({ type: 'work.assign', conversationId: group, agentId: worker, roleId: 'eeeeeeeeeeee' }, peer)).toThrow('not in this project')+ f.run({ type: 'work.assign', conversationId: group, agentId: worker, roleId: 'dev' }, peer)+ expect(f.state.agents.find(a => a.id === worker)!.roleId).toBe('dev')+ const plain = f.project('public', peer)+ expect(() => f.run({ type: 'agent.start', request: request(plain.conversationId, { roleId: 'dev' }) } as Command)).toThrow('not in this project')+ })++ it('tells agents whose kind has no role in the new set, then gives them no new work, and refuses review groups without a reviewer role', () => {+ const { f, p } = custom([role('lead', 'Product Manager', 'lead'), role('dev', 'Engineer', 'builder')])+ const lead = f.add(p.conversationId, 'app-lead')+ const reviewer = f.add(p.conversationId, 'app-reviewer', false)+ f.state.agents.find(a => a.id === reviewer)!.role = 'reviewer'+ const build = String(f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Build', brief: 'Do it', checks: [{ description: 'Done', independent: false }] }, peer).conversationId)+ f.run({ type: 'project.skills', projectId: p.projectId, mode: 'custom' }, peer)+ expect(f.messages).toEqual(expect.arrayContaining([expect.objectContaining({ recipients: [reviewer],+ text: expect.stringContaining('has no Reviewer role') })]))+ expect(f.messages.filter(m => m.recipients.includes(lead))).toEqual([])+ expect(() => f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Review', brief: 'Check it', reviewOf: build, checks: [] }, peer)).toThrow('no reviewer role')+ expect(() => f.run({ type: 'agent.start', request: request(p.conversationId, { role: 'reviewer' }) } as Command)).toThrow('no reviewer role')+ f.run({ type: 'project.skills', projectId: p.projectId, mode: 'default' }, peer)+ const review = String(f.run({ type: 'conversation.create', projectId: p.projectId, title: 'Review', brief: 'Check it', reviewOf: build, checks: [{ description: 'Read', independent: true }] }, peer).conversationId)+ f.run({ type: 'project.skills', projectId: p.projectId, mode: 'custom' }, peer)+ expect(() => f.run({ type: 'work.assign', conversationId: review, agentId: reviewer }, peer)).toThrow('no reviewer role')+ })++ it('shows clients the set, the project\'s skillSet and each agent\'s role id, never a role text', () => {+ const { f, p } = custom()+ const lead = f.add(p.conversationId, 'app-lead'), worker = f.add(p.conversationId, 'w1', false)+ let visible = visibleState(f.state, peer)+ expect(visible.projects!.find(x => x.id === p.projectId)).toMatchObject({ skillSet: 'default', roles: expect.any(Array) })+ expect(visible.agents.find(a => a.id === worker)).not.toHaveProperty('roleId')+ f.run({ type: 'project.skills', projectId: p.projectId, mode: 'custom' }, peer)+ visible = visibleState(f.state, peer)+ expect(visible.projects!.find(x => x.id === p.projectId)!.skillSet).toBe('custom')+ expect(visible.agents.filter(a => [lead, worker].includes(a.id)).map(a => a.roleId)).toEqual(['lead', 'dev'])+ expect(visible.projects!.find(x => x.id === 'lead')!.skillSet).toBe('default')+ })+})diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex a9960b061..662c982f8 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -1,10 +1,19 @@-import { activeWork, agent, author, conversation, fail, isLeads, nextConversationNumber, person, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'+import { createHash } from 'node:crypto'+import { activeWork, agent, agentRole, author, conversation, fail, isLeads, nextConversationNumber, person, type Actor, type Agent, type Conversation, type SuperTabState } from './model.js'import type { SwarmRule } from './rules.js'export type ProjectVisibility = 'public' | 'private'/** Which built-in skill texts the project's agents get: Default (the team process only) or today's Harness orchestration. */export type SkillMode = 'default' | 'orchestration'-export const SKILL_MODE_NAMES: Record<SkillMode, string> = { default: 'Default', orchestration: 'Harness orchestration' }+/** What new clients read: a built-in mode, or the project's own custom role set. */+export type SkillSet = SkillMode | 'custom'+export const SKILL_SET_NAMES: Record<SkillSet, string> = { default: 'Default', orchestration: 'Harness orchestration', custom: 'Custom' }+export type RoleKind = 'lead' | 'builder' | 'reviewer'+/** A role of a project's custom set as the tab state keeps it. Its text lives outside the state (store.ts roleText), so a+ * roster or tab read never carries up to 20 x 64 KB of skill text; `version` names the text. */+export interface ProjectRole { id: string; name: string; kind: RoleKind; version: string }+export const MAX_ROLES = 20+export const roleVersion = (text: string): string => createHash('sha256').update(text).digest('hex').slice(0, 16)export interface SwarmProject {id: stringname: string@@ -25,9 +34,27 @@ export interface SwarmProject {repository?: { machineId: string; cwd: string; repositoryUrl: string | null }/** Absent on projects from before skill modes, which keep the texts their agents already run. */skillMode?: SkillMode+ /** Absent before custom sets. While it is 'custom', skillMode stays 'default' so older clients run the Default text. */+ skillSet?: SkillSet+ /** The project's custom set, kept when the project switches away from it. */+ roles?: ProjectRole[]}export const skillModeOf = (project: SwarmProject): SkillMode => project.skillMode ?? 'orchestration'+/** Custom only while the stored mode is still Default: a release from before custom sets switches a project by skillMode+ * alone during a rolling deploy, and that switch must hold here too. */+export const skillSetOf = (project: SwarmProject): SkillSet =>+ project.skillSet === 'custom' && project.roles && skillModeOf(project) === 'default' ? 'custom' : skillModeOf(project)++/** The Lead is whoever leads the project; every other agent is the kind it was started as. */+export const agentKind = (state: SuperTabState, target: Agent): RoleKind => ledProject(state, target.id) ? 'lead' : agentRole(target)++/** The custom role an agent runs: its own role id while that role is of its kind, else the set's first role of its kind+ * (agents from before custom sets read as the copied Engineer and Reviewer), else none: its role is gone. */+export function agentSetRole(state: SuperTabState, project: SwarmProject, target: Agent): ProjectRole | null {+ const kind = agentKind(state, target), roles = project.roles ?? []+ return roles.find(r => r.id === target.roleId && r.kind === kind) ?? roles.find(r => r.kind === kind) ?? null+}/** Existing tabs are one project; their conversation IDs and messages stay intact. */export function projectsOf(state: SuperTabState): SwarmProject[] {diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 505dd27e2..e862d98df 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -10,7 +10,7 @@ import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_ATimport { randomBytes } from 'node:crypto'import type { Readable } from 'node:stream'import { logger } from '../utils/logger.js'-import { canReadAgent, canReadProject, groupProject, ledProject, projectsOf, agentProjectId, readConversation, skillModeOf, type ProjectVisibility } from './projects.js'+import { agentSetRole, canReadAgent, canReadProject, groupProject, ledProject, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, skillSetOf, type ProjectVisibility } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'import { revokeNativeContexts, SuperTabNativeStore } from './native.js'@@ -607,6 +607,7 @@ export class SuperTabStore {stableId(s.request.machineId, s.harnessId) === command.agentId)if (start?.routeDecisionId) await closeUnassignedStart(tx, tabId, start.routeDecisionId, start.id, 'stopped', context.now)}+ if (command.type === 'project.delete' || command.type.startsWith('project.role')) await this.writeRoleTexts(tx, tabId, effects.state, command)if (effects.terminal) await this.writeTerminal(tx, tabId, effects.terminal, context.now)if (command.type === 'work.cancel') {await closeAssignment(tx, tabId, command.assignmentId, 'cancelled', context.now)@@ -712,6 +713,49 @@ export class SuperTabStore {})}+ /** Keeps the project's stored texts equal to its custom set: the roles the command wrote, nothing for roles it dropped. */+ private async writeRoleTexts(tx: Transaction, tabId: string, state: SuperTabState, command: Command) {+ if (!('projectId' in command) || !command.projectId) return+ const { projectId } = command+ const kept = projectsOf(state).find(p => p.id === projectId)?.roles?.map(r => r.id) ?? []+ await tx.superTabRoleText.deleteMany({ where: { tabId, projectId, roleId: { notIn: kept } } })+ const written = command.type === 'project.role.set' ? [command.role]+ : command.type === 'project.roles.create' || command.type === 'project.roles.reset' ? command.roles : []+ for (const role of written) {+ const id = stableId(tabId, projectId, role.id), data = { version: roleVersion(role.text), text: role.text }+ await tx.superTabRoleText.upsert({ where: { id }, create: { id, tabId, projectId, roleId: role.id, ...data }, update: data })+ }+ }++ /** A custom role's text, for the project's owner, its Lead, and the hosts of its agents (which fetch it when the version+ * in their roster changes). Anyone else, like a missing role, reads it as unavailable. */+ async roleText(user: AuthUser, tabId: string, projectId: string, roleId: string, asAgentId?: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ const unavailable = () => fail('NOT_FOUND', 'This role is unavailable.', 404)+ const project = projectsOf(state).find(p => p.id === projectId) ?? unavailable()+ const role = project.roles?.find(r => r.id === roleId) ?? unavailable()+ if (asAgentId) {+ await this.actor(tx, user, state, asAgentId)+ if (ledProject(state, asAgentId)?.id !== project.id) unavailable()+ } else if (!(user.sub === project.ownerId && state.people.some(p => p.id === user.sub)) && !await this.hostsProject(tx, state, user, project.id)) {+ unavailable()+ }+ const stored = await tx.superTabRoleText.findUnique({ where: { id: stableId(tabId, projectId, roleId) } })+ if (stored?.version !== role.version) unavailable()+ return { version: stored!.version, text: stored!.text }+ })+ }++ /** Whether this account could host one of the project's agents now, by the same live grant as its host reads. */+ private async hostsProject(tx: Transaction, state: SuperTabState, user: AuthUser, projectId: string): Promise<boolean> {+ for (const target of state.agents.filter(a => a.machineOwnerId === user.sub && agentProjectId(state, a) === projectId)) {+ try { agent(state, target.id); await this.agentGrant(tx, state, target); return true }+ catch (error) { if (!(error instanceof SuperTabError)) throw error }+ }+ return false+ }+private async writeTerminal(tx: Transaction, tabId: string, effect: TerminalEffect, now: number) {if (effect.op === 'request') {const { op: _op, id, ...request } = effect@@ -982,7 +1026,9 @@ export class SuperTabStore {// whose project is gone reads like one from before skill modes instead of failing the host's whole poll.const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))const skillMode = home ? skillModeOf(home) : 'orchestration'- result.push({ tabId: row.id, tabName: state.name, revision: row.revision, paused: state.paused, active, attention, agent: target, joinSwarm, skillMode,+ // On Custom, the role it runs and its text's version, never the text (roleText); null when its kind has no role there.+ const role = home && skillSetOf(home) === 'custom' ? { role: agentSetRole(state, home, target) } : {}+ result.push({ tabId: row.id, tabName: state.name, revision: row.revision, paused: state.paused, active, attention, agent: target, joinSwarm, skillMode, ...role,lead: !!ledProject(state, target.id),stopRequested: target.workDecision === 'stop' && !state.conversations.some(c => activeWork(c) && c.assignment?.agentId === target.id),observers: people.filter(p => p.id !== user.sub &&