orca-multiagent-kit 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +13 -7
  3. package/VERSION +1 -1
  4. package/bin/omk.js +47 -4
  5. package/bin/orca.js +170 -0
  6. package/bin/sea.js +95 -0
  7. package/bin/setup.js +326 -0
  8. package/bin/team.js +353 -0
  9. package/core/AGENTS.md +1 -1
  10. package/docs/EJECUTABLE.md +70 -0
  11. package/docs/PLUGIN-ORCA.md +126 -28
  12. package/orca-plugin/README.md +5 -1
  13. package/orca-plugin/assets/logos/README.md +10 -0
  14. package/orca-plugin/assets/logos/agent.png +0 -0
  15. package/orca-plugin/assets/logos/aider.png +0 -0
  16. package/orca-plugin/assets/logos/amp.png +0 -0
  17. package/orca-plugin/assets/logos/antigravity.png +0 -0
  18. package/orca-plugin/assets/logos/claude.png +0 -0
  19. package/orca-plugin/assets/logos/cline.png +0 -0
  20. package/orca-plugin/assets/logos/codex.png +0 -0
  21. package/orca-plugin/assets/logos/copilot.png +0 -0
  22. package/orca-plugin/assets/logos/cursor.png +0 -0
  23. package/orca-plugin/assets/logos/devin.png +0 -0
  24. package/orca-plugin/assets/logos/droid.png +0 -0
  25. package/orca-plugin/assets/logos/gemini.png +0 -0
  26. package/orca-plugin/assets/logos/goose.png +0 -0
  27. package/orca-plugin/assets/logos/grok.png +0 -0
  28. package/orca-plugin/assets/logos/kimi.png +0 -0
  29. package/orca-plugin/assets/logos/kiro.png +0 -0
  30. package/orca-plugin/assets/logos/opencode.png +0 -0
  31. package/orca-plugin/assets/logos/qwen-code.png +0 -0
  32. package/orca-plugin/orca-plugin.json +28 -7
  33. package/orca-plugin/src/icons.test.ts +14 -0
  34. package/orca-plugin/src/icons.ts +30 -0
  35. package/orca-plugin/src/kit.test.ts +456 -9
  36. package/orca-plugin/src/kit.ts +639 -16
  37. package/orca-plugin/src/models.test.ts +28 -0
  38. package/orca-plugin/src/models.ts +29 -0
  39. package/orca-plugin/src/node.d.ts +40 -0
  40. package/orca-plugin/src/panel-state.ts +28 -0
  41. package/orca-plugin/src/panel.test.tsx +298 -0
  42. package/orca-plugin/src/panel.tsx +609 -0
  43. package/orca-plugin/src/plan-card.test.ts +99 -0
  44. package/orca-plugin/src/plan-card.ts +107 -0
  45. package/orca-plugin/src/protocol.ts +179 -0
  46. package/orca-plugin/src/tabs/autonomy.tsx +70 -0
  47. package/orca-plugin/src/tabs/history.test.tsx +78 -0
  48. package/orca-plugin/src/tabs/history.tsx +118 -0
  49. package/orca-plugin/src/tabs/notices.test.tsx +183 -0
  50. package/orca-plugin/src/tabs/notices.tsx +274 -0
  51. package/orca-plugin/src/tabs/worktrees.test.tsx +130 -0
  52. package/orca-plugin/src/tabs/worktrees.tsx +138 -0
  53. package/orca-plugin/src/ui/agent-icon.tsx +13 -0
  54. package/orca-plugin/src/worker/context.test.ts +32 -0
  55. package/orca-plugin/src/worker/context.ts +92 -0
  56. package/orca-plugin/src/worker/history.test.ts +149 -0
  57. package/orca-plugin/src/worker/history.ts +181 -0
  58. package/orca-plugin/src/worker/notices.test.ts +356 -0
  59. package/orca-plugin/src/worker/notices.ts +291 -0
  60. package/orca-plugin/src/worker/system.test.ts +58 -0
  61. package/orca-plugin/src/worker/system.ts +122 -0
  62. package/orca-plugin/src/worker/worktrees.test.ts +177 -0
  63. package/orca-plugin/src/worker/worktrees.ts +188 -0
  64. package/orca-plugin/src/worker.test.ts +297 -15
  65. package/orca-plugin/src/worker.ts +353 -32
  66. package/package.json +3 -2
  67. package/skills/orca/SKILL.md +1 -0
  68. package/skills/orca/references/engine-orca.md +1 -0
  69. package/skills/orca/references/olimpo.md +1 -0
  70. package/skills/orca/references/plan-card.md +45 -0
