@ngockhoale/ckit 0.0.0-stage → 0.1.1

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 (246) hide show
  1. package/.env.example +21 -0
  2. package/README.md +70 -2
  3. package/dist/src/adapters/agent/claude/errors.d.ts +13 -0
  4. package/dist/src/adapters/agent/claude/errors.js +16 -0
  5. package/dist/src/adapters/agent/claude/normalize.d.ts +11 -0
  6. package/dist/src/adapters/agent/claude/normalize.js +83 -0
  7. package/dist/src/adapters/agent/errors.d.ts +13 -0
  8. package/dist/src/adapters/agent/errors.js +19 -0
  9. package/dist/src/adapters/agent/fixtures/claude-transcript.d.ts +70 -0
  10. package/dist/src/adapters/agent/fixtures/claude-transcript.js +15 -0
  11. package/dist/src/adapters/agent/fixtures/omp-transcript.d.ts +60 -0
  12. package/dist/src/adapters/agent/fixtures/omp-transcript.js +14 -0
  13. package/dist/src/adapters/agent/normalize.d.ts +18 -0
  14. package/dist/src/adapters/agent/normalize.js +77 -0
  15. package/dist/src/adapters/agent/transport.d.ts +35 -0
  16. package/dist/src/adapters/agent/transport.js +39 -0
  17. package/dist/src/adapters/agent/worker-service.d.ts +49 -0
  18. package/dist/src/adapters/agent/worker-service.js +77 -0
  19. package/dist/src/adapters/fake/fake-advisor.d.ts +15 -0
  20. package/dist/src/adapters/fake/fake-advisor.js +29 -0
  21. package/dist/src/adapters/fake/fake-agent.d.ts +12 -0
  22. package/dist/src/adapters/fake/fake-agent.js +21 -0
  23. package/dist/src/adapters/fake/fake-store.d.ts +13 -0
  24. package/dist/src/adapters/fake/fake-store.js +23 -0
  25. package/dist/src/adapters/fake/fake-web.d.ts +12 -0
  26. package/dist/src/adapters/fake/fake-web.js +21 -0
  27. package/dist/src/adapters/fake/fault-injector.d.ts +18 -0
  28. package/dist/src/adapters/fake/fault-injector.js +64 -0
  29. package/dist/src/adapters/fake/virtual-clock.d.ts +12 -0
  30. package/dist/src/adapters/fake/virtual-clock.js +35 -0
  31. package/dist/src/adapters/launch/discover.d.ts +18 -0
  32. package/dist/src/adapters/launch/discover.js +55 -0
  33. package/dist/src/adapters/launch/executor.d.ts +117 -0
  34. package/dist/src/adapters/launch/executor.js +383 -0
  35. package/dist/src/adapters/launch/profile.d.ts +35 -0
  36. package/dist/src/adapters/launch/profile.js +73 -0
  37. package/dist/src/adapters/launch/spawn.d.ts +29 -0
  38. package/dist/src/adapters/launch/spawn.js +18 -0
  39. package/dist/src/adapters/openai/openai-advisor.d.ts +56 -0
  40. package/dist/src/adapters/openai/openai-advisor.js +146 -0
  41. package/dist/src/cli/ckit.d.ts +5 -0
  42. package/dist/src/cli/ckit.js +384 -0
  43. package/dist/src/cli/demo.d.ts +1 -0
  44. package/dist/src/cli/demo.js +30 -0
  45. package/dist/src/cli/lifecycle.d.ts +19 -0
  46. package/dist/src/cli/lifecycle.js +90 -0
  47. package/dist/src/cli/sessions.d.ts +10 -0
  48. package/dist/src/cli/sessions.js +381 -0
  49. package/dist/src/cli/setup.d.ts +11 -0
  50. package/dist/src/cli/setup.js +115 -0
  51. package/dist/src/committee/decision.d.ts +84 -0
  52. package/dist/src/committee/decision.js +167 -0
  53. package/dist/src/committee/handover.d.ts +115 -0
  54. package/dist/src/committee/handover.js +191 -0
  55. package/dist/src/committee/no-progress.d.ts +44 -0
  56. package/dist/src/committee/no-progress.js +64 -0
  57. package/dist/src/committee/primary-registry.d.ts +15 -0
  58. package/dist/src/committee/primary-registry.js +60 -0
  59. package/dist/src/committee/reply-parser.d.ts +28 -0
  60. package/dist/src/committee/reply-parser.js +53 -0
  61. package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
  62. package/dist/src/committee/reviewer-scheduler.js +163 -0
  63. package/dist/src/committee/role-epoch.d.ts +91 -0
  64. package/dist/src/committee/role-epoch.js +154 -0
  65. package/dist/src/core/control.d.ts +18 -0
  66. package/dist/src/core/control.js +29 -0
  67. package/dist/src/core/entities.d.ts +166 -0
  68. package/dist/src/core/entities.js +119 -0
  69. package/dist/src/core/errors.d.ts +9 -0
  70. package/dist/src/core/errors.js +17 -0
  71. package/dist/src/core/events.d.ts +72 -0
  72. package/dist/src/core/events.js +125 -0
  73. package/dist/src/core/ids.d.ts +47 -0
  74. package/dist/src/core/ids.js +32 -0
  75. package/dist/src/core/machine.d.ts +55 -0
  76. package/dist/src/core/machine.js +110 -0
  77. package/dist/src/core/policy.d.ts +34 -0
  78. package/dist/src/core/policy.js +59 -0
  79. package/dist/src/core/provenance.d.ts +20 -0
  80. package/dist/src/core/provenance.js +21 -0
  81. package/dist/src/core/record.d.ts +35 -0
  82. package/dist/src/core/record.js +67 -0
  83. package/dist/src/core/replay.d.ts +10 -0
  84. package/dist/src/core/replay.js +36 -0
  85. package/dist/src/core/run-task.d.ts +20 -0
  86. package/dist/src/core/run-task.js +48 -0
  87. package/dist/src/diagnostics/doctor.d.ts +78 -0
  88. package/dist/src/diagnostics/doctor.js +365 -0
  89. package/dist/src/diagnostics/journal-lock.d.ts +38 -0
  90. package/dist/src/diagnostics/journal-lock.js +181 -0
  91. package/dist/src/evidence/linker.d.ts +44 -0
  92. package/dist/src/evidence/linker.js +75 -0
  93. package/dist/src/evidence/report-parser.d.ts +27 -0
  94. package/dist/src/evidence/report-parser.js +17 -0
  95. package/dist/src/evidence/store.d.ts +36 -0
  96. package/dist/src/evidence/store.js +57 -0
  97. package/dist/src/gui/server.d.ts +27 -0
  98. package/dist/src/gui/server.js +497 -0
  99. package/dist/src/host/checkpoint.d.ts +22 -0
  100. package/dist/src/host/checkpoint.js +74 -0
  101. package/dist/src/host/export.d.ts +52 -0
  102. package/dist/src/host/export.js +45 -0
  103. package/dist/src/host/ipc.d.ts +57 -0
  104. package/dist/src/host/ipc.js +124 -0
  105. package/dist/src/host/leases.d.ts +27 -0
  106. package/dist/src/host/leases.js +40 -0
  107. package/dist/src/host/retention.d.ts +47 -0
  108. package/dist/src/host/retention.js +130 -0
  109. package/dist/src/host/supervisor.d.ts +59 -0
  110. package/dist/src/host/supervisor.js +64 -0
  111. package/dist/src/intake/owner-intake.d.ts +31 -0
  112. package/dist/src/intake/owner-intake.js +97 -0
  113. package/dist/src/intake/types.d.ts +46 -0
  114. package/dist/src/intake/types.js +2 -0
  115. package/dist/src/intent/context-packet.d.ts +68 -0
  116. package/dist/src/intent/context-packet.js +76 -0
  117. package/dist/src/intent/idea-ledger.d.ts +50 -0
  118. package/dist/src/intent/idea-ledger.js +136 -0
  119. package/dist/src/intent/ledger.d.ts +35 -0
  120. package/dist/src/intent/ledger.js +40 -0
  121. package/dist/src/intent/registry.d.ts +51 -0
  122. package/dist/src/intent/registry.js +44 -0
  123. package/dist/src/intent/revision.d.ts +37 -0
  124. package/dist/src/intent/revision.js +48 -0
  125. package/dist/src/orchestration/dispatcher.d.ts +32 -0
  126. package/dist/src/orchestration/dispatcher.js +136 -0
  127. package/dist/src/orchestration/milestone-loop.d.ts +149 -0
  128. package/dist/src/orchestration/milestone-loop.js +132 -0
  129. package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
  130. package/dist/src/orchestration/recovery-coordinator.js +180 -0
  131. package/dist/src/orchestration/work-order-contract.d.ts +44 -0
  132. package/dist/src/orchestration/work-order-contract.js +85 -0
  133. package/dist/src/orchestration/work-queue.d.ts +56 -0
  134. package/dist/src/orchestration/work-queue.js +95 -0
  135. package/dist/src/ports/advisor.d.ts +33 -0
  136. package/dist/src/ports/advisor.js +2 -0
  137. package/dist/src/ports/agent.d.ts +31 -0
  138. package/dist/src/ports/agent.js +2 -0
  139. package/dist/src/ports/capabilities.d.ts +3 -0
  140. package/dist/src/ports/capabilities.js +5 -0
  141. package/dist/src/ports/clock.d.ts +5 -0
  142. package/dist/src/ports/clock.js +5 -0
  143. package/dist/src/ports/store.d.ts +13 -0
  144. package/dist/src/ports/store.js +2 -0
  145. package/dist/src/ports/web.d.ts +29 -0
  146. package/dist/src/ports/web.js +2 -0
  147. package/dist/src/run/api-run.d.ts +49 -0
  148. package/dist/src/run/api-run.js +173 -0
  149. package/dist/src/run/plan-run.d.ts +22 -0
  150. package/dist/src/run/plan-run.js +233 -0
  151. package/dist/src/run/plan.d.ts +36 -0
  152. package/dist/src/run/plan.js +119 -0
  153. package/dist/src/run/verify.d.ts +25 -0
  154. package/dist/src/run/verify.js +81 -0
  155. package/dist/src/security/redact.d.ts +7 -0
  156. package/dist/src/security/redact.js +21 -0
  157. package/dist/src/settings/env-config.d.ts +64 -0
  158. package/dist/src/settings/env-config.js +232 -0
  159. package/dist/src/storage/artifacts.d.ts +30 -0
  160. package/dist/src/storage/artifacts.js +105 -0
  161. package/dist/src/storage/audit.d.ts +6 -0
  162. package/dist/src/storage/audit.js +6 -0
  163. package/dist/src/storage/db.d.ts +9 -0
  164. package/dist/src/storage/db.js +43 -0
  165. package/dist/src/storage/events.d.ts +20 -0
  166. package/dist/src/storage/events.js +69 -0
  167. package/dist/src/storage/migrations.d.ts +8 -0
  168. package/dist/src/storage/migrations.js +48 -0
  169. package/dist/src/storage/outbox.d.ts +25 -0
  170. package/dist/src/storage/outbox.js +40 -0
  171. package/dist/src/storage/projections.d.ts +18 -0
  172. package/dist/src/storage/projections.js +40 -0
  173. package/dist/src/storage/reconcile.d.ts +14 -0
  174. package/dist/src/storage/reconcile.js +93 -0
  175. package/dist/src/storage/reservations.d.ts +12 -0
  176. package/dist/src/storage/reservations.js +80 -0
  177. package/dist/src/storage/store.d.ts +34 -0
  178. package/dist/src/storage/store.js +105 -0
  179. package/dist/src/team/attachments.d.ts +22 -0
  180. package/dist/src/team/attachments.js +211 -0
  181. package/dist/src/team/cli-models.d.ts +24 -0
  182. package/dist/src/team/cli-models.js +72 -0
  183. package/dist/src/team/config.d.ts +20 -0
  184. package/dist/src/team/config.js +113 -0
  185. package/dist/src/team/engine.d.ts +28 -0
  186. package/dist/src/team/engine.js +443 -0
  187. package/dist/src/team/journal.d.ts +30 -0
  188. package/dist/src/team/journal.js +70 -0
  189. package/dist/src/team/runners.d.ts +79 -0
  190. package/dist/src/team/runners.js +436 -0
  191. package/dist/src/team/secrets.d.ts +10 -0
  192. package/dist/src/team/secrets.js +68 -0
  193. package/dist/src/team/types.d.ts +157 -0
  194. package/dist/src/team/types.js +5 -0
  195. package/dist/src/tui/app.d.ts +29 -0
  196. package/dist/src/tui/app.js +96 -0
  197. package/dist/src/tui/control-model.d.ts +101 -0
  198. package/dist/src/tui/control-model.js +109 -0
  199. package/dist/src/tui/control-screens.d.ts +27 -0
  200. package/dist/src/tui/control-screens.js +85 -0
  201. package/dist/src/tui/graph-model.d.ts +34 -0
  202. package/dist/src/tui/graph-model.js +29 -0
  203. package/dist/src/tui/graph-screens.d.ts +13 -0
  204. package/dist/src/tui/graph-screens.js +4 -0
  205. package/dist/src/tui/inspector-model.d.ts +150 -0
  206. package/dist/src/tui/inspector-model.js +15 -0
  207. package/dist/src/tui/inspector-screens.d.ts +14 -0
  208. package/dist/src/tui/inspector-screens.js +61 -0
  209. package/dist/src/tui/live.d.ts +16 -0
  210. package/dist/src/tui/live.js +39 -0
  211. package/dist/src/tui/mission-action-screens.d.ts +15 -0
  212. package/dist/src/tui/mission-action-screens.js +105 -0
  213. package/dist/src/tui/mission-actions.d.ts +46 -0
  214. package/dist/src/tui/mission-actions.js +53 -0
  215. package/dist/src/tui/mission-model.d.ts +120 -0
  216. package/dist/src/tui/mission-model.js +164 -0
  217. package/dist/src/tui/mission-nav.d.ts +82 -0
  218. package/dist/src/tui/mission-nav.js +131 -0
  219. package/dist/src/tui/mission-plan-screens.d.ts +11 -0
  220. package/dist/src/tui/mission-plan-screens.js +40 -0
  221. package/dist/src/tui/mission-plan.d.ts +45 -0
  222. package/dist/src/tui/mission-plan.js +166 -0
  223. package/dist/src/tui/mission-screens.d.ts +7 -0
  224. package/dist/src/tui/mission-screens.js +263 -0
  225. package/dist/src/tui/provenance-label.d.ts +11 -0
  226. package/dist/src/tui/provenance-label.js +16 -0
  227. package/dist/src/tui/screens.d.ts +10 -0
  228. package/dist/src/tui/screens.js +34 -0
  229. package/dist/src/tui/session-outcome.d.ts +14 -0
  230. package/dist/src/tui/session-outcome.js +57 -0
  231. package/dist/src/tui/setup-model.d.ts +159 -0
  232. package/dist/src/tui/setup-model.js +234 -0
  233. package/dist/src/tui/setup-screens.d.ts +66 -0
  234. package/dist/src/tui/setup-screens.js +72 -0
  235. package/dist/src/tui/team/app.d.ts +24 -0
  236. package/dist/src/tui/team/app.js +228 -0
  237. package/dist/src/tui/team/demo-handle.d.ts +22 -0
  238. package/dist/src/tui/team/demo-handle.js +42 -0
  239. package/dist/src/tui/team/model.d.ts +81 -0
  240. package/dist/src/tui/team/model.js +133 -0
  241. package/gui/app.css +177 -0
  242. package/gui/app.js +677 -0
  243. package/gui/index.html +51 -0
  244. package/gui/network.js +413 -0
  245. package/package.json +44 -4
  246. package/src/storage/schema.sql +42 -0
