@ngockhoale/ckit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/.env.example +42 -0
  2. package/README.md +116 -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 +472 -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/sessions.d.ts +10 -0
  46. package/dist/src/cli/sessions.js +381 -0
  47. package/dist/src/cli/setup.d.ts +11 -0
  48. package/dist/src/cli/setup.js +115 -0
  49. package/dist/src/committee/decision.d.ts +84 -0
  50. package/dist/src/committee/decision.js +167 -0
  51. package/dist/src/committee/handover.d.ts +115 -0
  52. package/dist/src/committee/handover.js +191 -0
  53. package/dist/src/committee/no-progress.d.ts +44 -0
  54. package/dist/src/committee/no-progress.js +64 -0
  55. package/dist/src/committee/primary-registry.d.ts +15 -0
  56. package/dist/src/committee/primary-registry.js +60 -0
  57. package/dist/src/committee/reply-parser.d.ts +28 -0
  58. package/dist/src/committee/reply-parser.js +53 -0
  59. package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
  60. package/dist/src/committee/reviewer-scheduler.js +163 -0
  61. package/dist/src/committee/role-epoch.d.ts +91 -0
  62. package/dist/src/committee/role-epoch.js +154 -0
  63. package/dist/src/core/control.d.ts +18 -0
  64. package/dist/src/core/control.js +29 -0
  65. package/dist/src/core/entities.d.ts +166 -0
  66. package/dist/src/core/entities.js +119 -0
  67. package/dist/src/core/errors.d.ts +9 -0
  68. package/dist/src/core/errors.js +17 -0
  69. package/dist/src/core/events.d.ts +72 -0
  70. package/dist/src/core/events.js +125 -0
  71. package/dist/src/core/ids.d.ts +47 -0
  72. package/dist/src/core/ids.js +32 -0
  73. package/dist/src/core/machine.d.ts +55 -0
  74. package/dist/src/core/machine.js +110 -0
  75. package/dist/src/core/policy.d.ts +34 -0
  76. package/dist/src/core/policy.js +59 -0
  77. package/dist/src/core/provenance.d.ts +20 -0
  78. package/dist/src/core/provenance.js +21 -0
  79. package/dist/src/core/record.d.ts +35 -0
  80. package/dist/src/core/record.js +67 -0
  81. package/dist/src/core/replay.d.ts +10 -0
  82. package/dist/src/core/replay.js +36 -0
  83. package/dist/src/core/run-task.d.ts +20 -0
  84. package/dist/src/core/run-task.js +48 -0
  85. package/dist/src/diagnostics/doctor.d.ts +78 -0
  86. package/dist/src/diagnostics/doctor.js +365 -0
  87. package/dist/src/diagnostics/journal-lock.d.ts +38 -0
  88. package/dist/src/diagnostics/journal-lock.js +181 -0
  89. package/dist/src/evidence/linker.d.ts +44 -0
  90. package/dist/src/evidence/linker.js +75 -0
  91. package/dist/src/evidence/report-parser.d.ts +27 -0
  92. package/dist/src/evidence/report-parser.js +17 -0
  93. package/dist/src/evidence/store.d.ts +36 -0
  94. package/dist/src/evidence/store.js +57 -0
  95. package/dist/src/gui/server.d.ts +27 -0
  96. package/dist/src/gui/server.js +497 -0
  97. package/dist/src/host/checkpoint.d.ts +22 -0
  98. package/dist/src/host/checkpoint.js +74 -0
  99. package/dist/src/host/export.d.ts +52 -0
  100. package/dist/src/host/export.js +45 -0
  101. package/dist/src/host/ipc.d.ts +57 -0
  102. package/dist/src/host/ipc.js +124 -0
  103. package/dist/src/host/leases.d.ts +27 -0
  104. package/dist/src/host/leases.js +40 -0
  105. package/dist/src/host/retention.d.ts +47 -0
  106. package/dist/src/host/retention.js +130 -0
  107. package/dist/src/host/supervisor.d.ts +59 -0
  108. package/dist/src/host/supervisor.js +64 -0
  109. package/dist/src/intake/owner-intake.d.ts +31 -0
  110. package/dist/src/intake/owner-intake.js +97 -0
  111. package/dist/src/intake/types.d.ts +46 -0
  112. package/dist/src/intake/types.js +2 -0
  113. package/dist/src/intent/context-packet.d.ts +68 -0
  114. package/dist/src/intent/context-packet.js +76 -0
  115. package/dist/src/intent/idea-ledger.d.ts +50 -0
  116. package/dist/src/intent/idea-ledger.js +136 -0
  117. package/dist/src/intent/ledger.d.ts +35 -0
  118. package/dist/src/intent/ledger.js +40 -0
  119. package/dist/src/intent/registry.d.ts +51 -0
  120. package/dist/src/intent/registry.js +44 -0
  121. package/dist/src/intent/revision.d.ts +37 -0
  122. package/dist/src/intent/revision.js +48 -0
  123. package/dist/src/orchestration/dispatcher.d.ts +32 -0
  124. package/dist/src/orchestration/dispatcher.js +136 -0
  125. package/dist/src/orchestration/milestone-loop.d.ts +149 -0
  126. package/dist/src/orchestration/milestone-loop.js +132 -0
  127. package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
  128. package/dist/src/orchestration/recovery-coordinator.js +180 -0
  129. package/dist/src/orchestration/work-order-contract.d.ts +44 -0
  130. package/dist/src/orchestration/work-order-contract.js +85 -0
  131. package/dist/src/orchestration/work-queue.d.ts +56 -0
  132. package/dist/src/orchestration/work-queue.js +95 -0
  133. package/dist/src/ports/advisor.d.ts +33 -0
  134. package/dist/src/ports/advisor.js +2 -0
  135. package/dist/src/ports/agent.d.ts +31 -0
  136. package/dist/src/ports/agent.js +2 -0
  137. package/dist/src/ports/capabilities.d.ts +3 -0
  138. package/dist/src/ports/capabilities.js +5 -0
  139. package/dist/src/ports/clock.d.ts +5 -0
  140. package/dist/src/ports/clock.js +5 -0
  141. package/dist/src/ports/store.d.ts +13 -0
  142. package/dist/src/ports/store.js +2 -0
  143. package/dist/src/ports/web.d.ts +29 -0
  144. package/dist/src/ports/web.js +2 -0
  145. package/dist/src/run/api-run.d.ts +49 -0
  146. package/dist/src/run/api-run.js +173 -0
  147. package/dist/src/run/plan-run.d.ts +22 -0
  148. package/dist/src/run/plan-run.js +233 -0
  149. package/dist/src/run/plan.d.ts +36 -0
  150. package/dist/src/run/plan.js +119 -0
  151. package/dist/src/run/verify.d.ts +25 -0
  152. package/dist/src/run/verify.js +81 -0
  153. package/dist/src/security/redact.d.ts +7 -0
  154. package/dist/src/security/redact.js +21 -0
  155. package/dist/src/settings/env-config.d.ts +64 -0
  156. package/dist/src/settings/env-config.js +232 -0
  157. package/dist/src/storage/artifacts.d.ts +30 -0
  158. package/dist/src/storage/artifacts.js +105 -0
  159. package/dist/src/storage/audit.d.ts +6 -0
  160. package/dist/src/storage/audit.js +6 -0
  161. package/dist/src/storage/db.d.ts +9 -0
  162. package/dist/src/storage/db.js +43 -0
  163. package/dist/src/storage/events.d.ts +20 -0
  164. package/dist/src/storage/events.js +69 -0
  165. package/dist/src/storage/migrations.d.ts +8 -0
  166. package/dist/src/storage/migrations.js +48 -0
  167. package/dist/src/storage/outbox.d.ts +25 -0
  168. package/dist/src/storage/outbox.js +40 -0
  169. package/dist/src/storage/projections.d.ts +18 -0
  170. package/dist/src/storage/projections.js +40 -0
  171. package/dist/src/storage/reconcile.d.ts +14 -0
  172. package/dist/src/storage/reconcile.js +93 -0
  173. package/dist/src/storage/reservations.d.ts +12 -0
  174. package/dist/src/storage/reservations.js +80 -0
  175. package/dist/src/storage/store.d.ts +34 -0
  176. package/dist/src/storage/store.js +105 -0
  177. package/dist/src/team/attachments.d.ts +22 -0
  178. package/dist/src/team/attachments.js +211 -0
  179. package/dist/src/team/cli-models.d.ts +24 -0
  180. package/dist/src/team/cli-models.js +72 -0
  181. package/dist/src/team/config.d.ts +20 -0
  182. package/dist/src/team/config.js +111 -0
  183. package/dist/src/team/engine.d.ts +28 -0
  184. package/dist/src/team/engine.js +443 -0
  185. package/dist/src/team/journal.d.ts +30 -0
  186. package/dist/src/team/journal.js +70 -0
  187. package/dist/src/team/runners.d.ts +79 -0
  188. package/dist/src/team/runners.js +436 -0
  189. package/dist/src/team/secrets.d.ts +10 -0
  190. package/dist/src/team/secrets.js +68 -0
  191. package/dist/src/team/types.d.ts +155 -0
  192. package/dist/src/team/types.js +5 -0
  193. package/dist/src/tui/app.d.ts +29 -0
  194. package/dist/src/tui/app.js +96 -0
  195. package/dist/src/tui/control-model.d.ts +101 -0
  196. package/dist/src/tui/control-model.js +109 -0
  197. package/dist/src/tui/control-screens.d.ts +27 -0
  198. package/dist/src/tui/control-screens.js +85 -0
  199. package/dist/src/tui/graph-model.d.ts +34 -0
  200. package/dist/src/tui/graph-model.js +29 -0
  201. package/dist/src/tui/graph-screens.d.ts +13 -0
  202. package/dist/src/tui/graph-screens.js +4 -0
  203. package/dist/src/tui/inspector-model.d.ts +150 -0
  204. package/dist/src/tui/inspector-model.js +15 -0
  205. package/dist/src/tui/inspector-screens.d.ts +14 -0
  206. package/dist/src/tui/inspector-screens.js +61 -0
  207. package/dist/src/tui/live.d.ts +16 -0
  208. package/dist/src/tui/live.js +39 -0
  209. package/dist/src/tui/mission-action-screens.d.ts +15 -0
  210. package/dist/src/tui/mission-action-screens.js +105 -0
  211. package/dist/src/tui/mission-actions.d.ts +46 -0
  212. package/dist/src/tui/mission-actions.js +53 -0
  213. package/dist/src/tui/mission-model.d.ts +120 -0
  214. package/dist/src/tui/mission-model.js +164 -0
  215. package/dist/src/tui/mission-nav.d.ts +82 -0
  216. package/dist/src/tui/mission-nav.js +131 -0
  217. package/dist/src/tui/mission-plan-screens.d.ts +11 -0
  218. package/dist/src/tui/mission-plan-screens.js +40 -0
  219. package/dist/src/tui/mission-plan.d.ts +45 -0
  220. package/dist/src/tui/mission-plan.js +166 -0
  221. package/dist/src/tui/mission-screens.d.ts +7 -0
  222. package/dist/src/tui/mission-screens.js +263 -0
  223. package/dist/src/tui/provenance-label.d.ts +11 -0
  224. package/dist/src/tui/provenance-label.js +16 -0
  225. package/dist/src/tui/screens.d.ts +10 -0
  226. package/dist/src/tui/screens.js +34 -0
  227. package/dist/src/tui/session-outcome.d.ts +14 -0
  228. package/dist/src/tui/session-outcome.js +57 -0
  229. package/dist/src/tui/setup-model.d.ts +159 -0
  230. package/dist/src/tui/setup-model.js +234 -0
  231. package/dist/src/tui/setup-screens.d.ts +66 -0
  232. package/dist/src/tui/setup-screens.js +72 -0
  233. package/dist/src/tui/team/app.d.ts +24 -0
  234. package/dist/src/tui/team/app.js +228 -0
  235. package/dist/src/tui/team/demo-handle.d.ts +22 -0
  236. package/dist/src/tui/team/demo-handle.js +42 -0
  237. package/dist/src/tui/team/model.d.ts +81 -0
  238. package/dist/src/tui/team/model.js +133 -0
  239. package/gui/app.css +177 -0
  240. package/gui/app.js +675 -0
  241. package/gui/index.html +51 -0
  242. package/gui/network.js +413 -0
  243. package/package.json +45 -4
  244. package/src/storage/schema.sql +42 -0