@@ -0,0 +1,58 @@
1
+ // Lo que el worker lee del disco para los chats de Orca, contra una carpeta temporal de verdad.
2
+ import { afterEach, assert, test } from 'orca/testing'
3
+ import { mkdir, mkdtemp, rm, symlink, utimes, writeFile } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { tmpdir } from 'node:os'
6
+ import { createNodeSystem, PLAN_FILE_MAX } from './system.ts'
7
+
8
+ let dir: string | null = null
9
+ afterEach(async () => {
10
+ if (dir) await rm(dir, { recursive: true, force: true })
11
+ dir = null
12
+ })
13
+
14
+ const plan = async (root: string, run: string, content: string, mtimeSeconds: number) => {
15
+ await mkdir(join(root, '.work', 'runs', run), { recursive: true })
16
+ const file = join(root, '.work', 'runs', run, 'plan.json')
17
+ await writeFile(file, content)
18
+ await utimes(file, mtimeSeconds, mtimeSeconds)
19
+ return file
20
+ }
21
+
22
+ test('lee los plan.json nuevos de .work/runs y nada más', async () => {
23
+ dir = await mkdtemp(join(tmpdir(), 'omk-plans-'))
24
+ const old = 1_000_000
25
+ const fresh = 2_000_000
26
+ await plan(dir, 'viejo', '{"v":"viejo"}', old)
27
+ const nuevo = await plan(dir, 'nuevo', '{"v":"nuevo"}', fresh)
28
+ await plan(dir, 'enorme', 'x'.repeat(PLAN_FILE_MAX + 1), fresh)
29
+ await plan(dir, 'con espacio', '{}', fresh)
30
+ const plans = await createNodeSystem().readPlans(dir, (old + 1) * 1000)
31
+ assert.deepEqual(plans.map(({ path, content }) => ({ path, content })), [{ path: nuevo, content: '{"v":"nuevo"}' }])
32
+ })
33
+
34
+ test('un enlace simbólico en lugar del plan.json no se sigue', async () => {
35
+ dir = await mkdtemp(join(tmpdir(), 'omk-plans-'))
36
+ await writeFile(join(dir, 'secreto.txt'), 'no')
37
+ await mkdir(join(dir, '.work', 'runs', 'r1'), { recursive: true })
38
+ try {
39
+ await symlink(join(dir, 'secreto.txt'), join(dir, '.work', 'runs', 'r1', 'plan.json'))
40
+ } catch (error) {
41
+ // Windows sin modo desarrollador no deja crear enlaces: no hay nada que probar.
42
+ assert.equal((error as { code?: unknown }).code, 'EPERM')
43
+ return
44
+ }
45
+ assert.deepEqual(await createNodeSystem().readPlans(dir, 0), [])
46
+ })
47
+
48
+ test('sin .work/runs no hay planes', async () => {
49
+ dir = await mkdtemp(join(tmpdir(), 'omk-plans-'))
50
+ assert.deepEqual(await createNodeSystem().readPlans(dir, 0), [])
51
+ assert.deepEqual(await createNodeSystem().readPlans(join(dir, 'no-existe'), 0), [])
52
+ })
53
+
54
+ test('un id de run que no es de Orca no llega a la CLI', async () => {
55
+ for (const id of ['run_x; rm -rf ~', '--help', 'run:otro', '']) {
56
+ await assert.rejects(createNodeSystem().sendToRun(id, 'asunto', 'sí'), /no válido/)
57
+ }
58
+ })
@@ -0,0 +1,122 @@
1
+ // Lo que el worker hace fuera de la API de Orca, para que funcione también con agentes que corren
2
+ // como chat de Orca (sin terminal: la API no puede escribirles ni avisa de sus herramientas):
3
+ // - leer los `plan.json` de la skill orca del disco, y
4
+ // - mandar la respuesta de la persona al buzón del run con `orca orchestration send`, que Orca
5
+ // entrega en el chat del coordinador.
6
+ // Nunca pasa por una shell: `execFile` con los argumentos tal cual. Los tests lo sustituyen.
7
+
8
+ /** Un `plan.json` de `<workspace>/.work/runs/<run>/`. */
9
+ export type PlanFile = { path: string; mtimeMs: number; content: string }
10
+
11
+ export type KitSystem = {
12
+ /** Los `plan.json` de un workspace, cambiados después de `since` (ms desde epoch). */
13
+ readPlans(workspacePath: string, since: number): Promise<PlanFile[]>
14
+ /** Manda `body` al buzón del run de Orca `orcaRun`: le llega al coordinador en su chat. */
15
+ sendToRun(orcaRun: string, subject: string, body: string): Promise<void>
16
+ }
17
+
18
+ export const PLAN_FILE_MAX = 64 * 1024
19
+ // Un id de run de Orca (`run_4fbb2d2e147c`) y una carpeta de run del kit (`20261112-plugin-avisos`).
20
+ export const ORCA_RUN = /^run_[a-z0-9]{4,40}$/
21
+ const KIT_RUN = /^(?!\.+$)[\w.-]{1,80}$/
22
+ const RUNS_MAX = 50
23
+ const SEND_TIMEOUT_MS = 20_000
24
+
25
+ // Lo que falta es lo normal (no hay run, ni plan, ni esa ruta en esta plataforma); otro error sube.
26
+ const isMissing = (error: unknown) => {
27
+ const code = (error as { code?: unknown } | null)?.code
28
+ return code === 'ENOENT' || code === 'ENOTDIR'
29
+ }
30
+
31
+ /** La CLI de Orca que viene con la app que ejecuta este worker. */
32
+ async function orcaCli(): Promise<string> {
33
+ const path = await import('node:path')
34
+ const fs = await import('node:fs/promises')
35
+ const app = path.dirname(process.execPath)
36
+ const candidates =
37
+ process.platform === 'win32'
38
+ ? [path.join(app, 'resources', 'bin', 'orca.exe')]
39
+ : [path.join(app, 'resources', 'bin', 'orca'), path.join(app, '..', 'Resources', 'bin', 'orca')]
40
+ for (const file of candidates) {
41
+ try {
42
+ await fs.access(file)
43
+ return file
44
+ } catch (error) {
45
+ if (!isMissing(error)) throw error
46
+ }
47
+ }
48
+ throw Object.assign(new Error('no encuentro la CLI de Orca junto a la app'), { code: 'unavailable' })
49
+ }
50
+
51
+ /**
52
+ * El entorno de la CLI. Orca arranca el worker con un entorno mínimo (sin `APPDATA` ni `HOME`), y
53
+ * sin ellos la CLI no encuentra el runtime. Se completan desde la carpeta del usuario.
54
+ */
55
+ async function cliEnv(): Promise<Record<string, string | undefined>> {
56
+ const os = await import('node:os')
57
+ const path = await import('node:path')
58
+ const home = os.homedir()
59
+ const env: Record<string, string | undefined> = { ...process.env, HOME: process.env.HOME ?? home }
60
+ delete env.ELECTRON_RUN_AS_NODE
61
+ if (process.platform === 'win32') {
62
+ env.USERPROFILE ??= home
63
+ env.APPDATA ??= path.join(home, 'AppData', 'Roaming')
64
+ env.LOCALAPPDATA ??= path.join(home, 'AppData', 'Local')
65
+ }
66
+ return env
67
+ }
68
+
69
+ export function createNodeSystem(): KitSystem {
70
+ return {
71
+ async readPlans(workspacePath, since) {
72
+ const fs = await import('node:fs/promises')
73
+ const path = await import('node:path')
74
+ const runsDir = path.join(workspacePath, '.work', 'runs')
75
+ let runs: string[]
76
+ try {
77
+ runs = await fs.readdir(runsDir)
78
+ } catch (error) {
79
+ // Sin `.work/runs/` no hay planes: es lo normal fuera de un run del kit.
80
+ if (isMissing(error)) return []
81
+ throw error
82
+ }
83
+ const plans: PlanFile[] = []
84
+ for (const run of runs.filter((name) => KIT_RUN.test(name)).slice(-RUNS_MAX)) {
85
+ const file = path.join(runsDir, run, 'plan.json')
86
+ try {
87
+ // `lstat`: un enlace simbólico no cuenta, solo un fichero de verdad dentro del run.
88
+ const stat = await fs.lstat(file)
89
+ if (!stat.isFile() || stat.size > PLAN_FILE_MAX || stat.mtimeMs <= since) continue
90
+ plans.push({ path: file, mtimeMs: stat.mtimeMs, content: await fs.readFile(file, 'utf8') })
91
+ } catch (error) {
92
+ // Ese run no tiene plan.json (o desapareció mientras se leía).
93
+ if (!isMissing(error)) throw error
94
+ }
95
+ }
96
+ return plans
97
+ },
98
+
99
+ async sendToRun(orcaRun, subject, body) {
100
+ if (!ORCA_RUN.test(orcaRun)) throw Object.assign(new Error('id de run de Orca no válido'), { code: 'invalid_params' })
101
+ const [cp, cli, env] = await Promise.all([import('node:child_process'), orcaCli(), cliEnv()])
102
+ const handle = `run:${orcaRun}`
103
+ // `--from` el propio run: el plugin no es un terminal de Orca y la CLI pide un remitente.
104
+ const args = ['orchestration', 'send', '--from', handle, '--to', handle, '--subject', subject, '--body', body, '--json']
105
+ const stdout = await new Promise<string>((resolve, reject) => {
106
+ cp.execFile(cli, args, { timeout: SEND_TIMEOUT_MS, windowsHide: true, env, maxBuffer: 1024 * 1024 }, (error, out) =>
107
+ error && !out ? reject(error) : resolve(out)
108
+ )
109
+ })
110
+ let reply: { ok?: boolean; error?: { code?: string; message?: string } }
111
+ try {
112
+ reply = JSON.parse(stdout) as typeof reply
113
+ } catch {
114
+ throw Object.assign(new Error('la CLI de Orca no respondió en JSON'), { code: 'unavailable' })
115
+ }
116
+ if (reply.ok !== true) {
117
+ const message = `${reply.error?.code ?? 'error'}: ${String(reply.error?.message ?? '').split('\n')[0]}`
118
+ throw Object.assign(new Error(`Orca no entregó el mensaje (${message})`), { code: 'unavailable' })
119
+ }
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,177 @@
1
+ // La pestaña Worktrees en el worker: qué worktrees salen, el modelo de cada agente y los cambios.
2
+ import { afterEach, assert, mockHost, mountWorker, test, type TestWorker } from 'orca/testing'
3
+ import type { WorktreeGroup } from '../protocol.ts'
4
+ import * as main from '../worker.ts'
5
+
6
+ const workspace = (id: string, name: string, kind: 'worktree' | 'folder' = 'worktree') => ({
7
+ id,
8
+ kind,
9
+ name,
10
+ path: `/repo/${name}`,
11
+ branch: `refs/heads/feat/${name}`,
12
+ hostId: null
13
+ })
14
+
15
+ const RESULTS = {
16
+ 'workspace.readContext': { branch: 'main', displayName: 'app', terminals: [] },
17
+ 'workspace.list': {
18
+ workspaces: [
19
+ workspace('w1', 'app'),
20
+ workspace('w2', 'u1-login'),
21
+ workspace('w3', 'u2-pagos'),
22
+ workspace('w4', 'otro-run'),
23
+ workspace('w5', 'carpeta', 'folder')
24
+ ],
25
+ truncated: false
26
+ },
27
+ 'agents.list': { agents: [] },
28
+ 'workspace.open': { opened: true },
29
+ 'terminal.sendText': { accepted: true },
30
+ 'notifications.show': { delivered: true },
31
+ 'statusBar.update': { ok: true }
32
+ }
33
+
34
+ let worker: TestWorker | undefined
35
+ afterEach(async () => {
36
+ await worker?.deactivate()
37
+ worker = undefined
38
+ })
39
+
40
+ const start = async (results: Record<string, unknown> = {}) => {
41
+ worker = await mountWorker(main, { host: mockHost({ results: { ...RESULTS, ...results }, settings: {} }) })
42
+ return worker
43
+ }
44
+
45
+ const spec = (unit: string, title: string, run: string) =>
46
+ `UNIT: ${unit} — ${title} RUN: ${run} BASE: abc123\nROL: Proteo · implementación · nivel medio — una unidad cada vez`
47
+
48
+ type State = 'working' | 'blocked' | 'waiting' | 'done'
49
+ const status = (terminalId: string, workspaceId: string, state: State, receivedAt: number) => ({
50
+ workspaceId,
51
+ paneKey: `p-${terminalId}`,
52
+ terminalId,
53
+ state,
54
+ receivedAt
55
+ })
56
+ const launch = (terminalId: string, workspaceId: string, command: string, agent = 'claude') =>
57
+ ({ agent, workspaceId, workspaceKind: 'worktree', terminalId, command, env: {} }) as const
58
+
59
+ const dispatch = (w: TestWorker, terminalId: string, text: string) =>
60
+ w.hooks.fire('agent.prompt.before', { agent: 'claude', terminalId, prompt: text, inputKind: 'orchestration' })
61
+
62
+ // Dos unidades del mismo run en dos worktrees, la primera con `--model sonnet`.
63
+ const twoUnits = async (w: TestWorker) => {
64
+ await w.hooks.fire('agent.launch.before', launch('t1', 'w2', 'claude --model sonnet --permission-mode plan'))
65
+ await w.hooks.fire('agent.launch.before', launch('t2', 'w3', 'claude'))
66
+ await dispatch(w, 't1', spec('U1', 'Login', '20261112-auth'))
67
+ await dispatch(w, 't2', spec('U2', 'Pagos', '20261112-auth'))
68
+ await w.emit('agent.status.changed', status('t1', 'w2', 'working', 1))
69
+ await w.emit('agent.status.changed', status('t2', 'w3', 'waiting', 2))
70
+ }
71
+
72
+ const list = async (w: TestWorker) => ((await w.request('worktrees.list')) as { groups: WorktreeGroup[] }).groups
73
+
74
+ test('dos unidades de un run salen bajo RUN con su agente y el modelo de su orden de arranque', async () => {
75
+ const w = await start()
76
+ await twoUnits(w)
77
+ const groups = await list(w)
78
+ assert.deepEqual(groups.map((g) => g.title), ['RUN 20261112-auth'])
79
+ const [first, second] = groups[0]?.worktrees ?? []
80
+ assert.equal(first?.name, 'u1-login')
81
+ assert.equal(first?.branch, 'feat/u1-login')
82
+ assert.equal(first?.unit, 'U1 — Login')
83
+ assert.deepEqual(first?.agents, [
84
+ { id: 't:t1', agent: 'claude', title: 'U1 · Proteo — Login', state: 'trabajando', blocked: false, model: 'sonnet', canSetModel: true }
85
+ ])
86
+ assert.equal(second?.name, 'u2-pagos')
87
+ assert.equal(second?.agents[0]?.model, null)
88
+ })
89
+
90
+ test('los worktrees con agentes fuera del kit van a «Otros», tras los runs; las carpetas no salen', async () => {
91
+ const w = await start()
92
+ await twoUnits(w)
93
+ await w.emit('agent.status.changed', status('t3', 'w4', 'blocked', 3))
94
+ await w.emit('agent.status.changed', status('t4', 'w5', 'working', 4))
95
+ const groups = await list(w)
96
+ assert.deepEqual(groups.map((g) => g.title), ['RUN 20261112-auth', 'Otros worktrees con agentes'])
97
+ const others = groups[1]?.worktrees ?? []
98
+ assert.deepEqual(others.map((item) => item.name), ['otro-run'])
99
+ assert.equal(others[0]?.agents[0]?.blocked, true)
100
+ })
101
+
102
+ test('el run más reciente va primero', async () => {
103
+ const w = await start()
104
+ await w.hooks.fire('agent.launch.before', launch('t1', 'w3', 'claude'))
105
+ await w.hooks.fire('agent.launch.before', launch('t2', 'w2', 'claude'))
106
+ await dispatch(w, 't1', spec('U1', 'A', '20261101-vieja'))
107
+ await dispatch(w, 't2', spec('U2', 'B', '20261112-nueva'))
108
+ assert.deepEqual((await list(w)).map((g) => g.title), ['RUN 20261112-nueva', 'RUN 20261101-vieja'])
109
+ })
110
+
111
+ test('un chat de Orca sale en su worktree sin poder cambiar el modelo', async () => {
112
+ const w = await start()
113
+ await w.emit('agent.status.changed', {
114
+ workspaceId: 'w2',
115
+ paneKey: 'structured-agent-session-claude_abc:1',
116
+ state: 'waiting',
117
+ receivedAt: 1
118
+ })
119
+ const [agent] = (await list(w))[0]?.worktrees[0]?.agents ?? []
120
+ assert.equal(agent?.agent, 'claude')
121
+ assert.equal(agent?.canSetModel, false)
122
+ assert.equal(agent?.model, null)
123
+ await assert.rejects(w.request('worktrees.model', { id: agent?.id ?? '', model: 'opus' }), /terminal/)
124
+ assert.equal(w.host.callsOf('terminal.sendText').length, 0)
125
+ })
126
+
127
+ test('cambiar el modelo de un agente que espera manda /model e Intro a su terminal', async () => {
128
+ const w = await start()
129
+ await twoUnits(w)
130
+ const reply = await w.request('worktrees.model', { id: 't:t2', model: 'opus' })
131
+ assert.match(reply.message, /opus/)
132
+ assert.deepEqual(w.host.callsOf('terminal.sendText'), [{ terminalId: 't2', text: '/model opus', enter: true }])
133
+ assert.equal((await list(w))[0]?.worktrees[1]?.agents[0]?.model, 'opus')
134
+ assert.ok(w.posts.some((p) => p.event === 'worktrees.changed'))
135
+ })
136
+
137
+ test('trabajando o bloqueado, o con un modelo hostil, se rechaza sin enviar nada', async () => {
138
+ const w = await start()
139
+ await twoUnits(w)
140
+ await assert.rejects(w.request('worktrees.model', { id: 't:t1', model: 'opus' }), /espera a que termine su turno/)
141
+ await w.emit('agent.status.changed', status('t1', 'w2', 'blocked', 5))
142
+ await assert.rejects(w.request('worktrees.model', { id: 't:t1', model: 'opus' }), /espera a que termine su turno/)
143
+ for (const model of ['opus; rm -rf /', 'opus\nrm', '', 'Opus']) {
144
+ await assert.rejects(w.request('worktrees.model', { id: 't:t2', model }), /modelo no válido/)
145
+ }
146
+ await assert.rejects(w.request('worktrees.model', { id: 't:nadie', model: 'opus' }), /ya no está activo/)
147
+ assert.equal(w.host.callsOf('terminal.sendText').length, 0)
148
+ })
149
+
150
+ test('abrir solo vale para un worktree de la lista', async () => {
151
+ const w = await start()
152
+ await twoUnits(w)
153
+ assert.deepEqual(await w.request('worktrees.open', { workspaceId: 'w3' }), { message: 'Abierto u2-pagos.' })
154
+ assert.deepEqual(w.host.callsOf('workspace.open'), [{ workspaceId: 'w3' }])
155
+ await assert.rejects(w.request('worktrees.open', { workspaceId: 'w1' }), /ya no está en la lista/)
156
+ await assert.rejects(w.request('worktrees.open', { workspaceId: 'w5' }), /ya no está en la lista/)
157
+ assert.equal(w.host.callsOf('workspace.open').length, 1)
158
+ })
159
+
160
+ test('publica worktrees.changed solo cuando cambia y quita el workspace borrado', async () => {
161
+ const w = await start()
162
+ await twoUnits(w)
163
+ const count = () => w.posts.filter((p) => p.event === 'worktrees.changed').length
164
+ const before = count()
165
+ await w.emit('agent.status.changed', status('t2', 'w3', 'waiting', 9))
166
+ assert.equal(count(), before)
167
+ await w.emit('workspace.removed', { workspaceId: 'w3', kind: 'worktree', path: '/repo/u2-pagos' })
168
+ assert.equal(count(), before + 1)
169
+ assert.deepEqual((await list(w))[0]?.worktrees.map((item) => item.name), ['u1-login'])
170
+ })
171
+
172
+ test('si el terminal no acepta el cambio de modelo, se dice y no se apunta', async () => {
173
+ const w = await start({ 'terminal.sendText': { accepted: false } })
174
+ await twoUnits(w)
175
+ await assert.rejects(w.request('worktrees.model', { id: 't:t2', model: 'opus' }), /no aceptó/)
176
+ assert.notEqual((await list(w))[0]?.worktrees[1]?.agents[0]?.model, 'opus')
177
+ })
@@ -0,0 +1,188 @@
1
+ // Pestaña Worktrees: los worktrees que crea la orquestación, agrupados por run, con sus agentes y
2
+ // el modelo de cada uno. Cambiar el modelo escribe `/model <x>` en el terminal de un Claude Code
3
+ // que espera instrucciones.
4
+ import { canonicalWorkspaceId, groupAgents, type TrackedAgent, type UnitInfo } from '../kit.ts'
5
+ import { isModelId, modelFromCommand } from '../models.ts'
6
+ import type { WorktreeAgent, WorktreeGroup, WorktreeItem } from '../protocol.ts'
7
+ import type { KitContext } from './context.ts'
8
+
9
+ const OTHERS_TITLE = 'Otros worktrees con agentes'
10
+ // Terminales de los que se recuerda el modelo; los más antiguos se olvidan.
11
+ const MODELS_MAX = 200
12
+
13
+ const invalidParams = (message: string) => Object.assign(new Error(message), { code: 'invalid_params' })
14
+
15
+ // La unidad de un worktree: «U2 — Pagos» si es una, «U1, U2» si son varias.
16
+ function unitText(units: readonly UnitInfo[]): string | null {
17
+ const distinct = [...new Map(units.map((unit) => [unit.unit, unit])).values()]
18
+ const [only] = distinct
19
+ if (!only) return null
20
+ if (distinct.length === 1) return only.title ? `${only.unit} — ${only.title}` : only.unit
21
+ return distinct.map((unit) => unit.unit).join(', ')
22
+ }
23
+
24
+ type Found = { run: string | null; units: UnitInfo[]; agents: [string, TrackedAgent][] }
25
+
26
+ export function registerWorktrees(ctx: KitContext): void {
27
+ // Modelo de cada terminal: el de su orden de arranque o el último que se pidió desde el panel.
28
+ const models = new Map<string, string>()
29
+ // Workspaces que `workspace.list` no trajo: no se vuelve a pedir la lista por ellos.
30
+ const unknown = new Set<string>()
31
+ let posted = ''
32
+
33
+ const rememberModel = (terminalId: string, model: string | null) => {
34
+ models.delete(terminalId)
35
+ if (model === null) return
36
+ models.set(terminalId, model)
37
+ if (models.size > MODELS_MAX) {
38
+ const oldest = models.keys().next().value
39
+ if (oldest !== undefined) models.delete(oldest)
40
+ }
41
+ }
42
+
43
+ const canSetModel = (agent: TrackedAgent) => agent.agent === 'claude' && Boolean(agent.terminalId)
44
+
45
+ const build = (): WorktreeGroup[] => {
46
+ const index = ctx.workspaces()
47
+ const canonical = (id: string) => canonicalWorkspaceId(id, index)
48
+ const isWorktree = (id: string) => index.byId.get(id)?.kind === 'worktree'
49
+ const found = new Map<string, Found>()
50
+ const entry = (id: string) => {
51
+ let item = found.get(id)
52
+ if (!item) found.set(id, (item = { run: null, units: [], agents: [] }))
53
+ return item
54
+ }
55
+ const addUnit = (id: string, unit: UnitInfo) => {
56
+ const item = entry(id)
57
+ item.run ??= unit.run
58
+ item.units.push(unit)
59
+ }
60
+ for (const info of ctx.terminals.values()) {
61
+ if (!info.unit || !info.workspaceId) continue
62
+ const id = canonical(info.workspaceId)
63
+ if (isWorktree(id)) addUnit(id, info.unit)
64
+ }
65
+ for (const [key, agent] of ctx.agents) {
66
+ if (agent.state === 'done' || !agent.workspaceId) continue
67
+ const id = canonical(agent.workspaceId)
68
+ if (!isWorktree(id)) continue
69
+ if (agent.unit) addUnit(id, agent.unit)
70
+ entry(id).agents.push([key, agent])
71
+ }
72
+ const groups = new Map<string | null, WorktreeItem[]>()
73
+ for (const [workspaceId, { run, units, agents }] of found) {
74
+ const info = index.byId.get(workspaceId)
75
+ if (!info) continue
76
+ const tracked = new Map(agents)
77
+ const lines = groupAgents(agents, index.byId).flatMap((group) => group.agents)
78
+ const worktreeAgents = lines.flatMap((line): WorktreeAgent[] => {
79
+ const agent = tracked.get(line.id)
80
+ if (!agent) return []
81
+ return [
82
+ {
83
+ id: line.id,
84
+ agent: agent.agent ?? null,
85
+ title: line.title,
86
+ state: line.state,
87
+ blocked: line.blocked,
88
+ model: agent.terminalId ? (models.get(agent.terminalId) ?? null) : null,
89
+ canSetModel: canSetModel(agent)
90
+ }
91
+ ]
92
+ })
93
+ const item: WorktreeItem = {
94
+ workspaceId,
95
+ name: info.name,
96
+ branch: info.branch,
97
+ unit: unitText(units),
98
+ agents: worktreeAgents
99
+ }
100
+ groups.set(run, [...(groups.get(run) ?? []), item])
101
+ }
102
+ const byName = (a: WorktreeItem, b: WorktreeItem) => a.name.localeCompare(b.name, 'es')
103
+ // Los ids de run empiezan por la fecha: el más reciente es el mayor.
104
+ const runs = [...groups.keys()].filter((run): run is string => run !== null).sort((a, b) => b.localeCompare(a))
105
+ const result: WorktreeGroup[] = runs.map((run) => ({
106
+ run,
107
+ title: `RUN ${run}`,
108
+ worktrees: (groups.get(run) ?? []).sort(byName)
109
+ }))
110
+ const others = groups.get(null)
111
+ if (others) result.push({ run: null, title: OTHERS_TITLE, worktrees: others.sort(byName) })
112
+ return result
113
+ }
114
+
115
+ // Los workspaces de agentes que `workspace.list` no conoce: se pide la lista una vez por id.
116
+ const learnMissing = () => {
117
+ const index = ctx.workspaces()
118
+ const missing = [...ctx.agents.values()].flatMap(({ workspaceId }) =>
119
+ workspaceId && !index.byId.has(canonicalWorkspaceId(workspaceId, index)) && !unknown.has(workspaceId)
120
+ ? [workspaceId]
121
+ : []
122
+ )
123
+ if (missing.length === 0) return
124
+ for (const id of missing) unknown.add(id)
125
+ void ctx.refreshWorkspaces().then(publish)
126
+ }
127
+
128
+ // Los paneles abiertos reciben los worktrees solo cuando cambian: los eventos llegan a ráfagas.
129
+ function publish(): void {
130
+ const groups = build()
131
+ const serialized = JSON.stringify(groups)
132
+ if (serialized !== posted) {
133
+ posted = serialized
134
+ ctx.panels.post('worktrees.changed', { groups })
135
+ }
136
+ learnMissing()
137
+ }
138
+
139
+ ctx.on('agent', publish)
140
+ ctx.on('dispatch', publish)
141
+ ctx.on('workspaceRemoved', publish)
142
+ ctx.on('launch', ({ terminalId, agent, command }) => {
143
+ if (agent === 'claude') rememberModel(terminalId, modelFromCommand(command))
144
+ publish()
145
+ })
146
+
147
+ ctx.panels.handle('worktrees.list', () => ({ groups: build() }))
148
+
149
+ ctx.panels.handle('worktrees.open', async (input) => {
150
+ const workspaceId: unknown = input?.workspaceId
151
+ const listed = build()
152
+ .flatMap((group) => group.worktrees)
153
+ .find((item) => item.workspaceId === workspaceId)
154
+ if (!listed) throw invalidParams('ese worktree ya no está en la lista')
155
+ await ctx.host.call('workspace.open', { workspaceId: listed.workspaceId })
156
+ return { message: `Abierto ${listed.name}.` }
157
+ })
158
+
159
+ ctx.panels.handle('worktrees.model', async (input) => {
160
+ const id: unknown = input?.id
161
+ const model: unknown = input?.model
162
+ const agent = typeof id === 'string' ? ctx.agents.get(id) : undefined
163
+ if (typeof id !== 'string' || !agent || agent.state === 'done') throw invalidParams('ese agente ya no está activo')
164
+ const terminalId = agent.terminalId
165
+ if (!canSetModel(agent) || !terminalId) {
166
+ throw invalidParams('solo se puede cambiar el modelo de un Claude Code con terminal')
167
+ }
168
+ // En `working` o `blocked` el texto acabaría en su turno o en un diálogo de permiso.
169
+ if (agent.state !== 'waiting') throw invalidParams('espera a que termine su turno')
170
+ if (!isModelId(model)) throw invalidParams('modelo no válido')
171
+ const title = groupAgents([[id, agent]], ctx.workspaces().byId)[0]?.agents[0]?.title ?? 'agente'
172
+ const { accepted } = await ctx.host.call('terminal.sendText', { terminalId, text: `/model ${model}`, enter: true })
173
+ if (!accepted) {
174
+ throw Object.assign(new Error('el terminal no aceptó el cambio: puede que ya se haya cerrado'), { code: 'unavailable' })
175
+ }
176
+ rememberModel(terminalId, model)
177
+ ctx.emit('action', {
178
+ kind: 'model',
179
+ title: `Modelo de ${title} → ${model}`,
180
+ detail: null,
181
+ agentKey: id,
182
+ run: agent.unit?.run ?? null,
183
+ at: Date.now()
184
+ })
185
+ publish()
186
+ return { message: `Pedido a ${title} el modelo ${model}.` }
187
+ })
188
+ }