Team Orchestrator: welcome screen, quick starts (Squad, All-Purpose Team, Tech Team), a table-style team form, and a live roster to spawn and manage teams of…

Team Orchestrator runs a team of Claude Code sessions for you. Each member is its own Claude Code session in its own Orca tab. You build the team, watch it and change it from a panel above the prompt. The members message each other, start when they are first needed, and reopen when a message arrives. Automatic close and eviction are paused until native cleanup verification exists.
A guard keeps the members inside their roles: members with reports plan and delegate instead of writing files, and nobody starts subagents unless you allow it.
Version 0.5.39. What changed in each version is in the changelog.
| Feature | What it does |
|---|---|
| Team builder | Quick starts (Squad, All-Purpose Team, Tech Team), a team form, or an interview that designs the team with you |
| Live roster | One card per team: state, context use, model, effort and briefing for every member |
| Org chart | A live chart whose dots follow each member's state |
| Layouts | Stacked, side by side, or docked beside the transcript |
| On-demand start | Leads and workers start the first time their boss messages them |
| Role files | One file per member: a generated role, plus your own notes that the mod never changes |
| Team messaging | team_message starts or reopens a member, then delivers. @team sends your message to a team's head. |
| Adding members | New members on a running team, within a lead's purview and with your approval (0.5.17) |
| Auto-close and reopen | A message can reopen a member; automatic close and eviction are paused until native cleanup verification exists |
| Assumptions (opt-in, 0.5.25) | Each member's open assumptions from Session Panel: "N open" on its row, and Confirm or Wrong for its boss and the team top. Off by default; needs Session Panel. |
| Session cap and queue | A limit on open sessions; messages wait until there is room |
| Permission guard | No subagents for members, and no file writes for members with reports, unless you allow it |
| Locked team files | Only the team top changes the roster and the team settings |
| Identity tracking | Members stay recognised after /clear, /rename or a fresh claude; unclear sessions are held for you |
| Crash and sleep handling | Waking up closes nothing; only members proved to have crashed are reopened |
| Two computers | A team can span computers that share one project folder |
| Other CLIs | Tabs that run another CLI can sit on the roster, unmanaged |
| Windows, macOS and Linux | Every platform Orca runs on |
A separate Orca plugin lives in team-orchestrator-orca-plugin/ (release 0.1.06). It brings this mod's team creation into Orca's own plugin panel: the quick starts (Squad, All-Purpose Team, Tech Team) and custom hierarchies, the organisation tree, the roster and member details. It launches each member as a named Codex or Claude Code agent tab on the selected workspace, through a bundled local Node worker and an in-memory runtime adapter. It needs no separate installer and no change to Orca's own files.
How it differs from this mod:
claude plugin install..claude/team-orchestrator/, so a team made in one does not show in the other.| What | Details |
|---|---|
| Claude Code | A build that loads mods (plugins with hooks). Every member runs claude in its own tab. |
| Orca | Orca must be running, and its command-line tool must work. The mod opens, closes and switches tabs through it. |
| Operating system | Windows, macOS or Linux. On Windows the mod uses PowerShell for process checks. On macOS and Linux it uses ps and tail. |
| git (optional) | When the project is a git repository, the mod keeps its team folder out of commits. |
The mod has one option, Orca command (orcaCommand). You find it in /config, or with claude plugin configure team-orchestrator.
| Value | What happens |
|---|---|
| Empty (the default) | At the next start the mod tries orca.exe on Windows or orca on macOS and Linux. If --version works, it saves that value. |
| A command or a full path | The mod checks it at every start. When you edit the option, the mod refuses a command that does not start and shows the reason. |
| A saved value that fails on this computer | If the platform default works, the mod switches to it and shows a toast. This covers settings synced from another platform. |
claude plugin marketplace add herman925/925-cc-pluginsclaude plugin install team-orchestrator@herman-mods --scope user/reload-plugins.claude plugin marketplace update herman-modsclaude plugin update team-orchestrator@herman-mods/reload-plugins in every open session of the team. Reload the team top first, then the others.Why the order matters: the team top stamps the team files with its version. A session whose mod is older than that stamp writes no team file. It shows a toast once and waits until you update and reload it. A session that has not reloaded yet may also show as offline in the updated top's panel until it reloads.
The version in the band and in the panel header shows what each session has loaded.
t, or type /team. The panel opens above the prompt.@<team name> and your message in your own session. The message goes to that team's head.Only the top and the team heads start at Launch. Everyone else starts the first time their boss messages them.
The guard watches every session that is on the roster. A session that is not on the roster, such as your own, is never judged. A subagent runs inside its session, so a rule for the session covers its subagents too.
| Tool | Who is refused | Unless |
|---|---|---|
Agent (subagents) | Every roster member | Allow subagents is on, or #allow-subagent this turn. Claude Code's own helpers statusline-setup and claude-code-guide always pass. |
Write, Edit, NotebookEdit | Members with reports (the top, heads and leads) | Allow writes is on, or #allow-write this turn. The member's own memory folder (~/.claude/projects/<project>/memory/) is always open. |
Write, Edit, NotebookEdit on the team files | Every member except the team top | No switch or keyword opens them. |
Bash, PowerShell commands that name the team files | Every member except the team top | Plain reads of the named file pass: cat, type, Get-Content, ls, dir, grep, Select-String, jq without -i. |
Bash, PowerShell commands that change into the team folder (cd, chdir, pushd, sl, Set-Location) | Every member except the team top | Always refused, even a read. A cd is not a plain read, so the whole command counts as a team-file command. |
The team files are roster.json, settings.json, meta.json, the changes/ folder and, from 0.5.17, the requests/ folder. Request files are written only through member_add, never by hand. roles/ and queue/ stay writable. Bash and PowerShell are otherwise not guarded.
A command names the team files when it names roster.json (anywhere), names settings.json or meta.json with the team folder, names changes/ or requests/ inside the team folder, or puts the team folder and a wildcard, a variable or a substitution in one word (rm .claude/team-orchestrator/*.json, $D/team-orchestrator/a). From 0.5.23 the folder and the wildcard must share a word, so claude plugin test team-orchestrator | grep -E "[0-9]+ pass" passes. From 0.5.24 a change into the team folder counts as naming it, so cd .claude/team-orchestrator && rm .json is refused.
Each refusal says who was refused and why, and tells the model to hand the work to a worker or to ask you. It also shows a toast. A permission that lets a call through shows a toast only once per session and reason.
A session on hold (see Identity and member_claim) gets the strictest guard: no writes and no subagents without a one-turn keyword, and no team tools at all.
| Way | How long | How |
|---|---|---|
| Standing switch | Until you switch it off | Settings → Permissions → Allow subagents / Allow writes, per member. Stored in the roster, so it counts at once in every session. |
| One-turn keyword | The current turn | Type #allow-subagent or #allow-write in your own message to that member's session. |
The keywords count only in a prompt typed at that session's own prompt. The same words in a message from another session, in a tool result or in another plugin's prompt allow nothing. A later prompt of yours without the keyword takes the grant back, and the grant ends with the turn. A reload forgets it.
A subagent or a workflow agent is judged as the member that started it, by the grants standing right now. A one-turn keyword lasts until the spawning member's own turn ends.
The mod records what it last wrote for each member's two switches. If the roster file shows a different value on two refreshes in a row, the team top gets a toast and the member's row gets a note. Nothing is reverted.
The roster is .claude/team-orchestrator/roster.json. Only one session writes it, and settings.json: the team top's session, on the team top's computer. The guard refuses every other member's tools and shell commands on these files (see the table above).
changes/ with only the fields it changed. Its own panel shows the change at once.changes/applied.json. Change files older than 7 days are ignored.meta.json records the schema version, the version of the mod that last wrote the roster, and the team top's computer. A session whose mod is older than that version writes no team file.requests/ are locked the same way: no member can write them with Write, Edit or the shell, and only member_add creates them. Before the team top applies a request, it checks again that the member who asked is still on the roster and still allowed to ask for that team.| The mod can | The mod does not |
|---|---|
| Open, close and switch Orca tabs of this project's members on this computer | Close or reopen members of other computers, or members that run another CLI |
Start claude sessions for members, with their role pointer | Kill operating-system processes. Cleanup status is self-reported. |
Write in .claude/team-orchestrator/, in its status folder on this computer, and in the repository's info/exclude | Delete files. Applied change files and queue entries stay, listed in an index. |
| Read session transcripts (title, requested model, last model, effort, context use and working folder only) | Keep or show anything else from a transcript |
| Read the session registry and look up member processes by id | Poll processes on a timer |
| Record an explicit cleanup field as a self-report in a member's status file | Treat it as OS verification or auto-approve cleanup deletes |
| Send messages to members by session id | Message sessions of other projects or Remote Control copies |
Paused in the interim safety phase. The autoScratch setting remains in saved team settings for compatibility, but the mod does not turn an ask into allow for cleanup deletes. Every delete—including own scratch, shared temp, project scratch, task output, logs, tests, retained results and artifacts—uses normal Claude Code permissions. The mod never overrides a deny.
This is deliberate: a literal path and a session folder do not prove that the current task created the file. Native task-owned resource tracking is future work; no cleanup ledger or auto-approval exists in this phase.
Per session. These change only the look of your own panel. They survive /reload-plugins, not a new session.
| Setting | What it does | Default |
|---|---|---|
| Layout | Stacked, Side by side or Dock right. See Layouts. | Stacked |
| Org chart | Shows or hides the live org chart above the cards | Show |
| Columns | Shows or hides STATUS, CONTEXT, MODEL, EFFORT and BRIEF. NAME always shows. | All shown |
Team-wide (Settings → Workers). Shared by every session, in .claude/team-orchestrator/settings.json.
| Setting | What it does | Default |
|---|---|---|
| Auto-close | Setting is retained, but automatic close is paused until a native verifier can prove task-owned resources are gone | On |
| Idle minutes | Future verifier's idle threshold (5, 10, 20, 30, 60) | 10 |
| Reopen as | Resume keeps the conversation; Fresh starts a new session that reads its role file again | Resume |
| Max open | Most of this computer's members open at once (No cap, 6, 8, 10, 12) | 8 |
| Launch | On demand starts only the top and the team heads; All at Create starts everyone | On demand |
| Batch size | Sessions started at once at Launch (1, 2, 3, 4, 6); the next batch follows 5 seconds after the last is ready | 3 |
| Scratch | Stored for compatibility; auto-approval is paused and all cleanup deletes ask. See Scratch clean-up. | On |
| Scratch dir | Stored for compatibility; does not grant cleanup approval | .claude/scratch |
| Never close | A tick box per worker; a ticked worker is never auto-closed | None ticked |
Team-wide (Settings → Assumptions, 0.5.27). Shared by every session, in .claude/team-orchestrator/settings.json.
| Setting | What it does | Default |
|---|---|---|
| Show | Shows each member's open assumptions from Session Panel. The files are read only when this is On and Session Panel is enabled in this session. See Assumptions from Session Panel. | Off |
Per member, team-wide (Settings → Permissions). Stored in the roster.
| Setting | What it does | Default |
|---|---|---|
| Allow subagents | Lets this member use the Agent tool | Off |
| Allow writes | Lets this member, if it has reports, use Write, Edit and NotebookEdit | Off |
Plugin option.
| Setting | What it does | Default |
|---|---|---|
Orca command (orcaCommand) | Orca's command-line tool, or its full path. See Requirements. | Empty: detected and saved at the next start |
A project can hold several teams. Each member has a name, a role, a level and a boss.
| Term | Who it is |
|---|---|
| Team top | The member that reports to you (its boss is user). In a one-team setup this is the head. Under a CEO it is the CEO. If several members report to you, the first one on the roster is the team top. |
| Head | The member at the top of one team. Under a CEO, each team has its own head, which reports to the CEO. |
| Lead | A member with its own reports, below a head. Leads appear in three-level teams. |
| Worker | A member with no reports. Workers do the tasks. |
Members with reports (the top, heads and leads) plan, delegate and review. Workers do the work and report back to their boss only.
Member names are unique across the project. When a new team reuses a name that another team has, the new member gets its team name in front (Team2-Head).
Each member has a role file: .claude/team-orchestrator/roles/<name>.md. It has two parts.
| Part | Contents | Who writes it |
|---|---|---|
| Above the marker | The member's job for its level, its boss and reports, how to message, housekeeping, the whole team, and the team files | The mod. It rewrites this part whenever the team changes. |
| Personality and notes, below the marker | A voice, a working style or extra rules for this member | You. The mod never changes this part. |
Every member starts with a short pointer in its system prompt (--append-system-prompt). The pointer gives its name, its boss, the one rule for its level, and the path of its role file. The member reads the file before its first action. When the file changes, Claude Code tells the session what changed.
Launch writes the whole roster first. Then it starts sessions in batches.
team_message.Each batch starts, waits until the sessions are ready, and then the next batch follows 5 seconds later. The batch size is 3 by default. Both options are in Settings → Workers.
team_message and SendMessage| Tool | Use it for | Why |
|---|---|---|
team_message | A boss messaging its own reports | It starts a member that has not started yet, or reopens one that was closed, and then delivers. It addresses the member by session id, so it never reaches a same-named session of another project or a Remote Control copy. |
SendMessage | A worker reporting to its boss, and heads and leads talking to each other | It is Claude Code's own tool. It only knows sessions that are running now. |
The mod adds a note to the SendMessage description that says when to use team_message instead. For roster members, team_message is listed up front, not behind ToolSearch.
In your own session, type @<team name> and your message. The mod sends the message to that team's head and keeps your session out of the conversation. A head on this computer with a known session id is addressed by that id.
To rename a team, type a new name in the team card's Team name field, or use /team name <old> <new>. The @ mention changes with it.
Each member writes its own status file on its own computer:
~/.claude/team-orchestrator/<project key>/status/<name>.json
~/.claude is your Claude config folder (CLAUDE_CONFIG_DIR when set). The project key is the project path with every character except letters and digits turned into -.
A member writes its status when a turn starts and ends, when it asks you a question, and on a 60-second heartbeat. The file holds its state, model, effort, context use and window, its current task line, and the latest self-reported cleanup field (if supplied). A cleanup report is not OS verification. Historical lastClean, leftover and countedAt values from older versions are not proof and no longer drive closure. The mod does not census processes on each turn. Nobody reads other members' screens. Only the team top (or your own session, when it is not on the roster) checks Orca tabs after a member has been silent for over 2 minutes; it backs off when Orca is slow.
Every member records its home computer (its computer name) at launch, adopt, reopen and identity re-attach.
team_message to it answers that its conversation lives on that computer. With your yes, startHere: true starts a fresh copy here, and this computer becomes its home.meta.json records the team top on another computer, the team-top work here is off: writing the team files, auto-close and the queue. A toast names the computer that holds the top. The team top's session here asks you whether to take over, and applies your answer with team_take_top.member_claimA member stays recognised after /clear, /rename or a fresh claude in its tab. Each session compares three facts with the roster: its Orca tab, its session id and its session name.
| Facts that match | Result |
|---|---|
| Tab, id and name | The member |
Tab and id, new name (/rename) | The member. The roster, its reports, its role file and its status file take the new name. |
Tab and name, new id (/clear) | The member. The roster takes the new id. |
| Id and name, another tab | The member if its old tab is gone; on hold if the old tab is still open |
Tab only (a fresh claude in the tab) | The member, re-attached. Its next prompt tells it to read its role file. |
| Id only, or name only | On hold |
| Nothing | Not on the team. The guard leaves it alone. |
Outside Orca, the session registry (~/.claude/sessions/) stands in for the tab, but only beside an id or a name. A /rename to another member's name is not followed.
A session on hold gets the strictest guard and no team tools, and writes no status under the member's name. The mod warns the member's head and tells the team top to ask you at once, with three choices:
| Choice | Effect, applied by the team top with member_claim |
|---|---|
| This is X | The roster takes the session's id, tab and name as member X. |
| New member under X's boss | The session joins as a worker under that boss, with its own role f
hooks/register.tsx 4445 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Act, Bulk, Form, Member, Settings, Spawn, View } from '../types'
5import { headOf, joinLaunch, newMember, newProblem, purview, requestProblem } from './adding'
6import type { NewSpec } from './adding'
7import { AGENT_TOOL, grantChanges, type GrantMap, grantMap, grantsFrom, judge, judgeTeamFiles, namesTeamFile, NO_GRANTS, pathOf, recordAfterWrite, SHELL_TOOLS, WRITE_TOOLS } from './guard'
8import type { Grants } from './guard'
9import { bodyOf, parseCleanupReport, reportsTo, senderOf, shouldPoll } from './housekeeping'
10import { freshName, headWarning, holdNote, holdTool, identify, judgeHeld, nameTaken, relabel, roleNote, topAsk, topOf } from './identity'
11import type { Claim, Level } from './identity'
12import type { Sleep, Status, TeamSettings } from './status'
13import { livenessOf, MEND_DIRS, parseWinProcs, psProc, winProcScript } from './platform'
14import type { Liveness, Proc } from './platform'
15import { mergeRole, orgOf, pointer, roleText, WELCOME } from './roles'
16import type { EnvModels } from './status'
17import { admit, awakeAge, chunk, cliOf, heartbeatStale, isManaged, locationOf, MIN, modelArg, needsTabCheck, nextCheckInterval, noteTick, pathInWorktreeId, roleFile, shownModel, shownState, STALE_MS, startsAtCreate, statusFile, TEAM_SETTINGS0, taskLine, toClose, windowFor, worktreeHolds } from './status'
18import { afterTry, appliedAfter, applyOps, applySettings, diffOps, fileName, fromOldQueue, isAway, KEEP_MS, META0, metaAfter, olderThan, pendingNames, project, projectKey, projectTop, queueAction, rightsChanges, rosterOps, sameMachine, STRUCT, timeOf, topElsewhere } from './changes'
19import type { Change, Meta, QEntry, QReason } from './changes'
20import { CHECK as CHECK_W, cell, chartLabelInfo, columnPlan, EFFORT_SHORT, family, fit, headerLine, shorten, sideBySide } from './layout'
21import { ASSUMPTIONS_DIR, askDelete, collectOpen, confirmLine, wrongLine } from './assumptions'
22import type { OpenAssumption } from './assumptions'
23
24// Orca's CLI is orca.exe on Windows and orca on macOS and Linux. The command is the plugin option "orcaCommand" (/config);
25// empty, the mod picks it from the platform, checks it starts, and writes it into the option once (see session.start).
26// PowerShell (transcript tails, leftover counts) is Windows only; macOS and Linux use tail and ps.
27const os = { windows: undefined as boolean | undefined }
28async function isWindows($: any): Promise<boolean> {
29 if (os.windows === undefined) os.windows = String((await $.env.get('OS').catch(() => undefined)) ?? '') === 'Windows_NT'
30 return os.windows
31}
32// Every file write goes through putFile (0.5.30). Refused with EACCES on macOS or Linux (a folder made without its x
33// bit, see MEND_DIRS), it mends the folders on the way and writes once more; any other failure is the caller's as before.
34async function putFile($: any, path: string, text: string): Promise<void> {
35 try {
36 return await $.fs.write(path, text)
37 } catch (err) {
38 if (!/EACCES/.test(String(err)) || (await isWindows($))) throw err
39 const r = await $.process.run(['sh', '-c', MEND_DIRS, 'sh', path.replace(/[\\/][^\\/]*$/, '')], { timeoutMs: 20000 }).catch(() => undefined)
40 if (r?.exitCode !== 0) throw err
41 return $.fs.write(path, text)
42 }
43}
44const cfg = { orcaCommand: '', version: '', versionRead: false }
45// the version shown in the panel, read once per load from this plugin's own manifest, so it always matches what is installed
46async function readVersion($: any) {
47 if (cfg.versionRead) return
48 cfg.versionRead = true
49 try {
50 cfg.version = String(JSON.parse(String(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))).version ?? '')
51 } catch {
52 cfg.version = ''
53 }
54}
55const ORCA_KEY = 'team-orchestrator.orcaCommand'
56const orcaBin = async ($: any) => cfg.orcaCommand || ((await isWindows($)) ? 'orca.exe' : 'orca')
57/** '' when the command starts and answers --version, else why not, in a sentence. */
58async function orcaProblem($: any, command: string): Promise<string> {
59 const r = await $.process.run([command, '--version'], { timeoutMs: 20000 }).catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: String(err) }))
60 return r.exitCode === 0 ? '' : `"${command} --version" did not run (${String(r.stderr || r.stdout || `exit ${r.exitCode}`).trim().slice(0, 160)}).`
61}
62const TOOL = 'mcp__team-orchestrator__team_launch'
63const ADOPT = 'mcp__team-orchestrator__team_adopt'
64const REMOVE_TEAM = 'mcp__team-orchestrator__team_remove'
65const REMOVE_MEMBER = 'mcp__team-orchestrator__member_remove'
66const MOVE = 'mcp__team-orchestrator__member_move'
67const MESSAGE = 'mcp__team-orchestrator__team_message'
68const CLAIM = 'mcp__team-orchestrator__member_claim'
69const TAKE = 'mcp__team-orchestrator__team_take_top'
70const ADD = 'mcp__team-orchestrator__member_add'
71const MODELS = ['default', 'opus', 'sonnet', 'haiku', 'fable']
72const EFFORTS = ['default', 'low', 'medium', 'high', 'xhigh', 'max']
73
74const INTERVIEW =
75 'Interview me with AskUserQuestion to design a team of Claude Code sessions: ask about the team name, function, whether a CEO sits above several teams (and their names), how many levels, how many workers per head, model and effort per level, and any role specifics. Then call the mcp__team-orchestrator__team_launch tool with members ordered boss-first (boss "user" for the top member). Give every member a team; a CEO gets its own team name. Launching briefs every member automatically.'
76
77// The quick starts. Each fills the form, which stays editable, and Launch then briefs every session.
78// `sketch` uses the glyphs of the roster and the preview: ■ CEO, ● head, ◇ lead, ○ worker.
79const PRESETS = [
80 {
81 label: 'Squad', sketch: '●┬○○○', hint: 'head + 3 workers',
82 form: { team: 'Squad', ceo: '0', levels: '2', fan: '3', groups: '' },
83 },
84 {
85 label: 'All-Purpose Team', sketch: '■┬●●', hint: 'CEO + 2 heads, 4 workers each',
86 form: { team: 'All-Purpose-Team', ceo: '1', levels: '3', fan: '4', groups: 'Team 1, Team 2' },
87 },
88 {
89 label: 'Tech Team', sketch: '■┬●●●●', hint: 'CEO + 4 heads, 4 workers each',
90 form: { team: 'Tech-Team', ceo: '1', levels: '3', fan: '4', groups: 'Dev Team, UI Team, Test Team, Security Team' },
91 },
92]
93const sameShape = (f: Form, p: (typeof PRESETS)[number]) =>
94 f.ceo === p.form.ceo && f.fan === p.form.fan && (f.ceo === '1' ? f.groups === p.form.groups : f.levels === p.form.levels)
95
96// How a stored value reads on screen, and the colour it is drawn in. The stored values stay as `claude --model` takes them.
97const LABEL: Record<string, string> = {
98 default: 'Default', opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku', fable: 'Fable',
99 low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max',
100}
101const SHADE: Record<string, string> = {
102 default: 'gray', opus: 'magenta', sonnet: 'cyan', haiku: 'green', fable: 'yellow',
103 // effort: one graded scale, low cool to max hot, in the form and the roster alike
104 low: '#6c8cff', medium: '#4ec9b0', high: '#e5c07b', xhigh: '#ff8c42', max: '#ff4d4d',
105}
106const nice = (v: string) => LABEL[v] ?? v
107// One colour per level for names in the roster and the org chart, the same in every team. None is the green or
108// yellow of the context bar; each reads on a dark background. Deeper levels share the last.
109const LEVEL_SHADE = ['#ff79c6', '#bd93f9', '#8be9fd', '#a0a8b8']
110const levelShade = (level: number) => LEVEL_SHADE[Math.min(Math.max(level, 1), LEVEL_SHADE.length) - 1] as string
111const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
112// When the person last changed a form field. A redraw while they type could drop a keystroke, so the form
113// animates only after 1.5 s of quiet.
114let typedAt = 0
115
116const FORM0: Form = {
117 team: 'team',
118 fn: '',
119 levels: '2',
120 fan: '3',
121 ceo: '0',
122 groups: '',
123 m1: 'default',
124 e1: 'default',
125 m2: 'default',
126 e2: 'default',
127 m3: 'default',
128 e3: 'default',
129}
130const form = atom({ plugin: 'team-orchestrator', key: 'form' } as const, FORM0)
131// State kept across a hot reload may predate a field, so defaults go under whatever was stored.
132const readForm = async ($: any): Promise<Form> => ({ ...FORM0, ...(await read($, form)) })
133const members = atom({ plugin: 'team-orchestrator', key: 'members' } as const, [] as Member[])
134const view = atom({ plugin: 'team-orchestrator', key: 'view' } as const, 'closed' as View)
135const teamName = atom({ plugin: 'team-orchestrator', key: 'teamName' } as const, '')
136const note = atom({ plugin: 'team-orchestrator', key: 'note' } as const, '')
137// frame counter for the animations; only advanced while something animated is on screen (see session.start)
138const frame = atom({ plugin: 'team-orchestrator', key: 'frame' } as const, 0)
139// which model/effort dropdown is open in the form ('' none, 'm2' = level 2's model, 'e1' = level 1's effort)
140const menu = atom({ plugin: 'team-orchestrator', key: 'menu' } as const, '')
141// The roster's look. Plugin state: it outlives a reload and a refresh, not a new session. Defaults are the old look.
142const SETTINGS0: Settings = { layout: 'stacked', chart: true, hide: [] }
143const settings = atom({ plugin: 'team-orchestrator', key: 'settings' } as const, SETTINGS0)
144const readSettings = async ($: any): Promise<Settings> => ({ ...SETTINGS0, ...(await read($, settings)) })
145const COLS = ['STATUS', 'CONTEXT', 'MODEL', 'EFFORT', 'BRIEF'] as const
146// a card's border and padding, around the cells columnPlan lays out
147const FRAME = 4
148// Team cards per row: side by side only where two fit, so a narrow terminal keeps the stacked look.
149// side by side and dock right: as many cards as fit at the narrower tiers (each card then picks the widest tier its
150// width allows); stacked keeps one full-width card per row
151const cardsPerRow = (s: Settings, cols: number, _cardW: number, cards: number) =>
152 s.layout === 'columns' || s.layout === 'dock' ? sideBySide(cols, cards, FRAME) : 1
153const ACT0: Act = { menu: '', kind: 'none', to: '', key: '', draft: '', boss: '', handle: '', role: '', tabs: [], msg: '', name: '', model: 'default', effort: 'default' }
154const act = atom({ plugin: 'team-orchestrator', key: 'act' } as const, ACT0)
155// the open assumptions of each session, by session id; read on each roster refresh only (see readAssumptions)
156const assumptions = atom({ plugin: 'team-orchestrator', key: 'assumptions' } as const, {} as Record<string, OpenAssumption[]>)
157// whether the assumptions view is on here: the team's switch is on and Session Panel is on in this session (see refresh)
158const assumptionsOn = atom({ plugin: 'team-orchestrator', key: 'assumptionsOn' } as const, false)
159const readAct = async ($: any): Promise<Act> => ({ ...ACT0, ...(await read($, act)) })
160// the side pane the panel moves to under the dock layout (the panes of earlier versions had other ids)
161const DOCK = 'team-dock'
162const SPAWN0: Spawn = { names: [], batch: 0, of: 0 }
163const spawn = atom({ plugin: 'team-orchestrator', key: 'spawn' } as const, SPAWN0)
164const bulk = atom({ plugin: 'team-orchestrator', key: 'bulk' } as const, {
165 prefix: '',
166 base: '',
167 numbering: 'none',
168 model: 'keep',
169 effort: 'keep',
170 msg: '',
171} as Bulk)
172
173type Spec = { name: string; role: string; level: number; boss: string; team?: string; model?: string; effort?: string; short?: string }
174
175const clean = (s: string) => s.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 40)
176
177const uuid = () =>
178 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
179 const r = Math.floor(Math.random() * 16)
180 return (c === 'x' ? r : (r % 4) + 8).toString(16)
181 })
182
183const levelName = (l: number, f: Form) =>
184 f.ceo === '1' ? (['CEO', 'Heads', 'Workers'][l - 1] ?? 'Workers') : l === 1 ? 'Head' : l === Number(f.levels) ? 'Workers' : 'Leads'
185
186const groupsOf = (f: Form): string[] => f.groups.split(',').map(g => clean(g.trim())).filter(Boolean)
187
188// One team: a head, then `fan` reports per manager down `levels` tiers (1 = head only, 3 = head/leads/workers).
189// With a CEO: the CEO, one head per named team, and `fan` workers under each head.
190const plan = (f: Form): Spec[] => {
191 const lv = (l: number) => ({
192 model: (f as any)[`m${l}`] as string,
193 effort: (f as any)[`e${l}`] as string,
194 })
195 const goal = f.fn || 'unspecified'
196 const fan = Number(f.fan)
197 if (f.ceo === '1') {
198 const org = clean(f.team) || 'Org'
199 const ceo: Spec = {
200 name: 'CEO', team: org, level: 1, boss: 'user',
201 role: `CEO: owns the goal "${goal}", splits it between the team heads, reviews, reports to the user`, ...lv(1),
202 }
203 const out: Spec[] = [ceo]
204 for (const g of groupsOf(f)) {
205 const head: Spec = {
206 name: `${g}-Head`, team: g, level: 2, boss: ceo.name,
207 role: `Head of team ${g}: takes goals from the CEO, splits them among its workers, reviews, reports to the CEO`, ...lv(2),
208 }
209 out.push(head)
210 for (let i = 1; i <= fan; i++) {
211 out.push({
212 name: `${g}-Worker-${i}`, team: g, level: 3, boss: head.name,
213 role: `Worker: executes tasks from ${head.name} and reports back`, ...lv(3),
214 })
215 }
216 }
217 return out
218 }
219 const levels = Number(f.levels)
220 const team = clean(f.team) || 'team'
221 const head: Spec = {
222 name: 'Head', team, level: 1, boss: 'user',
223 role: `Team head: owns the goal "${goal}", splits it, delegates, reviews, reports to the user`, ...lv(1),
224 }
225 const out: Spec[] = [head]
226 let tier: Spec[] = [head]
227 for (let l = 2; l <= levels; l++) {
228 const next: Spec[] = []
229 tier.forEach((b, bi) => {
230 for (let i = 1; i <= fan; i++) {
231 const isLast = l === levels
232 const n = levels === 2 ? `${i}` : `${bi + 1}-${i}`
233 next.push({
234 name: isLast ? `Worker-${n}` : `Lead-${levels === 2 ? i : `${bi + 1}-${i}`}`,
235 team,
236 role: isLast
237 ? `Worker: executes tasks from ${b.name} and reports back`
238 : `Lead: splits work from ${b.name} among its own reports and reviews them`,
239 level: l,
240 boss: b.name,
241 ...lv(l),
242 })
243 }
244 })
245 out.push(...next)
246 tier = next
247 }
248 return out
249}
250
251// ASCII org chart: depth-first from the head, with guide lines.
252const treeLines = (list: { name: string; boss: string }[]): { name: string; prefix: string }[] => {
253 const kids = new Map<string, string[]>()
254 for (const m of list) kids.set(m.boss, [...(kids.get(m.boss) ?? []), m.name])
255 const out: { name: string; prefix: string }[] = []
256 const walk = (name: string, guide: string, isLast: boolean, isRoot: boolean) => {
257 out.push({ name, prefix: isRoot ? '' : guide + (isLast ? '└─ ' : '├─ ') })
258 const c = kids.get(name) ?? []
259 c.forEach((k, i) => walk(k, isRoot ? '' : guide + (isLast ? ' ' : '│ '), i === c.length - 1, false))
260 }
261 const names = new Set(list.map(m => m.name))
262 list.filter(m => !names.has(m.boss)).forEach(m => walk(m.name, '', true, true))
263 return out
264}
265
266// state -> [glyph, label, color]
267const look = (s: string): [string, string, string] =>
268 s === 'working' ? ['◐', 'working', 'yellow']
269 : s === 'idle' ? ['●', 'idle', 'green']
270 : s === 'asking' ? ['◆', 'asking', 'magenta']
271 : s === 'starting' ? ['◌', 'starting', 'cyan']
272 : s === 'offline' ? ['○', 'offline', 'gray']
273 : s === 'failed' ? ['✗', 'failed', 'red']
274 : s === 'closed' ? ['–', 'closed', 'gray']
275 : s === 'unstarted' ? ['·', 'not yet', 'gray']
276 : s === 'queued' ? ['○', 'queued', 'gray']
277 : s === 'away' ? ['◌', 'away', 'gray']
278 : s === 'unmanaged' ? ['◇', 'external', 'gray']
279 : ['?', s.slice(0, 8), 'magenta']
280
281// `cells` wide bar and the percent on one line; 0 cells is the percent alone
282const bar = (pct: number, cells = 8): [string, string] => {
283 const frame = (inner: string) => (cells > 0 ? `[${inner}] ` : '')
284 if (pct < 0) return [`${frame('·'.repeat(cells))} --`, 'gray']
285 const f = Math.min(cells, Math.round((pct * cells) / 100))
286 return [`${frame(`${'█'.repeat(f)}${'░'.repeat(cells - f)}`)}${String(pct).padStart(3)}%`, pct < 50 ? 'green' : pct < 80 ? 'yellow' : 'red']
287}
288
289const handleOf = (json: string): string => json.match(/term_[0-9a-f-]+/)?.[0] ?? ''
290
291async function orca($: any, ...args: string[]) {
292 const r = await $.process.run([await orcaBin($), ...args, '--json'], { timeoutMs: 120000 }).catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: String(err) }))
293 return r.exitCode === 0
294 ? { ok: true, out: r.stdout as string }
295 : { ok: false, out: String(r.stderr || r.stdout) }
296}
297
298// The ANTHROPIC_DEFAULT_*_MODEL values of this configuration, read before each start command is built (see modelArg).
299let envModels: EnvModels = {}
300async function readEnvModels($: any): Promise<EnvModels> {
301 const get = (p: Promise<string | undefined>) => p.then(v => v?.trim() || undefined).catch(() => undefined)
302 const [opus, sonnet, haiku, fable] = await Promise.all([
303 get($.env.get('ANTHROPIC_DEFAULT_OPUS_MODEL')),
304 get($.env.get('ANTHROPIC_DEFAULT_SONNET_MODEL')),
305 get($.env.get('ANTHROPIC_DEFAULT_HAIKU_MODEL')),
306 get($.env.get('ANTHROPIC_DEFAULT_FABLE_MODEL')),
307 ])
308 return Object.fromEntries(Object.entries({ opus, sonnet, haiku, fable }).filter(([, v]) => v)) as EnvModels
309}
310
311const flags = (model?: string, effort?: string) => {
312 const m = modelArg(model ?? '', envModels)
313 // "[1m]" is a pattern to zsh: a name carrying it goes in double quotes (cmd.exe and bash take those too)
314 return `${m ? ` --model ${/[[\]]/.test(m) ? `"${m}"` : m}` : ''}${effort && effort !== 'default' && effort !== 'keep' ? ` --effort ${effort}` : ''}`
315}
316
317
318// State kept across a hot reload may predate the team field: such members belong to the one team the old version knew.
319const readMembers = async ($: any): Promise<Member[]> => {
320 const fallback = (await read($, teamName)) || 'team'
321 return (await read($, members)).map(m => ({ ...m, team: m.team || fallback }))
322}
323
324// Every session runs its own copy of this mod, so the teams live in one folder per project, inside the project:
325// <project root>/.claude/team-orchestrator/. roster.json holds the structure (teams, bosses, roles) and, for each
326// member, the status file it writes (statusFile); settings.json holds the team-wide worker settings; meta.json the schema
327// stamp; changes/ the changes other sessions made, waiting for the team top; queue/ the messages waiting for room.
328// Another project has its own folder. Live status is kept on each machine, outside the project (see readStatus).
329const rootOf = async ($: any) => String(await $.session.root()).replace(/[\/]+$/, '')
330const teamDir = async ($: any) => `${await rootOf($)}/.claude/team-orchestrator`
331const teamFile = async ($: any) => `${await teamDir($)}/roster.json`
332// the single file of versions before 0.5.0, migrated into the folder on first read
333const oldTeamFile = async ($: any) => `${await rootOf($)}/.claude/team-orchestrator.json`
334
335// An Orca workspace as Orca knows it now: whether it still exists, and its folder ('' when Orca gives none).
336async function worktreeInfo($: any, id: string): Promise<{ exists: boolean; path: string }> {
337 const r = await orca($, 'worktree', 'show', '--worktree', `id:${id}`)
338 if (!r.ok) return { exists: false, path: '' }
339 try {
340 return { exists: true, path: String(JSON.parse(r.out).result?.worktree?.path ?? '') || pathInWorktreeId(id) }
341 } catch {
342 return { exists: true, path: pathInWorktreeId(id) }
343 }
344}
345
346// The Orca workspace (worktree id) this session runs in (#68). The tab's own ORCA_WORKTREE_ID counts only while that
347// workspace's folder contains the project root: after a /cd or a moved project it names the old one. Otherwise
348// `orca worktree current`, run in the session's own folder, answers.
349async function currentWorktree($: any): Promise<string> {
350 // Orca names the workspace of the tab this session runs in; asking Orca by folder picks the wrong one when two
351 // workspaces share a folder
352 const own = String((await $.env.get('ORCA_WORKTREE_ID').catch(() => undefined)) ?? '').trim()
353 if (own) {
354 const root = await rootOf($)
355 const inId = pathInWorktreeId(own)
356 if (worktreeHolds(inId !== '' ? inId : (await worktreeInfo($, own)).path, root)) return own
357 }
358 const cur = await orca($, 'worktree', 'current')
359 return cur.ok ? (cur.out.match(/"worktree":\s*\{\s*"id":\s*"((?:[^"\\]|\\.)*)"/)?.[1] ?? '').replace(/\\\\/g, '\\') : ''
360}
361
362// The workspace a member starts in (#68): its saved one while Orca still has it and it holds the project root; else the
363// one this session finds, which the caller records on the member (from a session that is not the team top, through a
364// change file, like every roster change). '' when neither is known.
365async function memberWorktree($: any, m: Member): Promise<string> {
366 if (m.worktree) {
367 const i = await worktreeInfo($, m.worktree)
368 if (i.exists && worktreeHolds(i.path, await rootOf($))) return m.worktree
369 }
370 return (await currentWorktree($)) || m.worktree || ''
371}
372
373// Before 0.5.0 the roster was one file, .claude/team-orchestrator.json. Its content moves into the folder once (a copy
374// stays as roster.json.bak) and the old file is left as a pointer, so an old copy of the mod no longer reads it as a roster.
375async function migrate($: any) {
376 const [from, to] = [await oldTeamFile($), await teamFile($)]
377 if ((await $.fs.exists(to)) || !(await $.fs.exists(from))) return
378 const text = String(await $.fs.read(from))
379 try {
380 if (!Array.isArray(JSON.parse(text))) return
381 } catch {
382 return
383 }
384 await putFile($, to, text)
385 await putFile($, `${await teamDir($)}/roster.json.bak`, text)
386 await putFile($, from, JSON.stringify({ movedTo: '.claude/team-orchestrator/roster.json' }))
387}
388
389// The file sits inside the repo, so the first write of each load lists it in the repo's info/exclude: git then
390// never offers it to a commit. git answers for a worktree (.git is a file there) and a subfolder; outside a repo it fails.
391const excluded = new Set<string>()
392async function exclude($: any) {
393 const root = String(await $.session.root())
394 if (excluded.has(root)) return
395 excluded.add(root)
396 const r = await $.process.run(['git', '-C', root, 'rev-parse', '--show-prefix', '--path-format=absolute', '--git-path', 'info/exclude']).catch(() => undefined)
397 if (r?.exitCode !== 0) return
398 const [prefix, path] = String(r.stdout).split(/\r?\n/)
399 if (!path) return
400 const line = `${prefix ?? ''}.claude/team-orchestrator/`
401 const before = (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
402 if (before.split(/\r?\n/).some(l => l.trim().replace(/^\//, '') === line)) return
403 await putFile($, path, `${before}${before === '' || before.endsWith('\n') ? '' : '\n'}${line}\n`)
404}
405
406// ── One writer (0.5.12, #59) and machines (#64), see changes.ts ──────────────────────────────────────────────
407// Only the team top's session, on the top's machine, writes roster.json and settings.json. Every other session writes
408// a change file (changes/<ms>-<rand>.json) with the fields it changed, and applies the change to its own view at once;
409// every session reads the roster as the file plus the change files not yet applied, so all of them see the same team.
410// The top folds the change files into the file on its next refresh (30 s at most) and lists them in changes/applied.json
411// (the mod cannot delete a file). Until a team has a running top on this machine, a session that is not on the roster
412// (the person's own) writes in its place; the first write of a new team is always direct.
413
414// This machine's name, for each member's home machine and the top machine; '' when the platform gives none. macOS and
415// Linux export no COMPUTERNAME and seldom HOSTNAME (a shell variable), so there it is asked once per load: macOS's
416// LocalHostName (`uname -n` there follows the network), else `uname -n`. "localhost" names no machine.
417const host = { name: undefined as Promise<string> | undefined }
418async function machineOf($: any): Promise<string> {
419 const none = () => undefined
420 const env = String((await $.env.get('COMPUTERNAME').catch(none)) || (await $.env.get('HOSTNAME').catch(none)) || '').trim()
421 if (env || (await isWindows($))) return env
422 host.name ??= (async () => {
423 for (const argv of [['scutil', '--get', 'LocalHostName'], ['uname', '-n']]) {
424 const r = await $.process.run(argv, { timeoutMs: 10000 }).catch(none)
425 const name = r?.exitCode === 0 ? String(r.stdout).trim() : ''
426 if (name) return /^localhost(\.|$)/i.test(name) ? '' : name
427 }
428 return ''
429 })()
430 return host.name
431}
432
433// A member launched while this PC gave no name has no machine recorded, so its crash check can never prove its home.
434// A running one records it when its own session identifies; for the rest (a crashed one never will) the writer gives
435// this PC to each whose session's transcript is in this PC's config folder: that session ran here. One with no
436// transcript here is left alone, since it may run on another PC. Each session id is looked up once per load.
437const homeLooked = new Set<string>()
438async function homeHere($: any, here: string) {
439 const bare = (await readMembers($)).filter(m => !m.machine && m.sessionId && !homeLooked.has(m.sessionId))
440 if (bare.length === 0) return
441 for (const m of bare) homeLooked.add(m.sessionId)
442 const ran = new Set((await transcripts($)).map(t => t.id))
443 const mine = new Set(bare.filter(m => ran.has(m.sessionId)).map(keyOf))
444 if (mine.size === 0) return
445 await update($, members, old => old.map(m => (mine.has(keyOf(m)) && !m.machine ? { ...m, machine: here } : m)))
446 await share($)
447}
448
449const changesDir = async ($: any) => `${await teamDir($)}/changes`
450const metaFile = async ($: any) => `${await teamDir($)}/meta.json`
451const rand = () => Math.random().toString(36).slice(2, 10).padEnd(8, '0')
452
453async function readJson($: any, path: string): Promise<any> {
454 if (!(await $.fs.exists(path).catch(() => false))) return undefined
455 try {
456 return JSON.parse(String(await $.fs.read(path)))
457 } catch {
458 return undefined
459 }
460}
461
462async function readMeta($: any): Promise<Meta> {
463 const m = await readJson($, await metaFile($))
464 return m && typeof m === 'object' && !Array.isArray(m) ? { ...META0, ...m } : META0
465}
466
467// A change file never changes once written, so each is read once per load.
468const changeMemo = new Map<string, Change>()
469type Pending = { name: string; change: Change }
470async function readApplied($: any): Promise<string[]> {
471 const v = await readJson($, `${await changesDir($)}/applied.json`)
472 return Array.isArray(v?.names) ? v.names.filter((n: unknown): n is string => typeof n === 'string') : []
473}
474
475/** The change files not yet applied, oldest first. */
476async function pendingChanges($: any): Promise<Pending[]> {
477 const dir = await changesDir($)
478 const now = Date.now()
479 const names = ((await $.fs.list(dir).catch(() => [])) as any[])
480 .filter(f => f.kind === 'file')
481 .map(f => String(f.name))
482 .filter(n => now - timeOf(n) <= KEEP_MS)
483 if (names.length === 0) return []
484 const out: Pending[] = []
485 for (const n of pendingNames(names, new Set(await readApplied($)), now)) {
486 let c = changeMemo.get(n)
487 if (!c) {
488 const v = await readJson($, `${dir}/${n}`)
489 // one being written (or synced) right now is read next time
490 if (!v || (v.kind !== 'roster' && v.kind !== 'settings')) continue
491 c = v as Change
492 changeMemo.set(n, c)
493 }
494 out.push({ name: n, change: c })
495 }
496 return out
497}
498
499async function markApplied($: any, names: string[]) {
500 if (names.length === 0) return
501 await putFile($, `${await changesDir($)}/applied.json`, JSON.stringify({ names: appliedAfter(await readApplied($), names, Date.now()) }, null, 1))
502}
503
504// The roster as this session last read it (the file plus the pending changes), and which change files that read
505// included: a non-writer's change file holds only what differs from this base, field by field.
506const seenRoster = { base: undefined as Partial<Member>[] | undefined, overlay: new Set<string>() }
507
508/** The roster file's rows with the pending change files applied; undefined when there is no roster file. */
509async function effective($: any): Promise<{ rows: Partial<Member>[]; applied: string[] } | undefined> {
510 const file = await teamFile($)
511 if (!(await $.fs.exists(file))) return undefined
512 let saved: unknown
513 try {
514 saved = JSON.parse(String(await $.fs.read(file)))
515 } catch {
516 return undefined
517 }
518 if (!Array.isArray(saved)) return undefined
519 const roster = (await pendingChanges($)).filter(c => c.change.kind === 'roster')
520 return { rows: roster.length > 0 ? applyOps(saved as Partial<Member>[], rosterOps(roster)) : (saved as Partial<Member>[]), applied: roster.map(c => c.name) }
521}
522
523/**
524 * Who writes the team files from this session:
525 * - top: the confirmed team top on the top's machine; standin: a session not on the roster while no top runs on this
526 * machine; boot: there is no roster file yet. These three write the files.
527 * - member: any other session; old: this mod is older than the one that last wrote the roster; away: the top machine
528 * is another PC. These write change files.
529 */
530type Role = 'top' | 'standin' | 'boot' | 'member' | 'old' | 'away'
531type Writer = { role: Role; meta: Meta; here: string; me: string }
532const writes = (r: Writer) => r.role === 'top' || r.role === 'standin' || r.role === 'boot'
533// what this session has been told (once each); reset at each load
534const told = { old: false, away: '', asked: false, declined: false }
535// an AskUserQuestion was answered in the turn that is running: team_take_top needs the user's answer first
536const turnAsk = { answered: false }
537
538async function writerRole($: any, who?: Who): Promise<Writer> {
539 await readVersion($)
540 const meta = await readMeta($)
541 const here = await machineOf($)
542 const base = { meta, here, me: who?.me?.name ?? '' }
543 if (olderThan(cfg.version, meta.writtenBy)) {
544 if (!told.old) {
545 told.old = true
546 await $.ui.toast(
547 `Team Orchestrator: this team's files were written by team-orchestrator ${meta.writtenBy}, newer than this session's ${cfg.version}. ` +
548 'Update team-orchestrator and /reload-plugins. Until then this session writes no team file; its roster changes wait for the team top.',
549 )
550 }
551 return { ...base, role: 'old' }
552 }
553 if (!(await $.fs.exists(await teamFile($)))) return { ...base, role: 'boot' }
554 const list = await readMembers($)
555 const w = who ?? (await identity($, list))
556 const me = w.me?.name ?? ''
557 const top = projectTop(list)
558 const elsewhere = topElsewhere(meta, here)
559 if (w.level === 'full' && w.me && top && keyOf(w.me) === keyOf(top)) {
560 if (!elsewhere) return { ...base, me, role: 'top' }
561 await topAway($, meta, here, true)
562 return { ...base, me, role: 'away' }
563 }
564 if (w.level === 'none') {
565 if (elsewhere) {
566 await topAway($, meta, here, false)
567 return { ...base, me, role: 'away' }
568 }
569 if (!(await topLive($, list, here))) return { ...base, me, role: 'standin' }
570 }
571 return { ...base, me, role: 'member' }
572}
573
574// The team top is running: its status on this machine is fresh, or this machine's registry lists its session. A top
575// whose home is another PC counts as running: this PC does not stand in for it.
576async function topLive($: any, list: Member[], here: string): Promise<boolean> {
577 const top = projectTop(list)
578 if (!top) return false
579 if (isAway(top, here)) return true
580 const s = await readStatus($, top.name)
581 if (s && s.state !== 'closed' && Date.now() - s.heartbeat < STALE_MS) return true
582 return !!top.sessionId && (await registry($)).some(r => r.sessionId === top.sessionId)
583}
584
585const takeAsk = (there: string, here: string) =>
586 `TEAM ORCHESTRATOR, act now: the team top is recorded on ${there}, not on this PC (${here}). Until that changes this session ` +
587 'writes no team file, closes no idle worker and delivers no queued message. Ask the user AT ONCE with AskUserQuestion whether this PC ' +
588 `takes over as the team top, with two options: (1) "Take over on ${here}": the roster records this PC as the top's, and ${there} becomes read-only; ` +
589 `(2) "Keep ${there}". Then apply the answer with team_take_top { take: true | false }.`
590
591// The top machine is another PC: said once per session, and a top session's model is asked to check with the user.
592async function topAway($: any, meta: Meta, here: string, isTop: boolean) {
593 if (told.away !== meta.topMachine) {
594 told.away = meta.topMachine
595 await $.ui.toast(
596 `Team Orchestrator: the team top runs on ${meta.topMachine}, not this PC (${here}). Here the team files are read-only: ` +
597 `changes wait in changes/ for ${meta.topMachine}, and auto-close and the queue run there.` +
598 (isTop ? ' You are asked whether this PC takes over.' : ' team_take_top moves the top here, once you say yes.'),
599 )
600 }
601 if (isTop && !told.asked && !told.declined) {
602 told.asked = true
603 addNote(String(await $.session.id().catch(() => '')), takeAsk(meta.topMachine, here))
604 }
605}
606
607// One writer at a time inside this session (a refresh and a Settings press may overlap).
608const lock = { chain: Promise.resolve() as Promise<unknown> }
609function serial<T>(fn: () => Promise<T>): Promise<T> {
610 const run = lock.chain.then(fn, fn)
611 lock.chain = run.catch(() => undefined)
612 return run
613}
614
615const FRESH = { state: 'idle', ctx: -1, model: '', effort: '', sel: false, note: '', briefed: false, noted: false }
616const rowText = (list: Partial<Member>[]) =>
617 JSON.stringify(list.map(m => Object.fromEntries(STRUCT.map(k => [k, k === 'statusFile' ? statusFile(String(m.name ?? '')) : (m as any)[k]]))), null, 1)
618
619// Persist this session's roster: written by the writer, else as a change file. Role files follow either way.
620// `who` is given by identity itself, which must not wait for its own answer.
621async function share($: any, who?: Who) {
622 await migrate($)
623 const r = await writerRole($, who)
624 await serial(() => (writes(r) ? writeRoster($, r) : writeChange($, r)))
625 if (r.role !== 'old') await writeRoles($, await readMembers($))
626}
627
628// The writer: change files that arrived since this session last read the roster are applied on top of its own view,
629// in time order, field by field; then the file is written and every pending change is listed as applied.
630async function writeRoster($: any, r: Writer) {
631 const pending = await pendingChanges($)
632 const roster = pending.filter(c => c.change.kind === 'roster')
633 const fresh = roster.filter(c => !seenRoster.overlay.has(c.name))
634 let list = await readMembers($)
635 if (fresh.length > 0) {
636 list = applyOps(list, rosterOps(fresh)).map(m => ({ ...FRESH, ...m }) as Member)
637 await update($, members, () => list)
638 }
639 const text = rowText(list)
640 const file = await teamFile($)
641 const before = (await $.fs.exists(file)) ? String(await $.fs.read(file)) : ''
642 if (before !== text) {
643 await exclude($)
644 const prev = await readGrantRecord($, file)
645 await putFile($, file, text)
646 await writeGrantRecord($, file, recordAfterWrite(prev, grantMap(rowsOf(before)), grantMap(list)))
647 }
648 // the stamp: the newest mod version that wrote, and the top's machine (moved only by team_take_top once set)
649 if (r.role === 'top') {
650 const next = metaAfter(r.meta, cfg.version, r.here)
651 const was = { schemaVersion: r.meta.schemaVersion, writtenBy: r.meta.writtenBy, topMachine: r.meta.topMachine }
652 if (JSON.stringify(next) !== JSON.stringify(was) || !(await $.fs.exists(await metaFile($)))) await putFile($, await metaFile($), JSON.stringify(next, null, 1))
653 }
654 const settingsChanges = pending.filter(c => c.change.kind === 'settings')
655 if (settingsChanges.length > 0) await writeSettingsFile($, applySettings(await readSettingsFile($), settingsChanges))
656 await markApplied($, pending.map(c => c.name))
657 const rights = rightsChanges(roster)
658 if (rights.length > 0) await $.ui.toast(`Team Orchestrator: applied a change of rights made in another session: ${rights.join('; ')}.`)
659 seenRoster.base = list.map(project)
660 seenRoster.overlay = new Set()
661}
662
663async function writeChangeFile($: any, r: Writer, body: { kind: 'roster'; ops: any[] } | { kind: 'settings'; patch: Partial<TeamSettings> }) {
664 const at = Date.now()
665 const name = fileName(at, rand())
666 const sid = String(await $.session.id().catch(() => ''))
667 const c = { v: 1, ...body, at, by: { session: sid, member: r.me, machine: r.here, version: cfg.version } } as Change
668 await putFile($, `${await changesDir($)}/${name}`, JSON.stringify(c, null, 1))
669 changeMemo.set(name, c)
670 // this session's view has it already: as the writer later, it does not apply it again over newer edits
671 seenRoster.overlay.add(name)
672}
673
674// Everyone else: what this session changed since it last read the roster, as one change file. Its own view keeps the
675// change (it was made there first), and the next read shows the same, since every read applies pending change files.
676async function writeChange($: any, r: Writer) {
677 const list = await readMembers($)
678 const base = seenRoster.base ?? (await effective($))?.rows ?? []
679 const ops = diffOps(base, list)
680 if (ops.length === 0) return
681 await writeChangeFile($, r, { kind: 'roster', ops })
682 seenRoster.base = list.map(project)
683}
684
685// ── Grants changed outside the mod (#58) ──
686// What the mod last wrote for each member's Allow writes and Allow subagents, per roster file: in $.store, which every
687// session of this machine shares, with this session's own copy as the fallback. The team top's refresh compares the
688// file with it (checkGrants). Reported only, never reverted.
689const grantMemo = new Map<string, GrantMap>()
690const grantKey = (file: string) => `grants:${file.replace(/\\/g, '/').toLowerCase()}`
691async function readGrantRecord($: any, file: string): Promise<GrantMap | undefined> {
692 const v = await $.store.get(grantKey(file)).catch(() => undefined)
693 return v && typeof v === 'object' ? (v as GrantMap) : grantMemo.get(grantKey(file))
694}
695async function writeGrantRecord($: any, file: string, g: GrantMap) {
696 grantMemo.set(grantKey(file), g)
697 await $.store.set(grantKey(file), g).catch(() => undefined)
698}
699const rowsOf = (text: string): Partial<Member>[] => {
700 try {
701 const v = JSON.parse(text)
702 return Array.isArray(v) ? v : []
703 } catch {
704 return []
705 }
706}
707
708// A difference is reported once it shows on two refreshes in a row (a write by another session's mod, caught between
709// its file and its record, is gone by the next one), and each difference once.
710const tamper = { last: '', told: new Set<string>() }
711const TAMPER_NOTE = 'roster.json changed outside the mod'
712async function checkGrants($: any) {
713 const file = await teamFile($)
714 if (!(await $.fs.exists(file))) return
715 const now = grantMap(rowsOf(String(await $.fs.read(file))))
716 const rec = await readGrantRecord($, file)
717 if (!rec) return void (await writeGrantRecord($, file, now))
718 const diff = grantChanges(rec, now)
719 const sig = JSON.stringify(diff)
720 const twice = sig === tamper.last
721 tamper.last = sig
722 if (diff.length === 0 || !twice || tamper.told.has(sig)) return
723 tamper.told.add(sig)
724 const say = diff.map(d => `${d.name}: ${d.changes.join(', ')}`).join('; ')
725 await $.ui.toast(`Team Orchestrator: ${TAMPER_NOTE} (${say}). Nothing was reverted; check Settings → Allow writes / Allow subagents.`)
726 await update($, members, old =>
727 old.map(m => {
728 const d = diff.find(x => x.key === keyOf(m))
729 if (!d) return m
730 const kept = m.note.split(', ').filter(p => p !== '' && !p.startsWith(TAMPER_NOTE))
731 return { ...m, note: [...kept, `${TAMPER_NOTE}: ${d.changes.join(', ')}`].join(', ') }
732 }),
733 )
734}
735
736// Each member's role file (roles.ts): the generated part follows the roster, the person's notes below the marker stay.
737// A file is read and written only when its generated part changed since this session last wrote or checked it.
738const roleSeen = new Map<string, string>()
739async function writeRoles($: any, list: Member[]) {
740 const dir = await teamDir($)
741 for (const m of list) {
742 const generated = roleText(m, orgOf(list, m.team))
743 const path = `${dir}/${roleFile(m.name)}`
744 if (roleSeen.get(path) === generated) continue
745 const before = (await $.fs.exists(path)) ? String(await $.fs.read(path)) : undefined
746 const after = mergeRole(before, generated)
747 if (after !== before) await putFile($, path, after)
748 roleSeen.set(path, generated)
749 }
750}
751
752// The command that starts a member: its role pointer in the system prompt, and an optional first prompt. A shell types
753// it (cmd.exe on Windows, bash or zsh elsewhere), so the texts go in double quotes and carry nothing a shell would
754// expand (pointer() and WELCOME see to that). The name is quoted too: unquoted, "Mod Builder 2" splits into --name Mod
755// and a first prompt "Builder". Inside double quotes bash still runs $(...) and backticks, so a name outside SAFE_NAME
756// (only an adopted one can be, from before 0.5.37) goes into the command in its cleaned form.
757const SAFE_NAME = /^[\p{L}\p{N} ._-]{1,64}$/u
758const shellName = (name: string) => (SAFE_NAME.test(name) ? name : clean(name))
759const startCmd = (m: Member, list: Member[], sessionId: string, resume: boolean, name = m.name, model = m.model, effort = m.effort, first = '') =>
760 `claude ${resume ? `--resume ${sessionId}` : `--session-id ${sessionId}`} --name "${shellName(name)}"${flags(model, effort)}` +
761 `${memberSettings.path ? ` --settings "${memberSettings.path}"` : ''}` +
762 ` --append-system-prompt "${pointer({ ...m, name: shellName(name) }, list)}"${first ? ` "${first}"` : ''}`
763
764// Browser-automation plugins (Chrome DevTools, Playwright) start an idle server in every session. A member starts with
765// the ones the person enabled turned off, by a settings file of its own (--settings, on this machine), so the person's
766// own sessions keep them. Read from the settings files the way sessionPanelOn reads them, never from this session's
767// merged settings (a member launching a worker carries the file's own "off"). The path is '' when nothing is turned off.
768const BROWSER_PLUGIN = /^(chrome-devtools-mcp|playwright)@/
769const memberSettings = { path: '' }
770async function writeMemberSettings($: any): Promise<void> {
771 memberSettings.path = ''
772 try {
773 const root = await rootOf($)
774 const [user] = await claudeDirs($)
775 const named = new Map<string, unknown>()
776 for (const f of [`${root}/.claude/settings.local.json`, `${root}/.claude/settings.json`, ...(user ? [`${user}/settings.json`] : [])])
777 for (const [k, v] of Object.entries((await readJson($, f))?.enabledPlugins ?? {})) if (!named.has(k)) named.set(k, v)
778 const off = [...named].filter(([k, v]) => BROWSER_PLUGIN.test(k) && v !== false).map(([k]) => [k, false])
779 const dir = await configDir($)
780 // the path goes in double quotes on a command line a shell types: nothing there may expand
781 if (off.length === 0 || !dir || /["%$`!\r\n]/.test(dir)) return
782 const path = `${dir}/team-orchestrator/member-settings.json`
783 await putFile($, path, JSON.stringify({ enabledPlugins: Object.fromEntries(off) }, null, 1))
784 memberSettings.path = path
785 } catch {
786 // no file: the member starts with the person's plugins, as before
787 }
788}
789
790// The roster as every session sees it: the file plus the change files not yet applied (see share). Under the writers'
791// lock: a pull between a change file's read of the roster and its record of it would leave that record behind the
792// roster, and the next change file would send other sessions' rows again as this session's.
793async function pull($: any) {
794 await serial(() => pullNow($))
795}
796async function pullNow($: any) {
797 await migrate($)
798 const eff = await effective($)
799 // an empty list is a real state (the last team was removed), not a missing file
800 if (!eff) return
801 const saved = eff.rows
802 seenRoster.base = saved.map(project)
803 seenRoster.overlay = new Set(eff.applied)
804 const fresh = { state: 'idle', ctx: -1, model: '', effort: '', sel: false, note: '' }
805 await update($, members, old =>
806 saved.map(m => {
807 const o = old.find(x => x.name === m.name && (x.team || m.team) === m.team)
808 // a member that never started shows so in every session, whatever state this one last saw
809 return { ...fresh, ...(o ?? {}), ...m, sel: o?.sel ?? false, ...(m.pending ? { state: 'unstarted' } : {}) } as Member
810 }),
811 )
812}
813
814// The one-time briefing: structure, reporting line and communication rules, sent once per session.
815const briefText = (m: Member, list: Member[], team: string): string => {
816 const kids = list.filter(x => x.boss === m.name)
817 const isManager = kids.length > 0
818 const peers = list.filter(x => x.name !== m.name && list.some(k => k.boss === x.name))
819 const addr = (x: Member) => `"${x.address || x.name}"`
820 const roster = list.map(x => `${x.address || x.name} (${x.level === 1 ? 'head' : list.some(k => k.boss === x.name) ? 'lead' : 'worker'}, reports to ${x.boss})`).join('; ')
821 const rules = isManager
822 ? `YOUR JOB: you ORCHESTRATE. You decide, plan and instruct only; you do NOT execute tasks yourself, you delegate execution to your direct reports and review what they send back. ` +
823 `Your direct reports: ${kids.map(addr).join(', ')}. ` +
824 (m.boss === 'user' ? 'You report to the user. ' : `Your boss: ${m.boss}. `) +
825 `COMMUNICATION: you may message your boss, your direct reports, and any other head or lead in any department` +
826 (peers.length ? ` (${peers.map(addr).join(', ')})` : '') +
827 `. Do not bypass a lead to instruct someone else's worker. ` +
828 `Message your direct reports with the team_message tool (mcp__team-orchestrator__team_message, { to: "<name>", message: "..." }), not SendMessage: a report may not have started yet or may have been closed while idle, and team_message starts it, briefs it and then delivers.`
829 : `YOUR JOB: you EXECUTE the tasks your direct boss gives you and report results back. Your direct boss (one level up): ${m.boss}. ` +
830 `COMMUNICATION: talk ONLY to your direct boss. Do NOT message your boss's boss, other leads, or other workers. ` +
831 `Worker-to-worker contact is forbidden unless your boss explicitly names that worker to you in a message.`
832 return (
833 `TEAM BRIEFING (one-time, from the Team Orchestrator). You are ${m.name} in team "${m.team}". Role: ${m.role}. ${rules} ` +
834 `Team structure: ${roster}. ` +
835 `TEAM FILES: the team lives in .claude/team-orchestrator/ in the project. roster.json is the structure (teams, bosses, roles) and settings.json the team's worker settings; only the team top's session writes them, and a change made in any other session waits in changes/ until the top applies it. Never edit roster.json, settings.json, meta.json or changes/ by hand. Each member's live status (state, task, model, context, last "clean") is written by the Team Orchestrator for its own session, on its own PC under ~/.claude/team-orchestrator/; never edit another member's status file. ` +
836 `To message a teammate use the SendMessage tool (Claude Code's native agent messaging), e.g. SendMessage({ to: "<their name>", message: "..." }), where the name is the quoted name shown above or in the structure list. If SendMessage says the name is ambiguous or unknown and the person is on the team, use team_message with the plain name instead (it addresses that member's own session by its id: never a same-named session of another project, never a Remote Control copy). Do NOT use orca terminal send or the terminal for messages to teammates. ` +
837 `Now reply with exactly "Noted" plus one short line restating your role and reporting line, then wait for instructions.`
838 )
839}
840
841async function briefTeam($: any, team: string, only?: Set<string>) {
842 const all: Member[] = await readMembers($)
843 const mine = all.filter(m => m.team === team)
844 // the briefing lists the team and every boss above it, so a head learns who its CEO is
845 const list = orgOf(all, team)
846 const sent = new Set<string>()
847 // a member on another PC has its tab there: its handle means nothing here
848 const here = await machineOf($)
849 await Promise.all(
850 mine
851 .filter(m => m.handle && !isAway(m, here) && isManaged(m) && (!only || only.has(keyOf(m))))
852 .map(async m => {
853 const r = await orca($, 'terminal', 'send', '--terminal', m.handle, '--text', briefText(m, list, team), '--enter')
854 if (r.ok) sent.add(m.name)
855 }),
856 )
857 await update($, members, old => old.map(m => ((m.team || 'team') === team && sent.has(m.name) ? { ...m, briefed: true, noted: false } : m)))
858 await share($)
859}
860
861// ── Transcripts: <config dir>/projects/<project>/<session id>.jsonl ──────────────────────────────────────────
862// Only these things are taken from a transcript: its last customTitle, its last requestedModel, and the last assistant
863// message's model, usage (as a context percent), effort and cwd. Nothing else is kept or shown: a transcript can hold
864// secrets.
865type Transcript = { id: string; path: string; mtimeMs: number }
866/** requested: the last model asked for, as typed ('' unknown); used: the tokens the last answer was given over */
867type Stats = { model: string; requested: string; used: number; ctx: number; effort: string; cwd: string }
868
869// Every transcript, newest first.
870async function transcripts($: any): Promise<Transcript[]> {
871 const none = () => undefined
872 const home = (await $.env.get('USERPROFILE').catch(none)) || (await $.env.get('HOME').catch(none))
873 const dir = (await $.env.get('CLAUDE_CONFIG_DIR').catch(none)) || (home ? `${home}/.claude` : '')
874 if (!dir) return []
875 const root = `${dir}/projects`
876 const projects = ((await $.fs.list(root).catch(() => [])) as any[]).filter(p => p.kind === 'dir')
877 const lists = await Promise.all(projects.map(async p => ((await $.fs.list(`${root}/${p.name}`).catch(() => [])) as any[]).map(f => ({ ...f, dir: `${root}/${p.name}` }))))
878 return lists
879 .flat()
880 .filter(f => f.kind === 'file' && /^[0-9a-f-]{36}\.jsonl$/.test(f.name))
881 .map(f => ({ id: f.name.slice(0, 36), path: `${f.dir}/${f.name}`, mtimeMs: f.mtimeMs }))
882 .sort((a, b) => b.mtimeMs - a.mtimeMs)
883}
884
885// The last TAIL bytes of each file, '' for one it cannot read: one PowerShell per 15 files, since stdout holds
886// 4 MiB, and $.fs.read takes a whole file (at most 4 MiB) where a transcript can be far larger.
887const TAIL = 256 * 1024
888const TAIL_PS =
889 "$o=[Console]::OpenStandardOutput(); foreach($p in $env:TO_FILES -split '\\|'){ $o.WriteByte(0); try { $f=[IO.File]::Open($p,'Open','Read','ReadWrite'); try { $k=[Math]::Min([long]$env:TO_BYTES,$f.Length); [void]$f.Seek(-$k,'End'); $b=New-Object byte[] $k; $o.Write($b,0,$f.Read($b,0,$k)) } finally { $f.Close() } } catch {} }; $o.Flush()"
890// the same on macOS and Linux: tail -c per file, each preceded by a NUL
891const TAIL_SH = 'for p in "$@"; do printf "\\0"; tail -c "$TO_BYTES" "$p" 2>/dev/null; done'
892async function tails($: any, files: string[]): Promise<string[]> {
893 const out: string[] = []
894 const win = await isWindows($)
895 for (let i = 0; i < files.length; i += 15) {
896 const part = files.slice(i, i + 15)
897 const cmd = win ? ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', TAIL_PS] : ['sh', '-c', TAIL_SH, 'sh', ...part]
898 const r = await $.process
899 .run(cmd, { env: { TO_FILES: part.join('|'), TO_BYTES: String(TAIL) }, timeoutMs: 60000 })
900 .catch(() => undefined)
901 const got = r?.exitCode === 0 ? String(r.stdout).split('\0').slice(1) : []
902 out.push(...part.map((_, j) => got[j] ?? ''))
903 }
904 return out
905}
906
907const lastTitle = (text: string): string | undefined => {
908 const hit = [...text.matchAll(/"customTitle":("(?:[^"\\]|\\.)*")/g)].pop()
909 try {
910 return hit ? String(JSON.parse(hit[1] as string)) : undefined
911 } catch {
912 return undefined
913 }
914}
915
916// The model the member asked for (#63): the last requestedModel of its own loop, as typed ([1m] and a gateway's name
917// kept, /model switches followed); message.model drops [1m] and may be a gateway's own id. '' when the tail has none.
918const lastRequested = (text: string): string => {
919 const lines = text.split('\n')
920 for (let i = lines.length - 1; i >= 0; i--) {
921 const l = lines[i] as string
922 if (!l.includes('"requestedModel"')) continue
923 try {
924 const d = JSON.parse(l)
925 if (!d?.isSidechain && typeof d?.requestedModel === 'string' && d.requestedModel.trim() !== '') return d.requestedModel.trim()
926 } catch {
927 // a line cut by the tail
928 }
929 }
930 return ''
931}
932
933// The model is the one asked for (else the one that answered), kept as typed. The context percent counts against
934// windowFor's guess (200k unless [1m] or past 200k); the roster uses the member's own reported window when it has one.
935const lastStats = (text: string): Stats | undefined => {
936 const lines = text.split('\n')
937 const requested = lastRequested(text)
938 for (let i = lines.length - 1; i >= 0; i--) {
939 const l = lines[i] as string
940 if (!l.includes('"type":"assistant"')) continue
941 let d: any
942 try {
943 d = JSON.parse(l)
944 } catch {
945 continue
946 }
947 const u = d?.message?.usage
948 const model = String(d?.message?.model ?? '')
949 if (d?.type !== 'assistant' || d.isSidechain || !u || model === '' || model === '<synthetic>') continue
950 const used = Number(u.input_tokens ?? 0) + Number(u.cache_read_input_tokens ?? 0) + Number(u.cache_creation_input_tokens ?? 0)
951 return {
952 model: requested || model,
953 requested,
954 used,
955 ctx: Math.round((used * 100) / windowFor(requested || model, used)),
956 effort: typeof d.effort === 'string' ? d.effort : '',
957 cwd: typeof d.cwd === 'string' ? d.cwd : '',
958 }
959 }
960 return undefined
961}
962
963// What each transcript's tail said, kept until the file changes, so a refresh reads only the files that moved.
964const seen = new Map<string, { mtimeMs: number; title?: string; stats?: Stats }>()
965async function peek($: any, files: Transcript[]) {
966 const stale = files.filter(f => seen.get(f.path)?.mtimeMs !== f.mtimeMs)
967 const texts = await tails($, stale.map(f => f.path))
968 stale.forEach((f, i) => seen.set(f.path, { mtimeMs: f.mtimeMs, title: lastTitle(texts[i] ?? ''), stats: lastStats(texts[i] ?? '') }))
969 return files.map(f => seen.get(f.path)!)
970}
971
972// Session id per name: the newest transcript of THIS project whose last customTitle is that name. A transcript that
973// last ran outside the project folder is another team's, even when it carries the same title.
974async function sessionsNamed($: any, all: Transcript[], names: string[], root: string): Promise<Map<string, string>> {
975 const want = new Set(names)
976 const found = new Map<string, string>()
977 for (let i = 0; i < all.length && found.size < want.size; i += 15) {
978 const part = all.slice(i, i + 15)
979 ;(await peek($, part)).forEach((s, j) => {
980 const cwd = s.stats?.cwd ?? ''
981 if (cwd !== '' && !under(cwd, root)) return
982 if (s.title !== undefined && want.has(s.title) && !found.has(s.title)) found.set(s.title, (part[j] as Transcript).id)
983 })
984 }
985 return found
986}
987
988async function statsOf($: any, all: Transcript[], ids: string[]): Promise<Map<string, Stats | undefined>> {
989 const files = all.filter(t => ids.includes(t.id))
990 const got = await peek($, files)
991 return new Map(files.map((f, i) => [f.id, got[i]?.stats]))
992}
993
994// The model a member last asked for in its own transcript, as typed ([1m] kept); '' when there is none (#63).
995async function requestedModel($: any, m: Member): Promise<string> {
996 if (!m.sessionId) return ''
997 const st = (await statsOf($, await transcripts($), [m.sessionId]).catch(() => undefined))?.get(m.sessionId)
998 return st?.requested ?? ''
999}
1000
1001// ── Who this session is (identity.ts) ──
1002// The tab, the session id and the name are matched against the roster by identify(); the answer is worked out once
1003// per refresh and kept while the session id and the roster's identity fields stay the same, so a tool call does not
1004// read the registry or a transcript.
1005type Reg = { sessionId: string; cwd: string; name: string; pid: number }
1006// The machine's session registry: <config dir>/sessions/<pid>.json, one per live local session. Only the id, the
1007// folder, the name and the process id are taken; the .key files beside them are never read. ok: some registry folder
1008// could be listed, so an empty answer means "no session", not "unreadable" (the crash check of 0.5.16 needs the difference).
1009async function readRegistry($: any): Promise<{ ok: boolean; list: Reg[] }> {
1010 const out: Reg[] = []
1011 let ok = false
1012 for (const dir of [...new Set(await claudeDirs($))]) {
1013 const at = `${dir}/sessions`
1014 let listed: any[]
1015 try {
1016 listed = (await $.fs.list(at)) as any[]
1017 ok = true
1018 } catch {
1019 continue
1020 }
1021 const files = listed.filter(f => f.kind === 'file' && /^\d+\.json$/.test(String(f.name)))
1022 for (const f of files) {
1023 try {
1024 const o = JSON.parse(String(await $.fs.read(`${at}/${f.name}`)))
1025 const pid = Number.isInteger(o?.pid) && o.pid > 0 ? (o.pid as number) : Number(String(f.name).replace(/\.json$/, ''))
1026 if (typeof o?.sessionId === 'string') out.push({ sessionId: o.sessionId, cwd: String(o.cwd ?? ''), name: typeof o.name === 'string' ? o.name : '', pid })
1027 } catch {
1028 // a record being rewritten: skip it this time
1029 }
1030 }
1031 }
1032 return { ok, list: out }
1033}
1034const registry = async ($: any): Promise<Reg[]> => (await readRegistry($)).list
1035
1036type Who = { me?: Member; level: Level; why: string }
1037const NOBODY: Who = { level: 'none', why: '' }
1038const sigOf = (list: Member[]) => list.map(m => [m.team, m.name, m.address ?? '', m.handle, m.sessionId, m.boss, m.machine ?? ''].join('|')).join('\n')
1039const self = {
1040 cur: undefined as undefined | { id: string; sig: string; key: string; level: Level; why: string },
1041 busy: undefined as undefined | Promise<Who>,
1042}
1043// the one-time note this session's next prompt carries: the role-file pointer after a re-attach, or the hold notice
1044// (or the question about taking over the team top); several notes for one session ride together
1045let pendingNote: { id: string; text: string } | undefined
1046const addNote = (id: string, text: string) => {
1047 pendingNote = pendingNote && pendingNote.id === id ? (pendingNote.text.includes(text) ? pendingNote : { id, text: `${pendingNote.text}\n\n${text}` }) : { id, text }
1048}
1049
1050async function identity($: any, list0?: Member[]): Promise<Who> {
1051 const list = list0 ?? (await readMembers($))
1052 if (list.length === 0) return NOBODY
1053 const id = String(await $.session.id().catch(() => ''))
1054 const c = self.cur
1055 if (c && c.id === id && c.sig === sigOf(list)) {
1056 if (c.level === 'none') return NOBODY
1057 const me = list.find(m => keyOf(m) === c.key)
1058 if (me) return { me, level: c.level, why: c.why }
1059 }
1060 if (!self.busy) self.busy = identifyNow($, list, id).finally(() => void (self.busy = undefined))
1061 return self.busy
1062}
1063
1064async function identifyNow($: any, list: Member[], id: string): Promise<Who> {
1065 const none = () => undefined
1066 const tab = String((await $.env.get('ORCA_TERMINAL_HANDLE').catch(none)) ?? '').trim()
1067 const here = await machineOf($)
1068 const root = await rootOf($)
1069 const reg = id ? await registry($) : []
1070 const mine = reg.filter(r => r.sessionId === id)
1071 const local = mine.some(r => under(r.cwd, root))
1072 let name = mine.find(r => r.name !== '')?.name ?? ''
1073 if (name === '' && id !== '') {
1074 const own = (await transcripts($)).filter(t => t.id === id)
1075 if (own.length > 0) name = (await peek($, own))[0]?.title ?? ''
1076 }
1077 // of the members this session might be, the ones running elsewhere: another live session holds their id, or their
1078 // own tab is open (Orca is asked only about those members, and only when this tab does not settle it)
1079 const others = new Set(reg.filter(r => r.sessionId !== id).map(r => r.sessionId))
1080 const live = new Set<string>()
1081 for (const m of list) {
1082 // a member from another PC: its tab and its registry are that PC's, never asked about here
1083 if (isAway(m, here)) continue
1084 if (!((id !== '' && m.sessionId === id) || (name !== '' && namesOf(m).includes(name)))) continue
1085 if (m.sessionId && m.sessionId !== id && others.has(m.sessionId)) live.add(keyOf(m))
1086 else if (m.handle && m.handle !== tab && (await showTab($, m.handle))) live.add(keyOf(m))
1087 }
1088 const r = identify({ list, facts: { tab, sessionId: id, name }, local, live, here })
1089 const me = r.member
1090 if (r.changed && me) {
1091 if (r.renamedFrom) await moveFiles($, r.renamedFrom, me.name)
1092 await update($, members, () => r.list)
1093 await share($, { me, level: r.level, why: r.why })
1094 if (r.renamedFrom) await $.ui.toast(`Team Orchestrator: ${r.renamedFrom} is now ${me.name} (renamed).`)
1095 }
1096 if (r.reattached && me) addNote(id, roleNote(me))
1097 if (r.level === 'restricted' && me) await holdOnce($, me, r.why, { sessionId: id, tab, name, machine: here })
1098 self.cur = { id, sig: sigOf(r.list), key: me ? keyOf(me) : '', level: r.level, why: r.why }
1099 return { me, level: r.level, why: r.why }
1100}
1101
1102// A relabelled member's files follow its new name: the role file (the person's notes in it kept) and the status file.
1103// The old files are left as pointers to the new ones.
1104async function moveFiles($: any, from: string, to: string) {
1105 const dir = await teamDir($)
1106 const [ro, rn] = [`${dir}/${roleFile(from)}`, `${dir}/${roleFile(to)}`]
1107 if (ro !== rn && (await $.fs.exists(ro))) {
1108 if (!(await $.fs.exists(rn))) await putFile($, rn, String(await $.fs.read(ro)))
1109 await putFile($, ro, `# ${from} was renamed\n\n${from} is now ${to}. Its role file is .claude/team-orchestrator/${roleFile(to)}.\n`)
1110 roleSeen.delete(ro)
1111 }
1112 const s = await readStatus($, from)
1113 if (s && statusFile(from) !== statusFile(to)) {
1114 await putFile($, await statusPath($, to), JSON.stringify({ ...s, name: to }, null, 1))
1115 await putFile($, await statusPath($, from), JSON.stringify({ name: from, movedTo: statusFile(to) }, null, 1))
1116 }
1117}
1118
1119// Held sessions waiting for the user's decision, one per session id: <team folder>/claims.json.
1120const claimsFile = async ($: any) => `${await teamDir($)}/claims.json`
1121// undefined when claims.json exists but cannot be read or parsed, or a row is malformed: callers then refuse to write or
1122// to decide, so a corrupt file is never overwritten or read as "no claims". A missing file holds no claims.
1123async function readClaims($: any): Promise<Claim[] | undefined> {
1124 try {
1125 const p = await claimsFile($)
1126 if (!(await $.fs.exists(p))) return []
1127 const c = JSON.parse(String(await $.fs.read(p)))
1128 return Array.isArray(c) && c.every((x: any) => !!x && typeof x === 'object' && typeof x.team === 'string' && typeof x.member === 'string') ? c : undefined
1129 } catch {
1130 return undefined
1131 }
1132}
1133const writeClaims = async ($: any, c: Claim[]) => putFile($, await claimsFile($), JSON.stringify(c, null, 1))
1134// The members an undecided identity claim names, as team|name. undefined when claims.json cannot be read: the caller
1135// then skips auto-close and eviction for the round. A missing file holds nobody.
1136async function heldMembers($: any): Promise<Set<string> | undefined> {
1137 const claims = await readClaims($)
1138 return claims ? new Set(claims.filter(c => c.decision === undefined).map(c => `${c.team}|${c.member}`)) : undefined
1139}
1140// The names of the roster's own members that the held keys name: a claim for a member not on the roster holds no slot.
1141const heldNamesOf = (list: Member[], keys: Set<string>) => new Set(list.filter(m => keys.has(keyOf(m))).map(m => m.name))
1142
1143// Once per session id: record the claim, warn the member's head, and tell the team top to ask the user at once.
1144async function holdOnce($: any, x: Member, why: string, f: { sessionId: string; tab: string; name: string; machine: string }) {
1145 const claims = await readClaims($)
1146 if (!claims) {
1147 await $.ui.toast('Team Orchestrator: claims.json could not be read, so this hold was not recorded. Repair or remove that file.')
1148 return
1149 }
1150 if (claims.some(c => c.sessionId === f.sessionId)) return
1151 const c: Claim = { sessionId: f.sessionId, member: x.name, team: x.team, tab: f.tab, name: f.name, why, at: Date.now(), ...(f.machine ? { machine: f.machine } : {}) }
1152 await writeClaims($, [...claims, c])
1153 addNote(f.sessionId, holdNote(x, why))
1154 const list = await readMembers($)
1155 const head = x.boss === 'user' ? undefined : (list.find(m => m.team === x.team && m.name === x.boss) ?? list.find(m => m.name === x.boss))
1156 const top = topOf(list, x)
1157 const say = async (to: Member | undefined, text: string) => {
1158 if (!to?.sessionId) return false
1159 const r: any = await $.session.send({ to: { sessionId: to.sessionId }, text }).catch(() => undefined)
1160 return !!r?.isDelivered
1161 }
1162 const told: string[] = []
1163 const ask = topAsk(c, x.boss === 'user' ? x.name : x.boss)
1164 if (head && top && keyOf(head) === keyOf(top)) {
1165 if (await say(top, `${headWarning(c)}\n\n${ask}`)) told.push(top.name)
1166 } else {
1167 if (head && (await say(head, headWarning(c)))) told.push(head.name)
1168 if (top && (await say(top, ask))) told.push(top.name)
1169 }
1170 await $.ui.toast(
1171 `Team Orchestrator: this session is on hold; it looks like ${x.name} but is not confirmed. ` +
1172 (told.length > 0 ? `Told ${told.join(' and ')}.` : 'Nobody on the team could be told: tell the team top yourself.'),
1173 )
1174}
1175
1176// The team top applies the user's answer to a held session (member_claim).
1177async function settleClaim($: any, input: { sessionId?: string; decision?: string; member?: string }): Promise<string> {
1178 const claims = await readClaims($)
1179 if (!claims) return 'claims.json could not be read, so no decision was recorded. Repair or remove that file, then decide again.'
1180 const c = claims.find(x => x.sessionId === String(input.sessionId ?? '').trim())
1181 if (!c) return `No session ${String(input.sessionId ?? '')} is waiting for an identity decision.`
1182 const decision = String(input.decision ?? '')
1183 if (decision !== 'is' && decision !== 'new' && decision !== 'reject') return 'decision must be "is", "new" or "reject".'
1184 const list = await readMembers($)
1185 const wanted = String(input.member ?? '').trim() || c.member
1186 const x = list.find(m => m.team === c.team && (m.name === wanted || m.address === wanted)) ?? list.find(m => m.name === wanted || m.address === wanted)
1187 if (!x && decision !== 'reject') return `No member "${wanted}" on the roster.`
1188 const tell = (text: string) => $.session.send({ to: { sessionId: c.sessionId }, text }).catch(() => undefined)
1189 // whoever held the session's id or tab lets go of it
1190 const letGo = (m: Member) => ({ ...m, ...(m.sessionId === c.sessionId ? { sessionId: '' } : {}), ...(c.tab && m.handle === c.tab ? { handle: '' } : {}) })
1191 let out = `Rejected: session ${c.sessionId} stays on hold and off the team.`
1192 if (decision === 'reject' || !x) {
1193 await tell('TEAM ORCHESTRATOR: the user did not take this session onto the team. It stays on hold: no writes, no subagents, no team tools.')
1194 } else if (decision === 'is') {
1195 let next = list.map(m => (m === x ? { ...m, sessionId: c.sessionId, ...(c.tab ? { handle: c.tab } : {}), ...(c.machine ? { machine: c.machine } : {}) } : letGo(m)))
1196 let name = x.name
1197 if (c.name && !namesOf(x).includes(c.name) && !nameTaken(list, c.name, x)) {
1198 next = relabel(next, keyOf(x), c.name)
1199 await moveFiles($, x.name, c.name)
1200 name = c.namehooks/adding.ts 136 lines1// New members on a running team (0.5.17, #77). Pure rules from the roster alone (no $), so a test can call them.
2//
3// - New member: a member saved "not yet" (pending), with its role file, that starts fresh and briefed on its boss's
4// first team_message, exactly like a member Create leaves for later.
5// - Who may add: you always may (the panel, or your own session that is not on the roster). A head or a lead may only
6// REQUEST members, and only within its purview: its own team and every team whose chain of bosses leads up to it.
7// A request takes effect once you approve it, asked by the team top with AskUserQuestion.
8// - A launch under a team name already on the roster never replaces that team: it is refused, and offers "add" (every
9// launched member joins as a new member) or "merge" (the launched team merges into the one there, by name).
10
11import type { Member } from '../types'
12
13export const EFFORTS = ['default', 'low', 'medium', 'high', 'xhigh', 'max']
14
15const clean = (s: string) => s.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 40)
16const keyOf = (m: Member) => `${m.team}|${m.name}`
17
18/**
19 * What a New member is made from. boss '' is the team's head; model and effort 'default' or '' leave it to claude.
20 * by: the head or lead that asked for it (member_add); it may be the boss from the team above.
21 */
22/** replace (0.5.35): the name is taken by a member of the same team, which this new member replaces, starting fresh. */
23export type NewSpec = { team: string; name: string; role?: string; boss?: string; model?: string; effort?: string; by?: string; replace?: boolean }
24
25/** A member's boss as the roster names it: the one in its own team first, else the one of that name in any team. */
26export const bossOf = (list: Member[], m: Member): Member | undefined =>
27 m.boss === 'user' ? undefined : (list.find(x => x.team === m.team && x.name === m.boss) ?? list.find(x => x.name === m.boss))
28
29/** The team's head: its first member whose boss is not in the team. */
30export const headOf = (list: Member[], team: string): Member | undefined => {
31 const mine = list.filter(m => m.team === team)
32 return mine.find(m => !mine.some(x => x.name === m.boss))
33}
34
35/** Does `who` sit on m's chain of bosses (m itself not counted)? */
36function under(list: Member[], m: Member, who: Member): boolean {
37 const seen = new Set<string>()
38 for (let b = bossOf(list, m); b && !seen.has(keyOf(b)); b = bossOf(list, b)) {
39 if (keyOf(b) === keyOf(who)) return true
40 seen.add(keyOf(b))
41 }
42 return false
43}
44
45/** A head (reports to the user, or level 1) or a lead (has reports): the members who may ask for new members. */
46export const manages = (list: Member[], me: Member) => me.boss === 'user' || me.level === 1 || list.some(k => keyOf(k) !== keyOf(me) && bossOf(list, k) && keyOf(bossOf(list, k)!) === keyOf(me))
47
48/** The teams in a head's or lead's purview: its own, then every team whose head's chain of bosses leads up to it. */
49export function purview(list: Member[], me: Member): string[] {
50 const teams = [...new Set(list.map(m => m.team))]
51 return [me.team, ...teams.filter(t => t !== me.team && list.some(m => m.team === t && headOf(list, t) === m && under(list, m, me)))]
52}
53
54/** Why a head or lead may not ask for a member of `team` under `boss`: '' when it may. */
55export function requestProblem(list: Member[], me: Member, team: string, boss = ''): string {
56 if (!manages(list, me)) return `${me.name} is a worker: only a head or a lead may ask for new members. Ask your boss.`
57 const p = purview(list, me)
58 if (!p.includes(team)) return `Refused: team "${team}" is outside ${me.name}'s purview (${p.join(', ')}). A head or lead may ask for members only in its own team and the teams below it.`
59 const b = boss && boss !== me.name ? (list.find(m => m.team === team && m.name === boss) ?? list.find(m => m.name === boss)) : undefined
60 if (b && !p.includes(b.team)) return `Refused: the boss "${boss}" (team ${b.team}) is outside ${me.name}'s purview (${p.join(', ')}).`
61 return ''
62}
63
64/** Why a New member cannot be added as given: '' when it can. Names are unique across the project (SendMessage finds a session by name). */
65export function newProblem(list: Member[], s: NewSpec): string {
66 const team = String(s.team ?? '').trim()
67 if (!list.some(m => m.team === team)) return `No team "${team}" on the roster. New members join a team that is running; start a new team from New team (or team_launch).`
68 const name = clean(String(s.name ?? '').trim())
69 if (name === '') return 'Give the new member a name.'
70 const taken = list.find(m => m.name === name || m.address === name)
71 if (taken && !s.replace)
72 return `The name "${name}" is taken (team ${taken.team}). Pick another, or replace that member with a fresh one: ask the user, then call member_add again with replace: true.`
73 if (taken && taken.team !== team) return `"${name}" is in team ${taken.team}, not ${team}: only a member of the same team can be replaced.`
74 if (taken && (taken.boss === 'user' || taken.name === s.by)) return `"${name}" is the team top or the one who asks, and cannot be replaced.`
75 if (taken && list.some(m => m.boss === taken.name && m.team === taken.team)) return `Others report to "${name}": move them first, then replace it.`
76 const boss = String(s.boss ?? '').trim()
77 const asker = boss !== '' && boss === s.by && list.some(m => m.name === boss)
78 if (boss !== '' && !asker && !list.some(m => m.team === team && m.name === boss)) return `No member "${boss}" in team "${team}" to be the boss.`
79 const effort = String(s.effort ?? '').trim()
80 if (effort !== '' && !EFFORTS.includes(effort)) return `Effort "${effort}" is not one of ${EFFORTS.join(', ')}.`
81 return ''
82}
83
84/** The New member as the roster keeps it (no worktree or machine yet: the caller adds those). Check newProblem first. */
85export function newMember(list: Member[], s: NewSpec): Member {
86 const name = clean(String(s.name).trim())
87 const boss = String(s.boss ?? '').trim()
88 // the boss in the team, else the head or lead that asked (it may sit in the team above), else the team's head
89 const b = boss ? (list.find(m => m.team === s.team && m.name === boss) ?? (boss === s.by ? list.find(m => m.name === boss) : undefined)) : headOf(list, s.team)
90 const model = String(s.model ?? '').trim()
91 const effort = String(s.effort ?? '').trim()
92 return {
93 team: s.team, name, address: name, role: String(s.role ?? '').trim() || 'worker', level: b ? b.level + 1 : 1, boss: b ? b.name : 'user',
94 handle: '', sessionId: '', state: 'unstarted', ctx: -1, model: model === 'default' ? '' : model, effort: effort === 'default' ? '' : effort,
95 sel: false, note: '', briefed: false, noted: false, pending: true, location: 'local',
96 }
97}
98
99/** A launched member, as team_launch and the form give it (team cleaned). */
100export type LaunchSpec = { name: string; role: string; level: number; boss: string; team: string; model?: string; effort?: string; short?: string }
101
102/**
103 * A launch into teams already on the roster (mode add or merge). Nobody on the roster is changed or removed.
104 * - add: every launched member is new; a name taken anywhere gets a number (Worker-1 -> Worker-1-2).
105 * - merge: a launched member named like a member of that team is that member, kept as it is; the rest join.
106 * Either way a launched member that would report to the user, in a team already there, reports to that team's head
107 * instead (a team has one top). Returns the members to add (boss-first) and the names merged into members there.
108 */
109export function joinLaunch(list: Member[], specs: LaunchSpec[], mode: 'add' | 'merge'): { add: LaunchSpec[]; merged: string[] } {
110 const there = new Set(list.map(m => m.team))
111 const taken = new Set(list.flatMap(m => [m.name, m.address ?? m.name]))
112 const renamed = new Map<string, string>()
113 const levels = new Map<string, number>(list.map(m => [`${m.team}|${m.name}`, m.level]))
114 const add: LaunchSpec[] = []
115 const merged: string[] = []
116 for (const s of specs) {
117 const base = clean(s.name)
118 if (mode === 'merge' && there.has(s.team) && list.some(m => m.team === s.team && m.name === base)) {
119 renamed.set(s.name, base)
120 merged.push(base)
121 continue
122 }
123 let name = base
124 if (taken.has(name) && !there.has(s.team)) name = clean(`${s.team}-${base}`)
125 for (let i = 2; taken.has(name); i++) name = clean(`${base}-${i}`)
126 taken.add(name)
127 renamed.set(s.name, name)
128 const head = headOf(list, s.team)
129 const boss = s.boss === 'user' ? (there.has(s.team) && head ? head.name : 'user') : (renamed.get(s.boss) ?? clean(s.boss))
130 const level = boss === 'user' ? 1 : (levels.get(`${s.team}|${boss}`) ?? [...levels].find(([k]) => k.endsWith(`|${boss}`))?.[1] ?? s.level - 1) + 1
131 levels.set(`${s.team}|${name}`, level)
132 add.push({ ...s, name, boss, level })
133 }
134 return { add, merged }
135}
136hooks/guard.ts 229 lines1// What a roster member may do with the Agent tool (subagents) and with Write, Edit and NotebookEdit, from the roster
2// and the grants alone: no $, no state, so a test can call it.
3//
4// - Every roster member is refused the Agent tool, unless the person allowed it (see below).
5// - A member that is somebody's boss (a head, a CEO) is refused Write, Edit and NotebookEdit, except in its own
6// memory folder, unless the person allowed it.
7// - A session that is not on the roster is never judged.
8//
9// The person allows in two ways: a standing switch per member (Settings: "Allow subagents", "Allow writes", kept in
10// the roster file), or one turn at a time by typing #allow-subagent or #allow-write in the prompt. Only a prompt the
11// person typed at the terminal counts (origin kind "composer"); a message from another session, a tool result, a
12// pasted text or a plugin's own prompt never allows anything.
13
14import type { Member } from '../types'
15
16export const AGENT_TOOL = 'Agent'
17export const WRITE_TOOLS = ['Write', 'Edit', 'NotebookEdit'] as const
18export const KEYWORDS = { agent: '#allow-subagent', write: '#allow-write' } as const
19
20export type Grants = { agent: boolean; write: boolean }
21export const NO_GRANTS: Grants = { agent: false, write: false }
22
23const has = (text: string, word: string) => new RegExp(`(^|\\s)${word.replace(/[-]/g, '\\-')}(?=$|[\\s.,;:!?)])`, 'i').test(text)
24
25/**
26 * The grants one prompt carries, or undefined when the prompt is not the person's own typing (it then changes
27 * nothing). A later prompt of the person's replaces the grants, so a prompt without the keyword takes them back.
28 */
29export function grantsFrom(origin: { kind?: string } | undefined, text: string): Grants | undefined {
30 if (origin?.kind !== 'composer') return undefined
31 return { agent: has(text, KEYWORDS.agent), write: has(text, KEYWORDS.write) }
32}
33
34/** Somebody reports to this member. */
35export const isBoss = (m: Member, list: Member[]) => list.some(x => x !== m && x.boss === m.name)
36
37/**
38 * The path is inside <dir>/projects/<project>/memory/ for one of the Claude config folders given (the person's own
39 * memory folders). A path with ".." in it is never taken as inside.
40 */
41export function isMemoryPath(path: string, claudeDirs: string[]): boolean {
42 const p = path.replace(/\\/g, '/').toLowerCase()
43 if (p.split('/').includes('..')) return false
44 return claudeDirs.some(d => {
45 const root = `${d.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()}/projects/`
46 return d !== '' && p.startsWith(root) && /^[^/]+\/memory\/./.test(p.slice(root.length))
47 })
48}
49
50const SEND = 'Hand the work to your worker with SendMessage, or allow it yourself'
51const SEND_ZH = '把工作用 SendMessage 交給你的 worker,或自行授權'
52
53/**
54 * Claude Code's own helper agents that a slash command starts (/statusline, the Claude Code guide): they only change
55 * the person's settings or answer questions about Claude Code, so they pass the Agent guard (0.5.13, #76).
56 */
57export const HELPER_AGENTS = ['statusline-setup', 'claude-code-guide'] as const
58
59export type Verdict =
60 | { kind: 'deny'; reason: string; line: string }
61 | { kind: 'allow'; line: string }
62 | undefined
63
64/** The pathOf of a call: where a Write, Edit or NotebookEdit goes. */
65export const pathOf = (e: Record<string, unknown>): string => String(e.file_path ?? e.notebook_path ?? '')
66
67/**
68 * Judge one tool call of the session `me` (a roster member). undefined: nothing to say, let it through. subagentType is
69 * the Agent call's subagent_type.
70 */
71export function judge(args: { me: Member; list: Member[]; tool: string; path: string; grants: Grants; claudeDirs: string[]; subagentType?: string }): Verdict {
72 const { me, list, tool, path, grants, claudeDirs } = args
73 if (tool === AGENT_TOOL) {
74 const kind = String(args.subagentType ?? '').trim()
75 if ((HELPER_AGENTS as readonly string[]).includes(kind)) return { kind: 'allow', line: `allowed Agent: ${me.name} (${kind}, a built-in Claude Code helper)` }
76 if (me.allowAgent) return { kind: 'allow', line: `allowed Agent: ${me.name} (Allow subagents is on)` }
77 if (grants.agent) return { kind: 'allow', line: `allowed Agent: ${me.name} (${KEYWORDS.agent}, this turn only)` }
78 return {
79 kind: 'deny',
80 reason: `Blocked Agent: ${me.name} has no subagent permission. ${SEND} (Settings → Allow subagents, or type ${KEYWORDS.agent} in your next message). ${SEND_ZH}(設定 → Allow subagents,或在下一則訊息輸入 ${KEYWORDS.agent})。`,
81 line: `blocked Agent: ${me.name} has no subagent permission`,
82 }
83 }
84 if (!(WRITE_TOOLS as readonly string[]).includes(tool) || !isBoss(me, list)) return undefined
85 if (isMemoryPath(path, claudeDirs)) return undefined
86 if (me.allowWrite) return { kind: 'allow', line: `allowed ${tool}: ${me.name} (Allow writes is on)` }
87 if (grants.write) return { kind: 'allow', line: `allowed ${tool}: ${me.name} (${KEYWORDS.write}, this turn only)` }
88 return {
89 kind: 'deny',
90 reason: `Blocked ${tool}: ${me.name} has reports, so it does not write files itself (its own memory folder is open). ${SEND} (Settings → Allow writes, or type ${KEYWORDS.write} in your next message). ${SEND_ZH}(設定 → Allow writes,或在下一則訊息輸入 ${KEYWORDS.write})。`,
91 line: `blocked ${tool}: ${me.name} has reports and no write permission`,
92 }
93}
94
95// ── The team files (0.5.11, #58) ──────────────────────────────────────────────────────────────────────────────
96// roster.json and settings.json in .claude/team-orchestrator/ carry every member's rights (Allow writes, Allow
97// subagents) and the team's settings (auto-approve, the session cap). Only the mod's own code (it writes through
98// $.fs, not a tool), sessions that are not on the roster (the person's own) and the team top (boss "user") may change
99// them. Every other member is refused Write, Edit and NotebookEdit on them, and any Bash or PowerShell command that
100// names them and is not plainly read-only. From 0.5.12 (#59) the same holds for meta.json (the schema stamp) and the
101// change files in changes/, which the top folds into the roster: a forged change file would be a forged roster.
102// From 0.5.17 (#77) also the member requests in requests/, which the top puts to the user: a forged one would ask
103// under a false name. Only member_add writes them. roles/ and queue/ stay writable; status files live on each machine.
104
105export const SHELL_TOOLS = ['Bash', 'PowerShell'] as const
106
107// one path segment as Windows reads it: no alternate stream (":$DATA"), no trailing dots or spaces
108const plain = (s: string) => s.replace(/:.*$/, '').replace(/[. ]+$/, '')
109const TEAM_DIR = /^(team-orchestrator|team-o~\d+)$/
110const TEAM_FILE = /^(roster\.json|settings\.json|meta\.json|roster~\d+\.jso|settin~\d+\.jso|meta~\d+\.jso)$/
111const CHANGES_DIR = /^(changes|change~\d+|requests)$/
112
113/**
114 * The path is .claude/team-orchestrator/roster.json, settings.json or meta.json, or a file in its changes/ or requests/ folder (any
115 * root; "." and ".." folded; 8.3 names too).
116 */
117export function isTeamFilePath(path: string): boolean {
118 const segs: string[] = []
119 for (const s of path.replace(/\\/g, '/').toLowerCase().split('/')) {
120 if (s === '' || s === '.') continue
121 if (s === '..') segs.pop()
122 else segs.push(s)
123 }
124 const n = segs.length
125 if (n >= 3 && CHANGES_DIR.test(plain(segs[n - 2] as string)) && TEAM_DIR.test(plain(segs[n - 3] as string))) return true
126 return n >= 2 && TEAM_FILE.test(plain(segs[n - 1] as string)) && TEAM_DIR.test(plain(segs[n - 2] as string))
127}
128
129/**
130 * The command names a team file: roster.json anywhere; settings.json beside the team folder's name or bare (the shell
131 * may stand in the team folder); or the team folder in one word with a wildcard, a variable or a substitution (the
132 * target is then unknowable). Best effort: a name built at run time is not seen.
133 */
134export function namesTeamFile(command: string): boolean {
135 const c = command.replace(/\\/g, '/').toLowerCase()
136 const dir = /team-orchestrator|team-o~\d/.test(c)
137 if (/roster(\.json|~\d)/.test(c)) return true
138 if (/(team-orchestrator|team-o~\d)\/+(changes|change~\d|requests)\b/.test(c)) return true
139 if (dir && /meta(\.json|~\d)/.test(c)) return true
140 if (/settin(gs\.json|~\d)/.test(c) && (dir || /(^|[\s'"=(,;|&<>])settings\.json/.test(c))) return true
141 // a change into the team folder: the rest of the command runs there, so the whole command counts
142 if (/(^|[\s;|&(])(cd|chdir|pushd|sl|set-location)\s[^;|&\n]*(team-orchestrator|team-o~\d)/.test(c)) return true
143 return [...c.matchAll(/\S*(team-orchestrator|team-o~\d)\S*/g)].some(w => /[*?[\]{}$`]/.test(w[0]))
144}
145
146const READERS = /^(cat|type|get-content|gc|ls|dir|get-childitem|gci|grep|select-string|sls|jq)$/
147// a redirect that only drops output or merges stderr writes nothing
148const HARMLESS = /\d?>>?\s*(&\d|\/dev\/null|\$null|nul)(?=$|[\s;|&)])/gi
149
150/** Why the command is not plainly read-only, or '' when it is: only cat, type, Get-Content, ls, dir, grep, Select-String or jq (without -i). */
151export function notReadOnly(command: string): string {
152 if (/`|\$\(|\$\{|<\(|>\(/.test(command)) return 'it runs a substitution, so what it does is unclear'
153 // quoted text is an argument (a jq filter, a grep pattern), never a redirect or a second command
154 const c = command.replace(/'[^']*'|"[^"]*"/g, ' Q ').replace(HARMLESS, ' ')
155 if (/['"]/.test(c)) return 'its quoting is unbalanced, so what it does is unclear'
156 if (/>/.test(c)) return 'it redirects output into a file'
157 const parts = c.replace(/<\s*\S+/g, ' ').split(/&&|\|\||[;|&\n\r]/).map(p => p.trim()).filter(p => p !== '')
158 if (parts.length === 0) return 'it is empty'
159 for (const p of parts) {
160 const w = p.split(/\s+/)
161 const first = (w[0] ?? '').toLowerCase()
162 if (!READERS.test(first)) return `it runs "${first}", which is not a plain read (cat, type, Get-Content, ls, dir, grep, Select-String, jq)`
163 if (first === 'jq' && w.some(x => x === '--in-place' || /^-[a-z]*i[a-z]*$/i.test(x))) return 'it runs jq -i, which writes in place'
164 }
165 return ''
166}
167
168const LOCKED = '.claude/team-orchestrator/roster.json, settings.json, meta.json, changes/ and requests/'
169
170/**
171 * Judge one call against the team files. `confirmed` is false for a held session, which is locked whatever its boss.
172 * undefined: the call does not touch them, or this member may (the team top).
173 */
174export function judgeTeamFiles(args: { me: Member; confirmed: boolean; tool: string; path: string; command: string }): Verdict {
175 const { me, confirmed, tool, path, command } = args
176 if (confirmed && me.boss === 'user') return undefined
177 const who = `${me.name}${confirmed ? '' : ' (on hold)'}`
178 const tail = `Only the team top and the Team Orchestrator itself change ${LOCKED}; ask the team top, or the user (Settings in the Team Orchestrator panel).`
179 if ((WRITE_TOOLS as readonly string[]).includes(tool)) {
180 if (!isTeamFilePath(path)) return undefined
181 return { kind: 'deny', reason: `Blocked ${tool}: ${who} may not change the team file ${path}. ${tail}`, line: `blocked ${tool}: ${me.name} on a team file` }
182 }
183 if (!(SHELL_TOOLS as readonly string[]).includes(tool) || !namesTeamFile(command)) return undefined
184 const why = notReadOnly(command)
185 if (why === '') return undefined
186 return {
187 kind: 'deny',
188 reason: `Blocked ${tool}: this command names a team file (${LOCKED}) and is not plainly read-only: ${why}. ${who} may only read them (cat, type, Get-Content, ls, dir, grep, Select-String, jq without -i), one plain command at a time. ${tail}`,
189 line: `blocked ${tool}: ${me.name} on a team file`,
190 }
191}
192
193// ── Grants changed outside the mod (0.5.11, #58) ──
194// What the mod last wrote for each member's Allow writes and Allow subagents is recorded beside the roster; the team
195// top's refresh compares the file with it and reports a difference. Nothing is reverted.
196
197export type GrantMap = Record<string, { agent: boolean; write: boolean }>
198
199/** team|name → the two standing switches, from roster rows. */
200export const grantMap = (rows: Partial<Member>[]): GrantMap =>
201 Object.fromEntries(rows.filter(r => typeof r?.name === 'string').map(r => [`${r.team ?? ''}|${r.name}`, { agent: r.allowAgent === true, write: r.allowWrite === true }]))
202
203const same = (a?: { agent: boolean; write: boolean }, b?: { agent: boolean; write: boolean }) => !!a && !!b && a.agent === b.agent && a.write === b.write
204
205/**
206 * The record after the mod writes the roster. A member whose switches this write changed (or that is new) is recorded
207 * as written; one the write left as the file had it keeps its earlier record, so a change somebody else made to the
208 * file, pulled in and written back unchanged, is not taken as the mod's.
209 */
210export function recordAfterWrite(prev: GrantMap | undefined, before: GrantMap, written: GrantMap): GrantMap {
211 const out: GrantMap = {}
212 for (const [k, v] of Object.entries(written)) out[k] = same(before[k], v) && prev?.[k] ? (prev[k] as GrantMap[string]) : v
213 return out
214}
215
216/** The members whose switches in the file differ from what the mod last wrote, with the rights in words. */
217export function grantChanges(recorded: GrantMap, file: GrantMap): { key: string; name: string; changes: string[] }[] {
218 const out: { key: string; name: string; changes: string[] }[] = []
219 for (const [k, v] of Object.entries(file)) {
220 const r = recorded[k]
221 if (!r || same(r, v)) continue
222 const changes: string[] = []
223 if (r.write !== v.write) changes.push(`Allow writes ${v.write ? 'on' : 'off'}`)
224 if (r.agent !== v.agent) changes.push(`Allow subagents ${v.agent ? 'on' : 'off'}`)
225 out.push({ key: k, name: k.slice(k.indexOf('|') + 1), changes })
226 }
227 return out
228}
229hooks/housekeeping.ts 36 lines1import type { Member } from '../types'
2
3/** A status report from the member, never proof of OS/process/file cleanup. */
4export type CleanupReport = {
5 status: 'reported-clean' | 'reported-incomplete' | 'unverified'
6 verified: false
7}
8
9const names = (m: Member) => [m.address, m.name].filter((x): x is string => !!x).map(x => x.toLowerCase())
10const bareTo = (to: string) => to.replace(/\s*\[[^\]]*\]\s*$/, '').trim().toLowerCase()
11export function reportsTo(me: Member, list: Member[], to: string): boolean {
12 const boss = list.find(m => m.name === me.boss && m.team === me.team) ?? list.find(m => m.name === me.boss)
13 return me.boss !== 'user' && !!boss && names(boss).includes(bareTo(to))
14}
15
16/** Message body from a peer envelope, or the original text for a normal SendMessage. */
17export const bodyOf = (text: string) => (text.match(/<cross-session-message[^>]*>([\s\S]*?)<\/cross-session-message>/)?.[1] ?? text).trim()
18export const senderOf = (text: string) => text.match(/from-name="([^"]+)"/)?.[1]
19
20/** Parse only an explicit Cleanup: field. General words such as "done" or "clean" are never enough. */
21export function parseCleanupReport(text: string): CleanupReport | undefined {
22 const body = bodyOf(text)
23 const match = /(?:^|[\n.]\s*)(?:cleanup status|cleanup|housekeeping)\s*[:=]\s*(clean|incomplete|failed|unverified)\b/i.exec(body)
24 if (!match) return undefined
25 const answer = match[1]!.toLowerCase()
26 if (answer === 'unverified') return { status: 'unverified', verified: false }
27 if (answer !== 'clean') return { status: 'reported-incomplete', verified: false }
28 const rest = body.slice(match.index + match[0].length)
29 if (/\b(?:not clean|incomplete|failed|unverified|still running|still exists|remain(?:s|ing)?|left|kept|retained|pending)\b|\b[1-9]\d*\s+(?:owned\s+)?(?:leftover\s+)?(?:files?|processes?|resources?)\b/i.test(rest))
30 return { status: 'reported-incomplete', verified: false }
31 return { status: 'reported-clean', verified: false }
32}
33
34/** Only the team top or a session that is not a member polls Orca. */
35export const shouldPoll = (me: { boss?: string } | undefined) => !me || me.boss === 'user'
36hooks/identity.ts 224 lines1// Who this session is, on the roster: the identity ladder of #57. Pure rules from the roster and this session's facts
2// (no $), so a test can call them.
3//
4// Three facts are checked against each member: the tab (this session's ORCA_TERMINAL_HANDLE against the member's
5// handle), the session id and the name (the registry's name, else the transcript title).
6//
7// | facts that match | treated as | roster update |
8// | tab + id + name | X, full | none |
9// | tab + id (new name) | X, full | follow and relabel (name, address, bosses) |
10// | tab + name (new id) | X, full | sessionId = the new id |
11// | id + name, other tab | X if X's tab is gone, else held | handle = this tab |
12// | tab only | X, full, re-attached | id and name taken; the role-file note is sent |
13// | id only, or name only | held (restricted) | none |
14// | nothing | not on the team | none |
15//
16// No tab handle at all (a session outside Orca) is "unknown", not a mismatch. The machine's session registry
17// (~/.claude/sessions/<pid>.json) vouches for it in place of the tab when it lists this session's id in a folder under
18// the project root: it is then on this machine. That proof stands in for the tab only next to an id or a name, never
19// alone, and never while the member it points at is live somewhere else (that would be a second copy).
20//
21// A member whose home is another PC (0.5.12, #64) is never matched by tab or registry here: handles and the registry
22// are valid only on their own machine. An id and a name alone then hold the session for the user to decide, like any other doubt.
23// A session confirmed as a member with no machine recorded takes this one.
24
25import type { Member } from '../types'
26import { AGENT_TOOL, KEYWORDS, WRITE_TOOLS } from './guard'
27import type { Grants, Verdict } from './guard'
28import { roleFile } from './status'
29import { isAway } from './changes'
30
31export type Level = 'full' | 'restricted' | 'none'
32export type Row = 'tab+id+name' | 'tab+id' | 'tab+name' | 'id+name' | 'tab' | 'id' | 'name' | 'none'
33
34/** This session's own facts. */
35export type Facts = {
36 /** its Orca tab handle (term_…); '' outside Orca, which is unknown, not a mismatch */
37 tab: string
38 sessionId: string
39 /** the session's name from the registry, else its transcript title; '' when it has none */
40 name: string
41}
42
43export type Identity = {
44 level: Level
45 /** the member this session is (full) or looks like (restricted), as it stands after the updates */
46 member?: Member
47 row: Row
48 /** the roster after the updates (the same array when nothing changed) */
49 list: Member[]
50 changed: boolean
51 /** set when the member was relabelled to the session's new name: its old name */
52 renamedFrom?: string
53 /** a fresh session in the member's tab, taken on as the member: it gets the role-file note once */
54 reattached: boolean
55 /** why a restricted session is held, in a sentence; '' otherwise */
56 why: string
57}
58
59export const keyOf = (m: Member) => `${m.team}|${m.name}`
60const namesOf = (m: Member) => [m.address, m.name].filter((x): x is string => !!x)
61
62// the rows in the order the ladder tries them; the first four and "tab" are full, the rest held
63const RANK: Row[] = ['tab+id+name', 'tab+id', 'tab+name', 'id+name', 'tab', 'id', 'name']
64
65/** A name some other member of the project already goes by. */
66export const nameTaken = (list: Member[], name: string, except?: Member) =>
67 list.some(m => m !== except && namesOf(m).some(n => n.toLowerCase() === name.toLowerCase()))
68
69/**
70 * The member (by team|name) renamed to `to`: its name and address take the new name, and the members that report to
71 * it follow. A boss is matched in the member's own team first, so another team's member of the same name is untouched.
72 */
73export function relabel(list: Member[], key: string, to: string): Member[] {
74 const x = list.find(m => keyOf(m) === key)
75 if (!x || to === '' || to === x.name) return list
76 const reportsTo = (m: Member) => m.boss === x.name && (m.team === x.team || !list.some(o => o !== x && o.team === m.team && o.name === x.name))
77 return list.map(m => (m === x ? { ...m, name: to, address: to } : reportsTo(m) ? { ...m, boss: to } : m))
78}
79
80/**
81 * Who this session is.
82 * - list: the roster
83 * - facts: this session's tab (or ''), id and name
84 * - local: the session registry lists this session's id in a folder under the project root (same machine)
85 * - live: the members (team|name) that are running somewhere else right now: a live tab, or another live session
86 * with their id
87 */
88export function identify(args: { list: Member[]; facts: Facts; local: boolean; live: ReadonlySet<string>; here?: string }): Identity {
89 const { list, facts, local, live } = args
90 const here = args.here ?? ''
91 const away = (m: Member) => isAway(m, here)
92 const none: Identity = { level: 'none', row: 'none', list, changed: false, reattached: false, why: '' }
93 if (list.length === 0) return none
94 const tabKnown = facts.tab !== ''
95 const rowOf = (m: Member): Row => {
96 const id = facts.sessionId !== '' && m.sessionId === facts.sessionId
97 const name = facts.name !== '' && namesOf(m).includes(facts.name)
98 // the tab: a real match or mismatch where both sides have one; else the registry's proof, which stands in for
99 // the tab only beside an id or a name, and only while the member is not live elsewhere
100 const both = tabKnown && m.handle !== ''
101 const tab = away(m) ? false : both ? m.handle === facts.tab : local && !live.has(keyOf(m)) && (id || name)
102 if (tab && id && name) return 'tab+id+name'
103 if (tab && id) return 'tab+id'
104 if (tab && name) return 'tab+name'
105 if (id && name) return 'id+name'
106 if (tab) return 'tab'
107 if (id) return 'id'
108 if (name) return 'name'
109 return 'none'
110 }
111 const rows = list.map(m => ({ m, row: rowOf(m) })).filter(r => r.row !== 'none')
112 if (rows.length === 0) return none
113 const best = Math.min(...rows.map(r => RANK.indexOf(r.row)))
114 const row = RANK[best] as Row
115 const top = rows.filter(r => r.row === row)
116 const x = (top[0] as { m: Member }).m
117 const held = (why: string): Identity => ({ level: 'restricted', member: x, row, list, changed: false, reattached: false, why })
118 // two members fit equally well (two of the same name, say): which one is unknown, so neither is granted
119 if (top.length > 1) return held(`it fits ${top.map(r => r.m.name).join(' and ')} equally well`)
120 const elsewhere = (why: string) => (tabKnown ? why : `${why}, and this session has no Orca tab`)
121 if (row === 'id+name') {
122 if (away(x)) return held(`its home is ${x.machine}, so this may be a second copy of the session running there`)
123 if (!tabKnown && !local) return held('it is not in this machine\'s session registry, so it may be running on another device')
124 if (live.has(keyOf(x))) return held(`${x.name}'s own tab is still open, so this looks like a second copy`)
125 }
126 if (row === 'id') return held(elsewhere(`only its session id matches ${x.name}; its tab and its name do not`))
127 if (row === 'name') return held(elsewhere(`only its name matches ${x.name}; its tab and its session id do not`))
128 // full from here: the roster follows the session
129 let next = list
130 const set = (patch: Partial<Member>) => {
131 next = next.map(m => (keyOf(m) === keyOf(x) ? { ...m, ...patch } : m))
132 }
133 if (row === 'tab+name' || row === 'tab') set({ sessionId: facts.sessionId })
134 // its home is this machine, recorded when the roster has none for it (a member from another PC never gets this far)
135 if (here !== '' && !x.machine) set({ machine: here })
136 if (row === 'id+name' && tabKnown) {
137 set({ handle: facts.tab })
138 // a member still recorded on this tab is not in it any more: a close of that member must not close this one
139 next = next.map(m => (keyOf(m) !== keyOf(x) && m.handle === facts.tab ? { ...m, handle: '' } : m))
140 }
141 // a new name (a /rename, or a fresh session's own name) is followed unless another member already goes by it
142 let renamedFrom: string | undefined
143 const wantsName = (row === 'tab+id' || row === 'tab') && facts.name !== '' && !namesOf(x).includes(facts.name)
144 if (wantsName && !nameTaken(list, facts.name, x)) {
145 next = relabel(next, keyOf(x), facts.name)
146 renamedFrom = x.name
147 }
148 const key = renamedFrom === undefined ? keyOf(x) : `${x.team}|${facts.name}`
149 const member = next.find(m => keyOf(m) === key) as Member
150 return { level: 'full', member, row, list: next, changed: next !== list, renamedFrom, reattached: row === 'tab', why: '' }
151}
152
153/** The one-time note a re-attached session gets on its next prompt. */
154export const roleNote = (m: Member) =>
155 `You are ${m.name} in team ${m.team}. Your role file is .claude/team-orchestrator/${roleFile(m.name)}; read it now.`
156
157/** The one-time note a held session gets on its next prompt. */
158export const holdNote = (m: Member, why: string) =>
159 `TEAM ORCHESTRATOR: this session is ON HOLD. It looks like ${m.name} of team ${m.team}, but that is not confirmed (${why}). ` +
160 'Until the user decides, it may not write files, use subagents or use any team tool. The team top has been asked to check with the user. ' +
161 `Do not act as ${m.name} meanwhile.`
162
163const tag = (m: Member, why: string) => `${m.name} of team ${m.team} (${why})`
164
165/** The sentence a team tool answers a held session with. */
166export const holdTool = (tool: string, m: Member, why: string) =>
167 `${tool} is on hold: this session looks like ${tag(m, why)} but is not confirmed. Team tools stay off until the user decides whether it is ${m.name}; the team top has been asked.`
168
169/** The strictest guard, for a held session: Agent, Write, Edit and NotebookEdit only with the person's one-turn word. */
170export function judgeHeld(args: { me: Member; why: string; tool: string; grants: Grants }): Verdict {
171 const { me, why, tool, grants } = args
172 const isAgent = tool === AGENT_TOOL
173 if (!isAgent && !(WRITE_TOOLS as readonly string[]).includes(tool)) return undefined
174 const word = isAgent ? KEYWORDS.agent : KEYWORDS.write
175 if (isAgent ? grants.agent : grants.write) return { kind: 'allow', line: `allowed ${tool} on hold (${word}, this turn only)` }
176 return {
177 kind: 'deny',
178 reason:
179 `Blocked ${tool}: this session is on hold. It looks like ${tag(me, why)} but is not confirmed, so it may not ` +
180 `${isAgent ? 'use subagents' : 'write files'} until the user decides (${word} in the user's next message allows one turn).`,
181 line: `blocked ${tool}: session on hold (looks like ${me.name})`,
182 }
183}
184
185/** The team top above a member: up the boss line to the one that reports to the user. */
186export function topOf(list: Member[], x: Member): Member | undefined {
187 let cur: Member | undefined = x
188 const seen = new Set<string>()
189 while (cur && cur.boss !== 'user' && !seen.has(keyOf(cur))) {
190 seen.add(keyOf(cur))
191 const c: Member = cur
192 cur = list.find(m => m.team === c.team && m.name === c.boss) ?? list.find(m => m.name === c.boss)
193 }
194 return cur && cur.boss === 'user' ? cur : undefined
195}
196
197/** A pending identity question: a held session and the member it looks like. */
198export type Claim = { sessionId: string; member: string; team: string; tab: string; name: string; why: string; at: number; machine?: string; decision?: 'is' | 'new' | 'reject' }
199
200/** The warning X's head gets once. */
201export const headWarning = (c: Claim) =>
202 `IDENTITY WARNING (Team Orchestrator): a session (id ${c.sessionId}, name "${c.name || 'none'}", tab ${c.tab || 'none'}) looks like your report ${c.member} ` +
203 `of team ${c.team}, but it is not confirmed (${c.why}). It is on hold: no writes, no subagents, no team tools. Do not give it work until the user decides.`
204
205/** What the team top is told: ask the user at once, then apply the answer with member_claim. */
206export const topAsk = (c: Claim, boss: string) =>
207 `IDENTITY CHECK (Team Orchestrator), act now: a session (id ${c.sessionId}, name "${c.name || 'none'}", tab ${c.tab || 'none'}) looks like ${c.member} ` +
208 `of team ${c.team}, but it is not confirmed (${c.why}). It is on hold. Ask the user AT ONCE with AskUserQuestion, with these three options: ` +
209 `(1) "This is ${c.member}": the roster takes its id, tab and name. ` +
210 `(2) "New member under ${boss}": it joins as a worker with its own role file. ` +
211 '(3) "Reject": it stays on hold, off the team. ' +
212 `Then apply the answer with member_claim { sessionId: "${c.sessionId}", decision: "is" | "new" | "reject", member: "${c.member}" }.`
213
214/** A name for a new member that nobody on the roster goes by: the wanted one, else the base with a number. */
215export function freshName(list: Member[], wanted: string, base: string): string {
216 const clean = (s: string) => s.replace(/[^A-Za-z0-9_ -]/g, '-').trim().slice(0, 40)
217 const w = clean(wanted)
218 if (w !== '' && !nameTaken(list, w)) return w
219 for (let i = 2; ; i++) {
220 const n = `${clean(base)}-${i}`
221 if (!nameTaken(list, n)) return n
222 }
223}
224hooks/status.ts 251 lines1// Event-driven member status. Each session writes only its own small status file (status/<name>.json inside
2// .claude/team-orchestrator/), on turn start and end, when it asks the person something, and on a 60 s heartbeat while
3// it works. Nobody reads other members' terminal screens, so Orca is not asked about every member on every refresh.
4//
5// The team top also decides, from these files alone, which idle workers to close and whether a message to a closed
6// worker can reopen it now or must wait (the session cap). Pure rules from data (no $), so a test can call them.
7
8import type { Member } from '../types'
9import type { CleanupReport } from './housekeeping'
10import { isAway } from './changes'
11
12export type Status = {
13 name: string
14 sessionId: string
15 /** working | idle | asking | offline | closed */
16 state: string
17 turnStart?: number
18 turnEnd?: number
19 heartbeat: number
20 model?: string
21 effort?: string
22 /** context used, percent */
23 ctx?: number
24 /** the session's live context window in tokens, from $.session.usage().context.window (0.5.13, #63) */
25 window?: number
26 /** what the member is on now: the Session Panel step, else the first line of the last order from its boss */
27 task?: string
28 /** Legacy worker-reported "clean" timestamp. It is not OS-verified and never authorizes automatic closure. */
29 lastClean?: number
30 /** Legacy process count from old turn-end census; it does not prove owned resources were removed. */
31 leftover?: number
32 /** When the legacy process count was sampled, not a cleanup-verification time. */
33 countedAt?: number
34 /** Latest explicit cleanup field reported to the boss; always self-reported, never proof. */
35 cleanupReport?: CleanupReport & { at: number; taskLabel?: string; deliveryId?: string; reportedLeftover?: number }
36}
37
38/** Team-wide settings for worker auto-close, kept in .claude/team-orchestrator/settings.json. */
39export type TeamSettings = {
40 autoClose: boolean
41 /** minutes idle after "clean" before a worker is closed */
42 idleMinutes: number
43 /** members never closed, besides anyone with reports */
44 exempt: string[]
45 /** reopen with claude --resume (keeps context) or fresh (briefed again) */
46 reopen: 'resume' | 'fresh'
47 /** most sessions open at once; 0 = no cap */
48 maxOpen: number
49 /** at Create: start only the top and the team heads under it (the rest on their first message), or everyone */
50 launch: 'demand' | 'all'
51 /** sessions started at once at Create; the next batch waits until these are ready and briefed */
52 batch: number
53 /** Legacy switch retained for saved settings; cleanup auto-approval is paused in the interim safety mode. */
54 autoScratch: boolean
55 /** show each member's open assumptions from Session Panel (#89); reads its files only when Session Panel is on here */
56 assumptions: boolean
57 /** Legacy project scratch path retained for settings compatibility; never auto-approved in interim mode. */
58 scratchDir: string
59}
60
61export const TEAM_SETTINGS0: TeamSettings = { autoClose: true, idleMinutes: 10, exempt: [], reopen: 'resume', maxOpen: 8, launch: 'demand', batch: 3, autoScratch: true, assumptions: false, scratchDir: '.claude/scratch' }
62
63export const MIN = 60_000
64/** a member with no write for this long shows as offline */
65export const STALE_MS = 5 * MIN
66/** the tab check runs only when some heartbeat is older than this */
67export const CHECK_AFTER_MS = 2 * MIN
68
69/** A file-safe name for a member's status file. */
70export const statusFile = (name: string) => `status/${name.replace(/[^\p{L}\p{N}._-]+/gu, '_')}.json`
71
72/** A member's role file, beside its status file: roles/<name>.md (read by the member through its start-up pointer). */
73export const roleFile = (name: string) => `roles/${name.replace(/[^\p{L}\p{N}._-]+/gu, '_')}.md`
74
75// ── Sleep-aware clocks (0.5.16, #71) ──
76// A session's 30 s round notes the time of each tick. A gap more than three minutes beyond the interval is time the
77// machine slept (or the session hung): it is kept as a sleep window for a day, and every age below (silent, idle) skips
78// the time spent asleep. Waking up closes nothing, and a hung top only delays auto-close, never brings it forward.
79
80/** a time the machine slept, from..to (ms) */
81export type Sleep = { from: number; to: number }
82/** a tick this much later than expected counts as sleep */
83export const SLEEP_SLACK_MS = 3 * MIN
84/** sleep windows are kept this long */
85export const SLEEP_KEEP_MS = 24 * 60 * MIN
86/** a member silent for longer than this is checked (is its process alive?) before a message is sent to it */
87export const CRASH_CHECK_MS = 90_000
88
89/** The sleep windows after a tick at now, the previous one at prev (0: none yet), the ticks every ms apart. */
90export function noteTick(prev: number, now: number, every: number, sleeps: readonly Sleep[]): Sleep[] {
91 const kept = sleeps.filter(w => now - w.to <= SLEEP_KEEP_MS)
92 return prev > 0 && now - prev > every + SLEEP_SLACK_MS ? [...kept, { from: prev + every, to: now }] : kept
93}
94
95/** How much of from..to was spent asleep. */
96export const asleepWithin = (sleeps: readonly Sleep[], from: number, to: number) =>
97 sleeps.reduce((n, w) => n + Math.max(0, Math.min(to, w.to) - Math.max(from, w.from)), 0)
98
99/** The age of a time stamp, the time spent asleep since then left out. */
100export const awakeAge = (since: number, now: number, sleeps: readonly Sleep[] = []) => Math.max(0, now - since - asleepWithin(sleeps, since, now))
101
102/** The state to show: a silent member is offline; a closed one stays closed. Time asleep is not silence. */
103export const shownState = (s: Status | undefined, now: number, sleeps: readonly Sleep[] = []) =>
104 !s ? undefined : s.state === 'closed' ? 'closed' : awakeAge(s.heartbeat, now, sleeps) > STALE_MS ? 'offline' : s.state
105
106/** The member has been silent long enough that a message to it first checks whether its session is alive (#71). */
107export const heartbeatStale = (s: Status, now: number, sleeps: readonly Sleep[] = []) => s.state !== 'closed' && awakeAge(s.heartbeat, now, sleeps) > CRASH_CHECK_MS
108
109/** Whether the tab check is worth an Orca call: some open member has been silent for over two minutes. */
110export const needsTabCheck = (statuses: (Status | undefined)[], now: number, sleeps: readonly Sleep[] = []) =>
111 statuses.some(s => s && s.state !== 'closed' && awakeAge(s.heartbeat, now, sleeps) > CHECK_AFTER_MS)
112
113/** The next tab-check interval: doubled while Orca answers slowly (over 500 ms), back to the base when it is fast. */
114export const nextCheckInterval = (current: number, tookMs: number, base = 2 * MIN, cap = 10 * MIN) =>
115 tookMs > 500 ? Math.min(cap, Math.max(base, current) * 2) : base
116
117/** Automatic closure is paused until native cleanup ownership can be verified. */
118export function toClose(_list: Member[], _statuses: Map<string, Status>, t: TeamSettings, _now: number, _sleeps: readonly Sleep[] = [], _held: ReadonlySet<string> = new Set()): Member[] {
119 // No native verifier is implemented in this phase. Legacy lastClean/leftover status fields are not evidence.
120 if (!t.autoClose) return []
121 return []
122}
123
124/** Count known and uncertain sessions as occupying capacity; only two closed views free a slot. */
125export const openCount = (statuses: Map<string, Status>, _now: number, _sleeps: readonly Sleep[] = [], held: ReadonlySet<string> = new Set(), members: Member[] = []) => {
126 const open = new Set<string>()
127 for (const [name, s] of statuses) if (s.state !== 'closed') open.add(name) // offline/unknown is not proof of closure
128 for (const name of held) if (statuses.get(name)?.state !== 'closed') open.add(name)
129 for (const m of members) {
130 const s = statuses.get(m.name)
131 if (!s && !m.pending && m.state !== 'closed' && m.state !== 'unstarted' && (!!m.handle || !!m.sessionId)) open.add(m.name) // roster identifies an open session; missing status is unknown
132 else if (s && m.state !== 'closed' && m.state !== 'unstarted') open.add(m.name)
133 }
134 return open.size
135}
136
137export type Admit = { kind: 'open' } | { kind: 'queue' }
138
139/** Never evict by worker cleanup claims; at the cap, wait for an explicit user-directed close. */
140export function admit(list: Member[], statuses: Map<string, Status>, t: TeamSettings, now: number, sleeps: readonly Sleep[] = [], held: ReadonlySet<string> = new Set()): Admit {
141 if (t.maxOpen <= 0 || openCount(statuses, now, sleeps, held, list) < t.maxOpen) return { kind: 'open' }
142 return { kind: 'queue' }
143}
144
145/** One short line for the task field. */
146export const taskLine = (text: string) => text.trim().split(/\r?\n/)[0]!.slice(0, 120)
147
148/**
149 * Who starts at Create when the rest start on demand: the top (boss "user") and, under a CEO, each team's head (a
150 * report of the top in another team). Leads and workers start the first time someone messages them.
151 */
152export const startsAtCreate = (m: Member, list: Member[]) =>
153 m.boss === 'user' || list.some(t => t.boss === 'user' && t.name === m.boss && t.team !== m.team)
154
155/** xs in groups of n (n below 1 counts as 1). */
156export const chunk = <T>(xs: T[], n: number): T[][] => {
157 const size = Math.max(1, Math.floor(n) || 1)
158 const out: T[][] = []
159 for (let i = 0; i < xs.length; i += size) out.push(xs.slice(i, i + size))
160 return out
161}
162
163/**
164 * The "name [ref]" of the session on this machine named name, from a ListAgents listing, or '' when there is none.
165 * Remote Control mirrors of old sessions often share a member's name, and then the bare name is ambiguous.
166 */
167export const localRef = (listing: string, name: string) => {
168 for (const line of listing.split(/\r?\n/)) {
169 const m = line.match(/^\s*(.+?) \[([0-9a-f]+)\]\s+·\s+interactive\b/)
170 if (m && m[1] === name) return `${name} [${m[2]}]`
171 }
172 return ''
173}
174
175/**
176 * A model name as claude --model accepts it (0.5.13, #63). The roster may keep the old short name shown on screen
177 * ("haiku-5-5", or "Haiku 5.5" from a status line), which the API rejects: only that form (opus, sonnet, haiku or fable
178 * followed by digits) gets the "claude-" prefix back. The aliases stay. Any other name (a full id with or without [1m],
179 * a gateway's model) goes through as typed, so a wrong one fails visibly at start. "default", "keep" and "" give no
180 * --model, and so does a name a shell would read as more than one word.
181 * On a custom config (`env`: the ANTHROPIC_DEFAULT_*_MODEL values set), a family's alias and short names start with that
182 * family's value, and a name equal to a set value goes through as typed, never given the "claude-" prefix.
183 */
184export type EnvModels = Partial<Record<'opus' | 'sonnet' | 'haiku' | 'fable', string>>
185export function modelArg(model: string, env: EnvModels = {}): string {
186 const raw = model.trim()
187 const s = raw.toLowerCase().replace(/\s+/g, '-').replace(/(\d)\.(\d)/g, '$1-$2')
188 if (s === '' || s === 'default' || s === 'keep') return ''
189 const safe = (x: string) => /^[A-Za-z0-9._:/@+-]+(\[1m\])?$/i.test(x)
190 if (Object.values(env).some(v => v?.toLowerCase() === raw.toLowerCase()) && safe(raw)) return raw
191 const fam = /^(opus|sonnet|haiku|fable)(-\d[\w.-]*)?(\[1m\])?$/.exec(s)
192 const set = fam ? env[fam[1] as keyof EnvModels]?.trim() : undefined
193 if (fam && set && safe(set)) return fam[3] && !/\[1m\]$/i.test(set) ? `${set}[1m]` : set
194 if (/^(opus|sonnet|haiku|fable)-\d[\w.-]*(\[1m\])?$/.test(s)) return `claude-${s}`
195 if (/^(opus|sonnet|haiku|fable|best|opusplan)(\[1m\])?$/.test(s)) return s
196 return safe(raw) ? raw : ''
197}
198
199/** A model id as the roster shows it: the "claude-" prefix cut, the rest as typed. */
200export const shownModel = (model: string) => model.replace(/^claude-/i, '')
201
202/**
203 * The context window to count a transcript's tokens against when the member has not reported its own (#63): the
204 * window its status file records, else 1M for an id with [1m] or a session already past 200k, else 200k.
205 */
206export const windowFor = (model: string, used: number, reported?: number) =>
207 reported && reported > 0 ? reported : /\[1m\]$/i.test(model) || used > 200000 ? 1000000 : 200000
208
209// ── Where a member runs, and which CLI (0.5.13, #67 and #69) ──
210
211/** The CLIs a tab can run; anything else is "other". */
212export const CLIS = ['claude', 'codex', 'hermes', 'gemini', 'opencode', 'qwen'] as const
213
214/**
215 * The CLI an Orca tab runs: Orca's own agentIdentity when it gives one, else the one CLI its command line or screen
216 * names. '' when unknown (several CLIs named, or none): the member is then treated as Claude, as before.
217 */
218export function cliOf(tab: { agentIdentity?: unknown; command?: unknown; preview?: unknown } | undefined): string {
219 if (!tab) return ''
220 const id = typeof tab.agentIdentity === 'string' ? tab.agentIdentity.trim().toLowerCase() : ''
221 if (id !== '') return CLIS.find(c => id.includes(c)) ?? 'other'
222 const text = [tab.command, tab.preview].filter((x): x is string => typeof x === 'string').join('\n').toLowerCase()
223 const named = new Set([...text.matchAll(/(?:^|[\s>"'\\/])(claude|codex|hermes|gemini|opencode|qwen)(?:\.exe|\.cmd|\.ps1)?(?=["'\s]|$)/gm)].map(x => x[1] as string))
224 return named.size === 1 ? ([...named][0] as string) : ''
225}
226
227/** A member the mod runs: a Claude Code session. One adopted from another CLI is "not managed" (#69). */
228export const isManaged = (m: Pick<Member, 'cli'>) => !m.cli || m.cli === 'claude'
229
230export type Location = 'local' | 'remote' | 'other-cli'
231
232/**
233 * How a message reaches a member from this machine (#67): local (send by session id), remote (another PC, or recorded
234 * remote: the messenger route of #72) or other-cli (not messaged).
235 */
236export const locationOf = (m: Member, here: string): Location =>
237 !isManaged(m) ? 'other-cli' : isAway(m, here) || m.location === 'remote' ? 'remote' : 'local'
238
239// ── Orca workspaces (0.5.13, #68) ──
240
241/** The folder in an Orca worktree id ("<repo>::<folder>"), '' when the id carries none. */
242export const pathInWorktreeId = (id: string) => {
243 const cut = id.indexOf('::')
244 return cut < 0 ? '' : id.slice(cut + 2).trim()
245}
246
247const slashed = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
248
249/** The workspace folder contains the project root (or is it). */
250export const worktreeHolds = (folder: string, root: string) => folder.trim() !== '' && `${slashed(root)}/`.startsWith(`${slashed(folder)}/`)
251hooks/platform.ts 85 lines1// Windows, macOS and Linux (0.5.06; interim cleanup limit).
2// No cleanup delete is auto-approved in this phase. Process presence checks are on-demand liveness checks for a
3// named session id, never a routine resource census.
4
5/** Forward slashes, a drive letter in Git Bash form (/c/...) as c:/..., no trailing slash; the case kept. */
6export const keepPath = (p: string) => p.replace(/\\/g, '/').replace(/^\/([a-zA-Z])\//, '$1:/').replace(/\/+$/, '')
7
8/**
9 * macOS and Linux (0.5.30): the shell that makes each folder on the way to $1 exist and enterable by its owner. A
10 * parent whose default ACL gives its owner rw- passes that to each new folder, so nothing can be written inside it
11 * (EACCES). A mended folder that carries a default ACL is set to pass rwx on, so later folders come out right.
12 */
13export const MEND_DIRS =
14 'd=$1; set --; while [ ! -d "$d" ] || [ ! -x "$d" ]; do set -- "$d" "$@"; n=$(dirname -- "$d"); [ "$n" = "$d" ] && exit 1; d=$n; done; ' +
15 'for p; do [ -d "$p" ] || mkdir -- "$p" || exit 1; chmod u+rwx -- "$p" || exit 1; ' +
16 '[ -z "$(getfacl -dcp -- "$p" 2>/dev/null)" ] || setfacl -m d:u::rwx -- "$p" || true; done'
17
18// ── Is a member's session still running? The send-time crash check (0.5.16, #71 and #65) ──
19// Run only when a message goes to a member that has been silent for over 90 s: never on a timer. The machine's session
20// registry (~/.claude/sessions/<pid>.json) names the process ids that hold the member's session id; each is then looked
21// up by its id alone (one Get-CimInstance query on Windows, `ps -o args= -p <pid>` elsewhere).
22
23/** One process as the check saw it: running or not, and its command line ('' when it cannot be read). */
24export type Proc = { running: boolean; args: string }
25
26/** dead: proved gone; alive: a claude process still holds the session; unsure: it cannot be told (so nothing is reopened). */
27export type Liveness = { kind: 'dead' } | { kind: 'alive'; pid: number } | { kind: 'unsure'; why: string }
28
29/** The PowerShell that looks the given process ids up in one Get-CimInstance query filtered by ProcessId. */
30export const winProcScript = (pids: number[]) => {
31 const ids = pids.filter(p => Number.isInteger(p) && p > 0)
32 return (
33 `$ErrorActionPreference='Stop'; $ps=@(Get-CimInstance Win32_Process -Filter '${ids.map(p => `ProcessId=${p}`).join(' OR ')}'); ` +
34 `foreach($i in @(${ids.join(',')})){ $p=$ps|?{$_.ProcessId -eq $i}|select -First 1; if($p){'RUN|'+$i+'|'+[string]$p.CommandLine}else{'NONE|'+$i} }; 'DONE'`
35 )
36}
37
38/** The processes in winProcScript's output; undefined when the output is not a complete answer for every id. */
39export function parseWinProcs(stdout: string, pids: number[]): Map<number, Proc> | undefined {
40 const lines = stdout.split(/\r?\n/).map(l => l.trim())
41 if (!lines.includes('DONE')) return undefined
42 const out = new Map<number, Proc>()
43 for (const l of lines) {
44 const m = l.match(/^(RUN|NONE)\|(\d+)(?:\|(.*))?$/)
45 if (m) out.set(Number(m[2]), { running: m[1] === 'RUN', args: m[3] ?? '' })
46 }
47 return pids.every(p => out.has(p)) ? out : undefined
48}
49
50/** One process from `ps -o args= -p <pid>`: exit 0 with a line is running, exit 1 with nothing is gone, anything else unknown. */
51export function psProc(r: { exitCode: number; stdout: string } | undefined): Proc | undefined {
52 if (!r) return undefined
53 const text = String(r.stdout ?? '').trim()
54 if (r.exitCode === 0 && text !== '') return { running: true, args: text }
55 if (r.exitCode === 1 && text === '') return { running: false, args: '' }
56 return undefined
57}
58
59/**
60 * Whether the session is alive, from the process ids the registry names for it and what the check found at each.
61 * - a running process whose command line carries the session id: alive
62 * - a running claude process without the id on its command line (a session started as plain `claude`): alive, as
63 * the registry file named after that pid still lists the session
64 * - a running process whose command line cannot be read: unsure
65 * - gone, or now another program (a reused pid): that registry entry is stale and proves nothing
66 * No pid at all, or only stale entries: dead. Any pid without an answer: unsure.
67 */
68export function livenessOf(sessionId: string, pids: number[], procs: ReadonlyMap<number, Proc>): Liveness {
69 const id = sessionId.toLowerCase()
70 let doubt = ''
71 for (const pid of pids) {
72 const p = procs.get(pid)
73 if (!p) {
74 doubt ||= `process ${pid} could not be looked up`
75 continue
76 }
77 if (!p.running) continue
78 const args = p.args.toLowerCase()
79 if (id !== '' && args.includes(id)) return { kind: 'alive', pid }
80 if (args.trim() === '') doubt ||= `process ${pid} is running but its command line cannot be read`
81 else if (/\bclaude\b/.test(args)) return { kind: 'alive', pid }
82 }
83 return doubt ? { kind: 'unsure', why: doubt } : { kind: 'dead' }
84}
85hooks/roles.ts 105 lines1// Role files (0.5.04). Each member's role lives in .claude/team-orchestrator/roles/<name>.md, not in a chat message
2// that a summary can shrink. The session is started with a short pointer in its system prompt (--append-system-prompt):
3// who it is, its boss, the one rule that matters most for its level, and the path of its role file. The file is read
4// once; when the team changes the mod rewrites it and Claude Code tells the session what changed.
5//
6// The file has two parts. Above the marker: generated from the roster, rewritten on every change. Below it: the
7// person's own notes (a voice, a working style, extra rules), never touched by the mod.
8//
9// Pure rules from the roster alone (no $), so a test can call them.
10
11import type { Member } from '../types'
12import { roleFile } from './status'
13
14export const MARKER = '<!-- END OF THE GENERATED PART. The Team Orchestrator rewrites everything above this line when the team changes. Write your own notes below it. -->'
15
16const NOTES =
17 '## Personality and notes\r\n\r\n' +
18 '(Optional. Add a voice, a working style or extra rules for this member here. The Team Orchestrator never changes this part.)\r\n'
19
20const kind = (x: Member, list: Member[]) => (x.boss === 'user' || x.level === 1 ? 'head' : list.some(k => k.boss === x.name) ? 'lead' : 'worker')
21const bossLine = (m: Member) => (m.boss === 'user' ? 'the user (the person at the keyboard)' : m.boss)
22
23/** The generated part of a member's role file. list: the member's team and every boss above it. */
24export function roleText(m: Member, list: Member[]): string {
25 const kids = list.filter(x => x.boss === m.name)
26 const peers = list.filter(x => x.name !== m.name && list.some(k => k.boss === x.name))
27 const manages = kids.length > 0
28 const lines = [
29 `# ${m.name}`,
30 '',
31 `Team: ${m.team}. Role: ${m.role}.`,
32 `Boss: ${bossLine(m)}.`,
33 ...(manages ? [`Direct reports: ${kids.map(k => k.name).join(', ')}.`] : []),
34 '',
35 '## Your job',
36 '',
37 manages
38 ? 'You orchestrate. You decide, plan and instruct; you do not do the tasks yourself. Give the work to your direct reports and review what they send back. Do not go around a lead to instruct someone else\'s worker.'
39 : 'You do the tasks your boss gives you and report the results back to your boss.',
40 '',
41 '## Messages',
42 '',
43 ...(manages
44 ? [
45 '- Message your direct reports with the team_message tool (mcp__team-orchestrator__team_message, { to, message }), not SendMessage. A report may not be running yet, or may have been closed while idle; team_message starts it and then delivers.',
46 `- Message your boss${peers.length ? ` and the other heads and leads (${peers.map(p => p.name).join(', ')})` : ''} with SendMessage.`,
47 ]
48 : ['- Talk only to your boss, with SendMessage. Do not message your boss\'s boss, other leads or other workers unless your boss names one to you.']),
49 '- If SendMessage says a teammate\'s name is ambiguous or unknown, use team_message with the plain name instead.',
50 '- Never type into another member\'s terminal (orca terminal send) to message it.',
51 '',
52 '## Housekeeping',
53 '',
54 'When you report a completed task, include one explicit cleanup field in that same message: `Cleanup: clean`, `Cleanup: incomplete`, `Cleanup: failed`, or `Cleanup: unverified`. This is self-reported only, never OS verification; old status-file counts do not prove cleanup. Never send a separate clean-only acknowledgement. Delete only exact task-owned files when the current permission allows it; otherwise ask. Never delete shared temp, project scratch, task outputs, logs, tests, retained results or artifacts. Stop no process for automated housekeeping in this interim phase; separate user-directed actions still use normal permission and ownership checks. If anything is unclear or failed, report incomplete or unverified rather than clean.',
55 '',
56 '## The team',
57 '',
58 ...list.map(x => `- ${x.name}: ${kind(x, list)}, reports to ${x.boss === 'user' ? 'the user' : x.boss}. ${x.role}`),
59 '',
60 '## Team files',
61 '',
62 'The team lives in .claude/team-orchestrator/. roster.json is the structure and settings.json the team settings; only the team top\'s session writes them, and every other session\'s change waits in changes/ until the top applies it. Never edit roster.json, settings.json, meta.json or changes/ by hand. Each member\'s live status is kept on its own PC, under ~/.claude/team-orchestrator/<project>/status/, written by the Team Orchestrator for its own session; never edit another member\'s. This file is ' + roleFile(m.name) + '.',
63 '',
64 ]
65 return lines.join('\r\n')
66}
67
68/** The whole file: the generated part, the marker, and the notes kept from the file as it was (or the empty notes). */
69export function mergeRole(existing: string | undefined, generated: string): string {
70 const at = existing?.indexOf(MARKER) ?? -1
71 const notes = existing && at >= 0 ? existing.slice(at + MARKER.length).replace(/^\r?\n/, '') : `\r\n${NOTES}`
72 return `${generated}${MARKER}\r\n${notes}`
73}
74
75// a shell types the start command (cmd.exe on Windows, an interactive bash or zsh elsewhere): no double quote (it would
76// end the argument), no % $ ` or backslash (variables and escapes), no ! (history expansion), no line breaks
77const safe = (s: string) => s.replace(/["%$`\\!\r\n]+/g, ' ')
78
79/** The system-prompt pointer a member starts with: short, because it is sent on every turn. */
80export function pointer(m: Member, list: Member[]): string {
81 const manages = list.some(x => x.boss === m.name)
82 const rule = manages
83 ? 'You plan, delegate and review; you do not do the work yourself. Message your direct reports with the team_message tool, not SendMessage.'
84 : 'You do the tasks your boss gives you and report back to your boss only, with SendMessage.'
85 return safe(
86 `You are ${m.name}, a member of the Team Orchestrator team '${m.team}'. Your boss is ${bossLine(m)}. ${rule} ` +
87 `Your full role is in the file .claude/team-orchestrator/${roleFile(m.name)}. Read it before your first action and follow it. ` +
88 'Read it again after any conversation summary, or when you are told it changed.',
89 )
90}
91
92/** The first prompt of a member started at Create: confirm it read its role, then wait. */
93export const WELCOME = 'Read your role file now (its path is in your system prompt). Then reply with Noted and one line that restates your role and your boss, and wait for instructions.'
94
95/** Who a team's members need to know: the team, every boss above it, and the direct reports it has in other teams (a CEO's heads). */
96export function orgOf(all: Member[], team: string): Member[] {
97 const org = new Set(all.filter(m => m.team === team).map(m => m.name))
98 for (let grew = true; grew; ) {
99 grew = false
100 for (const m of all) if (org.has(m.name)) for (const b of all) if (b.name === m.boss && !org.has(b.name)) (org.add(b.name), (grew = true))
101 }
102 for (const m of all) if (m.team === team) for (const k of all) if (k.boss === m.name) org.add(k.name)
103 return all.filter(m => org.has(m.name))
104}
105hooks/changes.ts 238 lines1// Safe roster writes across sessions, versions and machines (0.5.12, #59 and #64). Pure rules from data (no $), so a
2// test can call them.
3//
4// - One writer. Only the team top's session (on the top's machine) writes roster.json and settings.json. Every other
5// session writes a small change file, changes/<ms>-<rand>.json, holding the member fields it changed (or a settings
6// patch). Every session reads the roster as the file plus the change files not yet applied, in time order, field
7// by field; the top folds them into the file and records them in changes/applied.json. The mod's file API cannot
8// delete, so an applied change file stays where it is and the index says it is done; files older than 7 days are
9// ignored by their name alone.
10// - A schema stamp beside the roster (meta.json): schemaVersion, writtenBy (the writer's mod version) and topMachine.
11// roster.json stays a plain array, so older copies of the mod still read it. A session whose mod is older than
12// writtenBy writes only change files, which wait for a current top.
13// - The queue: one file per message, queue/<ms>-<rand>.json, with a state. Delivered and failed entries are kept a day,
14// everything at most 7 days; queue/pruned.json lists the entries the top's round has pruned.
15// - Machines: a member records its home machine; a member whose home is another PC is never matched, reopened, closed
16// or messaged from here.
17
18import type { Member } from '../types'
19import type { TeamSettings } from './status'
20
21export const SCHEMA = 2
22export const MIN_MS = 60_000
23export const DAY = 24 * 60 * MIN_MS
24/** change files and queue entries older than this are ignored by their name alone */
25export const KEEP_MS = 7 * DAY
26/** a queue entry marked sending this long ago was left by a round that stopped: it is tried again */
27export const SENDING_MS = 5 * MIN_MS
28export const MAX_TRIES = 3
29
30/** The member fields kept in the roster file. */
31export const STRUCT = ['team', 'name', 'address', 'role', 'level', 'boss', 'handle', 'sessionId', 'worktree', 'machine', 'short', 'allowAgent', 'allowWrite', 'briefed', 'noted', 'statusFile', 'pending', 'model', 'effort', 'location', 'cli'] as const
32
33export const keyOf = (m: Partial<Member>) => `${m.team ?? ''}|${m.name ?? ''}`
34
35/** A member as the roster file keeps it: its structure fields only. */
36export const project = (m: Partial<Member>): Partial<Member> => {
37 const out: Record<string, unknown> = {}
38 for (const k of STRUCT) if ((m as any)[k] !== undefined) out[k] = (m as any)[k]
39 return out as Partial<Member>
40}
41
42// ── change files ──
43
44export type Op =
45 | { op: 'set'; key: string; patch: Record<string, unknown> }
46 | { op: 'add'; member: Partial<Member> }
47 | { op: 'del'; key: string }
48/** who wrote a change: shown when the top applies a change of rights */
49export type By = { session: string; member: string; machine: string; version: string }
50export type Change =
51 | { v: 1; kind: 'roster'; at: number; by: By; ops: Op[] }
52 | { v: 1; kind: 'settings'; at: number; by: By; patch: Partial<TeamSettings> }
53
54const NAME = /^(\d{13})-[a-z0-9]{4,16}\.json$/
55
56/** A change or queue file name: the time first, so names sort in time order. */
57export const fileName = (at: number, rand: string) => `${String(Math.max(0, Math.floor(at))).padStart(13, '0')}-${rand.replace(/[^a-z0-9]/g, '').slice(0, 16).padEnd(4, '0')}.json`
58
59/** The time in a change or queue file's name; NaN for any other file. */
60export const timeOf = (name: string) => {
61 const m = name.match(NAME)
62 return m ? Number(m[1]) : NaN
63}
64
65/** The names still to apply: well formed, not older than 7 days, not in the applied index, oldest first. */
66export const pendingNames = (names: string[], applied: ReadonlySet<string>, now: number) =>
67 names.filter(n => !applied.has(n) && now - timeOf(n) <= KEEP_MS).sort()
68
69/** The applied index after adding names: entries older than 7 days are dropped (their files are ignored by name). */
70export const appliedAfter = (prev: string[], add: string[], now: number) =>
71 [...new Set([...prev, ...add])].filter(n => now - timeOf(n) <= KEEP_MS).sort()
72
73const same = (a: unknown, b: unknown) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
74
75/**
76 * What one session changed in the roster since it last read it: added members, removed members, and per member only
77 * the fields that differ (null clears a field). statusFile is derived from the name, so it is never a change of its own.
78 */
79export function diffOps(base: Partial<Member>[], local: Partial<Member>[]): Op[] {
80 const b = new Map(base.map(m => [keyOf(m), project(m)]))
81 const l = new Map(local.map(m => [keyOf(m), project(m)]))
82 const ops: Op[] = []
83 for (const [k, m] of l) {
84 const old = b.get(k)
85 if (!old) {
86 ops.push({ op: 'add', member: m })
87 continue
88 }
89 const patch: Record<string, unknown> = {}
90 for (const f of STRUCT) {
91 if (f === 'statusFile') continue
92 if (!same((m as any)[f], (old as any)[f])) patch[f] = (m as any)[f] ?? null
93 }
94 if (Object.keys(patch).length > 0) ops.push({ op: 'set', key: k, patch })
95 }
96 for (const k of b.keys()) if (!l.has(k)) ops.push({ op: 'del', key: k })
97 return ops
98}
99
100const merge = <T extends object>(m: T, patch: Record<string, unknown>): T => {
101 const out = { ...m } as Record<string, unknown>
102 for (const [f, v] of Object.entries(patch)) {
103 if (v === null) delete out[f]
104 else out[f] = v
105 }
106 return out as T
107}
108
109/**
110 * The roster with ops applied in order, field by field. A set or del of a member that is gone does nothing; an add of
111 * a member already there (its row sent again from an older read) only fills the fields it lacks, never rolls one back.
112 */
113export function applyOps<T extends Partial<Member>>(list: T[], ops: Op[]): T[] {
114 let out = list.slice()
115 for (const o of ops) {
116 if (o.op === 'del') out = out.filter(m => keyOf(m) !== o.key)
117 else if (o.op === 'set') out = out.map(m => (keyOf(m) === o.key ? merge(m, o.patch) : m))
118 else {
119 const k = keyOf(o.member)
120 out = out.some(m => keyOf(m) === k) ? out.map(m => (keyOf(m) === k ? ({ ...o.member, ...m } as T) : m)) : [...out, o.member as T]
121 }
122 }
123 return out
124}
125
126/** The roster changes in a set of change files, oldest first. */
127export const rosterOps = (changes: { name: string; change: Change }[]) =>
128 changes.flatMap(c => (c.change.kind === 'roster' && Array.isArray(c.change.ops) ? c.change.ops : []))
129
130/** The settings with every settings patch applied, oldest first. */
131export const applySettings = (s: TeamSettings, changes: { name: string; change: Change }[]): TeamSettings =>
132 changes.reduce((acc, c) => (c.change.kind === 'settings' && c.change.patch && typeof c.change.patch === 'object' ? { ...acc, ...c.change.patch } : acc), s)
133
134/** The changes of rights (Allow writes, Allow subagents) a set of change files makes, in words, for the top's toast. */
135export function rightsChanges(changes: { name: string; change: Change }[]): string[] {
136 const out: string[] = []
137 for (const { change: c } of changes) {
138 if (c.kind !== 'roster') continue
139 const from = [c.by?.member || 'a session not on the roster', c.by?.machine ? `on ${c.by.machine}` : ''].filter(Boolean).join(' ')
140 for (const o of c.ops ?? []) {
141 const p: Record<string, unknown> = o.op === 'set' ? o.patch : o.op === 'add' ? (o.member as Record<string, unknown>) : {}
142 const name = o.op === 'set' ? o.key.slice(o.key.indexOf('|') + 1) : o.op === 'add' ? String(o.member.name ?? '') : ''
143 const words: string[] = []
144 if ('allowWrite' in p && (o.op === 'set' || p.allowWrite === true)) words.push(`Allow writes ${p.allowWrite === true ? 'on' : 'off'}`)
145 if ('allowAgent' in p && (o.op === 'set' || p.allowAgent === true)) words.push(`Allow subagents ${p.allowAgent === true ? 'on' : 'off'}`)
146 if (words.length > 0) out.push(`${name}: ${words.join(', ')} (from ${from})`)
147 }
148 }
149 return out
150}
151
152// ── the schema stamp ──
153
154export type Meta = { schemaVersion: number; writtenBy: string; topMachine: string }
155export const META0: Meta = { schemaVersion: 1, writtenBy: '', topMachine: '' }
156
157/** a < b for dotted versions ("0.5.9" < "0.5.12"); an unknown version on either side is never older. */
158export function olderThan(a: string, b: string): boolean {
159 if (!a || !b) return false
160 const pa = a.split('.').map(x => parseInt(x, 10) || 0)
161 const pb = b.split('.').map(x => parseInt(x, 10) || 0)
162 for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
163 const d = (pa[i] ?? 0) - (pb[i] ?? 0)
164 if (d !== 0) return d < 0
165 }
166 return false
167}
168
169/** The stamp after a write by the top on `here`: the newer version, and the top's machine kept unless none is set. */
170export const metaAfter = (m: Meta, version: string, here: string): Meta => ({
171 schemaVersion: Math.max(SCHEMA, m.schemaVersion || 0),
172 writtenBy: olderThan(m.writtenBy, version) || !m.writtenBy ? version || m.writtenBy : m.writtenBy,
173 topMachine: m.topMachine || here,
174})
175
176// ── machines ──
177
178/** By the name before any domain: a Mac is "mac" to scutil and "mac.local" to a shell's HOSTNAME. */
179const shortName = (s: string) => s.trim().toLowerCase().split('.')[0] as string
180export const sameMachine = (a: string, b: string) => shortName(a) === shortName(b)
181
182/** The member's home is another PC. A member with no machine recorded, or a PC that does not know its own name, is local. */
183export const isAway = (m: Partial<Member>, here: string) => !!here && !!m.machine && !sameMachine(m.machine, here)
184
185/** The top machine is recorded and is not this one: team-top actions here are off. */
186export const topElsewhere = (meta: Meta, here: string) => !!here && !!meta.topMachine && !sameMachine(meta.topMachine, here)
187
188/** The roster's team top for writing: its first member that reports to the user. */
189export const projectTop = <T extends Partial<Member>>(list: T[]): T | undefined => list.find(m => m.boss === 'user')
190
191/**
192 * The folder name of a project under <claude config dir>/team-orchestrator/, made from the project root the way Claude
193 * names its projects folders: every character but a letter or a digit becomes "-" (the drive letter upper case).
194 */
195export function projectKey(root: string): string {
196 const r = root.replace(/[\\/]+$/, '').replace(/^([a-z]):/, (_, d: string) => `${d.toUpperCase()}:`)
197 const key = r.replace(/[^A-Za-z0-9]/g, '-')
198 if (key.length <= 200) return key
199 let h = 5381
200 for (const ch of r) h = ((h * 33) ^ ch.charCodeAt(0)) >>> 0
201 return `${key.slice(0, 200)}-${h.toString(36)}`
202}
203
204// ── the queue ──
205
206export type QState = 'pending' | 'sending' | 'delivered' | 'failed'
207/**
208 * reason (0.5.16, #65): why a pending entry waits for its member to answer rather than for room. hung: its claude
209 * process runs but it has written no status for a while; unsure: whether it runs could not be proved. Either is tried
210 * when the member's heartbeat is fresh again, or once it is proved dead and closed (then it is reopened first). told:
211 * when the team top was told the member looks hung (once per member per hour, across sessions).
212 */
213export type QReason = 'hung' | 'unsure'
214export type QEntry = { to: string; from: string; message: string; created: number; state: QState; tries: number; updated?: number; error?: string; reason?: QReason; told?: number }
215
216/** What the top's round does with one entry: prune it, keep it as it is, or try to deliver it. */
217export function queueAction(q: QEntry, now: number): 'prune' | 'keep' | 'try' {
218 if (now - q.created > KEEP_MS) return 'prune'
219 const since = now - (q.updated ?? q.created)
220 if (q.state === 'delivered' || q.state === 'failed') return since > DAY ? 'prune' : 'keep'
221 if (q.state === 'sending' && since < SENDING_MS) return 'keep'
222 return 'try'
223}
224
225/** The entry after one try: delivered; back to pending when there was no room (not a failed try); failed after the third failure. */
226export function afterTry(q: QEntry, ok: boolean | undefined, now: number, error = ''): QEntry {
227 if (ok === true) return { ...q, state: 'delivered', updated: now, error: undefined }
228 if (ok === undefined) return { ...q, state: 'pending', updated: now }
229 const tries = q.tries + 1
230 return { ...q, tries, state: tries >= MAX_TRIES ? 'failed' : 'pending', updated: now, error }
231}
232
233/** The old single queue.json (before 0.5.12) as queue entries. */
234export const fromOldQueue = (rows: unknown, now: number): QEntry[] =>
235 (Array.isArray(rows) ? rows : [])
236 .filter((r: any) => r && typeof r.to === 'string' && typeof r.message === 'string')
237 .map((r: any) => ({ to: r.to, from: String(r.from ?? 'someone'), message: r.message, created: Number(r.at) || now, state: 'pending' as const, tries: 0 }))
238hooks/layout.ts 151 lines1// The roster table's columns and the org chart's labels, from the members and the width alone: no $, no state,
2// so a test can call them. Every cell is cut with "…" to its width and ends in one space, so nothing wraps and
3// two values never touch.
4
5export type Tier = 'wide' | 'medium' | 'narrow'
6export type Col = { id: string; w: number; head: string }
7export type ColumnPlan = { tier: Tier; nameW: number; cols: Col[]; total: number }
8
9// "[x] " before the name; a row has no buttons (Open and Remove are in Team actions)
10export const CHECK = 6
11
12// Cells per tier, each width counting its trailing space. Measured sums: wide 58, medium 38, narrow 18; with the
13// checkbox a row needs 62 / 42 / 22 cells plus the name.
14const TIERS: { tier: Tier; cols: [string, number][] }[] = [
15 { tier: 'wide', cols: [['STATUS', 11], ['CONTEXT', 16], ['MODEL', 14], ['EFFORT', 8], ['BRIEF', 9]] },
16 { tier: 'medium', cols: [['STATUS', 11], ['CONTEXT', 12], ['MODEL', 8], ['EFFORT', 7]] },
17 { tier: 'narrow', cols: [['STATUS', 2], ['CONTEXT', 5], ['MODEL', 7], ['EFFORT', 4]] },
18]
19const SHORT_HEAD: Record<string, string> = { STATUS: '', CONTEXT: 'CTX', MODEL: 'MODEL', EFFORT: 'EFF', BRIEF: 'BR' }
20// a tier is taken while the name keeps this much (or all of itself, when shorter)
21const NAME_ROOM = 16
22const NAME_MIN = 8
23
24/**
25 * Cards per row in the side-by-side layout. Each card needs at least the medium tier with a short name (or, to keep
26 * two side by side, the narrow tier); a card that gets more width simply draws a wider tier. So a 1920x1080 screen
27 * (about 160-210 columns) shows a 2 x 2 grid for four teams instead of one card per row.
28 */
29export function sideBySide(cols: number, cards: number, frame: number): number {
30 if (cards <= 1) return 1
31 const mediumMin = CHECK + 38 + NAME_ROOM + frame
32 const narrowMin = CHECK + 18 + NAME_MIN + frame
33 const fit = Math.floor(cols / mediumMin)
34 const n = fit >= 2 ? fit : Math.floor(cols / narrowMin) >= 2 ? 2 : 1
35 return Math.max(1, Math.min(cards, n))
36}
37
38/** `s` cut to `w` cells, the last one "…" when cut */
39export const fit = (s: string, w: number) => (w <= 0 ? '' : s.length <= w ? s : `${s.slice(0, w - 1)}…`)
40/** `s` as a cell of `w`: cut to w - 1, then padded, so one space always follows */
41export const cell = (s: string, w: number) => fit(s, w - 1).padEnd(w)
42
43/**
44 * The widest tier whose cells leave the names room in `width` (the cells inside a card). `hide` is the settings'
45 * column toggles, applied on top of the tier.
46 */
47export function columnPlan(rows: { prefix: string; name: string }[], width: number, hide: string[]): ColumnPlan {
48 const want = Math.max(4, ...rows.map(r => r.prefix.length + r.name.length)) + 1
49 for (const t of TIERS) {
50 const cols = t.cols
51 .filter(([id]) => !hide.includes(id))
52 .map(([id, w]) => ({ id, w, head: id.length <= w - 1 ? id : (SHORT_HEAD[id] ?? '') }))
53 const fixed = CHECK + cols.reduce((a, c) => a + c.w, 0)
54 const room = width - fixed
55 if (room < Math.min(want, NAME_ROOM) && t.tier !== 'narrow') continue
56 const nameW = Math.max(NAME_MIN, Math.min(want, room))
57 return { tier: t.tier, nameW, cols, total: fixed + nameW }
58 }
59 throw new Error('unreachable: the narrow tier is always taken')
60}
61
62/** The header line, cut to the same widths as the cells below it. */
63export const headerLine = (p: ColumnPlan) => ' '.repeat(CHECK) + cell('NAME', p.nameW) + p.cols.map(c => cell(c.head, c.w)).join('')
64
65/** "Opus 5.5" / "opus-5-5" -> "Opus": the family, for the tiers that are short of room */
66export const family = (model: string) => {
67 const w = model.split(/[\s-]+/).find(x => x !== '') ?? ''
68 return w === '' ? '' : w[0]!.toUpperCase() + w.slice(1)
69}
70export const EFFORT_SHORT: Record<string, string> = { low: 'L', medium: 'M', high: 'H', xhigh: 'XH', max: 'MAX' }
71
72// ── org chart labels ──
73// A member's label is, first of all, the short name the person gave it (`short`), used as typed. Only a member with no
74// short name gets one from the rule below, and the rule keeps away from every short name already taken.
75// The rule makes the shortest label that tells each member apart, for any names, worked out each draw:
76// 1. drop the words the name shares with its team ("Hualong PC Worker A" in team Hualong -> "PC Worker A"),
77// and the words every member of the team starts with;
78// 2. try, in order: a leading acronym and the last word ("PC A", "PC Boss"); the initial and a number or letter
79// tail ("Worker 5" -> "W5", "Lead 1 2" -> "L1.2"); the last word ("CEO", "Workers"); the first word
80// ("Research Worker" -> "Research"); all the words left;
81// 3. members still alike get the team in front ("Dev Head", "UI Head"), then the whole name.
82// Every automatic member starts at its first try; those that clash (with another automatic label or with a short name)
83// move one try on, until no two labels are the same. Two characters at least. The rule knows nothing about what a
84// name means: "HK University of Hong Kong president" only becomes "HK president" when a person says so.
85// Two members that were given the same short name both keep it, and both are flagged (`dup`): the chart adds "!"
86// and the roster row says so. Nothing is renamed behind the person's back.
87const words = (s: string) => s.split(/[\s_-]+/).filter(w => w !== '')
88const isTail = (w: string) => /^\d+$/.test(w) || w.length <= 2
89
90export type LabelInfo = {
91 /** what the chart shows (before any "…" cut to fit) */
92 label: string
93 /** worked out by the rule, not given by the person: drawn dim */
94 auto: boolean
95 /** the person gave this short name to more than one member */
96 dup: boolean
97}
98type Labelled = { team: string; name: string; short?: string }
99
100/** `s` cut to `max` characters with "…" as the last one, when it is longer */
101export const shorten = (s: string, max: number) => (s.length <= max ? s : max <= 1 ? '…' : `${s.slice(0, max - 1)}…`)
102
103export function chartLabelInfo(list: Labelled[]): Map<string, LabelInfo> {
104 const given = list.map(m => (m.short ?? '').trim())
105 const rests = new Map<string, string[]>()
106 for (const team of new Set(list.map(m => m.team))) {
107 const mine = list.filter(m => m.team === team)
108 const lead = words(team)
109 const own = mine.map(m => {
110 const w = words(m.name)
111 return w.length > lead.length && lead.every((x, i) => w[i]?.toLowerCase() === x.toLowerCase()) ? w.slice(lead.length) : w
112 })
113 let n = 0
114 if (mine.length > 1) while (own.every(w => w.length > n + 1 && w[n] === own[0]![n])) n++
115 mine.forEach((m, i) => rests.set(`${m.team}|${m.name}`, own[i]!.slice(n)))
116 }
117 const ladder = (m: Labelled): string[] => {
118 const w = rests.get(`${m.team}|${m.name}`) ?? words(m.name)
119 const first = w[0] ?? m.name
120 const last = w[w.length - 1] ?? m.name
121 const tries: string[] = []
122 if (w.length > 1 && /^[A-Z0-9]{2,}$/.test(first)) tries.push(`${first} ${last}`)
123 if (w.length > 1 && w.slice(1).every(isTail)) tries.push(`${first[0]}${w.slice(1).join('.')}`)
124 tries.push(last, first, w.join(' '))
125 const inTeam = tries.filter(x => x.length >= 2)
126 const tag = words(m.team)[0] ?? m.team
127 return [...new Set([...inTeam, ...inTeam.map(x => `${tag} ${x}`), m.name, `${m.team}/${m.name}`])].filter(x => x.length >= 2)
128 }
129 const steps = list.map(ladder)
130 const at = list.map(() => 0)
131 const label = (i: number) => (given[i] !== '' ? (given[i] as string) : steps[i]![Math.min(at[i]!, steps[i]!.length - 1)]!)
132 for (let round = 0; round < 20; round++) {
133 const count = new Map<string, number>()
134 list.forEach((_, i) => count.set(label(i).toLowerCase(), (count.get(label(i).toLowerCase()) ?? 0) + 1))
135 // only the automatic labels move; a short name the person gave stays where it is
136 const clash = list.map((_, i) => given[i] === '' && (count.get(label(i).toLowerCase()) ?? 0) > 1)
137 if (!clash.some(Boolean)) break
138 clash.forEach((c, i) => c && (at[i] = at[i]! + 1))
139 }
140 const same = new Map<string, number>()
141 given.forEach(g => g !== '' && same.set(g.toLowerCase(), (same.get(g.toLowerCase()) ?? 0) + 1))
142 return new Map(
143 list.map((m, i) => [`${m.team}|${m.name}`, { label: label(i), auto: given[i] === '', dup: given[i] !== '' && (same.get(given[i]!.toLowerCase()) ?? 0) > 1 }]),
144 )
145}
146
147/** Just the labels, for a caller that does not need to know which are automatic. */
148export function chartLabels(list: Labelled[]): Map<string, string> {
149 return new Map([...chartLabelInfo(list)].map(([k, v]) => [k, v.label]))
150}
151hooks/assumptions.ts 60 lines1// The open assumptions of each member (#89), read from its Session Panel's file. This mod only reads them: a confirm or
2// a wrong goes to the member as one team message, and the member's own Session Panel changes its own file. A file is
3// matched to its member by the sessionId inside it, since a tagged name (<id>-<hash>.json) can also exist.
4
5export const ASSUMPTIONS_DIR = '.claude/session-panel/assumptions'
6
7export type OpenAssumption = { id: string; text: string; kind: string; turn: number }
8
9/** The open entries of one file and the session it belongs to; undefined when the text is not an assumptions file. */
10export function openFrom(text: string): { sessionId: string; entries: OpenAssumption[] } | undefined {
11 let v: any
12 try {
13 v = JSON.parse(text)
14 } catch {
15 return undefined
16 }
17 if (!v || typeof v !== 'object' || Array.isArray(v) || typeof v.sessionId !== 'string' || !Array.isArray(v.entries)) return undefined
18 const entries = v.entries
19 .filter((e: any) => e && typeof e === 'object' && e.status === 'open' && typeof e.id === 'string' && typeof e.text === 'string')
20 .map((e: any) => ({ id: e.id, text: e.text, kind: String(e.kind ?? ''), turn: Number(e.turn ?? 0) }))
21 return { sessionId: v.sessionId, entries }
22}
23
24/** The open entries by session id over the given file texts. A text that does not read is skipped; an entry in two files counts once. */
25export function collectOpen(texts: string[]): Record<string, OpenAssumption[]> {
26 const out: Record<string, OpenAssumption[]> = {}
27 for (const t of texts) {
28 const f = openFrom(t)
29 if (!f || f.sessionId === '') continue
30 const have = out[f.sessionId] ?? []
31 for (const e of f.entries) if (!have.some(h => h.id === e.id)) have.push(e)
32 out[f.sessionId] = have
33 }
34 return out
35}
36
37/** The one line a confirm sends to the member. The Session Panel reads it inside the team message (0.3.3). */
38export const confirmLine = (id: string) => `SESSION-PANEL: confirm ${id}`
39/** The one line a wrong sends to the member. */
40export const wrongLine = (id: string) => `SESSION-PANEL: wrong ${id}`
41/** The one line a delete sends to the member, after the head has said yes. Session Panel applies it on the member's side. */
42export const deleteLine = (id: string) => `SESSION-PANEL: delete ${id}`
43
44/**
45 * Asks the head once before an open assumption is deleted. Delete sends its one line; Keep sends nothing; no answer
46 * (the question could not be asked) sends nothing either. ask and send are the caller's, so the answer can be tested.
47 */
48export async function askDelete(
49 ask: (question: string, options: string[]) => Promise<string>,
50 send: (line: string) => Promise<unknown>,
51 id: string,
52 name: string,
53): Promise<'sent' | 'kept' | 'unasked'> {
54 const pick = await ask(`Delete open assumption ${id} of ${name}? Nobody has decided on it yet.`, ['Delete', 'Keep']).catch(() => undefined)
55 if (pick === undefined) return 'unasked'
56 if (pick !== 'Delete') return 'kept'
57 await send(deleteLine(id))
58 return 'sent'
59}
60types/index.d.ts 129 lines1export type Form = {
2 team: string
3 fn: string
4 levels: string
5 fan: string
6 /** '1' = a CEO above several teams, '0' = one team */
7 ceo: string
8 /** with a CEO: the team names, comma separated, one head each */
9 groups: string
10 // per-level defaults: model and effort for level 1 (head), 2, 3; 'default' = leave to claude
11 m1: string
12 e1: string
13 m2: string
14 e2: string
15 m3: string
16 e3: string
17}
18export type Member = {
19 /** the team this session belongs to */
20 team: string
21 name: string
22 /** the session's real name, what SendMessage addresses it by (defaults to name) */
23 address?: string
24 role: string
25 level: number
26 boss: string
27 handle: string
28 sessionId: string
29 /** starting | working | idle | asking | offline | failed | <raw orca state> */
30 state: string
31 /** context used, percent, -1 unknown */
32 ctx: number
33 model: string
34 effort: string
35 sel: boolean
36 note: string
37 /** the short name the person gave for the org chart; empty or missing: the chart works one out */
38 short?: string
39 /** this member may use the Agent tool (subagents); off unless set here or by #allow-subagent for one turn */
40 allowAgent?: boolean
41 /** a member with reports may use Write, Edit and NotebookEdit; off unless set here or by #allow-write for one turn */
42 allowWrite?: boolean
43 /** the one-time team briefing was sent */
44 briefed: boolean
45 /** the session answered "Noted" on screen */
46 noted: boolean
47 /** the Orca workspace (worktree id) the member was launched in; a reopen goes back there, never to the "active" one */
48 worktree?: string
49 /** the member's home machine (its computer name), set at launch, adopt, reopen and identity re-attach; empty: this one */
50 machine?: string
51 /** the status file this member's session writes, relative to <claude config dir>/team-orchestrator/<project>/ on its machine (status/<name>.json) */
52 statusFile?: string
53 /** on the roster since Create but never started: it starts, fresh and briefed, on its first message (team_message) */
54 pending?: boolean
55 /**
56 * how a message reaches it (0.5.13, #67): local (this machine, by session id), remote (another device, the messenger
57 * route of #72) or other-cli (not a Claude session: never messaged). Recorded at launch, adopt and reopen.
58 */
59 location?: 'local' | 'remote' | 'other-cli'
60 /** the CLI its tab runs, detected at adopt (claude, codex, hermes, gemini, opencode, qwen, other); empty: claude (#69) */
61 cli?: string
62}
63export type Bulk = {
64 prefix: string
65 base: string
66 /** none | 1 | 01 */
67 numbering: string
68 model: string
69 effort: string
70 msg: string
71}
72/** the Actions menu of the roster: what it is doing for the ticked rows */
73export type Act = {
74 /** the team whose Team actions list is open, '' none */
75 menu: string
76 /** none | remove | rmteam | boss | bulk | add | new | short | assume */
77 kind: string
78 /** the team card the open action (and its message) belongs to */
79 to: string
80 /** short: the row being named (team|name), and the text typed so far */
81 key: string
82 draft: string
83 /** add and new: the boss; boss: the new boss */
84 boss: string
85 /** add: the picked tab's handle; add and new: its role */
86 handle: string
87 role: string
88 /** new: the New member's name, model and effort ('default' leaves them to claude) */
89 name: string
90 model: string
91 effort: string
92 /** add: live tabs not on the roster, read when the action was picked */
93 tabs: { handle: string; title: string }[]
94 msg: string
95}
96export type View = 'closed' | 'roster' | 'new' | 'settings'
97/** a Create in progress: the members it starts now, the batch being started (1-based) and how many batches; empty when none */
98export type Spawn = { names: string[]; batch: number; of: number }
99export type Settings = {
100 /** stacked: team cards one under another | columns: side by side where the width allows | dock: the panel in a side pane */
101 layout: 'stacked' | 'columns' | 'dock'
102 /** show the live org chart */
103 chart: boolean
104 /** table columns hidden (STATUS, CONTEXT, MODEL, EFFORT, BRIEF); NAME always shows */
105 hide: string[]
106}
107
108declare module 'claude-code' {
109 interface PluginState {
110 'team-orchestrator': {
111 form: Form
112 members: Member[]
113 note: string
114 bulk: Bulk
115 view: View
116 teamName: string
117 frame: number
118 menu: string
119 settings: Settings
120 act: Act
121 spawn: Spawn
122 /** the open assumptions of each session, by session id (#89) */
123 assumptions: Record<string, { id: string; text: string; kind: string; turn: number }[]>
124 /** the assumptions view is on here: the team's switch is on and Session Panel is on in this session (#89) */
125 assumptionsOn: boolean
126 }
127 }
128}
129