@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,497 @@
1
+ // Local-only GUI server for Agent Company: static assets from repo-root gui/, token-guarded JSON API, SSE event stream.
2
+ import { createServer } from 'node:http';
3
+ import { createReadStream, createWriteStream, existsSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from 'node:fs';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { Transform } from 'node:stream';
6
+ import { extname, join, normalize, resolve, sep } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
9
+ import { spawn } from 'node:child_process';
10
+ import { hostname, networkInterfaces } from 'node:os';
11
+ import { loadCkitConfig, readDotenvFile, resolveProjectRoot } from '../settings/env-config.js';
12
+ import { checkConnection } from '../adapters/openai/openai-advisor.js';
13
+ import { defaultTeamConfig, loadTeamConfig, parseTeamConfig, teamConfigPath } from '../team/config.js';
14
+ import { deleteSecret, hasSecret, readSecret, setSecret, SECRET_NAME_RE } from '../team/secrets.js';
15
+ import { replayTeamRun, startTeamRun } from '../team/engine.js';
16
+ import { detectClis } from '../team/cli-models.js';
17
+ import { dispatchRunner } from '../team/runners.js';
18
+ import { listTeamRuns, readTeamJournal } from '../team/journal.js';
19
+ import { mkdirSync, writeFileSync } from 'node:fs';
20
+ import { dirname } from 'node:path';
21
+ const GUI_DIR = resolve(fileURLToPath(new URL('../../../gui/', import.meta.url)));
22
+ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
23
+ const ARTIFACT_RE = /^(report\.md|transcript\.md|handoff-ba\.md|qc-report-\d{1,3}\.md)$/;
24
+ const RUN_ID_RE = /^team-\d{8}-\d{6}-[0-9a-f]{4}$/;
25
+ /** Attachments: any file type. Limits only keep a runaway upload from filling the disk. */
26
+ const MAX_UPLOAD_BYTES = 2 * 1024 ** 3, MAX_PENDING_UPLOADS = 100, MAX_ATTACHMENTS_PER_SEND = 50;
27
+ const UPLOAD_ID_RE = /^[0-9a-f]{24}$/, ATTACHMENT_NAME_RE = /^[^\\/\0]{1,160}$/;
28
+ /** Shown inline (thumbnails / new tab); every other attachment is sent as a download so the browser never runs it. */
29
+ const INLINE_IMAGE = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
30
+ const allAgents = (c) => [c.director, ...c.teams.ba, ...c.teams.implement, ...c.teams.qc];
31
+ function json(res, status, body) {
32
+ const s = JSON.stringify(body);
33
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(s) });
34
+ res.end(s);
35
+ }
36
+ async function readBody(req, max = 1_000_000) {
37
+ const chunks = [];
38
+ let n = 0;
39
+ for await (const c of req) {
40
+ n += c.length;
41
+ if (n > max)
42
+ throw new Error('body too large');
43
+ chunks.push(c);
44
+ }
45
+ const t = Buffer.concat(chunks).toString('utf8');
46
+ return t ? JSON.parse(t) : {};
47
+ }
48
+ const obj = (v) => (v !== null && typeof v === 'object' && !Array.isArray(v) ? v : {});
49
+ export function openBrowser(url, platform = process.platform) {
50
+ const [cmd, args] = platform === 'darwin' ? ['open', [url]] : platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
51
+ try {
52
+ const c = spawn(cmd, args, { shell: false, detached: true, stdio: 'ignore' });
53
+ c.on('error', () => undefined);
54
+ c.unref();
55
+ }
56
+ catch { /* best effort */ }
57
+ }
58
+ export async function startGuiServer(opts) {
59
+ const root = opts.projectRoot;
60
+ const token = opts.token !== undefined && /^[A-Za-z0-9_-]{16,128}$/.test(opts.token) ? opts.token : randomBytes(24).toString('hex');
61
+ let port = 0;
62
+ let current = null;
63
+ const sse = new Set();
64
+ let unsub = null;
65
+ const sendEvent = (res, e) => { res.write(`data: ${JSON.stringify(e)}\n\n`); };
66
+ const attach = (handle, goal, simulated) => {
67
+ unsub?.();
68
+ const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null };
69
+ current = cur;
70
+ for (const r of sse)
71
+ r.write('event: reset\ndata: {}\n\n');
72
+ unsub = handle.subscribe(e => { for (const r of sse) {
73
+ try {
74
+ sendEvent(r, e);
75
+ }
76
+ catch { /* dead socket */ }
77
+ } });
78
+ for (const r of sse)
79
+ r.write('event: ready\ndata: {}\n\n');
80
+ void handle.done.then(o => { cur.outcome = o; });
81
+ };
82
+ const isRunning = () => current !== null && current.outcome === null;
83
+ const loadConfig = () => { const r = loadTeamConfig(root); return r.ok ? r.config : defaultTeamConfig(); };
84
+ const publicConfig = (c) => {
85
+ const dec = (a) => ({ ...a, hasKey: a.apiKeyRef ? hasSecret(a.apiKeyRef) : false });
86
+ return { version: 1, director: dec(c.director), teams: { ba: c.teams.ba.map(dec), implement: c.teams.implement.map(dec), qc: c.teams.qc.map(dec) }, limits: c.limits };
87
+ };
88
+ const runDirOf = (id) => {
89
+ if (id === 'current')
90
+ return current?.handle.runDir ?? null;
91
+ if (!RUN_ID_RE.test(id))
92
+ return null;
93
+ return listTeamRuns(root).find(r => r.runId === id)?.runDir ?? null;
94
+ };
95
+ // Uploaded files wait here until a run start / owner message claims them by id; then they move into that run's attachments folder.
96
+ const uploadDir = join(root, '.ckit', 'team', 'uploads');
97
+ const uploads = new Map();
98
+ // Leftovers of an earlier session that never sent them (older than a day) are removed at start.
99
+ try {
100
+ for (const n of readdirSync(uploadDir)) {
101
+ const f = join(uploadDir, n);
102
+ if (UPLOAD_ID_RE.test(n) && Date.now() - statSync(f).mtimeMs > 86_400_000)
103
+ rmSync(f, { force: true });
104
+ }
105
+ }
106
+ catch { /* no upload folder yet */ }
107
+ const claim = (ids) => {
108
+ if (ids === undefined)
109
+ return [];
110
+ if (!Array.isArray(ids) || ids.length > MAX_ATTACHMENTS_PER_SEND || !ids.every(i => typeof i === 'string' && uploads.has(i)))
111
+ return null;
112
+ return [...new Set(ids)].map(i => { const u = uploads.get(i); return { name: u.name, file: u.file }; });
113
+ };
114
+ const release = (ids) => { for (const i of Array.isArray(ids) ? ids : []) {
115
+ const u = uploads.get(i);
116
+ if (u) {
117
+ rmSync(u.file, { force: true });
118
+ uploads.delete(i);
119
+ }
120
+ } };
121
+ let checks = 0;
122
+ async function api(req, res, url) {
123
+ const m = req.method ?? 'GET', p = url.pathname;
124
+ if (m === 'GET' && p === '/api/events') {
125
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
126
+ res.write('retry: 2000\n\n');
127
+ sse.add(res);
128
+ const hb = setInterval(() => { try {
129
+ res.write(': hb\n\n');
130
+ }
131
+ catch { /* closed */ } }, 15_000);
132
+ req.on('close', () => { clearInterval(hb); sse.delete(res); });
133
+ if (current) { // replay history only to this client
134
+ const h = current.handle;
135
+ let un = null;
136
+ un = h.subscribe(e => { try {
137
+ sendEvent(res, e);
138
+ }
139
+ catch { /* closed */ } });
140
+ un(); // subscribe replays synchronously; live events arrive through the shared fan-out
141
+ }
142
+ res.write('event: ready\ndata: {}\n\n');
143
+ return;
144
+ }
145
+ if (m === 'GET' && p === '/api/state') {
146
+ const c = loadConfig();
147
+ const configured = allAgents(c).some(a => a.cli !== 'auto' && a.cli !== 'simulated');
148
+ return json(res, 200, { config: publicConfig(c), configExists: existsSync(teamConfigPath(root)), projectRoot: root, simulatedDefault: !configured,
149
+ run: current ? { runId: current.handle.runId, goal: current.goal, simulated: current.simulated, startedAt: current.startedAt, running: current.outcome === null, outcome: current.outcome } : null });
150
+ }
151
+ if (m === 'PUT' && p === '/api/config') {
152
+ const body = await readBody(req);
153
+ const stripped = JSON.parse(JSON.stringify(body, (k, v) => (k === 'hasKey' ? undefined : v)));
154
+ const r = parseTeamConfig(stripped);
155
+ if (!r.ok)
156
+ return json(res, 400, { errors: r.errors });
157
+ if (url.searchParams.get('dry') === '1')
158
+ return json(res, 200, { ok: true, dry: true });
159
+ const path = teamConfigPath(root);
160
+ mkdirSync(dirname(path), { recursive: true });
161
+ writeFileSync(path, JSON.stringify(r.config, null, 2) + '\n');
162
+ return json(res, 200, { ok: true, config: publicConfig(r.config) });
163
+ }
164
+ const sec = /^\/api\/secrets\/([^/]+)$/.exec(p);
165
+ if (sec) {
166
+ const name = decodeURIComponent(sec[1]);
167
+ if (!SECRET_NAME_RE.test(name))
168
+ return json(res, 400, { error: 'invalid secret name' });
169
+ if (m === 'PUT') {
170
+ const v = obj(await readBody(req))['value'];
171
+ if (typeof v !== 'string' || !v)
172
+ return json(res, 400, { error: 'value required' });
173
+ setSecret(name, v);
174
+ return json(res, 200, { ok: true, hasKey: true });
175
+ }
176
+ if (m === 'DELETE') {
177
+ deleteSecret(name);
178
+ return json(res, 200, { ok: true, hasKey: false });
179
+ }
180
+ }
181
+ if (m === 'POST' && p === '/api/test-connection') {
182
+ const id = obj(await readBody(req))['agentId'];
183
+ const a = allAgents(loadConfig()).find(x => x.id === id);
184
+ if (!a)
185
+ return json(res, 404, { error: 'unknown agent' });
186
+ if (a.cli !== 'api')
187
+ return json(res, 400, { error: 'agent is not cli=api' });
188
+ const ck = loadCkitConfig({ projectRoot: root });
189
+ const baseUrl = (a.baseUrl ?? (ck.ok ? ck.config.baseUrl : '')).replace(/\/+$/, '');
190
+ if (!/^https?:\/\//.test(baseUrl))
191
+ return json(res, 200, { status: 'unreachable', http: null, note: 'no base URL' });
192
+ const key = readSecret(a.apiKeyRef) ?? (ck.ok ? ck.config.apiKey : '');
193
+ const r = await checkConnection({ baseUrl, auth: key ? 'bearer' : 'none', apiKey: key });
194
+ return json(res, 200, r);
195
+ }
196
+ if (m === 'GET' && p === '/api/runs') {
197
+ const runs = listTeamRuns(root).map(r => {
198
+ const ev = readTeamJournal(r.runDir);
199
+ const first = ev[0], last = ev[ev.length - 1];
200
+ const goal = first?.type === 'run.started' ? first.goal : '';
201
+ const outcome = last?.type === 'run.completed' ? last.outcome : 'incomplete';
202
+ const durationMs = first && last ? Math.max(0, Date.parse(last.at) - Date.parse(first.at)) : 0;
203
+ return { runId: r.runId, goal, outcome, startedAt: first?.at ?? null, durationMs, simulated: first?.type === 'run.started' ? first.simulated : false };
204
+ });
205
+ return json(res, 200, { runs });
206
+ }
207
+ if (m === 'POST' && p === '/api/uploads') {
208
+ // Raw file body (any type), name in ?name=. Streamed to disk, never parsed or executed here.
209
+ const name = url.searchParams.get('name') ?? '';
210
+ if (!ATTACHMENT_NAME_RE.test(name))
211
+ return json(res, 400, { error: 'file name required' });
212
+ if (uploads.size >= MAX_PENDING_UPLOADS)
213
+ return json(res, 429, { error: 'too many files waiting; send or remove some first' });
214
+ const id = randomBytes(12).toString('hex'), file = join(uploadDir, id);
215
+ mkdirSync(uploadDir, { recursive: true });
216
+ let size = 0;
217
+ const meter = new Transform({ transform(chunk, _enc, cb) { size += chunk.length; cb(size > MAX_UPLOAD_BYTES ? new Error('too large') : null, chunk); } });
218
+ try {
219
+ await pipeline(req, meter, createWriteStream(file, { flags: 'wx', mode: 0o600 }));
220
+ }
221
+ catch {
222
+ rmSync(file, { force: true });
223
+ return json(res, size > MAX_UPLOAD_BYTES ? 413 : 400, { error: size > MAX_UPLOAD_BYTES ? 'file is larger than 2 GB' : 'upload interrupted' });
224
+ }
225
+ uploads.set(id, { name, file, size });
226
+ return json(res, 200, { id, name, size });
227
+ }
228
+ const up = /^\/api\/uploads\/([^/]+)$/.exec(p);
229
+ if (up && m === 'DELETE') {
230
+ if (!UPLOAD_ID_RE.test(up[1]) || !uploads.has(up[1]))
231
+ return json(res, 404, { error: 'unknown upload' });
232
+ release([up[1]]);
233
+ return json(res, 200, { ok: true });
234
+ }
235
+ if (m === 'POST' && p === '/api/runs') {
236
+ if (isRunning())
237
+ return json(res, 409, { error: 'a run is already active' });
238
+ const b = obj(await readBody(req));
239
+ const files = claim(b['attachments']);
240
+ if (files === null)
241
+ return json(res, 400, { error: 'unknown attachment; attach the file again' });
242
+ const goal = (typeof b['goal'] === 'string' ? b['goal'].trim() : '') || (files.length ? `Work from the attached file(s): ${files.map(f => f.name).join(', ')}` : '');
243
+ if (!goal)
244
+ return json(res, 400, { error: 'goal required' });
245
+ const simulated = b['simulated'] === true;
246
+ const handle = startTeamRun({ projectRoot: root, goal, config: loadConfig(), simulated, attachments: files });
247
+ release(b['attachments']);
248
+ attach(handle, goal, simulated);
249
+ return json(res, 200, { runId: handle.runId });
250
+ }
251
+ const rp = /^\/api\/runs\/([^/]+)\/(replay|(?:artifact|attachment)\/([^/]+))$/.exec(p);
252
+ if (rp) {
253
+ const id = decodeURIComponent(rp[1]);
254
+ if (m === 'POST' && rp[2] === 'replay') {
255
+ if (isRunning())
256
+ return json(res, 409, { error: 'a run is already active' });
257
+ const dir = runDirOf(id);
258
+ if (!dir || id === 'current')
259
+ return json(res, 404, { error: 'unknown run' });
260
+ const speed = Number(obj(await readBody(req))['speed']);
261
+ const handle = replayTeamRun(dir, { speed: [1, 2, 4].includes(speed) ? speed : 1 });
262
+ attach(handle, '(replay)', false);
263
+ return json(res, 200, { runId: handle.runId, replay: true });
264
+ }
265
+ if (m === 'GET' && rp[2]?.startsWith('attachment/') && rp[3]) {
266
+ // A file the owner attached to this run. Images are shown inline; everything else downloads.
267
+ const name = decodeURIComponent(rp[3]), dir = runDirOf(id);
268
+ if (!ATTACHMENT_NAME_RE.test(name) || name.startsWith('.') || !dir)
269
+ return json(res, 404, { error: 'not found' });
270
+ const file = join(dir, 'attachments', name);
271
+ let size = -1;
272
+ try {
273
+ const st = statSync(file);
274
+ if (st.isFile())
275
+ size = st.size;
276
+ }
277
+ catch { /* missing */ }
278
+ if (size < 0)
279
+ return json(res, 404, { error: 'not found' });
280
+ const inline = INLINE_IMAGE[extname(name).toLowerCase()];
281
+ res.writeHead(200, { 'content-type': inline ?? 'application/octet-stream', 'content-length': size, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
282
+ 'content-security-policy': "default-src 'none'; sandbox", 'content-disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(name)}` });
283
+ return void createReadStream(file).on('error', () => res.destroy()).pipe(res);
284
+ }
285
+ if (m === 'GET' && rp[2]?.startsWith('artifact/') && rp[3]) {
286
+ const name = decodeURIComponent(rp[3]);
287
+ const dir = runDirOf(id);
288
+ if (!ARTIFACT_RE.test(name) || !dir)
289
+ return json(res, 404, { error: 'not found' });
290
+ const file = join(dir, name);
291
+ if (!existsSync(file))
292
+ return json(res, 404, { error: 'not found' });
293
+ res.writeHead(200, { 'content-type': 'text/markdown; charset=utf-8', 'cache-control': 'no-store' });
294
+ return void res.end(readFileSync(file));
295
+ }
296
+ }
297
+ if (m === 'POST' && p === '/api/check-agent') {
298
+ // One tiny read-only turn through the same runner a real run uses, so "works here" means "works in a run".
299
+ const b = obj(await readBody(req)), cli = b['cli'], model = b['model'];
300
+ if (cli !== 'claude-code' && cli !== 'codex' && cli !== 'omp')
301
+ return json(res, 400, { error: 'cli must be claude-code, codex or omp' });
302
+ if (model !== null && (typeof model !== 'string' || !/^[A-Za-z0-9._:\/@\[\]-]{1,120}$/.test(model)))
303
+ return json(res, 400, { error: 'invalid model name' });
304
+ if (checks >= 3)
305
+ return json(res, 429, { error: 'too many checks running; wait for one to finish' });
306
+ checks++;
307
+ try {
308
+ const r = await dispatchRunner({ id: 'check', name: 'check', team: 'qc', cli, model, access: 'read' }, 'Reply with the single word OK. Do not use any tools.', { cwd: root, timeoutMs: 90_000 });
309
+ return json(res, 200, r.ok ? { ok: true } : { ok: false, reason: r.reason });
310
+ }
311
+ finally {
312
+ checks--;
313
+ }
314
+ }
315
+ if (m === 'GET' && p === '/api/clis')
316
+ return json(res, 200, { clis: detectClis(), configFile: teamConfigPath(root) });
317
+ if (m === 'POST' && p === '/api/runs/current/message') {
318
+ if (!isRunning() || !current)
319
+ return json(res, 409, { error: 'no active run' });
320
+ const b = obj(await readBody(req)), t = typeof b['text'] === 'string' ? b['text'] : '', files = claim(b['attachments']);
321
+ if (files === null)
322
+ return json(res, 400, { error: 'unknown attachment; attach the file again' });
323
+ if (!t.trim() && files.length === 0)
324
+ return json(res, 400, { error: 'text required' });
325
+ current.handle.sendToDirector(t.slice(0, 4000), files);
326
+ release(b['attachments']);
327
+ return json(res, 200, { ok: true });
328
+ }
329
+ if (m === 'POST' && p === '/api/runs/current/stop') {
330
+ if (!isRunning() || !current)
331
+ return json(res, 409, { error: 'no active run' });
332
+ current.handle.stop();
333
+ return json(res, 200, { ok: true });
334
+ }
335
+ json(res, 404, { error: 'not found' });
336
+ }
337
+ function serveStatic(res, pathname) {
338
+ let rel;
339
+ try {
340
+ rel = decodeURIComponent(pathname);
341
+ }
342
+ catch {
343
+ res.writeHead(400).end();
344
+ return;
345
+ }
346
+ if (rel.includes('\0')) {
347
+ res.writeHead(400).end();
348
+ return;
349
+ }
350
+ if (rel === '/' || rel === '')
351
+ rel = '/index.html';
352
+ const file = normalize(join(GUI_DIR, rel));
353
+ if (file !== GUI_DIR && !file.startsWith(GUI_DIR + sep)) {
354
+ res.writeHead(403).end('forbidden');
355
+ return;
356
+ }
357
+ let ok = false;
358
+ try {
359
+ ok = statSync(file).isFile();
360
+ }
361
+ catch { /* missing */ }
362
+ if (!ok || !(extname(file) in MIME)) {
363
+ res.writeHead(404, { 'content-type': 'text/plain' }).end('not found');
364
+ return;
365
+ }
366
+ res.writeHead(200, { 'content-type': MIME[extname(file)], 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-security-policy': "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'" });
367
+ res.end(readFileSync(file));
368
+ }
369
+ const bind = opts.host ?? '127.0.0.1', lan = bind !== '127.0.0.1';
370
+ const server = createServer((req, res) => {
371
+ const host = req.headers.host ?? '';
372
+ // Loopback mode: only the two local names. LAN mode (opt-in): any plain hostname/IP on our port; cross-site requests are still refused because Origin must match Host, and every API call needs the token.
373
+ const hostOk = lan ? new RegExp(`^[A-Za-z0-9.-]+:${port}$`).test(host) : host === `127.0.0.1:${port}` || host === `localhost:${port}`;
374
+ if (!hostOk) {
375
+ res.writeHead(403, { 'content-type': 'text/plain' }).end('bad host');
376
+ return;
377
+ }
378
+ const origin = req.headers.origin;
379
+ if (origin !== undefined && origin !== `http://${host}`) {
380
+ res.writeHead(403, { 'content-type': 'text/plain' }).end('bad origin');
381
+ return;
382
+ }
383
+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`);
384
+ if (url.pathname.startsWith('/api/')) {
385
+ const got = req.headers['x-ckit-token'] ?? url.searchParams.get('t') ?? '';
386
+ const a = Buffer.from(String(got)), b = Buffer.from(token);
387
+ if (a.length !== b.length || !timingSafeEqual(a, b))
388
+ return json(res, 401, { error: 'missing or bad token' });
389
+ api(req, res, url).catch(err => { if (!res.headersSent)
390
+ json(res, err instanceof SyntaxError ? 400 : 500, { error: err instanceof SyntaxError ? 'invalid JSON' : 'internal error' });
391
+ else
392
+ res.end(); });
393
+ return;
394
+ }
395
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
396
+ res.writeHead(405).end();
397
+ return;
398
+ }
399
+ serveStatic(res, url.pathname);
400
+ });
401
+ await new Promise((ok, bad) => { server.once('error', bad); server.listen(opts.port ?? 4317, bind, ok); });
402
+ port = server.address().port;
403
+ const url = `http://127.0.0.1:${port}/?t=${token}`;
404
+ if (opts.open === true)
405
+ openBrowser(url);
406
+ return {
407
+ url,
408
+ close: () => new Promise(done => {
409
+ try {
410
+ current?.handle.stop();
411
+ }
412
+ catch { /* ignore */ }
413
+ unsub?.();
414
+ for (const r of sse)
415
+ r.end();
416
+ release([...uploads.keys()]);
417
+ server.close(() => done());
418
+ server.closeAllConnections();
419
+ }),
420
+ };
421
+ }
422
+ /** Folder the GUI works in: the current folder itself (symlinks resolved), never a parent. */
423
+ export function guiWorkspace(cwd) { try {
424
+ return realpathSync(resolve(cwd));
425
+ }
426
+ catch {
427
+ return resolve(cwd);
428
+ } }
429
+ /** Where `ckit gui` listens. Order: flags > shell environment > project env file > .ckit/gui.json > default (this machine only). */
430
+ export function resolveGuiSettings(root, shellEnv, args, outerRoot) {
431
+ // Per-project GUI settings: .ckit/gui.json {"host": "0.0.0.0", "port": 4317}. Flags win over the file.
432
+ let port = 4317, open = true, explicitPort = false, host = '127.0.0.1';
433
+ try {
434
+ const g = JSON.parse(readFileSync(join(root, '.ckit', 'gui.json'), 'utf8'));
435
+ if (typeof g.host === 'string' && /^[A-Za-z0-9.:-]+$/.test(g.host))
436
+ host = g.host === 'localhost' ? '127.0.0.1' : g.host;
437
+ if (typeof g.port === 'number' && Number.isInteger(g.port) && g.port > 0 && g.port < 65536) {
438
+ port = g.port;
439
+ explicitPort = true;
440
+ }
441
+ }
442
+ catch { /* no file or unreadable: defaults */ }
443
+ // CKIT_GUI_HOST / CKIT_GUI_PORT / CKIT_GUI_TOKEN come from the shell or from the project's env file. Order: flags > shell > project env file > .ckit/gui.json > default.
444
+ let fileEnv = {};
445
+ // outerRoot = the enclosing repository when the GUI is started in a sub-folder: its env file supplies the network settings the folder itself does not set.
446
+ try {
447
+ fileEnv = { ...(outerRoot !== undefined && outerRoot !== root ? readDotenvFile(outerRoot).values : {}), ...readDotenvFile(root).values };
448
+ }
449
+ catch { /* unreadable file: shell only */ }
450
+ const setting = (name) => shellEnv[name] ?? fileEnv[name];
451
+ const rawToken = setting('CKIT_GUI_TOKEN') || undefined;
452
+ const tokenOk = rawToken !== undefined && /^[A-Za-z0-9_-]{16,128}$/.test(rawToken);
453
+ const eh = setting('CKIT_GUI_HOST'), ep = Number(setting('CKIT_GUI_PORT'));
454
+ if (eh !== undefined && /^[A-Za-z0-9.:-]+$/.test(eh))
455
+ host = eh === 'localhost' ? '127.0.0.1' : eh;
456
+ if (Number.isInteger(ep) && ep > 0 && ep < 65536) {
457
+ port = ep;
458
+ explicitPort = true;
459
+ }
460
+ for (const a of args) {
461
+ const m = /^--port=(\d+)$/.exec(a), hm = /^--host=([A-Za-z0-9.:-]+)$/.exec(a);
462
+ if (m) {
463
+ port = Number(m[1]);
464
+ explicitPort = true;
465
+ }
466
+ else if (hm)
467
+ host = hm[1] === 'localhost' ? '127.0.0.1' : hm[1];
468
+ else if (a === '--lan')
469
+ host = '0.0.0.0';
470
+ else if (a === '--no-open')
471
+ open = false;
472
+ }
473
+ return { host, port, explicitPort, open, ...(tokenOk ? { token: rawToken } : {}), tokenIgnored: rawToken !== undefined && !tokenOk };
474
+ }
475
+ export async function runGuiCommand(args) {
476
+ // The workspace is exactly the folder `ckit gui` was typed in: agents run there and .ckit/ (team config, runs) is kept there. It is NOT widened to an enclosing git repository.
477
+ const root = guiWorkspace(process.cwd());
478
+ const { host, port, explicitPort, open, token: fixedToken, tokenIgnored } = resolveGuiSettings(root, process.env, args, resolveProjectRoot(root));
479
+ if (tokenIgnored)
480
+ process.stderr.write('CKIT_GUI_TOKEN ignored: it must be 16-128 characters of letters, digits, _ or -. Using a random token.\n');
481
+ let srv;
482
+ const extra = fixedToken !== undefined ? { token: fixedToken } : {};
483
+ try {
484
+ srv = await startGuiServer({ projectRoot: root, port, open, host, ...extra });
485
+ }
486
+ catch (error) {
487
+ // Default port busy (another ckit GUI is open): take a free port instead of failing. An explicit --port still fails loudly.
488
+ if (explicitPort || error.code !== 'EADDRINUSE')
489
+ throw error;
490
+ srv = await startGuiServer({ projectRoot: root, port: 0, open, host, ...extra });
491
+ }
492
+ process.stdout.write(`CKit Agent Company GUI: ${srv.url}\nProject folder (agents run here): ${root}\n${host === '127.0.0.1' ? '' : `LAN access is ON (host ${host}): from another machine open one of:\n${[hostname(), ...Object.values(networkInterfaces()).flat().filter(i => i && i.family === 'IPv4' && !i.internal).map(i => i.address)].map(h => ` ${srv.url.replace('127.0.0.1', h)}`).join('\n')}\nAnyone on the network holding this link can drive the agents; the link is plain HTTP.\n`}Ctrl+C to stop.\n`);
493
+ await new Promise(r => { process.once('SIGINT', () => r()); process.once('SIGTERM', () => r()); });
494
+ await srv.close();
495
+ return 0;
496
+ }
497
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,22 @@
1
+ import type { StorageDatabase } from '../storage/db.js';
2
+ export interface CheckpointInput {
3
+ readonly sessionId: string;
4
+ readonly sessionIdentity: string;
5
+ readonly state: unknown;
6
+ readonly lastSequence: number;
7
+ readonly references?: readonly string[];
8
+ }
9
+ export interface CheckpointRestoreRequest {
10
+ readonly sessionId: string;
11
+ readonly sessionIdentity: string;
12
+ }
13
+ export interface RestoredCheckpoint extends CheckpointInput {
14
+ readonly schemaVersion: 1;
15
+ }
16
+ /** Durable checkpoint metadata stored in the existing T02-01 checkpoints table. */
17
+ export declare class CheckpointStore {
18
+ private readonly db;
19
+ constructor(db: StorageDatabase);
20
+ save(input: CheckpointInput): void;
21
+ restore(request: CheckpointRestoreRequest): RestoredCheckpoint;
22
+ }
@@ -0,0 +1,74 @@
1
+ import { createHash } from 'node:crypto';
2
+ const CHECKPOINT_SCHEMA = '1';
3
+ /** Durable checkpoint metadata stored in the existing T02-01 checkpoints table. */
4
+ export class CheckpointStore {
5
+ db;
6
+ constructor(db) {
7
+ this.db = db;
8
+ }
9
+ save(input) {
10
+ validateInput(input);
11
+ const session = this.db.raw.prepare('SELECT session_id FROM sessions WHERE session_id=?').get(input.sessionId);
12
+ if (!session)
13
+ throw new Error(`checkpoint session not found: ${input.sessionId}`);
14
+ const payload = { schemaVersion: 1, sessionId: input.sessionId, sessionIdentity: input.sessionIdentity, state: input.state, lastSequence: input.lastSequence, references: [...(input.references ?? [])] };
15
+ const json = JSON.stringify(payload), digest = createHash('sha256').update(json).digest('hex'), referencesJson = JSON.stringify([json, ...(input.references ?? [])]);
16
+ this.db.transaction(() => this.db.raw.prepare('INSERT INTO checkpoints(session_id,last_sequence,state_digest,references_json,compatibility_version) VALUES(?,?,?,?,?) ON CONFLICT(session_id) DO UPDATE SET last_sequence=excluded.last_sequence,state_digest=excluded.state_digest,references_json=excluded.references_json,compatibility_version=excluded.compatibility_version').run(input.sessionId, input.lastSequence, digest, referencesJson, CHECKPOINT_SCHEMA));
17
+ }
18
+ restore(request) {
19
+ if (!request.sessionId || !request.sessionIdentity)
20
+ throw new TypeError('checkpoint session identity required');
21
+ const row = this.db.raw.prepare('SELECT last_sequence,state_digest,references_json,compatibility_version FROM checkpoints WHERE session_id=?').get(request.sessionId);
22
+ if (!row)
23
+ throw new Error(`checkpoint not found for session ${request.sessionId}`);
24
+ if (String(row['compatibility_version']) !== CHECKPOINT_SCHEMA) {
25
+ const events = this.db.raw.prepare('SELECT event_json FROM events WHERE session_id=? ORDER BY session_sequence').all(request.sessionId);
26
+ if (events.length === 0)
27
+ throw new Error(`unsupported checkpoint schema: ${String(row['compatibility_version'])}; no valid events available to rebuild`);
28
+ throw new Error(`unsupported checkpoint schema: ${String(row['compatibility_version'])}; event rebuild is not implemented and checkpoint retained`);
29
+ }
30
+ let refs;
31
+ try {
32
+ refs = JSON.parse(String(row['references_json']));
33
+ }
34
+ catch (error) {
35
+ throw new Error('corrupt checkpoint payload: invalid JSON', { cause: error });
36
+ }
37
+ if (!Array.isArray(refs))
38
+ throw new Error('corrupt checkpoint payload: invalid references');
39
+ if (typeof refs[0] === 'string' && refs[0] !== '') {
40
+ try {
41
+ JSON.parse(refs[0]);
42
+ }
43
+ catch (error) {
44
+ throw new Error('corrupt checkpoint payload: invalid JSON', { cause: error });
45
+ }
46
+ }
47
+ else
48
+ throw new Error('corrupt checkpoint payload: invalid references');
49
+ if (refs.slice(1).some(ref => typeof ref !== 'string'))
50
+ throw new Error('corrupt checkpoint payload: invalid references');
51
+ if (!Array.isArray(refs) || typeof refs[0] !== 'string' || refs.slice(1).some(ref => typeof ref !== 'string'))
52
+ throw new Error('corrupt checkpoint payload: invalid references');
53
+ let data;
54
+ try {
55
+ data = JSON.parse(refs[0]);
56
+ }
57
+ catch (error) {
58
+ throw new Error('corrupt checkpoint payload: invalid JSON', { cause: error });
59
+ }
60
+ if (createHash('sha256').update(JSON.stringify(data)).digest('hex') !== String(row['state_digest']))
61
+ throw new Error('corrupt checkpoint payload: digest mismatch');
62
+ if (!isRecord(data) || data['schemaVersion'] !== 1 || data['sessionId'] !== request.sessionId || typeof data['sessionIdentity'] !== 'string' || !Number.isSafeInteger(data['lastSequence']) || data['lastSequence'] !== Number(row['last_sequence']) || !Array.isArray(data['references']))
63
+ throw new Error('corrupt checkpoint payload: invalid structure');
64
+ if (data['sessionIdentity'] !== request.sessionIdentity)
65
+ throw new Error('checkpoint identity mismatch; refusing to attach');
66
+ return Object.freeze({ schemaVersion: 1, sessionId: request.sessionId, sessionIdentity: request.sessionIdentity, state: structuredClone(data['state']), lastSequence: Number(data['lastSequence']), references: Object.freeze(data['references'].map((x) => { if (typeof x !== 'string')
67
+ throw new Error('corrupt checkpoint payload: invalid reference'); return x; })) });
68
+ }
69
+ }
70
+ function validateInput(value) { if (!value.sessionId || !value.sessionIdentity || !Number.isSafeInteger(value.lastSequence) || value.lastSequence < 0)
71
+ throw new TypeError('invalid checkpoint input'); if (value.references?.some(ref => typeof ref !== 'string' || !ref))
72
+ throw new TypeError('invalid checkpoint reference'); JSON.stringify(value.state); }
73
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
74
+ //# sourceMappingURL=checkpoint.js.map
@@ -0,0 +1,52 @@
1
+ export interface ExportInput {
2
+ readonly sessionId: string;
3
+ readonly cwd: string;
4
+ readonly profile: string;
5
+ readonly state?: unknown;
6
+ readonly pendingOrders: readonly unknown[];
7
+ readonly environment?: Readonly<Record<string, string>>;
8
+ readonly args?: readonly string[];
9
+ readonly sensitiveRefs?: readonly string[];
10
+ readonly diagnostics?: unknown;
11
+ }
12
+ export interface ExportBundle {
13
+ readonly schemaVersion: 1;
14
+ readonly sessionId: string;
15
+ readonly state: unknown;
16
+ readonly pendingOrders: readonly unknown[];
17
+ readonly diagnostics: unknown;
18
+ readonly rebindRequired: true;
19
+ readonly sourceBinding: {
20
+ readonly cwd: string;
21
+ readonly profile: string;
22
+ };
23
+ readonly launch: {
24
+ readonly args: readonly string[];
25
+ readonly environment: Readonly<Record<string, string>>;
26
+ };
27
+ readonly sensitiveRefs: readonly {
28
+ readonly ref: string;
29
+ readonly label: 'sensitive';
30
+ }[];
31
+ }
32
+ export interface ImportOptions {
33
+ readonly cwd: string;
34
+ readonly profile: string;
35
+ readonly rebind?: boolean;
36
+ readonly dispatch?: (order: unknown) => void;
37
+ }
38
+ export interface ImportedSession {
39
+ readonly sessionId: string;
40
+ readonly state: unknown;
41
+ readonly pendingOrders: readonly unknown[];
42
+ readonly binding: {
43
+ readonly cwd: string;
44
+ readonly profile: string;
45
+ };
46
+ readonly dispatchRequired: true;
47
+ }
48
+ /** Portable, redacted snapshot. Import is data-only: it never dispatches queued work. */
49
+ export declare class ExportService {
50
+ export(input: ExportInput): ExportBundle;
51
+ import(bundle: ExportBundle, options: ImportOptions): ImportedSession;
52
+ }