@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
package/gui/app.js ADDED
@@ -0,0 +1,677 @@
1
+ /* CKit Agent Company GUI: state, views, SSE, comic, bubbles, config editor. Vanilla JS. */
2
+ (function () {
3
+ 'use strict';
4
+ var Q = new URLSearchParams(location.search);
5
+ if (Q.get('t')) { sessionStorage.setItem('ckit-token', Q.get('t')); history.replaceState(null, '', location.pathname + location.hash); }
6
+ var TOKEN = sessionStorage.getItem('ckit-token') || '';
7
+ var SHOT = Q.get('shot') || '', CLIS = [], CHECK = {};
8
+ var TC = {director: '#A36BFF', ba: '#21D6E8', implement: '#F3A544', qc: '#4AD69A'};
9
+ var TL = {director: 'DIRECTOR', ba: 'TEAM BA', implement: 'TEAM IMPLEMENT', qc: 'TEAM QC'};
10
+ var STAGES = ['director-intake', 'ba-discussion', 'implement', 'qc', 'ba-review', 'delivery'];
11
+ var STAGE_LABEL = ['Director', 'BA', 'Implement', 'QC', 'BA Review', 'Delivery'];
12
+ var PHASE = {'director-intake': 'Director intake', 'ba-discussion': 'BA internal discussion', 'implement': 'Implement team at work', 'qc': 'QC inspection', 'ba-review': 'BA review', 'delivery': 'Delivery'};
13
+ var STAGE_TEAM = {'director-intake': 'director', 'ba-discussion': 'ba', 'implement': 'implement', 'qc': 'qc', 'ba-review': 'ba', 'delivery': 'director'};
14
+ var $ = function (id) { return document.getElementById(id); };
15
+ function h(tag, attrs, kids) {
16
+ var e = document.createElement(tag);
17
+ Object.keys(attrs || {}).forEach(function (k) {
18
+ var v = attrs[k]; if (v === false || v == null) return;
19
+ if (k === 'class') e.className = v; else if (k === 'text') e.textContent = v; else if (k.slice(0, 2) === 'on') e.addEventListener(k.slice(2), v);
20
+ else if (k === 'style') e.setAttribute('style', v); else e[k] = v === true ? true : v;
21
+ });
22
+ (kids || []).forEach(function (c) { if (c != null) e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); });
23
+ return e;
24
+ }
25
+ function api(method, path, body) {
26
+ return fetch(path, {method: method, headers: {'x-ckit-token': TOKEN, 'content-type': 'application/json'}, body: body === undefined ? undefined : JSON.stringify(body)})
27
+ .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { return {status: r.status, body: j}; }); });
28
+ }
29
+ function hexA(hex, a) { var n = parseInt(hex.slice(1), 16); return 'rgba(' + (n >> 16) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')'; }
30
+ function fmtT(ms) { var s = Math.max(0, Math.floor(ms / 1000)); return String(Math.floor(s / 60)).padStart(2, '0') + ':' + String(s % 60).padStart(2, '0'); }
31
+ function fmtN(n) { return n >= 10000 ? (n / 1000).toFixed(1) + 'k' : String(n); }
32
+ function clock(iso) { var d = new Date(iso); return isNaN(d) ? '' : d.toTimeString().slice(0, 8); }
33
+
34
+ var S = {config: null, view: 'live', comic: false, run: null, agents: {}, order: [], events: [], msgs: 0, tokens: 0, stageIdx: -1, loop: 1, stageTimes: {}, selected: null,
35
+ started: 0, ended: 0, outcome: null, replay: false, history: true, buckets: [], tokBuckets: [], handoffs: [], verdicts: [], lastStageAt: 0, dirty: true, bubbles: {}, narr: '', lastPanelSub: {}, lastAt: 0};
36
+ var net = window.CKNet.create($('net'));
37
+ window.__ck = {S: S, net: net};
38
+
39
+ function cfgAgents(cfg) { return [cfg.director].concat(cfg.teams.ba, cfg.teams.implement, cfg.teams.qc); }
40
+ function setupAgents(cfg) {
41
+ S.agents = {}; S.order = [];
42
+ cfgAgents(cfg).forEach(function (a) { S.order.push(a.id); S.agents[a.id] = {cfg: a, state: 'idle', task: '', activity: '', step: 0, total: null, label: '', tokens: 0, t0: 0, spark: [], outputs: [], subs: {}, msgs: 0}; });
43
+ net.setAgents(cfgAgents(cfg));
44
+ }
45
+ function resetRun() {
46
+ S.events = []; S.atts = []; S.fails = []; S.msgs = 0; S.tokens = 0; S.stageIdx = -1; S.loop = 1; S.stageTimes = {}; S.started = 0; S.ended = 0; S.outcome = null; S.handoffs = []; S.verdicts = []; S.buckets = []; S.tokBuckets = []; S.lastStageAt = 0; S.narr = '';
47
+ $('feed').innerHTML = ''; $('comicpanels').innerHTML = ''; $('bubbles').innerHTML = ''; S.bubbles = {}; S.lastPanelSub = {};
48
+ $('overlay').hidden = true; $('hobanner').classList.remove('on');
49
+ if (S.config) setupAgents(S.config);
50
+ net.reset(); setNarr('Waiting for a mission…'); S.dirty = true;
51
+ }
52
+ function A(id) { return S.agents[id]; }
53
+ function nm(id) { return A(id) ? A(id).cfg.name : id === 'all' ? 'everyone' : TL[id] || id; }
54
+ function tcol(id) { return A(id) ? TC[A(id).cfg.team] : TC[id] || '#8A9AAF'; }
55
+ function ini(id) { return A(id) ? net.initials(A(id).cfg) : '?'; }
56
+ function setNarr(t) { S.narr = t; $('nowtext').textContent = t; }
57
+
58
+ function activeSubs() { var n = 0; S.order.forEach(function (id) { Object.keys(A(id).subs).forEach(function (k) { if (A(id).subs[k].state === 'run') n++; }); }); return n; }
59
+ function caption() {
60
+ var st = STAGES[S.stageIdx], n = activeSubs(), c;
61
+ if (S.outcome) c = S.outcome === 'delivered' ? '<b>Mission delivered</b> — báo cáo đã sẵn sàng' : '<b>Run ' + S.outcome + '</b>';
62
+ else if (!st) c = 'Chờ nhiệm vụ…';
63
+ else if (st === 'director-intake') c = '<b>Director</b> đang tiếp nhận và phân tích yêu cầu';
64
+ else if (st === 'ba-discussion') c = '<b>Team BA</b> đang thảo luận yêu cầu (các BA tranh luận → HANDOFF)';
65
+ else if (st === 'implement') c = '<b>Implement</b> đang viết code' + (n ? ' — <b>' + n + ' subagent</b> đang hỗ trợ' : '') + (S.loop > 1 ? ' (sửa lỗi vòng ' + S.loop + ')' : '');
66
+ else if (st === 'qc') c = '<b>QC</b> đang kiểm thử' + (n ? ' — ' + n + ' subagent hỗ trợ' : '') + (S.loop > 1 ? ' (QC loop ' + S.loop + ')' : '');
67
+ else if (st === 'ba-review') c = '<b>Team BA</b> đang review kết quả so với yêu cầu';
68
+ else c = '<b>Director</b> đang tổng hợp báo cáo giao khách';
69
+ $('caption').innerHTML = c;
70
+ }
71
+ function narrate(st) {
72
+ var m = {'director-intake': 'Director nhận yêu cầu từ chủ dự án và giao cho Team BA.', 'ba-discussion': 'Team BA: hai analyst tranh luận để chốt yêu cầu, rồi tạo HANDOFF.', 'implement': 'Team Implement nhận HANDOFF và bắt đầu viết code' + (S.loop > 1 ? ' — sửa lỗi QC vừa tìm ra (vòng ' + S.loop + ').' : '.'),
73
+ 'qc': 'Team QC kiểm tra sản phẩm' + (S.loop > 1 ? ' lần ' + S.loop + '.' : '.'), 'ba-review': 'Team BA đối chiếu sản phẩm với yêu cầu ban đầu.', 'delivery': 'Director tổng hợp báo cáo và giao hàng.'};
74
+ setNarr(m[st] || '');
75
+ }
76
+
77
+ /* bubbles */
78
+ function plain(t) { return t.replace(/[#*`>|]+/g, ' ').replace(/\s+/g, ' ').trim(); }
79
+ function bubbleFor(id, text, e, to) {
80
+ if (S.history) return;
81
+ var n = A(id); if (!n) return;
82
+ var old = S.bubbles[id]; if (old) { old.el.remove(); clearInterval(old.timer); }
83
+ var full = text, flat = plain(full), long = flat.length > 150, show = long ? flat.slice(0, 149) + '…' : flat, col = tcol(id);
84
+ var el = h('div', {class: 'bub', style: '--bc:' + col + ';--bg2:' + hexA(col, .5) + ';--bg3:' + hexA(col, .22)});
85
+ var body = h('span'), cur = h('span', {class: 'cur', text: '▍'});
86
+ el.appendChild(h('div', {class: 'who'}, [h('i'), h('b', {text: nm(id)}), h('em', {text: '→ ' + nm(to)})]));
87
+ el.appendChild(h('div', {class: 'btx'}, [body, cur]));
88
+ if (long) el.appendChild(h('div', {class: 'more', text: 'Read full message ⤢'}));
89
+ el.addEventListener('click', function () { showMessage({from: id, to: to, at: e.at, tokens: e.tokens, text: full}); });
90
+ var rec = {el: el, hover: false, id: id, typed: 0};
91
+ el.addEventListener('mouseenter', function () { rec.hover = true; }); el.addEventListener('mouseleave', function () { rec.hover = false; if (rec.typed) rec.typed = performance.now() - 3000; });
92
+ $('bubbles').appendChild(el); S.bubbles[id] = rec;
93
+ var i = 0; rec.timer = setInterval(function () { i += 2; body.textContent = show.slice(0, i); if (i >= show.length) { clearInterval(rec.timer); rec.typed = performance.now(); } }, 24);
94
+ placeBubble(rec);
95
+ }
96
+ function placeBubble(rec) {
97
+ var p = net.getNodePos(rec.id), el = rec.el, w = el.offsetWidth || 240, hgt = el.offsetHeight || 80;
98
+ var team = A(rec.id) ? A(rec.id).cfg.team : '', idx = S.order.filter(function (i) { return A(i).cfg.team === team; }).indexOf(rec.id);
99
+ var below = (idx % 2 === 1 && team !== 'director') || p.y - p.r - hgt - 34 < 8;
100
+ var x = Math.min(p.w - w - 6, Math.max(6, p.x - 44)), y = below ? p.y + p.r + (team === 'director' ? 26 : 64) : p.y - p.r - hgt - 28;
101
+ y = Math.max(4, Math.min(p.h - hgt - 4, y));
102
+ el.style.left = x + 'px'; el.style.top = y + 'px'; el.style.setProperty('--tail', Math.max(14, Math.min(w - 26, p.x - x - 5)) + 'px'); el.classList.toggle('below', below);
103
+ }
104
+ function tickBubbles(now) {
105
+ Object.keys(S.bubbles).forEach(function (id) {
106
+ var r = S.bubbles[id]; placeBubble(r);
107
+ var age = r.typed ? now - r.typed : 0;
108
+ if (r.typed && !r.hover && age > 4500 && !SHOT) { r.el.classList.add('fade'); if (age > 5200) { r.el.remove(); delete S.bubbles[id]; } }
109
+ else r.el.classList.remove('fade');
110
+ var cur = r.el.querySelector('.cur'); if (cur) cur.style.display = r.typed ? 'none' : '';
111
+ });
112
+ }
113
+ function toast(t) { var el = h('div', {class: 'toast', text: t}); document.body.appendChild(el); setTimeout(function () { el.classList.add('out'); }, 3600); setTimeout(function () { el.remove(); }, 4200); }
114
+ function shortPath(p) { var parts = String(p || '').split(/[\\/]/).filter(Boolean); return parts.length > 3 ? '…/' + parts.slice(-3).join('/') : String(p || ''); }
115
+
116
+ /* modal */
117
+ function closeModal() { $('modal').hidden = true; $('modal').innerHTML = ''; }
118
+ function openModal(node) { var m = $('modal'); m.innerHTML = ''; m.appendChild(node); m.hidden = false; }
119
+ $('modal').addEventListener('mousedown', function (e) { if (e.target === $('modal')) closeModal(); });
120
+ document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { closeModal(); $('overlay').hidden = true; } });
121
+ function showMessage(m) {
122
+ openModal(h('div', {class: 'dlg', style: 'border-color:' + tcol(m.from)}, [
123
+ h('header', {}, [h('div', {}, [h('b', {text: nm(m.from)}), h('span', {text: ' → ' + nm(m.to), class: 'mono'}), h('div', {class: 'ml', text: clock(m.at) + (m.tokens != null ? ' · ' + m.tokens + ' tokens' : '')})]), h('button', {text: '✕', onclick: closeModal})]),
124
+ h('div', {class: 'body'}, [h('div', {class: 'full', text: m.text})]),
125
+ h('footer', {}, [h('button', {text: 'Copy', onclick: function () { if (navigator.clipboard) navigator.clipboard.writeText(m.text); }}), h('button', {class: 'primary', text: 'Close', onclick: closeModal})])]));
126
+ }
127
+ function mdToHtml(md) {
128
+ var esc = function (s) { return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); };
129
+ var out = [], inList = false;
130
+ md.split('\n').forEach(function (l) {
131
+ var t = esc(l).replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>');
132
+ var m = /^(#{1,3})\s+(.*)$/.exec(t);
133
+ if (/^\s*[-*]\s+/.test(t)) { if (!inList) { out.push('<ul>'); inList = true; } out.push('<li>' + t.replace(/^\s*[-*]\s+/, '') + '</li>'); return; }
134
+ if (inList) { out.push('</ul>'); inList = false; }
135
+ out.push(m ? '<h' + m[1].length + '>' + m[2] + '</h' + m[1].length + '>' : t.trim() ? '<p>' + t + '</p>' : '');
136
+ });
137
+ if (inList) out.push('</ul>'); return out.join('\n');
138
+ }
139
+ function showArtifact(title, name) {
140
+ var body = h('div', {class: 'body report'}, [h('p', {text: 'Loading…'})]);
141
+ openModal(h('div', {class: 'dlg wide'}, [h('header', {}, [h('b', {text: title}), h('button', {text: '✕', onclick: closeModal})]), body, h('footer', {}, [h('button', {class: 'primary', text: 'Close', onclick: closeModal})])]));
142
+ fetch('/api/runs/' + ((S.run && S.run.runId) || 'current') + '/artifact/' + name, {headers: {'x-ckit-token': TOKEN}}).then(function (r) { return r.ok ? r.text() : Promise.reject(); })
143
+ .then(function (t) { body.innerHTML = mdToHtml(t); }).catch(function () { body.innerHTML = '<p>Artifact not available.</p>'; if (name === 'report.md' && S.reportText) body.innerHTML = mdToHtml(S.reportText); });
144
+ }
145
+
146
+ /* reducer */
147
+ function onEvent(e) {
148
+ S.events.push(e); S.dirty = true;
149
+ var now = performance.now(), a = e.agentId ? A(e.agentId) : null;
150
+ if (e.type === 'run.started') {
151
+ S.started = Date.parse(e.at); S.config = e.config; S.simulated = e.simulated; S.run = S.run || {}; S.run.runId = e.runId; S.run.goal = e.goal; S.run.running = true; setupAgents(e.config);
152
+ $('goal').textContent = e.goal; $('goal').title = e.goal; $('runid').textContent = e.runId.replace('team-', '');
153
+ setNarr('Mission: ' + e.goal.slice(0, 120)); feedBanner('dir', '◆ MISSION STARTED — ' + e.goal); feedAtts(e.attachments);
154
+ comicCaption('Episode 1: ' + e.goal.slice(0, 90), 'director');
155
+ }
156
+ S.lastAt = Date.parse(e.at);
157
+ switch (e.type) {
158
+ case 'stage.changed': {
159
+ var idx = STAGES.indexOf(e.stage), prev = S.stageIdx;
160
+ if (prev >= 0 && S.lastStageAt) S.stageTimes[STAGES[prev] + (e.loop > 1 && prev >= 2 && prev <= 3 ? '#' + e.loop : '')] = Date.parse(e.at) - S.lastStageAt;
161
+ S.lastStageAt = Date.parse(e.at); S.loop = e.loop; S.stageIdx = idx; net.setStage(idx, e.loop); narrate(e.stage);
162
+ feedPhase(PHASE[e.stage] + (e.loop > 1 ? ' · loop ' + e.loop : ''), STAGE_TEAM[e.stage]);
163
+ comicCaption(['Meanwhile, at the Director’s desk…', 'Team BA huddles to debate the requirements…', 'Meanwhile, at Team IMPLEMENT…' + (e.loop > 1 ? ' (round ' + e.loop + ')' : ''), 'Meanwhile, at Team QC…', 'Team BA reviews the delivery…', 'The Director prepares the final report…'][idx], STAGE_TEAM[e.stage]);
164
+ break;
165
+ }
166
+ case 'agent.started':
167
+ if (a) { a.state = 'thinking'; a.task = e.task; a.t0 = now; a.step = 0; a.label = ''; a.total = null; a.activity = ''; net.setState(e.agentId, 'thinking'); net.setStep(e.agentId, null); if (S.config && e.agentId !== S.config.director.id && !S.history) net.pulse(S.config.director.id, e.agentId); }
168
+ break;
169
+ case 'agent.activity': if (a) { a.activity = e.text; bump(a); } break;
170
+ case 'agent.step': if (a) { a.step = e.step; a.total = e.total; a.label = e.label; a.activity = e.label; net.setStep(e.agentId, {step: e.step, total: e.total, label: e.label}); bump(a); } break;
171
+ case 'agent.message':
172
+ S.msgs++; S.tokens += e.tokens || 0; if (a) { a.state = 'done'; a.tokens += e.tokens || 0; a.msgs++; a.label = ''; a.outputs.unshift({text: e.text, to: e.to, at: e.at, tokens: e.tokens}); a.outputs.length = Math.min(a.outputs.length, 5); net.setState(e.agentId, 'done'); a.activity = 'finished turn'; }
173
+ S.tokBuckets.push([Date.parse(e.at), S.tokens]); S.buckets.push(Date.parse(e.at));
174
+ if (!S.history) { net.pulse(e.agentId, e.to === 'all' ? S.config.director.id : e.to); bubbleFor(e.agentId, e.text, e, e.to); }
175
+ feedMsg(e); comicMsg(e);
176
+ break;
177
+ case 'agent.failed': if (a) { a.state = 'failed'; a.activity = e.reason; net.setState(e.agentId, 'failed'); } S.fails.push(e); feedBanner('fail', '✕ ' + nm(e.agentId) + ' failed: ' + plain(e.reason).slice(0, 220) + ' (click for details)', function () { showFailure(); }); break;
178
+ case 'handoff.created':
179
+ S.handoffs.push(e); if (!S.history) { net.handoff(e.from, e.to, e.title); showHoBanner('📦 HANDOFF ' + TL[e.from] + ' → ' + TL[e.to]); }
180
+ feedBanner('ho', '📦 HANDOFF ' + (TL[e.from] || e.from) + ' → ' + (TL[e.to] || e.to) + ' · ' + e.title); comicHandoff(e);
181
+ S.order.forEach(function (id) { if (A(id).cfg.team === e.from) { A(id).state = 'idle'; net.setState(id, 'idle'); } });
182
+ break;
183
+ case 'qc.verdict': S.verdicts.push(e); if (!S.history) net.verdict(e.verdict);
184
+ feedBanner(e.verdict === 'PASS' ? 'pass' : 'fail', (e.verdict === 'PASS' ? '✔ QC PASS' : '✕ QC FAIL') + ' · loop ' + e.loop + ' — ' + e.summary);
185
+ comicVerdict(e); setNarr(e.verdict === 'FAIL' ? 'QC phát hiện lỗi → trả về Implement để sửa.' : 'QC PASS — sản phẩm đạt yêu cầu!');
186
+ break;
187
+ case 'user.message': feedBanner('you', '▸ OWNER: ' + e.text); feedAtts(e.attachments); comicSimple('you', 'OWNER', e.text + (e.attachments && e.attachments.length ? ' 📎 ' + e.attachments.length + ' file(s)' : '')); break;
188
+ case 'director.decision': feedBanner('dir', '◆ DIRECTOR ' + e.decision.toUpperCase() + ' — ' + e.note); comicSimple('director', 'DIRECTOR · ' + e.decision.toUpperCase(), e.note); break;
189
+ case 'subagent.started':
190
+ if (a) { a.subs[e.childId] = {kind: e.kind || 'sub', text: e.task, state: 'run'}; net.spawnSub(e.agentId, e.childId, e.kind); feedSub(e.agentId, '◆ spawned ' + (e.kind || 'subagent') + ': ' + e.task); comicSub(e); }
191
+ break;
192
+ case 'subagent.activity': if (a && a.subs[e.childId]) { a.subs[e.childId].text = e.text; net.subActivity(e.childId, e.text); } break;
193
+ case 'subagent.finished': if (a && a.subs[e.childId]) { a.subs[e.childId].state = e.ok ? 'done' : 'failed'; net.finishSub(e.childId, e.ok); feedSub(e.agentId, (e.ok ? '✓ ' : '✕ ') + a.subs[e.childId].kind + ': ' + e.summary); } break;
194
+ case 'run.completed':
195
+ S.ended = Date.parse(e.at); S.outcome = e.outcome; S.reportText = e.report; if (S.run) S.run.running = false;
196
+ if (S.stageIdx >= 0) S.stageTimes[STAGES[S.stageIdx]] = Date.parse(e.at) - S.lastStageAt;
197
+ if (e.outcome === 'delivered') { S.stageIdx = 6; net.setStage(6, S.loop); }
198
+ S.order.forEach(function (id) { if (A(id).state === 'thinking') { A(id).state = 'idle'; net.setState(id, 'idle'); } });
199
+ setNarr(e.outcome === 'delivered' ? 'MISSION DELIVERED ✔' : 'Run ended: ' + e.outcome + (e.outcome === 'failed' ? ' · click to see why' : '')); $('now').classList.toggle('click', e.outcome === 'failed'); comicCaption(e.outcome === 'delivered' ? 'THE END — mission delivered!' : 'The run ended: ' + e.outcome, 'director');
200
+ showOverlay(e);
201
+ break;
202
+ }
203
+ caption();
204
+ }
205
+ function bump(a) { a.spark.push(Date.now()); if (a.spark.length > 80) a.spark.shift(); }
206
+
207
+ /* feed */
208
+ function feedScroll() { var f = $('feed'); f.scrollTop = f.scrollHeight; }
209
+ function feedPhase(t, team) { $('feed').appendChild(h('div', {class: 'fphase', style: 'color:' + TC[team], text: '▍' + t})); feedScroll(); }
210
+ function feedBanner(kind, t, onclick) { $('feed').appendChild(h('div', {class: 'fban ' + kind + (onclick ? ' click' : ''), text: t, onclick: onclick})); feedScroll(); count(); }
211
+ function fmtSize(n) { return n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B'; }
212
+ function attUrl(a) { return '/api/runs/' + encodeURIComponent((S.run && S.run.runId) || 'current') + '/attachment/' + encodeURIComponent(a.name) + '?t=' + encodeURIComponent(TOKEN); }
213
+ /* a stored attachment: thumbnail for images, name + size for everything else; click opens / downloads it */
214
+ function attChip(a) {
215
+ var url = attUrl(a), img = a.kind === 'image' && /\.(png|jpe?g|gif|webp)$/i.test(a.name);
216
+ return h('a', {class: 'att', href: url, target: '_blank', rel: 'noopener', title: a.path + ' · agents read it from this path'}, [img ? h('img', {src: url, alt: ''}) : '📎', h('span', {class: 'n', text: a.name}), h('span', {class: 'sz', text: fmtSize(a.size)})]);
217
+ }
218
+ function feedAtts(list) {
219
+ if (!list || !list.length) return;
220
+ S.atts = (S.atts || []).concat(list);
221
+ $('feed').appendChild(h('div', {class: 'fatts'}, list.map(attChip))); feedScroll();
222
+ }
223
+ function feedSub(parent, t) { $('feed').appendChild(h('div', {class: 'fsub', text: '↳ ' + nm(parent) + ' ' + t})); feedScroll(); }
224
+ function count() { $('feedcount').textContent = S.events.filter(function (e) { return e.type === 'agent.message'; }).length + ' MESSAGES'; }
225
+ function typeInto(el, text) {
226
+ if (S.history) { el.textContent = text; return; }
227
+ var i = 0, t = setInterval(function () { i += 2; el.textContent = text.slice(0, i); feedScroll(); if (i >= text.length) clearInterval(t); }, 18);
228
+ }
229
+ function feedMsg(e) {
230
+ var col = tcol(e.agentId), short = plain(e.text); if (short.length > 280) short = short.slice(0, 279) + '…';
231
+ var txt = h('div', {class: 'ft'});
232
+ var row = h('div', {class: 'fm', style: '--tc:' + col + ';--tg:' + hexA(col, .3) + ';--tg2:' + hexA(col, .1), onclick: function () { showMessage({from: e.agentId, to: e.to, at: e.at, tokens: e.tokens, text: e.text}); }}, [
233
+ h('div', {class: 'fav', text: ini(e.agentId)}),
234
+ h('div', {class: 'fb'}, [h('div', {class: 'fh'}, [h('b', {text: nm(e.agentId)}), h('span', {class: 'to', text: '→ ' + nm(e.to)}), h('span', {class: 'tm', text: clock(e.at) + (e.tokens ? ' · ' + e.tokens + ' tok' : '')})]), txt])]);
235
+ $('feed').appendChild(row); typeInto(txt, short); feedScroll(); count();
236
+ }
237
+
238
+ /* comic */
239
+ function panelEl(team, cls) { var c = TC[team] || TC.director; return h('div', {class: 'panel ' + (cls || ''), style: '--pc:' + c + ';--pg:' + hexA(c, .35)}); }
240
+ function addPanel(p) { $('comicpanels').appendChild(p); var c = $('comic'); if (!c.hidden) c.scrollTop = c.scrollHeight; }
241
+ function comicCaption(t, team) { var p = panelEl(team, 'wide'); p.appendChild(h('div', {class: 'cap', text: t})); addPanel(p); }
242
+ function comicSimple(team, who, text) {
243
+ var p = panelEl(team); p.appendChild(h('div', {class: 'cap', text: who}));
244
+ p.appendChild(h('div', {class: 'cscene'}, [h('div', {class: 'cav', text: who[0]}), h('div', {class: 'cbub', text: text.slice(0, 200)})])); addPanel(p);
245
+ }
246
+ function comicMsg(e) {
247
+ var a = A(e.agentId), team = a ? a.cfg.team : 'director', left = !a || S.order.filter(function (i) { return A(i).cfg.team === team; }).indexOf(e.agentId) % 2 === 0;
248
+ var p = panelEl(team), full = e.text, text = full.replace(/\s+/g, ' ').trim(); if (text.length > 220) text = text.slice(0, 219) + '…';
249
+ var tx = h('span', {class: 'tx'});
250
+ var b = h('div', {class: 'cbub', onclick: function () { showMessage({from: e.agentId, to: e.to, at: e.at, tokens: e.tokens, text: full}); }}, [h('span', {class: 'to', text: '→ ' + nm(e.to).toUpperCase()}), tx]);
251
+ var av = h('div', {}, [h('div', {class: 'cav', text: ini(e.agentId)}), h('div', {class: 'cwho', text: nm(e.agentId)})]);
252
+ p.appendChild(h('div', {class: 'cscene' + (left ? '' : ' r')}, [av, b])); addPanel(p);
253
+ if (S.history) tx.textContent = text; else { var i = 0, t = setInterval(function () { i += 2; tx.textContent = text.slice(0, i); if (i >= text.length) clearInterval(t); }, 22); }
254
+ }
255
+ function comicHandoff(e) {
256
+ var p = panelEl(e.from, 'wide'); p.style.setProperty('--pg', hexA(TC[e.to] || TC.director, .5));
257
+ p.appendChild(h('div', {class: 'cap', text: 'HANDOFF!'}));
258
+ p.appendChild(h('div', {class: 'cscene', style: 'justify-content:space-around;align-items:center'}, [h('div', {class: 'cwho', style: 'color:' + TC[e.from], text: TL[e.from]}), h('div', {class: 'onom', text: '📦 WHOOSH!'}), h('div', {class: 'cwho', style: 'color:' + TC[e.to], text: TL[e.to]})]));
259
+ p.appendChild(h('div', {class: 'sm', text: e.title})); addPanel(p);
260
+ }
261
+ function comicVerdict(e) {
262
+ var ok = e.verdict === 'PASS', col = ok ? '#4AD69A' : '#F05668', p = panelEl('qc', 'wide'); p.style.setProperty('--pc', col); p.style.setProperty('--pg', hexA(col, .45));
263
+ p.appendChild(h('div', {class: 'cap', text: 'QC verdict — loop ' + e.loop}));
264
+ p.appendChild(h('div', {style: 'text-align:center;padding:10px'}, [ok ? h('span', {class: 'stamp', style: 'color:' + col + ';border-color:' + col, text: 'PASS ✔'}) : h('span', {class: 'onom', style: 'color:' + col, text: 'BUG!! ✕'})]));
265
+ p.appendChild(h('div', {class: 'sm', text: e.summary})); addPanel(p);
266
+ }
267
+ function comicSub(e) {
268
+ var key = e.agentId + ':' + S.stageIdx + ':' + S.loop, p = S.lastPanelSub[key];
269
+ if (!p) { p = S.lastPanelSub[key] = panelEl(A(e.agentId).cfg.team); p.appendChild(h('div', {class: 'cap', text: nm(e.agentId) + ' calls in the subagent squad!'})); p.appendChild(h('div', {class: 'dron'})); addPanel(p); }
270
+ p.querySelector('.dron').appendChild(h('span', {text: '◆ ' + (e.kind || 'sub') + ' · ' + e.task.slice(0, 50)}));
271
+ }
272
+
273
+ /* overlay */
274
+ function showHoBanner(t) { var b = $('hobanner'); b.textContent = t; b.classList.add('on'); clearTimeout(b._t); b._t = setTimeout(function () { b.classList.remove('on'); }, 3200); }
275
+ function showOverlay(e) {
276
+ var ok = e.outcome === 'delivered', ov = $('overlay');
277
+ var fails = S.verdicts.filter(function (v) { return v.verdict === 'FAIL'; }).length;
278
+ ov.innerHTML = '';
279
+ ov.appendChild(h('div', {class: 'mission' + (ok ? '' : ' fail')}, [
280
+ h('div', {class: 'ml', text: ok ? 'ALL STAGES COMPLETE' : 'RUN ENDED'}), h('h1', {text: ok ? 'MISSION DELIVERED' : e.outcome.toUpperCase()}),
281
+ h('div', {text: (S.run && S.run.goal) || ''}), e.outcome === 'failed' ? failBlock() : null,
282
+ h('div', {class: 'mstats'}, [stat('DURATION', fmtT(S.ended - S.started)), stat('TOKENS', fmtN(S.tokens)), stat('MESSAGES', S.msgs), stat('QC LOOPS', fails + 1)]),
283
+ h('div', {style: 'display:flex;gap:10px;justify-content:center'}, [h('button', {class: 'primary', text: 'View report', onclick: function () { ov.hidden = true; showArtifact('Final report', 'report.md'); }}), h('button', {text: 'View transcript', onclick: function () { ov.hidden = true; showArtifact('Transcript', 'transcript.md'); }}), e.outcome === 'failed' ? h('button', {text: 'Open Config', onclick: function () { ov.hidden = true; setView('settings'); }}) : null, h('button', {text: 'Close', onclick: function () { ov.hidden = true; }})])]));
284
+ ov.hidden = !(!S.history || SHOT === 'delivery');
285
+ }
286
+ /* plain-language "how to fix" for the failure reasons the runners produce */
287
+ function fixHint(reason, cfg) {
288
+ var r = String(reason || ''), cli = cfg ? cfg.cli : 'the CLI', m;
289
+ if (/not found on PATH/.test(r)) return 'The ' + cli + ' program is not installed (or not on PATH) on this machine. Install it, or open Config and switch this agent to an engine you have.';
290
+ if ((m = /Missing environment variable: `?([A-Z0-9_]+)/.exec(r))) return cli + ' needs the environment variable ' + m[1] + ' and did not get it.' + (/env boundary withheld/.test(r) ? ' CKit withheld it because it holds the same key as the CKit advisor; worker agents never receive the advisor key. Fix: give this agent its own key or let ' + cli + ' use its own login, or open Config and switch this agent to another engine (for example claude-code).' : ' Fix: set it in the terminal before running ckit gui, or switch this agent to another engine in Config.');
291
+ if (/401|403|unauthori[sz]ed|invalid api key|authentication/i.test(r)) return 'The provider rejected the credentials. Check the API key or login for ' + cli + ', then use Test connection in Config.';
292
+ if (/model.*(not found|does not exist|may not exist|unknown)|unknown model|unrecognized_model/i.test(r)) return 'The model "' + (cfg && cfg.model || '') + '" is not available to ' + cli + '. Open Config and set this agent\'s Model to a name that ' + cli + ' accepts when you run it yourself in the terminal' + (cli === 'claude-code' ? ' (for example haiku, sonnet or opus)' : '') + ', or leave it blank to use the CLI default.';
293
+ if (/timed out/.test(r)) return 'The agent did not answer in time. Check the network or provider, or raise the timeout in Config.';
294
+ if (/429|rate limit|quota/i.test(r)) return 'The provider is rate-limiting or the quota is used up. Wait and retry, or switch this agent to another model.';
295
+ if (/ECONNREFUSED|ENOTFOUND|network|fetch failed/i.test(r)) return 'The provider could not be reached. Check the network and the endpoint URL of this agent in Config.';
296
+ return 'Read the error text above; it is the exact output of ' + cli + '. Usual fixes: change this agent\'s engine or model in Config, then start the run again.';
297
+ }
298
+ function runFolder() { return S.projectRoot && S.run && S.run.runId ? S.projectRoot + '/.ckit/team/runs/' + S.run.runId : ''; }
299
+ function failBlock() {
300
+ var box = h('div', {class: 'failbox'});
301
+ (S.fails || []).forEach(function (f) { var c = A(f.agentId); box.appendChild(h('div', {class: 'fl'}, [h('b', {text: nm(f.agentId)}), h('span', {class: 'mono', text: c ? ' ' + c.cfg.cli + (c.cfg.model ? ' · ' + c.cfg.model : '') : ''})])); box.appendChild(h('pre', {text: f.reason})); box.appendChild(h('div', {class: 'fix'}, [h('b', {text: 'How to fix '}), fixHint(f.reason, c && c.cfg)])); });
302
+ if (!S.fails || !S.fails.length) box.appendChild(h('pre', {text: S.reportText || 'No error detail was recorded.'}));
303
+ if (runFolder()) { box.appendChild(h('div', {class: 'ml', text: 'RUN FILES (events.jsonl · transcript.md · report.md)'})); box.appendChild(h('div', {class: 'mono path', text: runFolder()})); }
304
+ return box;
305
+ }
306
+ function showFailure() {
307
+ openModal(h('div', {class: 'dlg wide'}, [h('header', {}, [h('b', {text: 'What went wrong'}), h('button', {text: '✕', onclick: closeModal})]), h('div', {class: 'body'}, [failBlock()]),
308
+ h('footer', {}, [h('button', {text: 'Open Config', onclick: function () { closeModal(); setView('settings'); }}), h('button', {text: 'View transcript', onclick: function () { showArtifact('Transcript', 'transcript.md'); }}), h('button', {class: 'primary', text: 'Close', onclick: closeModal})])]));
309
+ }
310
+ function stat(k, v) { return h('div', {}, [h('b', {text: String(v)}), h('span', {class: 'ml', text: k})]); }
311
+
312
+ /* panels */
313
+ function spark(arr, color) {
314
+ var now = Date.now(), B = 20, step = 2500, c = new Array(B).fill(0);
315
+ arr.forEach(function (t) { var k = B - 1 - Math.floor((now - t) / step); if (k >= 0 && k < B) c[k]++; });
316
+ var mx = Math.max(1, Math.max.apply(null, c)), pts = c.map(function (v, i) { return (i / (B - 1) * 100).toFixed(1) + ',' + (15 - v / mx * 14).toFixed(1); }).join(' ');
317
+ return '<svg class="spark" viewBox="0 0 100 16" preserveAspectRatio="none"><polyline fill="none" stroke="' + color + '" stroke-width="1.4" points="' + pts + '"/></svg>';
318
+ }
319
+ function renderRoster() {
320
+ var r = $('roster'), keep = r.scrollTop; r.innerHTML = '';
321
+ ['director', 'ba', 'implement', 'qc'].forEach(function (team) {
322
+ var ids = S.order.filter(function (i) { return A(i).cfg.team === team; }); if (!ids.length) return;
323
+ r.appendChild(h('div', {class: 'rteam', style: 'color:' + TC[team]}, [h('i', {style: 'background:' + TC[team]}), TL[team]]));
324
+ ids.forEach(function (id) {
325
+ var a = A(id), c = TC[team], el = h('div', {class: 'tile ' + a.state + (S.selected === id ? ' sel' : ''), style: '--tc:' + c + ';--tg:' + hexA(c, .4), onclick: function () { S.selected = id; net.select(id); S.dirty = true; }});
326
+ var work = a.state === 'thinking';
327
+ el.appendChild(h('div', {class: 'trow'}, [h('div', {class: 'av w' + net.initials(a.cfg).length, text: net.initials(a.cfg)}), h('div', {style: 'min-width:0;flex:1'}, [h('div', {class: 'tname', text: a.cfg.name}), h('div', {class: 'tsub'}, [h('span', {class: 'pill', text: a.cfg.cli}), a.cfg.model ? h('span', {class: 'pill', title: a.cfg.model, text: a.cfg.model}) : null])]),
328
+ h('div', {class: 'tright'}, [h('span', {class: 'sp ' + a.state}, [h('i'), a.state]), h('span', {class: 'tok', text: (work ? fmtT(performance.now() - a.t0) + ' · ' : '') + fmtN(a.tokens) + ' tok'})])]));
329
+ if (work && a.label) {
330
+ el.appendChild(h('div', {class: 'step', text: 'Step ' + a.step + (a.total ? '/' + a.total : '') + ' · ' + a.label}));
331
+ el.appendChild(h('div', {class: 'bar'}, [h('b', {style: 'width:' + (a.total ? a.step / a.total * 100 : 35) + '%'})]));
332
+ }
333
+ if (a.state !== 'idle' || a.task) el.appendChild(h('div', {class: 'tact', text: a.activity || a.task}));
334
+ if (work) { var sp = h('div'); sp.innerHTML = spark(a.spark, c); el.appendChild(sp.firstChild); }
335
+ var run = Object.keys(a.subs).filter(function (k) { return a.subs[k].state === 'run'; });
336
+ if (run.length) { var sb = h('div', {class: 'subs'}, [h('span', {class: 'ml', text: 'Subagents (' + run.length + ' active)'})]); run.forEach(function (k) { sb.appendChild(h('div', {class: 'subl'}, [h('b', {text: '◆ ' + a.subs[k].kind + ' '}), a.subs[k].text])); }); el.appendChild(sb); }
337
+ r.appendChild(el);
338
+ });
339
+ });
340
+ r.scrollTop = keep;
341
+ }
342
+ function kv(k, v) { return h('div', {class: 'kv'}, [h('span', {text: k}), h('span', {class: 'mono', text: String(v)})]); }
343
+ function lineSvg(vals, col) {
344
+ if (vals.length < 2) return '<svg class="spark" style="height:32px" viewBox="0 0 100 32"></svg>';
345
+ var mx = Math.max.apply(null, vals) || 1, pts = vals.map(function (v, i) { return (i / (vals.length - 1) * 100).toFixed(1) + ',' + (30 - v / mx * 28).toFixed(1); }).join(' ');
346
+ return '<svg class="spark" style="height:32px" viewBox="0 0 100 32" preserveAspectRatio="none"><polyline fill="rgba(79,140,255,.15)" stroke="' + col + '" stroke-width="1.5" points="0,32 ' + pts + ' 100,32"/></svg>';
347
+ }
348
+ function barSvg() {
349
+ var end = S.outcome ? S.ended : Date.now(), B = 10, c = new Array(B).fill(0); S.buckets.forEach(function (t) { var k = B - 1 - Math.floor((end - t) / 10000); if (k >= 0 && k < B) c[k]++; });
350
+ var mx = Math.max(1, Math.max.apply(null, c));
351
+ return '<svg class="spark" style="height:32px" viewBox="0 0 100 32" preserveAspectRatio="none">' + c.map(function (v, i) { return '<rect x="' + (i * 10 + 1) + '" y="' + (32 - v / mx * 30) + '" width="8" height="' + (v / mx * 30) + '" fill="#A36BFF"/>'; }).join('') + '</svg>';
352
+ }
353
+ function renderInspector() {
354
+ var r = $('inspector'), keep = r.scrollTop; r.innerHTML = '';
355
+ var a = S.selected && A(S.selected);
356
+ if (a) {
357
+ var c = TC[a.cfg.team];
358
+ r.appendChild(h('h3', {text: 'Agent inspector'}));
359
+ r.appendChild(h('div', {class: 'card', style: 'border-color:' + c}, [h('div', {class: 'trow'}, [h('div', {class: 'av w' + net.initials(a.cfg).length, style: '--tc:' + c + ';--tg:' + hexA(c, .4), text: net.initials(a.cfg)}), h('div', {}, [h('b', {text: a.cfg.name}), h('div', {class: 'ml', text: TL[a.cfg.team]})])]),
360
+ kv('Engine', a.cfg.cli), kv('Model', a.cfg.model || 'default'), kv('Access', a.cfg.access === 'write' ? 'read + write' : 'read only'), a.cfg.baseUrl ? kv('Endpoint', a.cfg.baseUrl.replace(/^https?:\/\//, '').slice(0, 26)) : null, kv('State', a.state), kv('Tokens', fmtN(a.tokens)),
361
+ h('div', {class: 'ml', style: 'margin-top:6px', text: 'Current task'}), h('div', {style: 'font-size:12px', text: a.task || '—'})]));
362
+ var af = (S.fails || []).filter(function (f) { return f.agentId === a.cfg.id; }).pop();
363
+ if (af) r.appendChild(h('div', {class: 'card fail failcard'}, [h('b', {class: 'bad', text: 'WHY IT FAILED'}), h('pre', {text: af.reason}), h('div', {class: 'fix'}, [h('b', {text: 'How to fix '}), fixHint(af.reason, a.cfg)]), h('div', {style: 'display:flex;gap:6px;margin-top:8px'}, [h('button', {text: 'Full details', onclick: showFailure}), h('button', {class: 'primary', text: 'Open Config', onclick: function () { setView('settings'); }})])]));
364
+ r.appendChild(h('div', {class: 'ml', style: 'margin:4px 0', text: 'Recent outputs'}));
365
+ a.outputs.forEach(function (o) { r.appendChild(h('div', {class: 'out', text: o.text.replace(/\s+/g, ' '), onclick: function () { showMessage({from: a.cfg.id, to: o.to, at: o.at, tokens: o.tokens, text: o.text}); }})); });
366
+ if (!a.outputs.length) r.appendChild(h('div', {class: 'tact', text: 'no output yet'}));
367
+ r.appendChild(h('button', {text: '× deselect', style: 'margin-top:6px', onclick: function () { S.selected = null; net.select(null); S.dirty = true; }}));
368
+ } else {
369
+ r.appendChild(h('h3', {text: 'Handoffs & verdicts'}));
370
+ S.handoffs.slice(-3).forEach(function (e) { r.appendChild(h('div', {class: 'card ho'}, [h('div', {class: 'ml', text: '📦 ' + e.from + ' → ' + e.to}), h('div', {text: e.title})])); });
371
+ S.verdicts.slice(-3).forEach(function (e) { r.appendChild(h('div', {class: 'card ' + (e.verdict === 'PASS' ? 'pass' : 'fail')}, [h('b', {class: e.verdict === 'PASS' ? 'ok' : 'bad', text: e.verdict + ' · loop ' + e.loop}), h('div', {style: 'font-size:12px', text: e.summary})])); });
372
+ if (!S.handoffs.length && !S.verdicts.length) r.appendChild(h('div', {class: 'tact', text: 'Click an agent to inspect it.'}));
373
+ if (S.atts && S.atts.length) { r.appendChild(h('h3', {style: 'margin-top:12px', text: 'Attachments · ' + S.atts.length})); r.appendChild(h('div', {class: 'tact', text: 'Every team gets these with the request.'})); r.appendChild(h('div', {class: 'fatts', style: 'margin-top:6px'}, S.atts.map(attChip))); }
374
+ }
375
+ r.appendChild(h('h3', {style: 'margin-top:12px', text: 'Telemetry'}));
376
+ var tele = h('div', {class: 'tele'}), pct = S.stageIdx < 0 ? 0 : Math.max(0, Math.min(1, (S.stageIdx + (S.outcome ? 0 : .5)) / 6));
377
+ var gauge = h('div', {class: 'card gauge'}), circ = 2 * Math.PI * 28;
378
+ gauge.innerHTML = '<svg width="74" height="74" viewBox="0 0 74 74"><circle cx="37" cy="37" r="28" fill="none" stroke="#1a2538" stroke-width="6"/><circle cx="37" cy="37" r="28" fill="none" stroke="#21D6E8" stroke-width="6" stroke-linecap="round" stroke-dasharray="' + (circ * pct).toFixed(1) + ' ' + circ.toFixed(1) + '" transform="rotate(-90 37 37)"/><text x="37" y="42" text-anchor="middle" fill="#fff" font-family="monospace" font-size="15">' + Math.round(pct * 100) + '%</text></svg><span class="ml">PROGRESS</span>';
379
+ var tk = h('div', {class: 'card'}); tk.innerHTML = '<span class="ml">TOKENS / TIME</span>' + lineSvg(S.tokBuckets.map(function (x) { return x[1]; }), '#4F8CFF');
380
+ var mb = h('div', {class: 'card'}); mb.innerHTML = '<span class="ml">MSGS / 10s</span>' + barSvg();
381
+ var sd = h('div', {class: 'card'}); sd.innerHTML = '<span class="ml">STAGE DURATIONS</span>' + Object.keys(S.stageTimes).slice(-4).map(function (k) { return '<div class="kv mono" style="font-size:10px"><span>' + k.replace('director-intake', 'intake').replace('ba-discussion', 'ba').replace('ba-review', 'review') + '</span><span>' + fmtT(S.stageTimes[k]) + '</span></div>'; }).join('');
382
+ [gauge, tk, mb, sd].forEach(function (x) { tele.appendChild(x); }); r.appendChild(tele); r.scrollTop = keep;
383
+ }
384
+ function renderStrip() {
385
+ var st = $('stages'); st.innerHTML = '';
386
+ STAGE_LABEL.forEach(function (l, i) {
387
+ var cls = S.stageIdx > i ? 'done' : S.stageIdx === i ? 'cur' : '', dur = S.stageTimes[STAGES[i]];
388
+ st.appendChild(h('div', {class: 'st ' + cls}, [l, cls === 'done' && dur ? h('small', {text: fmtT(dur)}) : null, i === 3 && S.loop > 1 ? h('small', {text: 'loop ' + S.loop}) : null]));
389
+ });
390
+ }
391
+ function renderTop() {
392
+ var live = S.run && S.run.running && !S.outcome, b = $('badge');
393
+ b.className = 'badge ' + (S.outcome ? 'done' : live ? (S.replay ? 'replay' : 'live') : '');
394
+ b.querySelector('span').textContent = S.outcome ? (S.replay ? 'REPLAY DONE' : S.outcome === 'delivered' ? 'COMPLETE' : String(S.outcome).toUpperCase()) : live ? (S.replay ? 'REPLAY' : 'LIVE') : 'IDLE';
395
+ var end = S.outcome || S.replay ? (S.lastAt || S.started) : Date.now();
396
+ $('elapsed').textContent = S.started ? fmtT(end - S.started) : '00:00'; $('tokens').textContent = fmtN(S.tokens); $('msgs').textContent = S.msgs;
397
+ $('active').textContent = S.order.filter(function (i) { return A(i).state === 'thinking'; }).length + activeSubs();
398
+ $('idleHint').style.display = S.run ? 'none' : ''; $('now').style.display = S.run ? '' : 'none';
399
+ /* composer: talks to the Director during a run, starts a mission when nothing is running */
400
+ var sim = simDefault(), mode = live ? 'live' : sim ? 'sim' : 'real';
401
+ if (S.cmode !== mode) {
402
+ S.cmode = mode; $('clabel').textContent = live ? 'OWNER → DIRECTOR' : 'NEW MISSION → DIRECTOR'; $('send').textContent = live ? 'Send ▸' : 'Start ▸'; $('chips').style.display = live ? '' : 'none';
403
+ $('msg').placeholder = live ? 'Message the Director… (Enter to send)' : 'Describe the mission and press Enter to start the team…';
404
+ $('cnote').textContent = live ? '' : sim ? 'Demo mode: no real agent is configured, so this starts a simulated run.' : 'Starts real agents in ' + shortPath(S.projectRoot); $('cnote').title = S.projectRoot || '';
405
+ }
406
+ }
407
+ var lastRender = 0;
408
+ function loop(now) {
409
+ tickBubbles(now);
410
+ if (now - lastRender > 400 || S.dirty) { lastRender = now; S.dirty = false; if (S.view === 'live') { renderRoster(); renderInspector(); renderStrip(); } renderTop(); }
411
+ requestAnimationFrame(loop);
412
+ }
413
+
414
+ /* views */
415
+ function setView(v) {
416
+ S.view = v; ['live', 'settings', 'runs'].forEach(function (x) { $(x).hidden = x !== v; });
417
+ $('strip').hidden = v !== 'live'; $('bLive').classList.toggle('on', v === 'live' && !S.comic); $('bCfg').classList.toggle('on', v === 'settings');
418
+ if (v === 'settings') mountEditor($('settings'), false);
419
+ if (v === 'runs') renderRuns();
420
+ if (v === 'live') setTimeout(net.resize, 30);
421
+ if (location.hash.slice(1) !== v) history.replaceState(null, '', '#' + v);
422
+ }
423
+ function setComic(on) { S.comic = on; $('comic').hidden = !on; document.body.classList.toggle('comicmode', on); $('bComic').classList.toggle('on', on); $('bLive').classList.toggle('on', !on); if (on) $('comic').scrollTop = 1e9; }
424
+ $('bLive').onclick = function () { setComic(false); setView('live'); };
425
+ $('bComic').onclick = function () { setView('live'); setComic(!S.comic); };
426
+ $('bRuns').onclick = function () { setView('runs'); };
427
+ $('bCfg').onclick = function () { setView('settings'); }; $('bNew').onclick = newRunDialog; $('bHint').onclick = newRunDialog;
428
+ function renderRuns() {
429
+ var box = $('runs'); box.innerHTML = '<div class="ml" style="margin:6px 0 10px">PAST RUNS — open to replay</div>';
430
+ api('GET', '/api/runs').then(function (r) {
431
+ var rows = r.body.runs || [], t = h('table', {class: 'runs'}); t.innerHTML = '<tr><th>Date</th><th>Goal</th><th>Outcome</th><th>Duration</th><th>Replay</th></tr>';
432
+ rows.forEach(function (x) {
433
+ var tr = h('tr'); tr.appendChild(h('td', {class: 'mono', text: x.startedAt ? new Date(x.startedAt).toLocaleString() : x.runId})); tr.appendChild(h('td', {text: (x.simulated ? '[demo] ' : '') + x.goal}));
434
+ tr.appendChild(h('td', {class: x.outcome === 'delivered' ? 'ok' : x.outcome === 'failed' ? 'bad' : '', text: x.outcome})); tr.appendChild(h('td', {class: 'mono', text: fmtT(x.durationMs)}));
435
+ var td = h('td'); [1, 2, 4].forEach(function (sp) { td.appendChild(h('button', {text: sp + '×', style: 'margin-right:4px', onclick: function () { replay(x.runId, sp); }})); }); tr.appendChild(td); t.appendChild(tr);
436
+ });
437
+ if (!rows.length) t.appendChild(h('tr', {}, [h('td', {colSpan: 5, text: 'No runs yet.'})]));
438
+ box.appendChild(t);
439
+ });
440
+ }
441
+ function simDefault() { return !S.config || !!S.simulatedDefault || !cfgAgents(S.config).some(function (a) { return a.cli !== 'auto' && a.cli !== 'simulated'; }); }
442
+ function replay(id, speed) { api('POST', '/api/runs/' + id + '/replay', {speed: speed}).then(function (r) { if (r.status !== 200) { toast(r.body.error || 'replay failed'); return; } S.replay = true; setComic(false); setView('live'); }); }
443
+ function newRunDialog() {
444
+ var goal = h('textarea', {rows: 4, placeholder: 'Describe the mission… e.g. "Add a dark-mode toggle to the settings page"'}), sim = h('input', {type: 'checkbox', style: 'width:auto'});
445
+ sim.checked = simDefault();
446
+ openModal(h('div', {class: 'dlg'}, [h('header', {}, [h('b', {text: 'NEW RUN'}), h('button', {text: '✕', onclick: closeModal})]),
447
+ h('div', {class: 'body'}, [h('div', {class: 'ml', text: 'GOAL'}), goal, h('div', {class: 'ml', style: 'margin-top:12px', text: 'WORKSPACE (agents run in this folder)'}), h('div', {class: 'mono', style: 'font-size:12px;word-break:break-all;color:var(--cy)', text: S.projectRoot || ''}), h('div', {class: 'ml', style: 'margin-top:12px', text: 'ATTACHMENTS (any file type; the Director and every team read them)'}), h('div', {style: 'margin:6px 0'}, [h('button', {text: '📎 Attach files', onclick: function () { $('file').click(); }})]), h('div', {class: 'attlist'}), h('label', {style: 'display:flex;gap:8px;align-items:center;margin-top:12px'}, [sim, 'Demo mode (simulated agents, no API cost)'])]),
448
+ h('footer', {}, [h('button', {text: 'Cancel', onclick: closeModal}), h('button', {class: 'primary', text: 'Start ▸', onclick: function () { startRun(goal.value, sim.checked); }})])]));
449
+ renderPending(); setTimeout(function () { goal.focus(); }, 30);
450
+ }
451
+ /* attachments waiting to be sent: uploaded as soon as they are picked, claimed by id when the message / mission is sent */
452
+ var PEND = [];
453
+ function renderPending() {
454
+ Array.prototype.forEach.call(document.querySelectorAll('.attlist'), function (box) {
455
+ box.innerHTML = '';
456
+ PEND.forEach(function (p) {
457
+ box.appendChild(h('span', {class: 'att' + (p.state === 'up' ? ' up' : p.state === 'bad' ? ' bad' : ''), title: p.state === 'bad' ? p.error : p.name}, [p.thumb ? h('img', {src: p.thumb, alt: ''}) : '📎', h('span', {class: 'n', text: p.name}),
458
+ h('span', {class: 'sz', text: p.state === 'up' ? 'uploading…' : p.state === 'bad' ? 'failed' : fmtSize(p.size)}), h('span', {class: 'x', text: '✕', title: 'Remove', onclick: function () { dropPending(p); }})]));
459
+ });
460
+ });
461
+ }
462
+ function dropPending(p) { PEND = PEND.filter(function (x) { return x !== p; }); if (p.thumb) URL.revokeObjectURL(p.thumb); if (p.id) fetch('/api/uploads/' + p.id, {method: 'DELETE', headers: {'x-ckit-token': TOKEN}}); renderPending(); }
463
+ function addFiles(files) {
464
+ Array.prototype.forEach.call(files || [], function (f) {
465
+ var p = {name: f.name || 'pasted-file', size: f.size, state: 'up', id: null, thumb: /^image\/(png|jpeg|gif|webp)$/.test(f.type) ? URL.createObjectURL(f) : null};
466
+ if (!f.name && f.type) p.name = 'pasted-' + Date.now() + '.' + f.type.split('/')[1].replace('jpeg', 'jpg');
467
+ PEND.push(p);
468
+ fetch('/api/uploads?name=' + encodeURIComponent(p.name), {method: 'POST', headers: {'x-ckit-token': TOKEN, 'content-type': 'application/octet-stream'}, body: f})
469
+ .then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { if (r.status !== 200) throw new Error(j.error || 'upload failed'); p.id = j.id; p.size = j.size; p.state = 'ok'; }); })
470
+ .catch(function (e) { p.state = 'bad'; p.error = e.message || 'upload failed'; toast('Could not attach ' + p.name + ': ' + p.error); })
471
+ .then(renderPending);
472
+ });
473
+ renderPending();
474
+ }
475
+ /* ids ready to send; null (with a message) while something is still uploading or failed */
476
+ function pendingIds() {
477
+ if (PEND.some(function (p) { return p.state === 'up'; })) { toast('Files are still uploading — try again in a moment.'); return null; }
478
+ if (PEND.some(function (p) { return p.state === 'bad'; })) { toast('Remove the file that failed to upload (✕), then send.'); return null; }
479
+ return PEND.map(function (p) { return p.id; });
480
+ }
481
+ function clearPending() { PEND.forEach(function (p) { if (p.thumb) URL.revokeObjectURL(p.thumb); }); PEND = []; renderPending(); }
482
+ $('attach').onclick = function () { $('file').click(); };
483
+ $('file').addEventListener('change', function () { addFiles($('file').files); $('file').value = ''; });
484
+ $('msg').addEventListener('paste', function (ev) { var f = ev.clipboardData && ev.clipboardData.files; if (f && f.length) { ev.preventDefault(); addFiles(f); } });
485
+ var hasFiles = function (ev) { return ev.dataTransfer && Array.prototype.indexOf.call(ev.dataTransfer.types || [], 'Files') >= 0; };
486
+ document.addEventListener('dragover', function (ev) { if (hasFiles(ev)) { ev.preventDefault(); $('composer').classList.add('drop'); } });
487
+ document.addEventListener('dragleave', function (ev) { if (!ev.relatedTarget) $('composer').classList.remove('drop'); });
488
+ document.addEventListener('drop', function (ev) { if (hasFiles(ev)) { ev.preventDefault(); $('composer').classList.remove('drop'); addFiles(ev.dataTransfer.files); } });
489
+
490
+ function startRun(goal, sim) {
491
+ var ids = pendingIds(); if (!ids) return Promise.resolve(false);
492
+ if (!goal.trim() && !ids.length) return Promise.resolve(false);
493
+ return api('POST', '/api/runs', {goal: goal, simulated: sim, attachments: ids}).then(function (r) { if (r.status !== 200) { toast(r.body.error || 'could not start the run'); return false; } clearPending(); closeModal(); S.replay = false; setView('live'); return true; });
494
+ }
495
+ function send(text) {
496
+ var chip = !!text; text = (text || $('msg').value).trim(); if (!text && !PEND.length) return;
497
+ if (!(S.run && S.run.running && !S.outcome)) { startRun(text, simDefault()).then(function (ok) { if (ok) $('msg').value = ''; }); return; }
498
+ var ids = chip ? [] : pendingIds(); if (!ids) return;
499
+ api('POST', '/api/runs/current/message', {text: text, attachments: ids}).then(function (r) { if (r.status !== 200) toast(r.body.error || 'No active run'); else { if (!chip) { $('msg').value = ''; clearPending(); } } });
500
+ }
501
+ /* resizable panes: sizes are CSS variables on #live, remembered per browser; double-click a handle to go back to the default */
502
+ (function () {
503
+ var live = $('live'), saved = {};
504
+ try { saved = JSON.parse(localStorage.getItem('ckit-layout') || '{}') || {}; } catch (e) { saved = {}; }
505
+ var apply = function () { ['--rw', '--iw', '--dock', '--cw'].forEach(function (k) { if (typeof saved[k] === 'number') live.style.setProperty(k, saved[k] + 'px'); else live.style.removeProperty(k); }); };
506
+ var store = function () { try { localStorage.setItem('ckit-layout', JSON.stringify(saved)); } catch (e) { /* private mode */ } };
507
+ var clamp = function (v, lo, hi) { return Math.round(Math.max(lo, Math.min(Math.max(lo, hi), v))); };
508
+ [['rzL', '--rw', function (r, ev) { return clamp(ev.clientX - r.left - 12, 170, r.width * .4); }],
509
+ ['rzR', '--iw', function (r, ev) { return clamp(r.right - ev.clientX - 12, 200, r.width * .45); }],
510
+ ['rzD', '--dock', function (r, ev) { return clamp(r.bottom - ev.clientY - 12, 110, r.height - 150); }],
511
+ ['rzC', '--cw', function (r, ev) { return clamp(r.right - ev.clientX - 12, 240, r.width * .65); }]].forEach(function (d) {
512
+ var el = $(d[0]);
513
+ el.addEventListener('pointerdown', function (ev) {
514
+ ev.preventDefault(); try { el.setPointerCapture(ev.pointerId); } catch (e) { /* pointer already gone */ } el.classList.add('drag'); document.body.classList.add('resizing');
515
+ var move = function (e2) { saved[d[1]] = d[2](live.getBoundingClientRect(), e2); apply(); S.dirty = true; };
516
+ var up = function () { el.removeEventListener('pointermove', move); el.removeEventListener('pointerup', up); el.removeEventListener('pointercancel', up); el.classList.remove('drag'); document.body.classList.remove('resizing'); store(); net.resize(); };
517
+ el.addEventListener('pointermove', move); el.addEventListener('pointerup', up); el.addEventListener('pointercancel', up);
518
+ });
519
+ el.addEventListener('dblclick', function () { delete saved[d[1]]; apply(); store(); net.resize(); });
520
+ });
521
+ apply();
522
+ })();
523
+ $('send').onclick = function () { send(); };
524
+ $('msg').addEventListener('keydown', function (ev) { if (ev.key === 'Enter' && !ev.shiftKey) { ev.preventDefault(); send(); } });
525
+ [['Dừng', 'Dừng'], ['Đổi hướng…', 'Đổi hướng: '], ['Ưu tiên test', 'Ưu tiên test kỹ trước khi giao'], ['Báo cáo tiến độ', 'Báo cáo tiến độ hiện tại']].forEach(function (c, i) {
526
+ $('chips').appendChild(h('button', {class: 'chip', text: c[0], onclick: function () { if (i === 1) { $('msg').value = c[1]; $('msg').focus(); } else send(c[1]); }}));
527
+ });
528
+ /* compact layout: roster/inspector are drawers */
529
+ var picked = false;
530
+ function drawer(id, on) { $(id).classList.toggle('pop', on === undefined ? !$(id).classList.contains('pop') : on); }
531
+ net.onSelect(function (id) { S.selected = id; S.dirty = true; picked = true; drawer('inspector', true); });
532
+ $('net').addEventListener('click', function () { if (picked) { picked = false; return; } drawer('roster', false); drawer('inspector', false); });
533
+ $('now').addEventListener('click', function () { if ($('now').classList.contains('click')) showFailure(); });
534
+ $('bRoster').onclick = function () { drawer('roster'); }; $('bInsp').onclick = function () { drawer('inspector'); };
535
+ document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { drawer('roster', false); drawer('inspector', false); } });
536
+
537
+ /* config editor (settings view + popup) */
538
+ function strip(cfg) {
539
+ var c = JSON.parse(JSON.stringify(cfg));
540
+ [c.director].concat(c.teams.ba, c.teams.implement, c.teams.qc).forEach(function (a) { delete a.hasKey; delete a._auto; if (a.baseUrl === '') delete a.baseUrl; if (!a.persona) delete a.persona; if (!a.short) delete a.short; });
541
+ return c;
542
+ }
543
+ function mountEditor(box, modal) {
544
+ var draft = JSON.parse(JSON.stringify(S.config)), sel = 'director', tab = Q.get('tab') || 'form', dirty = false, errors = [], note = '', jsonText = '';
545
+ var serverCfg = JSON.stringify(strip(draft));
546
+ function allA() { return [draft.director].concat(draft.teams.ba, draft.teams.implement, draft.teams.qc); }
547
+ function find(id) { return allA().filter(function (a) { return a.id === id; })[0]; }
548
+ function mark() { dirty = JSON.stringify(strip(draft)) !== serverCfg; }
549
+ function render() {
550
+ box.innerHTML = '';
551
+ box.appendChild(h('div', {class: 'tabs'}, [h('button', {class: tab === 'form' ? 'on' : '', text: 'Form editor', onclick: function () { if (tab === 'json' && !fromJson()) return; tab = 'form'; render(); }}), h('button', {class: tab === 'json' ? 'on' : '', text: 'Raw JSON', onclick: function () { jsonText = JSON.stringify(strip(draft), null, 2); tab = 'json'; render(); }})]));
552
+ if (errors.length) box.appendChild(h('div', {class: 'errs'}, errors.map(function (er) { return h('div', {text: '• ' + er}); })));
553
+ box.appendChild(h('div', {class: 'firstrun', style: S.configExists ? 'border-color:var(--b2)' : ''}, [S.configExists ? 'Each agent = one CLI of this machine + one of that CLI\'s own models. Saved for this project only, in ' : 'Welcome to CKit. Nothing is set up for this project yet. For each agent choose a CLI installed on this machine and one of that CLI\'s own models, then press Save. No API keys are needed here: every CLI uses its own login and config. It will be saved for this project only, in ', h('span', {class: 'mono', style: 'color:var(--cy);word-break:break-all', text: S.configFile || '.ckit/team.json'})]));
554
+ if (note) box.appendChild(h('div', {class: 'ok', style: 'margin-bottom:8px', text: note}));
555
+ box.appendChild(tab === 'form' ? form() : jsonTab());
556
+ if (dirty || tab === 'json' || !S.configExists) box.appendChild(h('div', {class: 'unsaved'}, [h('span', {text: dirty ? '● Unsaved changes' : tab === 'json' ? 'Raw JSON editor' : 'First-time setup: not saved yet'}), h('span', {}, [
557
+ tab === 'json' ? h('button', {text: 'Validate', style: 'margin-right:6px', onclick: function () { if (fromJson()) api('PUT', '/api/config?dry=1', strip(draft)).then(function (r) { errors = r.body.errors || []; note = errors.length ? '' : 'Valid ✓'; render(); }); }}) : null,
558
+ h('button', {text: 'Revert', style: 'margin-right:6px', onclick: function () { draft = JSON.parse(JSON.stringify(S.config)); mark(); errors = []; note = ''; jsonText = ''; render(); }}), h('button', {class: 'primary', text: 'Save', onclick: save})])]));
559
+ }
560
+ function fromJson() { var ta = box.querySelector('textarea.json'); try { draft = JSON.parse(ta ? ta.value : jsonText); errors = []; mark(); return true; } catch (er) { errors = ['JSON syntax: ' + er.message]; render(); return false; } }
561
+ function save() {
562
+ if (tab === 'json' && !fromJson()) return;
563
+ api('PUT', '/api/config', strip(draft)).then(function (r) {
564
+ if (r.status !== 200) { errors = r.body.errors || [r.body.error || 'save failed']; note = ''; render(); return; }
565
+ S.config = r.body.config; draft = JSON.parse(JSON.stringify(S.config)); serverCfg = JSON.stringify(strip(draft)); errors = []; note = 'Saved to .ckit/team.json ✓'; dirty = false; S.configExists = true;
566
+ if (!S.run || !S.run.running) setupAgents(S.config); if (!find(sel)) sel = 'director'; render();
567
+ });
568
+ }
569
+ function jsonTab() { var t = h('textarea', {class: 'json', spellcheck: false}); t.value = jsonText || JSON.stringify(strip(draft), null, 2); t.addEventListener('input', function () { jsonText = t.value; dirty = true; }); return h('div', {style: 'height:' + (modal ? '56vh' : '66vh')}, [t]); }
570
+ function form() {
571
+ var wrap = h('div', {class: 'cfg', style: modal ? 'height:58vh' : ''}), left = h('div'), right = h('div');
572
+ [['director', 'DIRECTOR'], ['ba', 'TEAM BA'], ['implement', 'TEAM IMPLEMENT'], ['qc', 'TEAM QC']].forEach(function (g) {
573
+ var team = g[0], list = team === 'director' ? [draft.director] : draft.teams[team];
574
+ left.appendChild(h('div', {class: 'rteam', style: 'color:' + TC[team]}, [h('i', {style: 'background:' + TC[team]}), g[1]]));
575
+ list.forEach(function (a) { left.appendChild(h('div', {class: 'al' + (sel === a.id ? ' sel' : ''), style: '--tc:' + TC[team] + ';--tg:' + hexA(TC[team], .3), onclick: function () { sel = a.id; render(); }}, [h('b', {text: a.name}), h('small', {text: a.cli + (a.model ? ' · ' + a.model : '')})])); });
576
+ if (team !== 'director') left.appendChild(h('button', {text: '+ Add agent', style: 'width:100%;margin-bottom:6px', onclick: function () { var n = draft.teams[team].length + 1, id = team + '-' + n; while (find(id)) { n++; id = team + '-' + n; } draft.teams[team].push({id: id, name: TL[team].replace('TEAM ', '') + ' ' + n, team: team, cli: (CLIS.filter(function (c) { return c.installed; })[0] || {cli: 'claude-code'}).cli, model: null, access: team === 'implement' ? 'write' : 'read'}); sel = id; mark(); render(); }}));
577
+ });
578
+ right.appendChild(editAgent(find(sel) || draft.director)); right.appendChild(limits()); wrap.appendChild(left); wrap.appendChild(right); return wrap;
579
+ }
580
+ function fld(label, input, hint) { return h('div', {class: 'fld'}, [h('label', {class: 'ml', text: label}), input, hint ? h('div', {class: 'ml', style: 'margin-top:3px;text-transform:none', text: hint}) : null]); }
581
+ function bind(el, obj, key, num) {
582
+ el.addEventListener('input', function () { var v = el.value; obj[key] = num ? Number(v) : v; if (key === 'model' && v === '') obj[key] = null; if (key === 'baseUrl' && v === '') delete obj[key]; var was = dirty; mark(); if (dirty !== was) { var pos = el.selectionStart; render(); var again = box.querySelector('[data-k="' + (obj.id || 'lim') + key + '"]'); if (again) { again.focus(); try { again.setSelectionRange(pos, pos); } catch (er) { /* number input */ } } } });
583
+ el.setAttribute('data-k', (obj.id || 'lim') + key); return el;
584
+ }
585
+ function modelPick(a, ci) {
586
+ if (!ci) return bind(h('input', {value: a.model || '', placeholder: a.cli === 'api' ? 'model name' : 'not used', disabled: a.cli !== 'api', style: 'font-family:var(--mono)'}), a, 'model');
587
+ var s = h('select', {style: 'font-family:var(--mono)'}), known = ci.models.indexOf(a.model) >= 0;
588
+ s.appendChild(h('option', {value: '', text: 'CLI default' + (ci.defaultModel ? ' (' + ci.defaultModel + ')' : ''), selected: !a.model}));
589
+ ci.models.forEach(function (m) { s.appendChild(h('option', {value: m, text: m, selected: a.model === m})); });
590
+ if (a.model && !known) s.appendChild(h('option', {value: a.model, text: a.model + ' (typed by you, not in the CLI list)', selected: true}));
591
+ s.appendChild(h('option', {value: '\u0000', text: 'Other…'}));
592
+ s.addEventListener('change', function () { var v = s.value; if (v === '\u0000') { v = (prompt('Model name exactly as ' + a.cli + ' accepts it:', a.model || '') || '').trim(); } a.model = v || null; a._auto = true; mark(); render(); });
593
+ return s;
594
+ }
595
+ function editAgent(a) {
596
+ var isDir = a.team === 'director', f = h('div');
597
+ f.appendChild(h('div', {class: 'sec', text: 'IDENTITY'}));
598
+ var sn = h('input', {value: a.short || '', maxLength: 4, placeholder: net.initials({name: a.name || '?', team: a.team}), style: 'text-transform:uppercase;font-family:var(--mono);font-weight:700;letter-spacing:.08em', title: 'Shown inside the agent circle. 1-4 letters or digits. Empty = ' + net.initials({name: a.name || '?', team: a.team}) + ' (from the name).'});
599
+ sn.addEventListener('input', function () { var v = sn.value.replace(/[^\p{L}\p{N}]/gu, '').toUpperCase().slice(0, 4); if (v !== sn.value) sn.value = v; });
600
+ f.appendChild(h('div', {class: 'row2', style: 'grid-template-columns:150px 1fr 1fr'}, [fld('Short name (max 4)', bind(sn, a, 'short')), fld('Name', bind(h('input', {value: a.name}), a, 'name')), fld('Team', h('input', {value: a.team, disabled: true}))]));
601
+ f.appendChild(fld('Persona / extra guidance (optional)', bind(h('textarea', {rows: 2, value: a.persona || ''}), a, 'persona')));
602
+ f.appendChild(h('div', {class: 'sec', text: 'ENGINE'}));
603
+ /* an agent is: which CLI of this machine, and which of that CLI's own models. `api` stays selectable only where it is already in use. */
604
+ var info = function (n) { return CLIS.filter(function (c) { return c.cli === n; })[0]; }, ci = info(a.cli);
605
+ var cli = h('select'); ['claude-code', 'codex', 'omp'].concat(a.cli === 'api' ? ['api'] : [], isDir ? ['auto'] : [], ['simulated']).forEach(function (o) { var i = info(o), op = h('option', {text: o + (i && !i.installed ? ' (not installed)' : o === 'auto' ? ' (built-in, no model)' : o === 'simulated' ? ' (demo)' : ''), value: o}); if (o === a.cli) op.selected = true; cli.appendChild(op); });
606
+ cli.addEventListener('change', function () { a.cli = cli.value; a.model = null; a._auto = true; mark(); render(); });
607
+ var acc = h('select'); ['read', 'write'].forEach(function (o) { var op = h('option', {text: o === 'write' ? 'Read + write (can change code)' : 'Read only (changes nothing)', value: o}); if (o === a.access) op.selected = true; acc.appendChild(op); }); acc.addEventListener('change', function () { a.access = acc.value; mark(); render(); });
608
+ f.appendChild(h('div', {class: 'row3'}, [fld('CLI', cli), fld('Model', modelPick(a, ci)), fld('Access', acc)]));
609
+ f.appendChild(h('div', {class: 'clinote', text: a.access === 'write' ? 'Access: this agent reads the whole project and may change files in it.' : 'Access: this agent reads the whole project (code, docs, attachments) but changes nothing. Pick “Read + write” for agents that must edit code.'}));
610
+ if (ci && ci.installed) {
611
+ /* verify the pair with one real tiny turn; result is cached per CLI + model */
612
+ var ck = a.cli + '|' + (a.model || ''), st = CHECK[ck];
613
+ var run = function () { CHECK[ck] = {state: 'run'}; render(); api('POST', '/api/check-agent', {cli: a.cli, model: a.model || null}).then(function (r) { CHECK[ck] = r.status === 200 && r.body.ok ? {state: 'ok'} : {state: 'bad', reason: r.body.reason || r.body.error || 'check failed'}; render(); }); };
614
+ var line = h('div', {class: 'chk ' + (st ? st.state : '')}, [
615
+ h('button', {text: st && st.state === 'run' ? 'Checking…' : st ? 'Check again' : 'Check this CLI + model', disabled: !!(st && st.state === 'run'), onclick: run}),
616
+ h('span', {text: !st ? 'Runs one tiny real turn to confirm ' + a.cli + ' accepts this model.' : st.state === 'run' ? 'asking ' + a.cli + ' for a one-word reply (up to 90 s)…' : st.state === 'ok' ? '✓ works: ' + a.cli + ' answered with ' + (a.model || 'its default model') : '✕ ' + a.cli + ' rejected this setup'})]);
617
+ f.appendChild(line);
618
+ if (st && st.state === 'bad') { f.appendChild(h('pre', {class: 'chkerr', text: st.reason})); f.appendChild(h('div', {class: 'fix'}, [h('b', {text: 'How to fix '}), fixHint(st.reason, a)])); }
619
+ if (a._auto) { a._auto = false; if (!st) setTimeout(run, 0); }
620
+ }
621
+ if (ci) f.appendChild(h('div', {class: 'clinote ' + (ci.installed ? 'ok' : 'bad')}, [h('b', {text: ci.installed ? '● installed ' : '● not installed on this machine '}), h('span', {class: 'mono', text: ci.installed ? ci.path : 'install ' + a.cli + ' or pick another CLI'}), ci.configPath ? h('div', {class: 'mono', text: 'models read from ' + ci.configPath}) : null]));
622
+ if (a.cli === 'api') {
623
+ f.appendChild(h('div', {class: 'sec', text: 'ENDPOINT · OpenAI-compatible'}));
624
+ f.appendChild(fld('Base URL', bind(h('input', {value: a.baseUrl || '', placeholder: 'https://host/v1', style: 'font-family:var(--mono)'}), a, 'baseUrl'), 'must include the version segment, e.g. /v1. Empty = CKit advisor endpoint.'));
625
+ var key = h('input', {type: 'password', placeholder: a.hasKey ? '•••••••• (stored)' : 'API key', autocomplete: 'off', style: 'font-family:var(--mono)'}), res = h('span', {class: 'mono', style: 'margin-left:10px'});
626
+ f.appendChild(fld('API key', h('div', {style: 'display:flex;gap:8px;align-items:center'}, [key,
627
+ h('button', {text: 'Store key', onclick: function () { if (!key.value) return; var ref = 'agent-' + a.id; api('PUT', '/api/secrets/' + ref, {value: key.value}).then(function (r) { if (r.status === 200) { a.apiKeyRef = ref; a.hasKey = true; key.value = ''; mark(); render(); } else res.textContent = 'failed'; }); }}),
628
+ a.hasKey ? h('button', {class: 'danger', text: 'Clear key', onclick: function () { api('DELETE', '/api/secrets/' + (a.apiKeyRef || 'agent-' + a.id)).then(function () { a.hasKey = false; render(); }); }}) : null,
629
+ a.hasKey ? h('span', {class: 'ok mono', text: 'key stored ✓'}) : null]), 'Stored in your user config dir as agent-' + a.id + '; never shown again.'));
630
+ f.appendChild(h('div', {style: 'display:flex;align-items:center'}, [h('button', {text: 'Test connection', onclick: function () { res.className = 'mono'; if (dirty) { res.textContent = 'save first'; return; } res.textContent = 'testing…'; api('POST', '/api/test-connection', {agentId: a.id}).then(function (r) { var s = r.body.status || r.body.error; res.textContent = '● ' + s + (r.body.http ? ' (HTTP ' + r.body.http + ')' : ''); res.className = 'mono ' + (s === 'ok' ? 'ok' : 'bad'); }); }}), res]));
631
+ }
632
+ if (!isDir) f.appendChild(h('div', {style: 'margin-top:14px'}, [h('button', {class: 'danger', text: 'Remove agent', onclick: function () { draft.teams[a.team] = draft.teams[a.team].filter(function (x) { return x.id !== a.id; }); sel = 'director'; mark(); render(); }})]));
633
+ return f;
634
+ }
635
+ function limits() {
636
+ var f = h('div'); f.appendChild(h('div', {class: 'sec', text: 'LIMITS'}));
637
+ f.appendChild(h('div', {class: 'row3'}, [fld('BA rounds', bind(h('input', {type: 'number', value: draft.limits.baRounds, min: 1}), draft.limits, 'baRounds', true)), fld('QC loops', bind(h('input', {type: 'number', value: draft.limits.qcLoops, min: 0}), draft.limits, 'qcLoops', true)), fld('Agent timeout (ms)', bind(h('input', {type: 'number', value: draft.limits.agentTimeoutMs}), draft.limits, 'agentTimeoutMs', true))]));
638
+ return f;
639
+ }
640
+ render();
641
+ }
642
+
643
+ /* boot */
644
+ var shotDone = false;
645
+ function shots() {
646
+ if (shotDone) return; shotDone = true;
647
+ if (SHOT === 'config') setTimeout(function () { setView('settings'); }, 100);
648
+ if (SHOT === 'comic') setComic(true);
649
+ if (SHOT === 'newrun') newRunDialog();
650
+ }
651
+ function connect() {
652
+ var es = new EventSource('/api/events?t=' + encodeURIComponent(TOKEN));
653
+ es.onmessage = function (m) { try { onEvent(JSON.parse(m.data)); } catch (err) { console.error(err); } };
654
+ es.addEventListener('reset', function () { resetRun(); S.history = true; });
655
+ es.addEventListener('ready', function () { S.history = false; S.dirty = true; shots(); });
656
+ }
657
+ api('GET', '/api/clis').then(function (r) { if (r.status === 200) { CLIS = r.body.clis || []; S.configFile = r.body.configFile; if (S.view === 'settings') setView('settings'); } });
658
+ api('GET', '/api/state').then(function (r) {
659
+ if (r.status === 401) { /* opened without the access link (typical from another machine): ask for the token instead of a dead page */
660
+ var inp = h('input', {placeholder: 'paste the access link or token', style: 'width:100%;font-family:var(--mono)'});
661
+ var go = function () { var v = inp.value.trim(), m = /[?&]t=([A-Za-z0-9_-]+)/.exec(v); v = m ? m[1] : v; if (!v) return; sessionStorage.setItem('ckit-token', v); location.reload(); };
662
+ inp.addEventListener('keydown', function (e) { if (e.key === 'Enter') go(); });
663
+ openModal(h('div', {class: 'dlg'}, [h('header', {}, [h('b', {text: 'Access token needed'})]), h('div', {class: 'body'}, [h('p', {text: TOKEN ? 'That token was not accepted (it changes every time ckit gui restarts unless CKIT_GUI_TOKEN is set).' : 'This page was opened without its access link.'}), h('p', {text: 'In the terminal where ckit gui is running, copy the link it printed (it ends with ?t=...) and paste it here.'}), inp]), h('footer', {}, [h('button', {class: 'primary', text: 'Open', onclick: go})])]));
664
+ return;
665
+ }
666
+ if (r.status !== 200) { document.body.innerHTML = '<p style="padding:40px;color:#F05668;font-family:monospace">Missing or invalid session token. Open the URL printed by `ckit gui`.</p>'; return; }
667
+ S.config = r.body.config; S.configExists = r.body.configExists !== false; S.projectRoot = r.body.projectRoot || ''; (function (root) { var name = root.split(/[\\/]/).filter(Boolean).pop() || root, ws = $('cwd').parentNode; $('cwdn').textContent = name; $('cwd').textContent = '\u200e' + root; document.title = name + ' · CKit'; ws.title = 'Agents read and write files in this folder (click to copy):\n' + root; ws.onclick = function () { if (navigator.clipboard) navigator.clipboard.writeText(root).then(function () { $('cwdn').textContent = 'copied ✓'; setTimeout(function () { $('cwdn').textContent = name; }, 1200); }, function () {}); }; })(S.projectRoot); S.simulatedDefault = r.body.simulatedDefault; S.run = r.body.run ? {runId: r.body.run.runId, running: r.body.run.running, goal: r.body.run.goal} : null;
668
+ S.replay = !!(r.body.run && r.body.run.goal === '(replay)');
669
+ setupAgents(S.config);
670
+ // First run (no .ckit/team.json, nothing running): land on Config so setup starts in the GUI.
671
+ var v = location.hash.slice(1); setView(['live', 'settings', 'runs'].indexOf(v) >= 0 ? v : (!S.configExists && !r.body.run && !SHOT && Q.get('demo') !== '1') ? 'settings' : 'live');
672
+ connect(); requestAnimationFrame(loop);
673
+ if (Q.get('demo') === '1' && !r.body.run) startRun('Add a dark-mode toggle to the settings page', true);
674
+ });
675
+ if (SHOT === 'bubble' || SHOT === 'modal') { /* handled by the capture script timing */ }
676
+ window.addEventListener('resize', function () { S.dirty = true; });
677
+ })();