@@ -0,0 +1,443 @@
1
+ // Agent Company engine: Director -> BA -> Implement -> QC (loop) -> BA review -> delivery. Journals every event; the TUI only subscribes.
2
+ import { basename, join } from 'node:path';
3
+ import { attachmentLines, attachmentPromptBlock, storeAttachments } from './attachments.js';
4
+ import { readSecret } from './secrets.js';
5
+ import { createTeamJournal } from './journal.js';
6
+ import { readTeamJournal } from './journal.js';
7
+ import { advisorKeyOf, createSimulatedRunner, dispatchRunner, simHeader } from './runners.js';
8
+ /** Every secret value the agents may touch (stored apiKeyRefs + CKit advisor key): always redacted from journal/artifacts. */
9
+ function knownSecretValues(config, projectRoot) {
10
+ const out = [], key = advisorKeyOf(projectRoot);
11
+ if (key)
12
+ out.push(key);
13
+ for (const a of [config.director, ...config.teams.ba, ...config.teams.implement, ...config.teams.qc]) {
14
+ const v = readSecret(a.apiKeyRef);
15
+ if (v)
16
+ out.push(v);
17
+ }
18
+ return out;
19
+ }
20
+ class Redirect extends Error {
21
+ }
22
+ class Halt extends Error {
23
+ } // run already finished (stop) or failed; unwinds the pipeline
24
+ const oneLine = (s, max = 200) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
25
+ const clip = (s, max) => s.length > max ? `${s.slice(0, max)}\n[...truncated]` : s;
26
+ const STOP_RE = /^\s*(stop|dừng)/i, REDIRECT_RE = /^\s*(redirect|đổi hướng)[:\s]\s*/i;
27
+ /** Pure rule-based owner-chat decision (director cli 'auto', and the fallback for model directors). */
28
+ export function ruleDecision(text) {
29
+ if (STOP_RE.test(text))
30
+ return { decision: 'stop', note: 'Owner asked to stop' };
31
+ if (REDIRECT_RE.test(text))
32
+ return { decision: 'redirect', note: text.replace(REDIRECT_RE, '').trim() || text.trim() };
33
+ return { decision: 'continue', note: text.trim() };
34
+ }
35
+ /** Last `VERDICT: PASS|FAIL` wins; no verdict at all counts as FAIL (conservative). */
36
+ export function parseVerdict(text) {
37
+ const all = [...text.matchAll(/VERDICT\s*[:\-]?\s*\**\s*(PASS|FAIL)/gi)];
38
+ const last = all[all.length - 1]?.[1];
39
+ return last && last.toUpperCase() === 'PASS' ? 'PASS' : 'FAIL';
40
+ }
41
+ function makeHandle(runId, runDir, history, listeners, done, sendToDirector, stop) {
42
+ return {
43
+ runId, runDir, done, sendToDirector, stop,
44
+ subscribe(listener) {
45
+ for (const e of [...history]) {
46
+ try {
47
+ listener(e);
48
+ }
49
+ catch { /* listener must not break the engine */ }
50
+ }
51
+ listeners.add(listener);
52
+ return () => { listeners.delete(listener); };
53
+ },
54
+ };
55
+ }
56
+ export function startTeamRun(opts) {
57
+ const { config, goal } = opts, simulated = opts.simulated === true;
58
+ const known = [...(opts.secrets ?? []), ...knownSecretValues(config, opts.projectRoot)];
59
+ const journal = createTeamJournal({ projectRoot: opts.projectRoot, ...(opts.now ? { now: opts.now } : {}), secrets: known });
60
+ const runner = opts.runner ?? (simulated ? createSimulatedRunner(opts.simSpeed !== undefined ? { speed: opts.simSpeed } : {}) : dispatchRunner);
61
+ const history = [], listeners = new Set();
62
+ const abort = new AbortController();
63
+ const inbox = [], notes = [], convo = [];
64
+ let finished = false, handoff = '', qcReport = '', qcPassed = false, deliverable = '', resolveDone, intakeBrief = '';
65
+ const done = new Promise(r => { resolveDone = r; });
66
+ // Owner attachments: stored once in the run folder, then named in every agent prompt (Director, BA, Implement, QC) and in the BA handoff.
67
+ const atts = [], excerpts = new Map();
68
+ const addAttachments = (inputs) => {
69
+ const stored = storeAttachments(opts.projectRoot, journal.runDir, inputs, atts);
70
+ for (const s of stored) {
71
+ atts.push(s.info);
72
+ if (s.excerpt)
73
+ excerpts.set(s.info.name, journal.redact(s.excerpt));
74
+ }
75
+ return stored.map(s => s.info);
76
+ };
77
+ const images = () => atts.filter(a => a.kind === 'image').map(a => join(opts.projectRoot, a.path));
78
+ const emit = (ev) => {
79
+ if (finished && ev.type !== 'run.completed')
80
+ return;
81
+ const e = journal.append(ev);
82
+ history.push(e);
83
+ transcript(e);
84
+ for (const l of [...listeners]) {
85
+ try {
86
+ l(e);
87
+ }
88
+ catch { /* ignore */ }
89
+ }
90
+ };
91
+ const nameOf = (id) => [config.director, ...config.teams.ba, ...config.teams.implement, ...config.teams.qc].find(a => a.id === id)?.name ?? id;
92
+ function transcript(e) {
93
+ if (e.type === 'run.started')
94
+ journal.appendArtifact('transcript.md', `# Team run ${e.runId}\n\nGoal: ${e.goal}\n\n${e.attachments?.length ? `Attachments:\n${attachmentLines(e.attachments)}\n\n` : ''}`);
95
+ else if (e.type === 'stage.changed')
96
+ journal.appendArtifact('transcript.md', `\n## Stage: ${e.stage} (loop ${e.loop})\n\n`);
97
+ else if (e.type === 'agent.message')
98
+ journal.appendArtifact('transcript.md', `### ${nameOf(e.agentId)} -> ${nameOf(e.to)}\n\n${e.text}\n\n`);
99
+ else if (e.type === 'agent.failed')
100
+ journal.appendArtifact('transcript.md', `### ${nameOf(e.agentId)} FAILED\n\n${e.reason}\n\n`);
101
+ else if (e.type === 'user.message')
102
+ journal.appendArtifact('transcript.md', `### Owner\n\n${e.text}\n\n${e.attachments?.length ? `Attachments:\n${attachmentLines(e.attachments)}\n\n` : ''}`);
103
+ else if (e.type === 'director.decision')
104
+ journal.appendArtifact('transcript.md', `### Director decision: ${e.decision}\n\n${e.note}\n\n`);
105
+ else if (e.type === 'qc.verdict')
106
+ journal.appendArtifact('transcript.md', `### QC verdict: ${e.verdict} (loop ${e.loop})\n\n${e.summary}\n\n`);
107
+ else if (e.type === 'run.completed')
108
+ journal.appendArtifact('transcript.md', `\n## Run ${e.outcome}\n\n${e.report}\n`);
109
+ }
110
+ const finish = (outcome, report) => {
111
+ if (finished)
112
+ return;
113
+ emit({ type: 'run.completed', outcome, report }); // emitted while !finished (guard allows run.completed anyway)
114
+ finished = true;
115
+ journal.writeArtifact('report.md', report);
116
+ resolveDone(outcome);
117
+ };
118
+ const halted = () => { if (finished)
119
+ throw new Halt(); };
120
+ // ---- prompts ----
121
+ const header = (agent, stage, loop, turn = 1, turns = 1, final = false) => simulated || agent.cli === 'simulated' ? `${simHeader({ stage, loop, turn, turns, final })}\n` : '';
122
+ const recent = (n = 8) => convo.slice(-n).map(c => `${c.who}: ${clip(c.text, 1500)}`).join('\n\n') || '(nothing yet)';
123
+ const accessLine = (agent) => agent.access === 'write'
124
+ ? 'ACCESS: read + write. Read any file in the project folder to understand the request and the existing code, and change files there when your task needs it.'
125
+ : 'ACCESS: read only. Read any file in the project folder to understand the request and the existing code. Do not create, change or delete files.';
126
+ const role = (agent, what) => `You are ${agent.name}, member of the ${agent.team.toUpperCase()} team in a software "agent company" (Director -> BA -> Implement -> QC). ${agent.persona ?? ''}\n${what}\n${accessLine(agent)}\nAnswer concisely.`;
127
+ const common = () => `GOAL: ${oneLine(goal, 2000)}\n${notes.length ? `\nOWNER NOTES (follow them):\n${notes.map(n => `- ${n}`).join('\n')}\n` : ''}${intakeBrief ? `\nDIRECTOR BRIEF:\n${intakeBrief}\n` : ''}${attachmentPromptBlock(atts, excerpts)}`;
128
+ // ---- one agent turn ----
129
+ /** Heuristic step label for real runners' activity lines (null = not a step boundary). */
130
+ const stepOf = (text) => /^\$ /.test(text) ? 'Running commands' : /^edited |^tool: (Edit|Write|MultiEdit|NotebookEdit)/.test(text) ? 'Editing files' : /^tool: (Read|Grep|Glob|LS)/.test(text) ? 'Reading code' : /^thinking/.test(text) ? 'Thinking' : /^tool: /.test(text) ? 'Using tools' : null;
131
+ const simAgent = (a) => simulated || a.cli === 'simulated';
132
+ /** Runs one agent turn through the runner, wiring activity/step/subagent events. Never throws. */
133
+ async function callRunner(agent, prompt, first, last) {
134
+ let n = 0, lastLabel = '';
135
+ const step = (label, k, total) => {
136
+ if (label === lastLabel)
137
+ return;
138
+ lastLabel = label;
139
+ n = k ?? n + 1;
140
+ emit({ type: 'agent.step', agentId: agent.id, step: n, total: total ?? null, label });
141
+ };
142
+ const own = simAgent(agent);
143
+ if (!own)
144
+ step(first);
145
+ try {
146
+ const res = await runner(agent, prompt, {
147
+ cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: abort.signal, ...(atts.length ? { images: images() } : {}),
148
+ onActivity: text => { emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
149
+ step(l); },
150
+ onStep: (label, k, total) => step(oneLine(label, 80), k, total),
151
+ onSubagent: e => emit(e.type === 'started' ? { type: 'subagent.started', agentId: agent.id, childId: e.childId, kind: e.kind, task: oneLine(e.task, 160) }
152
+ : e.type === 'activity' ? { type: 'subagent.activity', agentId: agent.id, childId: e.childId, text: oneLine(e.text, 160) }
153
+ : { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) }),
154
+ });
155
+ if (res.ok && !own)
156
+ step(last);
157
+ return res;
158
+ }
159
+ catch (e) {
160
+ return { ok: false, reason: e instanceof Error ? e.message : 'runner threw' };
161
+ }
162
+ }
163
+ async function turn(agent, task, to, prompt) {
164
+ halted();
165
+ emit({ type: 'agent.started', agentId: agent.id, task });
166
+ const labels = agent.team === 'ba' ? ['Reading the goal', `Replying to ${nameOf(to)}`] : agent.team === 'implement' ? ['Planning', 'Reporting'] : ['Reviewing diff', 'Writing verdict'];
167
+ const res = await callRunner(agent, prompt, labels[0], labels[1]);
168
+ halted();
169
+ if (!res.ok) {
170
+ emit({ type: 'agent.failed', agentId: agent.id, reason: res.reason });
171
+ return null;
172
+ }
173
+ emit({ type: 'agent.message', agentId: agent.id, to, text: res.text, tokens: res.tokens });
174
+ const safe = journal.redact(res.text);
175
+ convo.push({ who: agent.name, text: safe });
176
+ return safe;
177
+ }
178
+ const fail = (agent, why) => {
179
+ const reason = history.filter(e => e.type === 'agent.failed').at(-1);
180
+ finish('failed', `Run failed: ${agent.name} (${agent.id}) could not complete ${why}${reason && reason.type === 'agent.failed' ? `: ${reason.reason}` : ''}. The Director stopped the pipeline; see transcript.md.`);
181
+ throw new Halt();
182
+ };
183
+ // ---- director ----
184
+ const modelDirector = () => !simulated && config.director.cli !== 'auto' && config.director.cli !== 'simulated';
185
+ async function directorAsk(task, prompt) {
186
+ emit({ type: 'agent.started', agentId: config.director.id, task });
187
+ const res = await callRunner(config.director, prompt, 'Reading the request', 'Writing the answer');
188
+ halted();
189
+ if (!res.ok) {
190
+ emit({ type: 'agent.failed', agentId: config.director.id, reason: res.reason });
191
+ return null;
192
+ }
193
+ return res.text;
194
+ }
195
+ function directorSay(to, text, tokens = null) {
196
+ emit({ type: 'agent.message', agentId: config.director.id, to, text, tokens });
197
+ return journal.redact(text);
198
+ }
199
+ async function intake() {
200
+ emit({ type: 'stage.changed', stage: 'director-intake', loop: 1 });
201
+ const rule = () => `Brief: deliver "${oneLine(goal, 300)}".${atts.length ? ` The owner attached ${atts.length} file(s): ${atts.map(a => a.name).join(', ')}. Every team reads them as part of the request.` : ''} Pipeline: BA agrees one handoff -> Implement builds it -> QC verifies (up to ${config.limits.qcLoops} return loops) -> BA checks against the handoff -> final report to the owner.`;
202
+ let brief = rule();
203
+ if (modelDirector()) {
204
+ const t = await directorAsk('intake brief', `${role(config.director, 'You are the Director. Write a short intake brief (scope, assumptions, what BA should clarify) for the owner request.')}\n${common()}`);
205
+ if (t?.trim())
206
+ brief = t;
207
+ }
208
+ else
209
+ emit({ type: 'agent.started', agentId: config.director.id, task: 'intake brief' });
210
+ intakeBrief = directorSay('ba', brief);
211
+ convo.push({ who: config.director.name, text: intakeBrief });
212
+ await drain();
213
+ }
214
+ async function decide(text) {
215
+ if (modelDirector()) {
216
+ const t = await directorAsk('owner message', `${role(config.director, 'The owner sent you a message mid-run. Reply with ONLY JSON {"decision":"continue|redirect|stop","note":"..."}: continue = keep going with the note applied, redirect = restart from the BA discussion with the note, stop = abort.')}\n${common()}\nOWNER MESSAGE: ${text}\nRECENT:\n${recent(4)}`);
217
+ const m = t ? /\{[\s\S]*\}/.exec(t) : null;
218
+ if (m) {
219
+ try {
220
+ const j = JSON.parse(m[0]);
221
+ if (j.decision === 'continue' || j.decision === 'redirect' || j.decision === 'stop')
222
+ return { decision: j.decision, note: typeof j.note === 'string' && j.note.trim() ? j.note : text.trim() };
223
+ }
224
+ catch { /* fall back to rules */ }
225
+ }
226
+ }
227
+ return ruleDecision(text);
228
+ }
229
+ /** Processes owner messages between agent turns. Throws Redirect / Halt. */
230
+ async function drain() {
231
+ let redirect = false;
232
+ while (inbox.length) {
233
+ const text = inbox.shift();
234
+ const d = await decide(text);
235
+ halted();
236
+ emit({ type: 'director.decision', decision: d.decision, note: d.note });
237
+ if (d.decision === 'stop') {
238
+ doStop('Owner asked the Director to stop.');
239
+ throw new Halt();
240
+ }
241
+ notes.push(d.note);
242
+ if (d.decision === 'redirect')
243
+ redirect = true;
244
+ }
245
+ if (redirect)
246
+ throw new Redirect();
247
+ }
248
+ function doStop(why) {
249
+ if (finished)
250
+ return;
251
+ abort.abort();
252
+ finish('stopped', `Run stopped. ${why}\n\nGoal: ${goal}\n${handoff ? `\nLast handoff: handoff-ba.md\n` : ''}`);
253
+ }
254
+ // ---- stages ----
255
+ async function baDiscussion() {
256
+ const ba = config.teams.ba, total = config.limits.baRounds * ba.length;
257
+ emit({ type: 'stage.changed', stage: 'ba-discussion', loop: 1 });
258
+ let last = '';
259
+ for (let i = 0; i < total; i++) {
260
+ const agent = ba[i % ba.length], peer = ba.length > 1 ? ba[(i + 1) % ba.length] : null, final = i === total - 1;
261
+ const what = final
262
+ ? `This is the final BA turn. Produce the ONE final HANDOFF document in markdown with sections: # HANDOFF, ## Goal, ## Scope, ## Acceptance criteria (checklist "- [ ]"), ## Out of scope, ## Risks. Reconcile the discussion; output only the document.`
263
+ : `Discuss the request with your BA partner${peer ? ` (${peer.name})` : ''}: clarify scope, propose acceptance criteria, challenge weak points. Address your partner directly.`;
264
+ const text = await turn(agent, final ? 'finalize handoff' : `BA discussion ${i + 1}/${total}`, final ? 'implement' : peer?.id ?? 'all', `${header(agent, 'ba-discussion', 1, i + 1, total, final)}${role(agent, what)}\n${common()}\nCONVERSATION SO FAR:\n${recent()}`);
265
+ if (text === null)
266
+ return fail(agent, 'the BA discussion');
267
+ last = text;
268
+ await drain();
269
+ }
270
+ handoff = atts.length ? `${last}\n\n## Attachments from the owner\nPart of this handoff. Read them together with the document above.\n${attachmentLines(atts)}\n` : last;
271
+ const art = journal.writeArtifact('handoff-ba.md', handoff);
272
+ emit({ type: 'handoff.created', from: 'ba', to: 'implement', title: 'BA handoff', artifact: art });
273
+ }
274
+ async function implement(loop) {
275
+ emit({ type: 'stage.changed', stage: 'implement', loop });
276
+ const [lead, ...helpers] = config.teams.implement;
277
+ const base = `HANDOFF (your spec):\n${clip(handoff, 6000)}\n${loop > 1 ? `\nQC REPORT TO FIX (loop ${loop - 1}):\n${clip(qcReport, 4000)}\n` : ''}`;
278
+ const leadText = await turn(lead, loop > 1 ? 'fix QC findings' : 'implement handoff', 'qc', `${header(lead, 'implement', loop)}${role(lead, 'Implement the handoff in the project (edit files, run tests). Finish with: what changed (files) and how to verify.')}\n${common()}\n${base}`);
279
+ if (leadText === null)
280
+ return fail(lead, 'the implementation');
281
+ deliverable = leadText;
282
+ await drain();
283
+ for (const h of helpers) {
284
+ const t = await turn(h, 'help implement', 'qc', `${header(h, 'implement', loop)}${role(h, 'You are a helper developer. Review the lead developer\'s work and complete or fix anything missing. Report what you changed.')}\n${common()}\n${base}\nLEAD REPORT:\n${leadText}`);
285
+ if (t === null)
286
+ return fail(h, 'helping with the implementation');
287
+ deliverable += `\n\n${h.name}: ${t}`;
288
+ await drain();
289
+ }
290
+ }
291
+ /** Returns true when QC passed. */
292
+ async function qc(loop) {
293
+ emit({ type: 'stage.changed', stage: 'qc', loop });
294
+ const agents = config.teams.qc, notesThisLoop = [];
295
+ let fails = 0, firstFail = '';
296
+ for (let i = 0; i < agents.length; i++) {
297
+ const agent = agents[i], peer = agents[(i + 1) % agents.length];
298
+ const text = await turn(agent, `QC review ${i + 1}/${agents.length}`, agents.length > 1 ? (i === agents.length - 1 ? 'implement' : peer.id) : 'implement', `${header(agent, 'qc', loop, i + 1, agents.length, i === agents.length - 1)}${role(agent, 'Review and test the deliverable against the handoff acceptance criteria (read the diff, run tests/commands as needed). Discuss with other QC reviewers: agree or disagree with their notes. End with a last line exactly "VERDICT: PASS" or "VERDICT: FAIL".')}\n${common()}\nHANDOFF:\n${clip(handoff, 6000)}\nDELIVERABLE REPORT:\n${clip(deliverable, 4000)}\n${notesThisLoop.length ? `\nOTHER QC NOTES:\n${notesThisLoop.join('\n\n')}\n` : ''}`);
299
+ let verdict, body;
300
+ if (text === null) { // QC failure = FAIL with reason (the agent.failed event already carries it)
301
+ const f = history.filter(e => e.type === 'agent.failed').at(-1);
302
+ verdict = 'FAIL';
303
+ body = `QC agent could not run: ${f && f.type === 'agent.failed' ? f.reason : 'unknown'}`;
304
+ }
305
+ else {
306
+ verdict = parseVerdict(text);
307
+ body = text;
308
+ }
309
+ notesThisLoop.push(`## ${agent.name} — ${verdict}\n\n${body}`);
310
+ if (verdict === 'FAIL') {
311
+ fails++;
312
+ if (!firstFail)
313
+ firstFail = body.replace(/\n?.*VERDICT.*$/i, '');
314
+ }
315
+ await drain();
316
+ }
317
+ const verdict = fails ? 'FAIL' : 'PASS';
318
+ qcReport = `# QC report (loop ${loop}) — ${verdict}\n\n${notesThisLoop.join('\n\n')}\n`;
319
+ const art = journal.writeArtifact(`qc-report-${loop}.md`, qcReport);
320
+ emit({ type: 'qc.verdict', verdict, loop, summary: oneLine(verdict === 'PASS' ? 'All QC reviewers passed the deliverable.' : firstFail, 300) });
321
+ if (verdict === 'FAIL' && loop <= config.limits.qcLoops)
322
+ emit({ type: 'handoff.created', from: 'qc', to: 'implement', title: `QC report ${loop}`, artifact: art });
323
+ return verdict === 'PASS';
324
+ }
325
+ async function baReview() {
326
+ emit({ type: 'stage.changed', stage: 'ba-review', loop: 1 });
327
+ const lead = config.teams.ba[0];
328
+ const text = await turn(lead, 'review deliverable vs handoff', 'director', `${header(lead, 'ba-review', 1)}${role(lead, 'Check the deliverable against the handoff acceptance criteria, one by one. State approved or not, with reasons.')}\n${common()}\nHANDOFF:\n${clip(handoff, 6000)}\nDELIVERABLE REPORT:\n${clip(deliverable, 4000)}\nQC: ${qcPassed ? 'PASSED' : 'DID NOT PASS (QC loops exhausted)'}\n${qcReport ? clip(qcReport, 3000) : ''}`);
329
+ if (text === null)
330
+ return fail(lead, 'the BA review');
331
+ await drain();
332
+ return text;
333
+ }
334
+ async function delivery(review) {
335
+ emit({ type: 'stage.changed', stage: 'delivery', loop: 1 });
336
+ const arts = ['handoff-ba.md', ...history.filter(e => e.type === 'qc.verdict').map(e => `qc-report-${e.loop}.md`), 'transcript.md'];
337
+ const rules = `# Delivery report\n\n**Goal:** ${oneLine(goal, 400)}\n\n**QC:** ${qcPassed ? 'PASSED' : 'DID NOT PASS within the loop limit — review the QC reports before relying on this'}\n\n## What was built\n${clip(deliverable, 3000)}\n\n## BA review\n${clip(review, 2000)}\n\n## Artifacts\n${arts.map(a => `- ${a}`).join('\n')}\n`;
338
+ let report = rules;
339
+ if (modelDirector()) {
340
+ const t = await directorAsk('delivery report', `${role(config.director, 'Write the final report to the owner in markdown: what was delivered, QC outcome, caveats, artifacts.')}\n${common()}\nHANDOFF:\n${clip(handoff, 4000)}\nDELIVERABLE:\n${clip(deliverable, 3000)}\nQC PASSED: ${qcPassed}\nBA REVIEW:\n${clip(review, 2000)}`);
341
+ if (t?.trim())
342
+ report = t;
343
+ }
344
+ else
345
+ emit({ type: 'agent.started', agentId: config.director.id, task: 'delivery report' });
346
+ directorSay('all', report);
347
+ await drain();
348
+ finish('delivered', journal.redact(report));
349
+ }
350
+ async function pipeline() {
351
+ try {
352
+ await intake();
353
+ let review = '';
354
+ for (;;) {
355
+ try {
356
+ handoff = '';
357
+ qcReport = '';
358
+ deliverable = '';
359
+ qcPassed = false;
360
+ convo.length = 0;
361
+ if (intakeBrief)
362
+ convo.push({ who: config.director.name, text: intakeBrief });
363
+ await baDiscussion();
364
+ for (let loop = 1;; loop++) {
365
+ await implement(loop);
366
+ qcPassed = await qc(loop);
367
+ if (qcPassed || loop > config.limits.qcLoops)
368
+ break;
369
+ }
370
+ review = await baReview();
371
+ await delivery(review);
372
+ break;
373
+ }
374
+ catch (e) {
375
+ if (!(e instanceof Redirect))
376
+ throw e;
377
+ }
378
+ }
379
+ }
380
+ catch (e) {
381
+ if (e instanceof Halt || e instanceof Redirect)
382
+ return;
383
+ finish('failed', `Run failed unexpectedly: ${e instanceof Error ? e.message : String(e)}`);
384
+ }
385
+ }
386
+ const initial = opts.attachments?.length ? addAttachments(opts.attachments) : [];
387
+ emit({ type: 'run.started', goal, config, simulated, ...(initial.length ? { attachments: initial } : {}) });
388
+ void Promise.resolve().then(pipeline);
389
+ return makeHandle(journal.runId, journal.runDir, history, listeners, done, (raw, files) => {
390
+ if (finished)
391
+ return;
392
+ const added = files?.length ? addAttachments(files) : [];
393
+ if (!raw.trim() && added.length === 0)
394
+ return;
395
+ const text = raw.trim() ? raw : 'Please take the attached file(s) into account.';
396
+ emit({ type: 'user.message', text, ...(added.length ? { attachments: added } : {}) });
397
+ if (STOP_RE.test(text)) {
398
+ emit({ type: 'director.decision', decision: 'stop', note: 'Owner asked to stop' });
399
+ doStop('Owner asked the Director to stop.');
400
+ return;
401
+ }
402
+ inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
403
+ }, () => doStop('Stopped from the console.'));
404
+ }
405
+ /** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
406
+ export function replayTeamRun(runDir, opts = {}) {
407
+ const speed = opts.speed && opts.speed > 0 ? opts.speed : 1;
408
+ const events = readTeamJournal(runDir), history = [], listeners = new Set();
409
+ let resolveDone, timer, ended = false;
410
+ const done = new Promise(r => { resolveDone = r; });
411
+ const end = (o) => { if (ended)
412
+ return; ended = true; clearTimeout(timer); resolveDone(o); };
413
+ let i = 0;
414
+ const step = () => {
415
+ if (ended)
416
+ return;
417
+ const e = events[i++];
418
+ history.push(e);
419
+ for (const l of [...listeners]) {
420
+ try {
421
+ l(e);
422
+ }
423
+ catch { /* ignore */ }
424
+ }
425
+ if (e.type === 'run.completed') {
426
+ end(e.outcome);
427
+ return;
428
+ }
429
+ const next = events[i];
430
+ if (!next) {
431
+ end('failed');
432
+ return;
433
+ }
434
+ const gap = Math.min(Math.max(0, Date.parse(next.at) - Date.parse(e.at) || 0), 1500) / speed;
435
+ timer = setTimeout(step, gap);
436
+ };
437
+ if (events.length === 0)
438
+ end('failed');
439
+ else
440
+ timer = setTimeout(step, 0);
441
+ return makeHandle(events[0]?.runId ?? basename(runDir), runDir, history, listeners, done, () => { }, () => end('stopped'));
442
+ }
443
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1,30 @@
1
+ import type { TeamEvent, TeamEventInput } from './types.js';
2
+ export declare function newRunId(now?: Date): string;
3
+ export declare const teamRunsDir: (root: string) => string;
4
+ /** Deep-redacts every string value. */
5
+ export declare function redactDeep<T>(value: T, secrets: readonly string[]): T;
6
+ export interface TeamJournal {
7
+ readonly runId: string;
8
+ readonly runDir: string;
9
+ append(event: TeamEventInput): TeamEvent;
10
+ /** Writes (or overwrites) a redacted artifact file; returns its file name. */
11
+ writeArtifact(name: string, text: string): string;
12
+ appendArtifact(name: string, text: string): void;
13
+ redact(text: string): string;
14
+ }
15
+ export declare function createTeamJournal(opts: {
16
+ projectRoot: string;
17
+ now?: () => Date;
18
+ secrets?: readonly string[];
19
+ runId?: string;
20
+ }): TeamJournal;
21
+ /** Skips malformed lines and reports how many. */
22
+ export declare function readTeamJournal(runDir: string): TeamEvent[] & {
23
+ malformed?: number;
24
+ };
25
+ export interface TeamRunInfo {
26
+ readonly runId: string;
27
+ readonly runDir: string;
28
+ }
29
+ /** Newest first (runId embeds the timestamp). */
30
+ export declare function listTeamRuns(root: string): TeamRunInfo[];
@@ -0,0 +1,70 @@
1
+ // Append-only team journal (JSONL) + artifacts under <root>/.ckit/team/runs/<runId>/. Every string is secret-redacted first.
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { redactSecretText } from '../security/redact.js';
6
+ const pad = (n) => String(n).padStart(2, '0');
7
+ export function newRunId(now = new Date()) {
8
+ return `team-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}-${randomBytes(2).toString('hex')}`;
9
+ }
10
+ export const teamRunsDir = (root) => join(root, '.ckit', 'team', 'runs');
11
+ /** Deep-redacts every string value. */
12
+ export function redactDeep(value, secrets) {
13
+ if (typeof value === 'string')
14
+ return redactSecretText(value, secrets);
15
+ if (Array.isArray(value))
16
+ return value.map(v => redactDeep(v, secrets));
17
+ if (value !== null && typeof value === 'object')
18
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactDeep(v, secrets)]));
19
+ return value;
20
+ }
21
+ export function createTeamJournal(opts) {
22
+ const now = opts.now ?? (() => new Date()), secrets = opts.secrets ?? [];
23
+ const runId = opts.runId ?? newRunId(now()), runDir = join(teamRunsDir(opts.projectRoot), runId);
24
+ mkdirSync(runDir, { recursive: true });
25
+ const file = join(runDir, 'events.jsonl');
26
+ let seq = 0;
27
+ return {
28
+ runId, runDir,
29
+ append(event) {
30
+ const full = redactDeep({ seq: ++seq, at: now().toISOString(), runId, ...event }, secrets);
31
+ appendFileSync(file, JSON.stringify(full) + '\n');
32
+ return full;
33
+ },
34
+ writeArtifact(name, text) { writeFileSync(join(runDir, name), redactSecretText(text, secrets)); return name; },
35
+ appendArtifact(name, text) { appendFileSync(join(runDir, name), redactSecretText(text, secrets)); },
36
+ redact: text => redactSecretText(text, secrets),
37
+ };
38
+ }
39
+ /** Skips malformed lines and reports how many. */
40
+ export function readTeamJournal(runDir) {
41
+ const path = join(runDir, 'events.jsonl');
42
+ const events = [];
43
+ if (!existsSync(path))
44
+ return events;
45
+ let bad = 0;
46
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
47
+ if (!line.trim())
48
+ continue;
49
+ try {
50
+ const e = JSON.parse(line);
51
+ if (typeof e.seq === 'number' && typeof e.type === 'string')
52
+ events.push(e);
53
+ else
54
+ bad++;
55
+ }
56
+ catch {
57
+ bad++;
58
+ }
59
+ }
60
+ events.malformed = bad;
61
+ return events;
62
+ }
63
+ /** Newest first (runId embeds the timestamp). */
64
+ export function listTeamRuns(root) {
65
+ const dir = teamRunsDir(root);
66
+ if (!existsSync(dir))
67
+ return [];
68
+ return readdirSync(dir).filter(n => /^team-\d{8}-\d{6}-[0-9a-f]{4}$/.test(n)).sort().reverse().map(runId => ({ runId, runDir: join(dir, runId) }));
69
+ }
70
+ //# sourceMappingURL=journal.js.map
@@ -0,0 +1,79 @@
1
+ import { type WorkerEnvPolicy, parseExecutorOutput } from '../adapters/launch/executor.js';
2
+ import { type FetchImpl } from '../adapters/openai/openai-advisor.js';
3
+ import type { AgentConfig } from './types.js';
4
+ export interface AgentRunOptions {
5
+ readonly cwd: string;
6
+ readonly timeoutMs: number;
7
+ readonly signal?: AbortSignal;
8
+ readonly onActivity?: (text: string) => void;
9
+ /** Current step label; step/total optional (engine auto-numbers when omitted). */
10
+ readonly onStep?: (label: string, step?: number, total?: number | null) => void;
11
+ readonly onSubagent?: (e: SubagentSignal) => void;
12
+ /** Child env; omitted = derived via executorEnvironment(process.env, advisorKey, kind). */
13
+ readonly env?: Readonly<Record<string, string>>;
14
+ /** Absolute paths of owner-attached images. codex receives them as image inputs (-i); the other CLIs open them by path from the prompt. */
15
+ readonly images?: readonly string[];
16
+ }
17
+ export type SubagentSignal = {
18
+ readonly type: 'started';
19
+ readonly childId: string;
20
+ readonly kind: string | null;
21
+ readonly task: string;
22
+ } | {
23
+ readonly type: 'activity';
24
+ readonly childId: string;
25
+ readonly text: string;
26
+ } | {
27
+ readonly type: 'finished';
28
+ readonly childId: string;
29
+ readonly ok: boolean;
30
+ readonly summary: string;
31
+ };
32
+ export type AgentRunResult = {
33
+ readonly ok: true;
34
+ readonly text: string;
35
+ readonly tokens: number | null;
36
+ } | {
37
+ readonly ok: false;
38
+ readonly reason: string;
39
+ };
40
+ export type AgentRunner = (agent: AgentConfig, prompt: string, opts: AgentRunOptions) => Promise<AgentRunResult>;
41
+ /** CKit advisor key to keep away from workers. The workspace may be a sub-folder of the repository that holds the CKit config, so the enclosing project is checked too. */
42
+ export declare const advisorKeyOf: (cwd: string) => string;
43
+ export interface CodexFrameInfo {
44
+ readonly activity?: string;
45
+ readonly message?: string;
46
+ readonly tokens?: number;
47
+ readonly error?: string;
48
+ }
49
+ /** Pure: one parsed `codex exec --json` frame -> activity line / final-message candidate / token usage. `error` items are warnings, not fatal. */
50
+ export declare function parseCodexFrame(frame: unknown): CodexFrameInfo;
51
+ export declare function codexArgs(agent: AgentConfig, cwd: string, prompt: string, images?: readonly string[]): string[];
52
+ /**
53
+ * Codex worker env. Same boundary as the other workers, with one documented exemption (mirrors the claude-code allowlist): a variable that
54
+ * codex's own config.toml names as a provider credential (`env_key = "NAME"`), or OPENAI_API_KEY (codex's built-in provider), is kept when it
55
+ * is inherited from the launching env even if its value equals the advisor key. An equal value there means the user points both tools at the
56
+ * same gateway, not that CKit copied the advisor key. Values that merely contain the key, and every other name, stay withheld.
57
+ */
58
+ export declare function codexWorkerEnv(processEnv: Readonly<Record<string, string | undefined>>, advisorKey: string, configToml: string): WorkerEnvPolicy;
59
+ export declare function runCodex(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
60
+ /** Pure: claude stream-json frame -> short activity lines. */
61
+ export declare function claudeFrameActivity(frame: unknown): string[];
62
+ export declare function runExecutorAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
63
+ export { parseExecutorOutput };
64
+ export declare function runApiAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions & {
65
+ readonly fetchImpl?: FetchImpl;
66
+ }): Promise<AgentRunResult>;
67
+ /** Default dispatch by agent.cli. `simulated` agents get the scripted runner. */
68
+ export declare const dispatchRunner: AgentRunner;
69
+ /** Engine prompts begin with `[[ckit-team stage=<s> loop=<n> turn=<i>/<n> final=<0|1>]]` and carry a `GOAL: ...` line; the simulator keys off those. */
70
+ export declare function simHeader(h: {
71
+ stage: string;
72
+ loop: number;
73
+ turn: number;
74
+ turns: number;
75
+ final: boolean;
76
+ }): string;
77
+ export declare function createSimulatedRunner(options?: {
78
+ readonly speed?: number;
79
+ }): AgentRunner;