@@ -0,0 +1,228 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Agent Company live TUI: header, stage pipeline, team cards, conversation feed, chat box to the Director.
3
+ // Presentation only: subscribes to a TeamRunHandle, no network, no file writes, no child processes.
4
+ import React, { useEffect, useMemo, useReducer, useState } from 'react';
5
+ import { Box, Text, useInput, useWindowSize } from 'ink';
6
+ import { STAGES } from '../../team/types.js';
7
+ import { STAGE_LABEL, TEAM_LABEL, activeAgentCount, activeTeam, formatClock, formatDuration, formatTokens, initialTeamView, reduceTeam, sanitize, stageDuration, stageIndex } from './model.js';
8
+ /** Text that tolerates explicit undefined props (exactOptionalPropertyTypes). */
9
+ function Tx({ color, bold, dimColor, inverse, wrap, children }) {
10
+ return _jsx(Text, { ...(color ? { color } : {}), ...(wrap ? { wrap } : {}), bold: bold === true, dimColor: dimColor === true, inverse: inverse === true, children: children });
11
+ }
12
+ const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
13
+ const TEAM_COLOR = { director: 'magenta', ba: 'cyan', implement: 'yellow', qc: 'green' };
14
+ const TEAM_ORDER = ['director', 'ba', 'implement', 'qc'];
15
+ const MAX_BODY_LINES = 6;
16
+ function wrap(text, width) {
17
+ const out = [];
18
+ for (const raw of text.split('\n')) {
19
+ let line = '';
20
+ for (const word of raw.split(/ +/)) {
21
+ let w = word;
22
+ while ([...w].length > width) {
23
+ if (line) {
24
+ out.push(line);
25
+ line = '';
26
+ }
27
+ const cp = [...w];
28
+ out.push(cp.slice(0, width).join(''));
29
+ w = cp.slice(width).join('');
30
+ }
31
+ if (!w)
32
+ continue;
33
+ if (!line)
34
+ line = w;
35
+ else if ([...line].length + 1 + [...w].length <= width)
36
+ line += ` ${w}`;
37
+ else {
38
+ out.push(line);
39
+ line = w;
40
+ }
41
+ }
42
+ out.push(line);
43
+ }
44
+ while (out.length > 0 && out.at(-1) === '')
45
+ out.pop();
46
+ return out;
47
+ }
48
+ const clockOf = (at) => new Date(at).toTimeString().slice(0, 8);
49
+ export function buildFeedLines(feed, names, width, showActivity) {
50
+ const lines = [];
51
+ const nameOf = (id) => names.get(id) ?? sanitize(id);
52
+ const target = (to) => (to === 'all' ? 'All' : to === 'director' ? 'Director' : to in TEAM_LABEL ? `Team ${TEAM_LABEL[to]}` : nameOf(to));
53
+ const bodyWidth = Math.max(10, width - 2);
54
+ for (const m of feed) {
55
+ const k = `m${m.id}`;
56
+ const color = m.fromTeam ? TEAM_COLOR[m.fromTeam] : undefined;
57
+ if (m.kind === 'activity') {
58
+ if (showActivity)
59
+ lines.push({ key: k, parts: [{ text: ` ⋯ ${nameOf(m.from)}: ${m.text}`, dim: true }] });
60
+ continue;
61
+ }
62
+ if (m.kind === 'system') {
63
+ lines.push({ key: k, parts: [{ text: `── ${m.text} ──`, color: m.tone === 'bad' ? 'red' : m.tone === 'pass' ? 'green' : undefined, dim: m.tone === undefined }] });
64
+ continue;
65
+ }
66
+ if (m.kind === 'handoff') {
67
+ lines.push({ key: `${k}s`, parts: [{ text: ' ' }] });
68
+ lines.push({ key: k, parts: [{ text: `📦 HANDOFF ${TEAM_LABEL[m.fromTeam ?? 'director'].toUpperCase()} → ${(m.to in TEAM_LABEL ? TEAM_LABEL[m.to] : m.to).toUpperCase()}: ${m.text}`, bold: true, color: m.to in TEAM_COLOR ? TEAM_COLOR[m.to] : 'white', inverse: true }] });
69
+ lines.push({ key: `${k}e`, parts: [{ text: ' ' }] });
70
+ continue;
71
+ }
72
+ if (m.kind === 'verdict') {
73
+ const pass = m.tone === 'pass';
74
+ lines.push({ key: `${k}s`, parts: [{ text: ' ' }] });
75
+ lines.push({ key: k, parts: [{ text: pass ? ' ✔ QC VERDICT: PASS ' : ' ✖ QC VERDICT: FAIL ', bold: true, inverse: true, color: pass ? 'green' : 'red' }] });
76
+ for (const [i, l] of wrap(m.text, bodyWidth).slice(0, MAX_BODY_LINES).entries())
77
+ lines.push({ key: `${k}b${i}`, parts: [{ text: ` ${l}`, color: pass ? 'green' : 'red' }] });
78
+ lines.push({ key: `${k}e`, parts: [{ text: ' ' }] });
79
+ continue;
80
+ }
81
+ const isUser = m.kind === 'user';
82
+ const head = isUser
83
+ ? [{ text: 'YOU → Director', bold: true, color: 'white', inverse: true }]
84
+ : [{ text: `${nameOf(m.from)}${m.fromTeam ? ` (${TEAM_LABEL[m.fromTeam]})` : ''}`, bold: true, color }, { text: ` → ${target(m.to)}`, color, dim: m.kind !== 'director' }];
85
+ head.push({ text: ` ${clockOf(m.at)}`, dim: true });
86
+ lines.push({ key: k, parts: head });
87
+ const body = wrap(m.text, bodyWidth);
88
+ const shown = body.slice(0, MAX_BODY_LINES);
89
+ if (body.length > MAX_BODY_LINES)
90
+ shown[MAX_BODY_LINES - 1] = `${[...(shown[MAX_BODY_LINES - 1] ?? '')].slice(0, Math.max(1, bodyWidth - 1)).join('')}…`;
91
+ for (const [i, l] of shown.entries())
92
+ lines.push({ key: `${k}b${i}`, parts: [{ text: ` ${l}`, color: m.kind === 'director' ? 'magenta' : isUser ? 'white' : undefined }] });
93
+ lines.push({ key: `${k}e`, parts: [{ text: ' ' }] });
94
+ }
95
+ return lines;
96
+ }
97
+ function Header({ state, width, tick, nowMs }) {
98
+ const elapsed = state.startedAt === null ? 0 : (state.endedAt ?? nowMs) - state.startedAt;
99
+ const badge = state.outcome === null ? 'LIVE' : state.endedAt !== null && nowMs - state.endedAt > 300000 ? 'REPLAY' : 'DONE';
100
+ const badgeColor = badge === 'LIVE' ? 'red' : badge === 'REPLAY' ? 'yellow' : state.outcome === 'delivered' ? 'green' : 'red';
101
+ const dot = badge === 'LIVE' ? (tick % 8 < 4 ? '●' : '○') : '■';
102
+ return (_jsxs(Box, { width: width, height: 1, paddingX: 1, children: [_jsx(Tx, { bold: true, color: "magenta", children: "\u25C6 CKIT \u00B7 AGENT COMPANY" }), _jsx(Tx, { dimColor: true, children: " \u2502 " }), _jsx(Box, { flexGrow: 1, flexShrink: 1, children: _jsx(Tx, { wrap: "truncate-end", bold: true, children: state.goal }) }), _jsxs(Tx, { dimColor: true, children: [state.runId ?? '', state.simulated ? ' · sim' : '', " "] }), _jsxs(Tx, { bold: true, color: "cyan", children: ["\u23F1 ", formatClock(elapsed), " "] }), _jsxs(Tx, { bold: true, color: badgeColor, children: [dot, " ", badge] })] }));
103
+ }
104
+ function Pipeline({ state, width, tick, nowMs }) {
105
+ const cur = stageIndex(state.stage);
106
+ const max = state.config?.limits.qcLoops ?? 0;
107
+ const looping = state.loop > 0 && (state.loop > 1 || state.verdicts.some(v => v.verdict === 'FAIL'));
108
+ const pulse = tick % 8 < 4;
109
+ return (_jsxs(Box, { width: width, borderStyle: "round", borderColor: state.outcome === null ? 'blue' : state.outcome === 'delivered' ? 'green' : 'red', paddingX: 1, height: 3, children: [STAGES.map((st, i) => {
110
+ const done = state.outcome === 'delivered' || i < cur;
111
+ const dur = stageDuration(state, st);
112
+ const sep = i > 0 ? _jsx(Tx, { dimColor: true, children: " \u25B8 " }) : null;
113
+ let label;
114
+ if (done)
115
+ label = _jsxs(Tx, { color: "green", children: ["\u2714 ", STAGE_LABEL[st], dur !== null ? ` ${formatDuration(dur)}` : ''] });
116
+ else if (i === cur && state.outcome === null) {
117
+ const span = state.stageHistory.at(-1);
118
+ const t = span ? ` ${formatDuration(nowMs - span.startedAt)}` : '';
119
+ label = _jsxs(Tx, { bold: true, inverse: true, color: pulse ? 'cyan' : 'blue', children: [" ", SPINNER[tick % SPINNER.length], " ", STAGE_LABEL[st], t, " "] });
120
+ }
121
+ else if (i === cur)
122
+ label = _jsxs(Tx, { color: "red", children: ["\u2716 ", STAGE_LABEL[st]] });
123
+ else
124
+ label = _jsx(Tx, { dimColor: true, children: STAGE_LABEL[st] });
125
+ return _jsxs(React.Fragment, { children: [sep, label] }, st);
126
+ }), looping ? _jsxs(Tx, { bold: true, color: "yellow", children: [" \u21BB QC loop ", state.loop, "/", max > 0 ? Math.max(max, state.loop) : state.loop] }) : null] }));
127
+ }
128
+ const STATE_ICON = {
129
+ idle: { icon: '·', dim: true }, thinking: { icon: '●' }, done: { icon: '✔', color: 'green' }, failed: { icon: '✖', color: 'red' }, waiting: { icon: '◌', color: 'yellow' },
130
+ };
131
+ function AgentRow({ agent, width, compact, tick, nowMs }) {
132
+ const color = TEAM_COLOR[agent.team];
133
+ const thinking = agent.state === 'thinking';
134
+ const pulse = tick % 8 < 4;
135
+ const ic = STATE_ICON[agent.state];
136
+ const timer = thinking && agent.turnStartedAt !== null ? `${formatDuration(nowMs - agent.turnStartedAt)} ` : '';
137
+ const tok = agent.tokens > 0 ? `${formatTokens(agent.tokens)}t` : '';
138
+ const badge = `${agent.cli}${agent.model ? ` · ${agent.model}` : ''}`;
139
+ return (_jsxs(Box, { flexDirection: "column", width: width, children: [_jsxs(Box, { width: width, children: [_jsx(Box, { flexGrow: 1, flexShrink: 1, children: _jsxs(Tx, { wrap: "truncate-end", children: [thinking ? _jsxs(Tx, { color: color, bold: true, children: [SPINNER[tick % SPINNER.length], " "] }) : null, thinking ? _jsx(Tx, { color: pulse ? color : undefined, dimColor: !pulse, children: "\u25CF " }) : _jsxs(Tx, { color: ic.color, dimColor: ic.dim, children: [ic.icon, " "] }), _jsx(Tx, { bold: thinking || agent.state === 'done', color: thinking ? color : undefined, dimColor: agent.state === 'idle', children: agent.name }), _jsxs(Tx, { dimColor: true, children: [" [", badge, "]"] })] }) }), _jsxs(Tx, { color: thinking ? 'cyan' : undefined, dimColor: !thinking, children: [timer, tok, agent.turns > 0 ? ` ×${agent.turns}` : ''] })] }), compact ? null : _jsx(Tx, { wrap: "truncate-end", dimColor: true, children: ` ${agent.lastActivity}` })] }));
140
+ }
141
+ function TeamCard({ team, agents, width, active, compact, tick, nowMs }) {
142
+ const color = TEAM_COLOR[team];
143
+ const title = team === 'director' ? 'DIRECTOR' : `TEAM ${TEAM_LABEL[team].toUpperCase()}`;
144
+ const h = 3 + agents.length * (compact ? 1 : 2);
145
+ return (_jsxs(Box, { flexDirection: "column", width: width, height: h, borderStyle: active ? 'bold' : 'round', borderColor: color, borderDimColor: !active, paddingX: 1, overflow: "hidden", children: [_jsxs(Tx, { bold: true, color: color, dimColor: !active, children: [active ? '▶ ' : ' ', title, active ? _jsxs(Tx, { color: color, children: [" ", tick % 8 < 4 ? '◀' : ' '] }) : null] }), agents.map(a => _jsx(AgentRow, { agent: a, width: width - 4, compact: compact, tick: tick, nowMs: nowMs }, a.id))] }));
146
+ }
147
+ function Feed({ lines, width, height, scroll, showActivity }) {
148
+ const rows = Math.max(1, height - 3);
149
+ const end = lines.length - scroll, start = Math.max(0, end - rows);
150
+ const slice = lines.slice(start, Math.max(start, end));
151
+ return (_jsxs(Box, { flexDirection: "column", width: width, height: height, borderStyle: "round", borderColor: "blue", paddingX: 1, overflow: "hidden", children: [_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Tx, { bold: true, color: "blue", children: "CONVERSATION" }), _jsxs(Tx, { dimColor: true, children: [scroll > 0 ? `↓ ${scroll} newer lines · ` : '', "activity ", showActivity ? 'on' : 'off'] })] }), slice.map(l => (_jsx(Tx, { wrap: "truncate-end", children: l.parts.map((p, i) => _jsx(Tx, { ...(p.color ? { color: p.color } : {}), bold: p.bold === true, dimColor: p.dim === true, inverse: p.inverse === true, children: p.text }, i)) }, l.key)))] }));
152
+ }
153
+ export function TeamApp({ handle, goal, onQuit, tickMs = 120, now = () => new Date() }) {
154
+ const { columns, rows } = useWindowSize();
155
+ const W = Math.max(60, columns || 100), H = Math.max(18, rows || 30);
156
+ const [state, dispatch] = useReducer(reduceTeam, undefined, initialTeamView);
157
+ const [tick, setTick] = useState(0);
158
+ const [nowMs, setNowMs] = useState(() => now().getTime());
159
+ const [typed, setTyped] = useState('');
160
+ const [scroll, setScroll] = useState(0);
161
+ const [showActivity, setShowActivity] = useState(false);
162
+ useEffect(() => handle.subscribe(e => dispatch(e)), [handle]);
163
+ useEffect(() => {
164
+ const t = setInterval(() => { setTick(x => x + 1); setNowMs(now().getTime()); }, tickMs);
165
+ return () => clearInterval(t);
166
+ }, [tickMs, now]);
167
+ useInput((input, key) => {
168
+ if (key.escape || (key.ctrl && input === 'c')) {
169
+ onQuit();
170
+ return;
171
+ }
172
+ if (key.return) {
173
+ const text = typed.trim();
174
+ if (text) {
175
+ handle.sendToDirector(text);
176
+ setScroll(0);
177
+ }
178
+ setTyped('');
179
+ return;
180
+ }
181
+ if (key.backspace || key.delete) {
182
+ setTyped(t => [...t].slice(0, -1).join(''));
183
+ return;
184
+ }
185
+ if (key.upArrow) {
186
+ setScroll(s => s + 1);
187
+ return;
188
+ }
189
+ if (key.downArrow) {
190
+ setScroll(s => Math.max(0, s - 1));
191
+ return;
192
+ }
193
+ if (key.pageUp) {
194
+ setScroll(s => s + 8);
195
+ return;
196
+ }
197
+ if (key.pageDown) {
198
+ setScroll(s => Math.max(0, s - 8));
199
+ return;
200
+ }
201
+ if (key.tab) {
202
+ setShowActivity(v => !v);
203
+ return;
204
+ }
205
+ if (key.ctrl || key.meta)
206
+ return;
207
+ const clean = sanitize(input).replace(/\n/g, ' ');
208
+ if (clean)
209
+ setTyped(t => (t + clean).slice(0, 500));
210
+ });
211
+ const names = useMemo(() => new Map(state.agents.map(a => [a.id, a.name])), [state.config]); // eslint-disable-line react-hooks/exhaustive-deps
212
+ const leftW = W >= 140 ? 56 : Math.max(40, Math.floor(W * 0.42));
213
+ const rightW = W - leftW;
214
+ const feedLines = useMemo(() => buildFeedLines(state.feed, names, rightW - 4, showActivity), [state.feed, names, rightW, showActivity]);
215
+ const outcomeLine = state.outcome === null ? 0 : 1;
216
+ const footerH = 2 + outcomeLine;
217
+ const mainH = Math.max(8, H - 1 - 3 - footerH);
218
+ const chatH = 3;
219
+ const byTeam = (t) => state.agents.filter(a => a.team === t);
220
+ const fullNeed = TEAM_ORDER.reduce((n, t) => n + 3 + byTeam(t).length * 2, 0);
221
+ const compact = fullNeed > mainH;
222
+ const active = activeTeam(state);
223
+ const caret = tick % 8 < 4 ? '▌' : ' ';
224
+ const reportPath = `${handle.runDir}/report.md`;
225
+ const handoffs = state.handoffs.length, loops = state.verdicts.filter(v => v.verdict === 'FAIL').length;
226
+ return (_jsxs(Box, { flexDirection: "column", width: W, height: H, children: [_jsx(Header, { state: { ...state, goal: state.goal || sanitize(goal) }, width: W, tick: tick, nowMs: nowMs, goal: goal }), _jsx(Pipeline, { state: state, width: W, tick: tick, nowMs: nowMs }), _jsxs(Box, { height: mainH, width: W, children: [_jsx(Box, { flexDirection: "column", width: leftW, height: mainH, overflow: "hidden", children: TEAM_ORDER.map(t => _jsx(TeamCard, { team: t, agents: byTeam(t), width: leftW, active: active === t, compact: compact, tick: tick, nowMs: nowMs }, t)) }), _jsxs(Box, { flexDirection: "column", width: rightW, height: mainH, children: [_jsx(Feed, { lines: feedLines, width: rightW, height: mainH - chatH, scroll: Math.min(scroll, Math.max(0, feedLines.length - 1)), showActivity: showActivity }), _jsxs(Box, { width: rightW, height: chatH, borderStyle: "round", borderColor: "magenta", paddingX: 1, children: [_jsx(Tx, { bold: true, color: "magenta", children: "You \u2192 Director \u203A " }), _jsx(Box, { flexShrink: 1, children: _jsxs(Tx, { wrap: "truncate-start", children: [typed, _jsx(Tx, { color: "magenta", children: caret })] }) })] })] })] }), _jsxs(Box, { flexDirection: "column", width: W, paddingX: 1, children: [state.outcome === null ? null : (_jsx(Tx, { bold: true, inverse: true, color: state.outcome === 'delivered' ? 'green' : 'red', wrap: "truncate-end", children: state.outcome === 'delivered' ? ` ✔ DELIVERED — report: ${reportPath} ` : state.outcome === 'failed' ? ` ✖ FAILED — report: ${reportPath} ` : ` ■ STOPPED — report: ${reportPath} ` })), _jsxs(Tx, { wrap: "truncate-end", children: [_jsx(Tx, { bold: true, children: "agents " }), activeAgentCount(state), "/", state.agents.length || 5, _jsx(Tx, { dimColor: true, children: " \u00B7 " }), "msgs ", state.messageCount, _jsx(Tx, { dimColor: true, children: " \u00B7 " }), "tokens ", formatTokens(state.totalTokens), _jsx(Tx, { dimColor: true, children: " \u00B7 " }), "handoffs ", handoffs, _jsx(Tx, { dimColor: true, children: " \u00B7 " }), "QC loops ", loops] }), _jsx(Tx, { dimColor: true, wrap: "truncate-end", children: "Enter send \u00B7 Esc quit \u00B7 \u2191\u2193 scroll feed \u00B7 Tab toggle activity" })] })] }));
227
+ }
228
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1,22 @@
1
+ import type { TeamEventInput, TeamRunHandle } from '../../team/types.js';
2
+ export interface ScriptedEvent {
3
+ readonly delayMs: number;
4
+ readonly event: TeamEventInput;
5
+ }
6
+ export interface FakeTeamHandle extends TeamRunHandle {
7
+ readonly sent: readonly string[];
8
+ readonly stopped: boolean;
9
+ /** Emit one event right now (as if the engine did). */
10
+ emit(event: TeamEventInput): void;
11
+ /** Cancel pending timers. */
12
+ dispose(): void;
13
+ }
14
+ /** `delayMs` is relative to the previous event. Late subscribers get a replay of everything already emitted. */
15
+ export declare function fakeTeamHandle(script: readonly ScriptedEvent[], opts?: {
16
+ readonly runId?: string;
17
+ readonly runDir?: string;
18
+ readonly now?: () => Date;
19
+ }): FakeTeamHandle;
20
+ import type { TeamConfig } from '../../team/types.js';
21
+ /** Five-agent company used by tests and visual checks. */
22
+ export declare function demoConfig(): TeamConfig;
@@ -0,0 +1,42 @@
1
+ /** `delayMs` is relative to the previous event. Late subscribers get a replay of everything already emitted. */
2
+ export function fakeTeamHandle(script, opts = {}) {
3
+ const runId = opts.runId ?? 'run-demo0001', runDir = opts.runDir ?? '.ckit/team/runs/run-demo0001';
4
+ const now = opts.now ?? (() => new Date());
5
+ const emitted = [], listeners = new Set(), sent = [], timers = new Set();
6
+ let seq = 0, stopped = false, resolveDone = () => undefined;
7
+ const done = new Promise(r => { resolveDone = r; });
8
+ const emit = (input) => {
9
+ const e = { ...input, seq: ++seq, at: now().toISOString(), runId };
10
+ emitted.push(e);
11
+ for (const l of [...listeners])
12
+ l(e);
13
+ if (e.type === 'run.completed')
14
+ resolveDone(e.outcome);
15
+ };
16
+ let t = 0;
17
+ for (const step of script) {
18
+ t += step.delayMs;
19
+ const timer = setTimeout(() => { timers.delete(timer); emit(step.event); }, t);
20
+ timers.add(timer);
21
+ }
22
+ const dispose = () => { for (const x of timers)
23
+ clearTimeout(x); timers.clear(); };
24
+ return {
25
+ runId, runDir, done, emit, dispose,
26
+ get sent() { return sent; }, get stopped() { return stopped; },
27
+ subscribe(l) { for (const e of emitted)
28
+ l(e); listeners.add(l); return () => { listeners.delete(l); }; },
29
+ sendToDirector(text) { sent.push(text); },
30
+ stop() { stopped = true; dispose(); emit({ type: 'run.completed', outcome: 'stopped', report: '' }); },
31
+ };
32
+ }
33
+ const ag = (id, name, team, cli, model, access = 'read') => ({ id, name, team, cli, model, access });
34
+ /** Five-agent company used by tests and visual checks. */
35
+ export function demoConfig() {
36
+ return {
37
+ version: 1, director: ag('director', 'Director An', 'director', 'auto', null),
38
+ teams: { ba: [ag('ba-1', 'Analyst Linh', 'ba', 'claude-code', 'sonnet'), ag('ba-2', 'Analyst Bao', 'ba', 'codex', 'gpt-5')], implement: [ag('impl-1', 'Dev Minh', 'implement', 'codex', 'gpt-5', 'write')], qc: [ag('qc-1', 'QC Hoa', 'qc', 'omp', null)] },
39
+ limits: { baRounds: 2, qcLoops: 3, agentTimeoutMs: 900000 },
40
+ };
41
+ }
42
+ //# sourceMappingURL=demo-handle.js.map
@@ -0,0 +1,81 @@
1
+ import { type AgentCli, type AgentState, type Stage, type TeamConfig, type TeamEvent, type TeamId } from '../../team/types.js';
2
+ export interface AgentView {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ readonly team: TeamId;
6
+ readonly cli: AgentCli;
7
+ readonly model: string | null;
8
+ readonly state: AgentState;
9
+ readonly lastActivity: string;
10
+ readonly turns: number;
11
+ readonly tokens: number;
12
+ /** epoch ms of the current turn start; null when not thinking */
13
+ readonly turnStartedAt: number | null;
14
+ }
15
+ export type FeedKind = 'agent' | 'user' | 'director' | 'system' | 'handoff' | 'verdict' | 'activity';
16
+ export interface FeedItem {
17
+ readonly id: number;
18
+ readonly kind: FeedKind;
19
+ readonly from: string;
20
+ readonly fromTeam: TeamId | null;
21
+ readonly to: string;
22
+ readonly text: string;
23
+ readonly at: number;
24
+ readonly tone?: 'pass' | 'fail' | 'bad';
25
+ }
26
+ export interface StageSpan {
27
+ readonly stage: Stage;
28
+ readonly loop: number;
29
+ readonly startedAt: number;
30
+ readonly endedAt: number | null;
31
+ }
32
+ export interface HandoffView {
33
+ readonly from: TeamId;
34
+ readonly to: TeamId;
35
+ readonly title: string;
36
+ readonly artifact: string;
37
+ readonly at: number;
38
+ }
39
+ export interface VerdictView {
40
+ readonly verdict: 'PASS' | 'FAIL';
41
+ readonly loop: number;
42
+ readonly summary: string;
43
+ readonly at: number;
44
+ }
45
+ export type Outcome = 'delivered' | 'failed' | 'stopped';
46
+ export interface TeamViewState {
47
+ readonly runId: string | null;
48
+ readonly goal: string;
49
+ readonly simulated: boolean;
50
+ readonly config: TeamConfig | null;
51
+ readonly startedAt: number | null;
52
+ readonly endedAt: number | null;
53
+ readonly lastAt: number | null;
54
+ readonly agents: readonly AgentView[];
55
+ readonly stage: Stage | null;
56
+ readonly loop: number;
57
+ readonly stageHistory: readonly StageSpan[];
58
+ readonly feed: readonly FeedItem[];
59
+ readonly handoffs: readonly HandoffView[];
60
+ readonly verdicts: readonly VerdictView[];
61
+ readonly outcome: Outcome | null;
62
+ readonly report: string;
63
+ readonly totalTokens: number;
64
+ readonly messageCount: number;
65
+ }
66
+ export declare const STAGE_LABEL: Readonly<Record<Stage, string>>;
67
+ export declare const TEAM_LABEL: Readonly<Record<TeamId, string>>;
68
+ export declare const stageTeam: (s: Stage) => TeamId;
69
+ export declare const stageIndex: (s: Stage | null) => number;
70
+ export declare const initialTeamView: () => TeamViewState;
71
+ /** Agent output is untrusted: drop ANSI/OSC escapes and control characters, keep newlines, tabs become spaces. */
72
+ export declare function sanitize(text: string): string;
73
+ export declare function activeTeam(s: TeamViewState): TeamId | null;
74
+ export declare function targetLabel(s: TeamViewState, to: string): string;
75
+ export declare function reduceTeam(state: TeamViewState, event: TeamEvent): TeamViewState;
76
+ /** Duration of the latest completed span of `stage`, or null. */
77
+ export declare function stageDuration(s: TeamViewState, stage: Stage): number | null;
78
+ export declare const activeAgentCount: (s: TeamViewState) => number;
79
+ export declare function formatClock(msTotal: number): string;
80
+ export declare function formatDuration(msTotal: number): string;
81
+ export declare const formatTokens: (n: number) => string;
@@ -0,0 +1,133 @@
1
+ // Pure view-model for the Agent Company TUI: folds TeamEvents into a renderable state. No React, no I/O.
2
+ import { STAGES } from '../../team/types.js';
3
+ export const STAGE_LABEL = { 'director-intake': 'Director', 'ba-discussion': 'BA', implement: 'Implement', qc: 'QC', 'ba-review': 'BA Review', delivery: 'Delivery' };
4
+ export const TEAM_LABEL = { director: 'Director', ba: 'BA', implement: 'Implement', qc: 'QC' };
5
+ const STAGE_TEAM = { 'director-intake': 'director', 'ba-discussion': 'ba', implement: 'implement', qc: 'qc', 'ba-review': 'ba', delivery: 'director' };
6
+ export const stageTeam = (s) => STAGE_TEAM[s];
7
+ export const stageIndex = (s) => (s === null ? -1 : STAGES.indexOf(s));
8
+ export const initialTeamView = () => ({ runId: null, goal: '', simulated: false, config: null, startedAt: null, endedAt: null, lastAt: null, agents: [], stage: null, loop: 0, stageHistory: [], feed: [], handoffs: [], verdicts: [], outcome: null, report: '', totalTokens: 0, messageCount: 0 });
9
+ /** Agent output is untrusted: drop ANSI/OSC escapes and control characters, keep newlines, tabs become spaces. */
10
+ export function sanitize(text) {
11
+ return text
12
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, '')
13
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '')
14
+ .replace(/\u001b[@-Z\\-_]?/g, '')
15
+ .replace(/\r\n?/g, '\n').replace(/\t/g, ' ')
16
+ .replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
17
+ }
18
+ const oneLine = (t) => sanitize(t).replace(/\s+/g, ' ').trim();
19
+ const ms = (at, fallback) => { const v = Date.parse(at); return Number.isFinite(v) ? v : (fallback ?? 0); };
20
+ export function activeTeam(s) { return s.outcome !== null || s.stage === null ? null : STAGE_TEAM[s.stage]; }
21
+ /** waiting = members of the active stage's team that are not thinking (and have no result to show). Everyone else idle/done/failed stays. */
22
+ function settle(s) {
23
+ const team = activeTeam(s);
24
+ let changed = false;
25
+ const agents = s.agents.map(a => {
26
+ if (a.state !== 'idle' && a.state !== 'waiting')
27
+ return a;
28
+ const next = team !== null && a.team === team ? 'waiting' : 'idle';
29
+ if (next === a.state)
30
+ return a;
31
+ changed = true;
32
+ return { ...a, state: next };
33
+ });
34
+ return changed ? { ...s, agents } : s;
35
+ }
36
+ const agentOf = (s, id) => s.agents.find(a => a.id === id);
37
+ const patch = (s, id, f) => s.agents.map(a => (a.id === id ? f(a) : a));
38
+ const push = (s, item) => ({ ...s, feed: [...s.feed, { ...item, id: s.feed.length }].slice(-400) });
39
+ const nameOf = (s, id) => agentOf(s, id)?.name ?? sanitize(id);
40
+ export function targetLabel(s, to) {
41
+ if (to === 'all')
42
+ return 'All';
43
+ if (to in TEAM_LABEL)
44
+ return `Team ${TEAM_LABEL[to]}`;
45
+ return nameOf(s, to);
46
+ }
47
+ export function reduceTeam(state, event) {
48
+ const at = ms(event.at, state.lastAt);
49
+ const s0 = { ...state, lastAt: at, runId: state.runId ?? event.runId };
50
+ switch (event.type) {
51
+ case 'run.started': {
52
+ const cfg = event.config;
53
+ const all = [cfg.director, ...cfg.teams.ba, ...cfg.teams.implement, ...cfg.teams.qc];
54
+ const agents = all.map(a => ({ id: a.id, name: sanitize(a.name), team: a.team, cli: a.cli, model: a.model, state: 'idle', lastActivity: '', turns: 0, tokens: 0, turnStartedAt: null }));
55
+ return push({ ...s0, goal: oneLine(event.goal), simulated: event.simulated, config: cfg, startedAt: at, agents }, { kind: 'system', from: 'system', fromTeam: null, to: 'all', text: `Run started: ${oneLine(event.goal)}`, at });
56
+ }
57
+ case 'stage.changed': {
58
+ const hist = state.stageHistory.map((h, i) => (i === state.stageHistory.length - 1 && h.endedAt === null ? { ...h, endedAt: at } : h));
59
+ const next = { ...s0, stage: event.stage, loop: event.loop, stageHistory: [...hist, { stage: event.stage, loop: event.loop, startedAt: at, endedAt: null }] };
60
+ return settle(push(next, { kind: 'system', from: 'system', fromTeam: null, to: 'all', text: `Stage → ${STAGE_LABEL[event.stage]}${event.loop > 0 ? ` (loop ${event.loop})` : ''}`, at }));
61
+ }
62
+ case 'agent.started': {
63
+ const a = agentOf(s0, event.agentId);
64
+ if (!a)
65
+ return s0;
66
+ return { ...s0, agents: patch(s0, event.agentId, x => ({ ...x, state: 'thinking', turnStartedAt: at, lastActivity: oneLine(event.task) })) };
67
+ }
68
+ case 'agent.activity': {
69
+ const text = oneLine(event.text);
70
+ const a = agentOf(s0, event.agentId);
71
+ const withAgent = a ? { ...s0, agents: patch(s0, event.agentId, x => ({ ...x, lastActivity: text })) } : s0;
72
+ return push(withAgent, { kind: 'activity', from: event.agentId, fromTeam: a?.team ?? null, to: '', text, at });
73
+ }
74
+ case 'agent.message': {
75
+ const a = agentOf(s0, event.agentId);
76
+ const tokens = event.tokens ?? 0;
77
+ const base = { ...s0, totalTokens: s0.totalTokens + tokens, messageCount: s0.messageCount + 1,
78
+ agents: a ? patch(s0, event.agentId, x => ({ ...x, state: 'done', turnStartedAt: null, turns: x.turns + 1, tokens: x.tokens + tokens, lastActivity: oneLine(event.text) })) : s0.agents };
79
+ return push(base, { kind: a?.team === 'director' ? 'director' : 'agent', from: event.agentId, fromTeam: a?.team ?? null, to: event.to, text: sanitize(event.text).trim(), at });
80
+ }
81
+ case 'agent.failed': {
82
+ const a = agentOf(s0, event.agentId);
83
+ const base = a ? { ...s0, agents: patch(s0, event.agentId, x => ({ ...x, state: 'failed', turnStartedAt: null, lastActivity: oneLine(event.reason) })) } : s0;
84
+ return push(base, { kind: 'system', from: event.agentId, fromTeam: a?.team ?? null, to: 'all', text: `✖ ${nameOf(s0, event.agentId)} failed: ${oneLine(event.reason)}`, at, tone: 'bad' });
85
+ }
86
+ case 'handoff.created':
87
+ return push({ ...s0, handoffs: [...s0.handoffs, { from: event.from, to: event.to, title: oneLine(event.title), artifact: oneLine(event.artifact), at }] }, { kind: 'handoff', from: event.from, fromTeam: event.from, to: event.to, text: oneLine(event.title), at });
88
+ case 'qc.verdict':
89
+ return push({ ...s0, verdicts: [...s0.verdicts, { verdict: event.verdict, loop: event.loop, summary: oneLine(event.summary), at }] }, { kind: 'verdict', from: 'qc', fromTeam: 'qc', to: 'all', text: oneLine(event.summary), at, tone: event.verdict === 'PASS' ? 'pass' : 'fail' });
90
+ case 'user.message':
91
+ return push({ ...s0, messageCount: s0.messageCount + 1 }, { kind: 'user', from: 'user', fromTeam: null, to: 'director', text: sanitize(event.text).trim(), at });
92
+ case 'director.decision':
93
+ return push(s0, { kind: 'director', from: 'director', fromTeam: 'director', to: 'all', text: `Decision: ${event.decision}${event.note ? ` — ${sanitize(event.note).trim()}` : ''}`, at });
94
+ case 'run.completed': {
95
+ const hist = state.stageHistory.map((h, i) => (i === state.stageHistory.length - 1 && h.endedAt === null ? { ...h, endedAt: at } : h));
96
+ const agents = s0.agents.map(a => (a.state === 'thinking' || a.state === 'waiting' ? { ...a, state: 'idle', turnStartedAt: null } : a));
97
+ return push({ ...s0, agents, stageHistory: hist, endedAt: at, outcome: event.outcome, report: oneLine(event.report) }, { kind: 'system', from: 'system', fromTeam: null, to: 'all', text: `Run ${event.outcome}`, at, tone: event.outcome === 'delivered' ? 'pass' : 'bad' });
98
+ }
99
+ case 'agent.step': {
100
+ const label = `step ${event.step}${event.total ? `/${event.total}` : ''} · ${oneLine(event.label)}`;
101
+ return agentOf(s0, event.agentId) ? { ...s0, agents: patch(s0, event.agentId, x => ({ ...x, lastActivity: label })) } : s0;
102
+ }
103
+ case 'subagent.started':
104
+ case 'subagent.activity':
105
+ case 'subagent.finished': {
106
+ const a = agentOf(s0, event.agentId);
107
+ const text = event.type === 'subagent.started' ? `↳ subagent ${event.kind ?? event.childId}: ${oneLine(event.task)}` : event.type === 'subagent.activity' ? `↳ ${oneLine(event.text)}` : `↳ subagent ${event.ok ? 'done' : 'failed'}: ${oneLine(event.summary)}`;
108
+ const withAgent = a ? { ...s0, agents: patch(s0, event.agentId, x => ({ ...x, lastActivity: text })) } : s0;
109
+ return push(withAgent, { kind: 'activity', from: event.agentId, fromTeam: a?.team ?? null, to: '', text, at });
110
+ }
111
+ }
112
+ }
113
+ /** Duration of the latest completed span of `stage`, or null. */
114
+ export function stageDuration(s, stage) {
115
+ for (let i = s.stageHistory.length - 1; i >= 0; i--) {
116
+ const h = s.stageHistory[i];
117
+ if (h && h.stage === stage && h.endedAt !== null)
118
+ return h.endedAt - h.startedAt;
119
+ }
120
+ return null;
121
+ }
122
+ export const activeAgentCount = (s) => s.agents.filter(a => a.state === 'thinking').length;
123
+ export function formatClock(msTotal) {
124
+ const t = Math.max(0, Math.floor(msTotal / 1000));
125
+ const m = Math.floor(t / 60);
126
+ return `${String(m).padStart(2, '0')}:${String(t % 60).padStart(2, '0')}`;
127
+ }
128
+ export function formatDuration(msTotal) {
129
+ const t = Math.max(0, Math.round(msTotal / 1000));
130
+ return t < 60 ? `${t}s` : `${Math.floor(t / 60)}m${String(t % 60).padStart(2, '0')}s`;
131
+ }
132
+ export const formatTokens = (n) => (n < 1000 ? String(n) : n < 100000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`);
133
+ //# sourceMappingURL=model.js.map