@chatpanel/gateway 0.6.109 → 0.7.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 (80) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +1 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2290
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
@@ -1,226 +1 @@
1
- // VENDORED from @chatpanel/events/team-record.js — edit there, then copy over.
2
- // The run record — a team run folded from its events, the same way on the gateway's store
3
- // and in either client. One fold, so what the desktop shows, what the extension shows and
4
- // what the store holds never disagree; and enough on the record to RESUME the run from
5
- // anywhere: the plan, every task's status and transcript, the board, the spend.
6
- //
7
- // The gateway vendors this file (its store used to carry a mirror of it, which is the copy
8
- // that drifts). `checkpointFrom(run)` is what a client hands `resumeTeam` after reading a
9
- // run the process that started it no longer runs.
10
-
11
- import { foldBoard, emptyBoardState } from './team-board.js';
12
-
13
- export const LIVE_RUN_STATUSES = Object.freeze(['planning', 'running', 'merging', 'waiting']);
14
- export const RESUMABLE_RUN_STATUSES = Object.freeze(['waiting', 'stopped', 'failed', 'partial', 'over-budget', 'answered']);
15
- const TASK_TEXT_MAX = 20_000;
16
-
17
- export function emptyRun({ id, client = '', now = Date.now() } = {}) {
18
- return { id, client: String(client || '').slice(0, 40), createdAt: now, lastEventAt: now, status: 'planning', team: '', request: '', roles: [], plan: null, tasks: [], jobs: [], board: [], threads: emptyBoardState(), checkpoint: null, proposal: null, usage: null, stopRequested: null, startedAt: null, endedAt: null };
19
- }
20
-
21
- const taskOf = (run, id) => run.tasks.find((x) => x.id === id);
22
-
23
- /** Fold one event (`{ type, at, payload }`, or a flat `{ type, at, ...payload }`) into the record. */
24
- export function foldRun(run, ev) {
25
- const type = String(ev?.type || '');
26
- const p = ev?.payload && typeof ev.payload === 'object' ? ev.payload : (ev || {});
27
- const at = Number(ev?.at) || Date.now();
28
- run.lastEventAt = at;
29
- switch (type) {
30
- case 'run.started':
31
- case 'run.resumed':
32
- run.team = p.team || run.team; run.request = p.request ?? run.request; run.budget = p.budget || run.budget;
33
- run.roles = Array.isArray(p.roles) ? p.roles : run.roles; run.status = 'planning'; run.startedAt = run.startedAt || at;
34
- if (type === 'run.resumed') { run.endedAt = null; run.checkpoint = null; run.resumedAt = at; }
35
- break;
36
- case 'plan.ready':
37
- run.plan = { by: p.by || 'fixed', tasks: Array.isArray(p.tasks) ? p.tasks : [] };
38
- // A resume replays the plan: keep what the tasks already hold (transcripts, attempts).
39
- run.tasks = run.plan.tasks.map((t) => ({ ...(taskOf(run, t.id) || {}), id: t.id, role: t.role, title: t.title, status: taskOf(run, t.id)?.status === 'ok' ? 'ok' : (t.parent && !t.role ? 'unassigned' : 'pending'), findings: taskOf(run, t.id)?.findings || 0, ...(t.parent ? { parent: t.parent, requestedBy: t.requestedBy || null } : {}), ...(t.grants ? { grants: t.grants, why: t.why || '' } : {}), ...(t.kind ? { kind: t.kind } : {}) }));
40
- run.status = 'running';
41
- break;
42
- // A SUB-TASK (§15.2): requested by a member mid-run, it joins the plan under its parent;
43
- // taken by a member, recruited from the pool, created on a person's approval — or not.
44
- case 'task.requested':
45
- if (p.taskId && !taskOf(run, p.taskId)) {
46
- const task = { id: p.taskId, role: null, title: p.title || p.taskId, prompt: p.prompt || '', dependsOn: Array.isArray(p.dependsOn) ? p.dependsOn : [], parent: p.parent || null, requestedBy: p.by || null, needs: p.needs || null, depth: p.depth || 1, wait: p.wait !== false };
47
- if (run.plan) run.plan.tasks = [...(run.plan.tasks || []), task];
48
- run.tasks.push({ id: task.id, role: null, title: task.title, status: 'requested', findings: 0, parent: task.parent, requestedBy: task.requestedBy, needs: task.needs, requestedAt: at });
49
- }
50
- break;
51
- // A TASK ADDED AFTER THE PLAN — the merge (the judge's task, opened when the members are
52
- // done). It joins the plan so a resume carries it and the board draws its thread and log.
53
- case 'task.added':
54
- if (p.taskId && !taskOf(run, p.taskId)) {
55
- const task = { id: p.taskId, role: p.role || null, title: p.title || p.taskId, dependsOn: Array.isArray(p.dependsOn) ? p.dependsOn : [], ...(p.kind ? { kind: p.kind } : {}) };
56
- if (run.plan) run.plan.tasks = [...(run.plan.tasks || []), task];
57
- run.tasks.push({ id: task.id, role: task.role, title: task.title, status: 'pending', findings: 0, ...(p.kind ? { kind: p.kind } : {}) });
58
- }
59
- break;
60
- case 'task.taken': { const t = taskOf(run, p.taskId); if (t) { t.role = p.role; t.status = 'pending'; t.takenBy = { by: p.by || 'fit', role: p.role, fit: p.fit ?? null, reasons: p.reasons || [], agentId: p.agentId || null, engine: p.engine || null, why: p.why || '', at }; } const pt = run.plan?.tasks?.find((x) => x.id === p.taskId); if (pt) pt.role = p.role; break; }
61
- case 'task.posted': { const t = taskOf(run, p.taskId); if (t) t.job = p.job || null; if (p.job && !run.jobs.some((j) => j.id === p.job.id)) run.jobs.push({ ...p.job, taskId: p.taskId, at }); break; }
62
- case 'task.proposed': { const t = taskOf(run, p.taskId); if (t) t.proposal = { agent: p.agent || null, threadId: p.threadId || null, postId: p.postId || null, why: p.why || '', at }; break; }
63
- case 'task.unassigned': { const t = taskOf(run, p.taskId); if (t) { t.status = 'unassigned'; t.error = p.why || null; t.endedAt = at; } const j = run.jobs.find((x) => x.taskId === p.taskId); if (j) j.status = 'failed'; break; }
64
- case 'task.nudged': { const t = taskOf(run, p.taskId); if (t) t.nudged = [...(t.nudged || []), { grants: p.grants || [], at }]; break; }
65
- case 'run.role-added': if (p.role?.id && !run.roles.includes(p.role.id)) { run.roles.push(p.role.id); run.recruited = [...(run.recruited || []), { ...p.role, jobId: p.jobId || null, at }]; const j = run.jobs.find((x) => x.id === p.jobId); if (j) { j.status = 'recruited'; j.recruited = { agentId: p.role.agent || p.role.id, engine: p.role.engine || null, at }; } } break;
66
- case 'task.started': {
67
- // A start the plan never named (a record from a build whose merge was not a task) gets
68
- // its row here rather than being dropped — the fold never loses a task that ran.
69
- let t = taskOf(run, p.taskId);
70
- if (!t && p.taskId) { t = { id: p.taskId, role: p.role || null, title: p.title || p.taskId, status: 'pending', findings: 0, ...(p.taskId === 'merge' ? { kind: 'merge' } : {}) }; run.tasks.push(t); }
71
- if (t) { t.status = 'running'; t.startedAt = at; t.error = null; }
72
- run.status = 'running'; break;
73
- }
74
- case 'task.model': { const t = taskOf(run, p.taskId); if (t) { t.model = p.model; t.attempts = [...(t.attempts || []), { model: p.model, ...(p.label ? { label: p.label } : {}), at, attempt: p.attempt }]; } break; }
75
- // Which engine the attempt runs on (pillars §13): kept on the attempt, so a record folded
76
- // from events names the model the way the runner's own `attempts` do.
77
- case 'task.routed': { const t = taskOf(run, p.taskId); const a = t?.attempts?.at?.(-1); if (a && p.engine && (a.attempt == null || a.attempt === p.attempt)) a.engine = p.engine; break; }
78
- case 'task.step': { const t = taskOf(run, p.taskId); if (t && Array.isArray(p.steps)) t.transcript = [...(t.transcript || []), ...p.steps]; break; }
79
- case 'task.handoff': { const t = taskOf(run, p.taskId); if (t) { t.model = p.to; t.handoffs = [...(t.handoffs || []), { from: p.from, to: p.to, by: p.by, reason: p.reason, at }]; } break; }
80
- case 'task.tool': { const t = taskOf(run, p.taskId); if (t) t.tools = (t.tools || 0) + 1; break; }
81
- case 'task.delta': { const t = taskOf(run, p.taskId); if (t) t.text = String(p.text || '').slice(0, TASK_TEXT_MAX); break; }
82
- case 'task.finding':
83
- if (p.finding && p.finding.text) { run.board.push({ ...p.finding, at }); const t = taskOf(run, p.taskId); if (t) t.findings += 1; }
84
- break;
85
- case 'task.waiting': { const t = taskOf(run, p.taskId); if (t) { t.status = 'waiting'; t.waitingOn = p.threadId; } break; }
86
- case 'task.done':
87
- case 'task.failed': {
88
- const t = taskOf(run, p.taskId);
89
- if (t) { t.status = p.status || (type === 'task.done' ? 'ok' : 'failed'); t.error = p.error || null; t.ms = p.ms; t.endedAt = at; }
90
- // A job posting's outcome is the sub-task's (§15.2.5): taken by, finished how.
91
- const j = run.jobs.find((x) => x.taskId === p.taskId);
92
- if (j) { j.status = type === 'task.done' ? 'done' : 'failed'; j.endedAt = at; }
93
- break;
94
- }
95
- case 'run.merging': run.status = 'merging'; break;
96
- case 'run.waiting': run.status = 'running'; break;
97
- case 'run.usage': run.usage = p.usage || run.usage; break;
98
- case 'run.done':
99
- run.status = p.status || 'completed'; run.usage = p.usage || run.usage; run.proposal = p.proposal ?? run.proposal; run.endedAt = at;
100
- if (p.checkpoint) run.checkpoint = p.checkpoint;
101
- break;
102
- case 'run.stop-requested': run.stopRequested = at; break;
103
- case 'board.thread': case 'board.post': case 'board.decision': case 'board.thread-status': case 'board.thread-removed':
104
- run.threads = foldBoard(run.threads || emptyBoardState(), ev);
105
- if (type === 'board.thread-status' && p.status !== 'waiting' && run.status === 'waiting' && !(run.threads.threads || []).some((t) => t.kind === 'ask' && t.status === 'waiting')) run.status = 'answered';
106
- break;
107
- default: break;
108
- }
109
- return run;
110
- }
111
-
112
- /** Fold a whole event list into a fresh record. */
113
- export function runFromEvents(id, events, opts = {}) {
114
- const run = emptyRun({ id, ...opts });
115
- for (const ev of events || []) foldRun(run, ev);
116
- return run;
117
- }
118
-
119
- /**
120
- * What `resumeTeam` needs, from the record alone — the runner's own checkpoint when the run
121
- * ended with one, else one built from the folded tasks: whatever the process that ran it
122
- * managed to write before it went. A task recorded `running` (its process died) resumes
123
- * from its transcript like a waiting one.
124
- */
125
- export function checkpointFrom(run) {
126
- if (!run?.plan?.tasks?.length) return null;
127
- if (run.checkpoint?.plan?.tasks?.length) return { ...run.checkpoint, board: run.threads && run.threads.threads?.length >= (run.checkpoint.board?.threads?.length || 0) ? run.threads : run.checkpoint.board };
128
- return {
129
- runId: run.id,
130
- startedAt: run.startedAt || run.createdAt,
131
- plan: run.plan,
132
- tasks: run.tasks.map((t) => ({ id: t.id, role: t.role, title: t.title, status: t.status === 'running' || t.status === 'pending' ? 'stopped' : t.status, text: t.text || '', error: t.error || null, transcript: t.transcript || [], attempts: t.attempts || [], usage: null })),
133
- board: run.threads || emptyBoardState(),
134
- budget: { cap: run.usage?.cap || run.budget || {}, spent: run.usage?.spent || {} },
135
- budgetAsked: false,
136
- };
137
- }
138
-
139
- /** Can this record be picked up again? Not one that completed, not one still being run by a live client. */
140
- export function isResumable(run) {
141
- if (!run?.plan?.tasks?.length) return false;
142
- if (RESUMABLE_RUN_STATUSES.includes(run.status)) return true;
143
- return !!run.stale && LIVE_RUN_STATUSES.includes(run.status); // its client went away mid-run
144
- }
145
-
146
- /**
147
- * The run's spend against its cap, as a board shows it: the record's last `run.usage` (or
148
- * nothing spent yet) with `ms` measured LIVE for a run still going — the stored figure is as
149
- * of the last task's end, and a board read "0 s" through a ten-minute research task.
150
- */
151
- export function spendOf(run, { now = Date.now() } = {}) {
152
- const cap = run?.usage?.cap || run?.budget || null;
153
- if (!cap || !Object.keys(cap).length) return null;
154
- const spent = { tokens: 0, calls: 0, usd: 0, ms: 0, ...(run?.usage?.spent || {}) };
155
- // The clock runs while the client is writing, and STOPS where it stopped: a run whose
156
- // record says `running` because its client died (or its end never landed) is not still
157
- // spending — it read "18m13s / 5m00s" and counting for a member that had finished.
158
- const st = runState(run, { now });
159
- if (LIVE_RUN_STATUSES.includes(run?.status) && run?.startedAt) spent.ms = Math.max(spent.ms || 0, (st.key === 'stalled' ? Number(run.lastEventAt) || now : now) - run.startedAt);
160
- const pct = cap.tokens ? Math.min(100, Math.round(((spent.tokens || 0) / cap.tokens) * 100)) : cap.ms ? Math.min(100, Math.round(((spent.ms || 0) / cap.ms) * 100)) : null;
161
- const over = BUDGET_KEYS.filter((k) => cap[k] && (spent[k] || 0) >= cap[k]);
162
- return { cap, spent, pct, exhausted: run?.usage?.exhausted || over[0] || null, over };
163
- }
164
- const BUDGET_KEYS = ['tokens', 'calls', 'usd', 'ms'];
165
-
166
- export const STALLED_AFTER_MS = 2 * 60_000;
167
-
168
- /**
169
- * What a run IS right now, for a person: the record's status read against the clock. A
170
- * record that says `running` with no event for minutes is STALLED — its client stopped
171
- * writing (died, or its end never landed) — not running. `{ key, label, tone, detail }`;
172
- * `tone` is the chip: on · warn · ok · err · muted.
173
- */
174
- export function runState(run, { now = Date.now(), stalledAfterMs = STALLED_AFTER_MS } = {}) {
175
- const s = String(run?.status || 'planning');
176
- const quiet = Number.isFinite(run?.quietMs) ? run.quietMs : Math.max(0, now - (Number(run?.lastEventAt) || now));
177
- const agoText = (ms) => { const sec = Math.round(ms / 1000); return sec < 60 ? `${sec} s` : sec < 3600 ? `${Math.round(sec / 60)} min` : `${Math.round(sec / 3600)} h`; };
178
- if (s === 'waiting') return { key: 'waiting', label: 'waiting on you', tone: 'warn', detail: '' };
179
- if (LIVE_RUN_STATUSES.includes(s)) {
180
- if (run?.stale === true || quiet > stalledAfterMs) return { key: 'stalled', label: 'stalled', tone: 'err', detail: `no events for ${agoText(quiet)} — its client stopped writing; Resume here picks it up from the record` };
181
- return { key: 'running', label: s === 'merging' ? 'merging' : s === 'planning' ? 'planning' : 'running', tone: 'on', detail: `last event ${agoText(quiet)} ago` };
182
- }
183
- if (s === 'completed') return { key: 'done', label: 'done', tone: 'ok', detail: '' };
184
- if (s === 'partial') return { key: 'partial', label: 'done with failures', tone: 'warn', detail: 'a member failed; the rest merged' };
185
- if (s === 'answered') return { key: 'answered', label: 'answered — resume to continue', tone: 'warn', detail: '' };
186
- if (s === 'over-budget') return { key: 'over-budget', label: 'over budget', tone: 'err', detail: 'stopped with what it had' };
187
- if (s === 'stopped') return { key: 'stopped', label: 'stopped', tone: 'muted', detail: '' };
188
- if (s === 'failed') return { key: 'failed', label: 'failed', tone: 'err', detail: '' };
189
- return { key: s, label: s, tone: 'muted', detail: '' };
190
- }
191
-
192
- /**
193
- * Earlier runs whose work a new run should read before repeating it (§12.2.6, the librarian's
194
- * first step): the same team (or any, when `team` is empty), a request that says the same
195
- * thing (word overlap ≥ `minSimilarity`), findings on the record, not the run itself, newest
196
- * first. `runs` is the store's list (`findings` is a count there). Returns
197
- * `[{ id, at, similarity, findings }]`; the host fetches the record for the findings.
198
- */
199
- export function priorWorkFor(runs, { team = '', request = '', excludeId = null, minSimilarity = 0.6, maxAgeMs = 7 * 24 * 3600_000, now = Date.now(), limit = 3 } = {}) {
200
- const words = (t) => new Set(String(t || '').toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter((w) => w.length > 2));
201
- const want = words(request);
202
- if (!want.size) return [];
203
- const sim = (t) => { const have = words(t); if (!have.size) return 0; let hit = 0; for (const w of want) if (have.has(w)) hit += 1; return hit / Math.max(want.size, have.size); };
204
- return (runs || [])
205
- .filter((r) => r && r.id && r.id !== excludeId && (!team || r.team === team) && !LIVE_RUN_STATUSES.includes(r.status) && (Number(r.findings) || (Array.isArray(r.board) ? r.board.length : 0)) > 0 && now - (Number(r.createdAt) || 0) <= maxAgeMs)
206
- .map((r) => ({ id: r.id, at: r.createdAt, similarity: Math.round(sim(r.request) * 100) / 100, findings: Number(r.findings) || (Array.isArray(r.board) ? r.board.length : 0), status: r.status }))
207
- .filter((r) => r.similarity >= minSimilarity)
208
- .sort((a, b) => b.similarity - a.similarity || b.at - a.at)
209
- .slice(0, limit);
210
- }
211
-
212
- const secs = (ms) => { const s = Math.max(0, Math.round((Number(ms) || 0) / 1000)); return s >= 60 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${s}s`; };
213
- const num = (n) => (Number(n) || 0).toLocaleString('en-US');
214
-
215
- /** One line: `1,240 / 40,000 tokens · 3 / 20 calls · 2m10s / 15m00s`. Only the capped dimensions. */
216
- export function describeSpend(spend) {
217
- if (!spend?.cap) return '';
218
- const { cap, spent } = spend;
219
- const over = (k) => ((spend.over || []).includes(k) ? ' (over)' : '');
220
- return [
221
- cap.tokens ? `${num(spent.tokens)} / ${num(cap.tokens)} tokens${over('tokens')}` : '',
222
- cap.calls ? `${num(spent.calls)} / ${num(cap.calls)} calls${over('calls')}` : '',
223
- cap.usd ? `$${(Number(spent.usd) || 0).toFixed(2)} / $${Number(cap.usd).toFixed(2)}${over('usd')}` : '',
224
- cap.ms ? `${secs(spent.ms)} / ${secs(cap.ms)}${over('ms')}` : '',
225
- ].filter(Boolean).join(' · ');
226
- }
1
+ import{foldBoard as I,emptyBoardState as g}from"./team-board.js";const p=Object.freeze(["planning","running","merging","waiting"]),A=Object.freeze(["waiting","stopped","failed","partial","over-budget","answered"]),w=2e4;function x({id:e,client:a="",now:n=Date.now()}={}){return{id:e,client:String(a||"").slice(0,40),createdAt:n,lastEventAt:n,status:"planning",team:"",request:"",roles:[],plan:null,tasks:[],jobs:[],board:[],threads:g(),checkpoint:null,proposal:null,usage:null,stopRequested:null,startedAt:null,endedAt:null}}const r=(e,a)=>e.tasks.find(n=>n.id===a);function S(e,a){const n=String(a?.type||""),t=a?.payload&&typeof a.payload=="object"?a.payload:a||{},d=Number(a?.at)||Date.now();switch(e.lastEventAt=d,n){case"run.started":case"run.resumed":e.team=t.team||e.team,e.request=t.request??e.request,e.budget=t.budget||e.budget,e.roles=Array.isArray(t.roles)?t.roles:e.roles,e.status="planning",e.startedAt=e.startedAt||d,n==="run.resumed"&&(e.endedAt=null,e.checkpoint=null,e.resumedAt=d);break;case"plan.ready":e.plan={by:t.by||"fixed",tasks:Array.isArray(t.tasks)?t.tasks:[]},e.tasks=e.plan.tasks.map(s=>({...r(e,s.id)||{},id:s.id,role:s.role,title:s.title,status:r(e,s.id)?.status==="ok"?"ok":s.parent&&!s.role?"unassigned":"pending",findings:r(e,s.id)?.findings||0,...s.parent?{parent:s.parent,requestedBy:s.requestedBy||null}:{},...s.grants?{grants:s.grants,why:s.why||""}:{},...s.kind?{kind:s.kind}:{}})),e.status="running";break;case"task.requested":if(t.taskId&&!r(e,t.taskId)){const s={id:t.taskId,role:null,title:t.title||t.taskId,prompt:t.prompt||"",dependsOn:Array.isArray(t.dependsOn)?t.dependsOn:[],parent:t.parent||null,requestedBy:t.by||null,needs:t.needs||null,depth:t.depth||1,wait:t.wait!==!1};e.plan&&(e.plan.tasks=[...e.plan.tasks||[],s]),e.tasks.push({id:s.id,role:null,title:s.title,status:"requested",findings:0,parent:s.parent,requestedBy:s.requestedBy,needs:s.needs,requestedAt:d})}break;case"task.added":if(t.taskId&&!r(e,t.taskId)){const s={id:t.taskId,role:t.role||null,title:t.title||t.taskId,dependsOn:Array.isArray(t.dependsOn)?t.dependsOn:[],...t.kind?{kind:t.kind}:{}};e.plan&&(e.plan.tasks=[...e.plan.tasks||[],s]),e.tasks.push({id:s.id,role:s.role,title:s.title,status:"pending",findings:0,...t.kind?{kind:t.kind}:{}})}break;case"task.taken":{const s=r(e,t.taskId);s&&(s.role=t.role,s.status="pending",s.takenBy={by:t.by||"fit",role:t.role,fit:t.fit??null,reasons:t.reasons||[],agentId:t.agentId||null,engine:t.engine||null,why:t.why||"",at:d});const o=e.plan?.tasks?.find(l=>l.id===t.taskId);o&&(o.role=t.role);break}case"task.posted":{const s=r(e,t.taskId);s&&(s.job=t.job||null),t.job&&!e.jobs.some(o=>o.id===t.job.id)&&e.jobs.push({...t.job,taskId:t.taskId,at:d});break}case"task.proposed":{const s=r(e,t.taskId);s&&(s.proposal={agent:t.agent||null,threadId:t.threadId||null,postId:t.postId||null,why:t.why||"",at:d});break}case"task.unassigned":{const s=r(e,t.taskId);s&&(s.status="unassigned",s.error=t.why||null,s.endedAt=d);const o=e.jobs.find(l=>l.taskId===t.taskId);o&&(o.status="failed");break}case"task.nudged":{const s=r(e,t.taskId);s&&(s.nudged=[...s.nudged||[],{grants:t.grants||[],at:d}]);break}case"run.role-added":if(t.role?.id&&!e.roles.includes(t.role.id)){e.roles.push(t.role.id),e.recruited=[...e.recruited||[],{...t.role,jobId:t.jobId||null,at:d}];const s=e.jobs.find(o=>o.id===t.jobId);s&&(s.status="recruited",s.recruited={agentId:t.role.agent||t.role.id,engine:t.role.engine||null,at:d})}break;case"task.started":{let s=r(e,t.taskId);!s&&t.taskId&&(s={id:t.taskId,role:t.role||null,title:t.title||t.taskId,status:"pending",findings:0,...t.taskId==="merge"?{kind:"merge"}:{}},e.tasks.push(s)),s&&(s.status="running",s.startedAt=d,s.error=null),e.status="running";break}case"task.model":{const s=r(e,t.taskId);s&&(s.model=t.model,s.attempts=[...s.attempts||[],{model:t.model,...t.label?{label:t.label}:{},at:d,attempt:t.attempt}]);break}case"task.routed":{const o=r(e,t.taskId)?.attempts?.at?.(-1);o&&t.engine&&(o.attempt==null||o.attempt===t.attempt)&&(o.engine=t.engine);break}case"task.step":{const s=r(e,t.taskId);s&&Array.isArray(t.steps)&&(s.transcript=[...s.transcript||[],...t.steps]);break}case"task.handoff":{const s=r(e,t.taskId);s&&(s.model=t.to,s.handoffs=[...s.handoffs||[],{from:t.from,to:t.to,by:t.by,reason:t.reason,at:d}]);break}case"task.tool":{const s=r(e,t.taskId);s&&(s.tools=(s.tools||0)+1);break}case"task.delta":{const s=r(e,t.taskId);s&&(s.text=String(t.text||"").slice(0,w));break}case"task.finding":if(t.finding&&t.finding.text){e.board.push({...t.finding,at:d});const s=r(e,t.taskId);s&&(s.findings+=1)}break;case"task.waiting":{const s=r(e,t.taskId);s&&(s.status="waiting",s.waitingOn=t.threadId);break}case"task.done":case"task.failed":{const s=r(e,t.taskId);s&&(s.status=t.status||(n==="task.done"?"ok":"failed"),s.error=t.error||null,s.ms=t.ms,s.endedAt=d);const o=e.jobs.find(l=>l.taskId===t.taskId);o&&(o.status=n==="task.done"?"done":"failed",o.endedAt=d);break}case"run.merging":e.status="merging";break;case"run.waiting":e.status="running";break;case"run.usage":e.usage=t.usage||e.usage;break;case"run.done":e.status=t.status||"completed",e.usage=t.usage||e.usage,e.proposal=t.proposal??e.proposal,e.endedAt=d,t.checkpoint&&(e.checkpoint=t.checkpoint);break;case"run.stop-requested":e.stopRequested=d;break;case"board.thread":case"board.post":case"board.decision":case"board.thread-status":case"board.thread-removed":e.threads=I(e.threads||g(),a),n==="board.thread-status"&&t.status!=="waiting"&&e.status==="waiting"&&!(e.threads.threads||[]).some(s=>s.kind==="ask"&&s.status==="waiting")&&(e.status="answered");break;default:break}return e}function E(e,a,n={}){const t=x({id:e,...n});for(const d of a||[])S(t,d);return t}function N(e){return e?.plan?.tasks?.length?e.checkpoint?.plan?.tasks?.length?{...e.checkpoint,board:e.threads&&e.threads.threads?.length>=(e.checkpoint.board?.threads?.length||0)?e.threads:e.checkpoint.board}:{runId:e.id,startedAt:e.startedAt||e.createdAt,plan:e.plan,tasks:e.tasks.map(a=>({id:a.id,role:a.role,title:a.title,status:a.status==="running"||a.status==="pending"?"stopped":a.status,text:a.text||"",error:a.error||null,transcript:a.transcript||[],attempts:a.attempts||[],usage:null})),board:e.threads||g(),budget:{cap:e.usage?.cap||e.budget||{},spent:e.usage?.spent||{}},budgetAsked:!1}:null}function v(e){return e?.plan?.tasks?.length?A.includes(e.status)?!0:!!e.stale&&p.includes(e.status):!1}function O(e,{now:a=Date.now()}={}){const n=e?.usage?.cap||e?.budget||null;if(!n||!Object.keys(n).length)return null;const t={tokens:0,calls:0,usd:0,ms:0,...e?.usage?.spent||{}},d=q(e,{now:a});p.includes(e?.status)&&e?.startedAt&&(t.ms=Math.max(t.ms||0,(d.key==="stalled"&&Number(e.lastEventAt)||a)-e.startedAt));const s=n.tokens?Math.min(100,Math.round((t.tokens||0)/n.tokens*100)):n.ms?Math.min(100,Math.round((t.ms||0)/n.ms*100)):null,o=j.filter(l=>n[l]&&(t[l]||0)>=n[l]);return{cap:n,spent:t,pct:s,exhausted:e?.usage?.exhausted||o[0]||null,over:o}}const j=["tokens","calls","usd","ms"],$=2*6e4;function q(e,{now:a=Date.now(),stalledAfterMs:n=$}={}){const t=String(e?.status||"planning"),d=Number.isFinite(e?.quietMs)?e.quietMs:Math.max(0,a-(Number(e?.lastEventAt)||a)),s=o=>{const l=Math.round(o/1e3);return l<60?`${l} s`:l<3600?`${Math.round(l/60)} min`:`${Math.round(l/3600)} h`};return t==="waiting"?{key:"waiting",label:"waiting on you",tone:"warn",detail:""}:p.includes(t)?e?.stale===!0||d>n?{key:"stalled",label:"stalled",tone:"err",detail:`no events for ${s(d)} — its client stopped writing; Resume here picks it up from the record`}:{key:"running",label:t==="merging"?"merging":t==="planning"?"planning":"running",tone:"on",detail:`last event ${s(d)} ago`}:t==="completed"?{key:"done",label:"done",tone:"ok",detail:""}:t==="partial"?{key:"partial",label:"done with failures",tone:"warn",detail:"a member failed; the rest merged"}:t==="answered"?{key:"answered",label:"answered — resume to continue",tone:"warn",detail:""}:t==="over-budget"?{key:"over-budget",label:"over budget",tone:"err",detail:"stopped with what it had"}:t==="stopped"?{key:"stopped",label:"stopped",tone:"muted",detail:""}:t==="failed"?{key:"failed",label:"failed",tone:"err",detail:""}:{key:t,label:t,tone:"muted",detail:""}}function _(e,{team:a="",request:n="",excludeId:t=null,minSimilarity:d=.6,maxAgeMs:s=168*36e5,now:o=Date.now(),limit:l=3}={}){const f=i=>new Set(String(i||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(c=>c.length>2)),u=f(n);if(!u.size)return[];const h=i=>{const c=f(i);if(!c.size)return 0;let b=0;for(const y of u)c.has(y)&&(b+=1);return b/Math.max(u.size,c.size)};return(e||[]).filter(i=>i&&i.id&&i.id!==t&&(!a||i.team===a)&&!p.includes(i.status)&&(Number(i.findings)||(Array.isArray(i.board)?i.board.length:0))>0&&o-(Number(i.createdAt)||0)<=s).map(i=>({id:i.id,at:i.createdAt,similarity:Math.round(h(i.request)*100)/100,findings:Number(i.findings)||(Array.isArray(i.board)?i.board.length:0),status:i.status})).filter(i=>i.similarity>=d).sort((i,c)=>c.similarity-i.similarity||c.at-i.at).slice(0,l)}const m=e=>{const a=Math.max(0,Math.round((Number(e)||0)/1e3));return a>=60?`${Math.floor(a/60)}m${String(a%60).padStart(2,"0")}s`:`${a}s`},k=e=>(Number(e)||0).toLocaleString("en-US");function B(e){if(!e?.cap)return"";const{cap:a,spent:n}=e,t=d=>(e.over||[]).includes(d)?" (over)":"";return[a.tokens?`${k(n.tokens)} / ${k(a.tokens)} tokens${t("tokens")}`:"",a.calls?`${k(n.calls)} / ${k(a.calls)} calls${t("calls")}`:"",a.usd?`$${(Number(n.usd)||0).toFixed(2)} / $${Number(a.usd).toFixed(2)}${t("usd")}`:"",a.ms?`${m(n.ms)} / ${m(a.ms)}${t("ms")}`:""].filter(Boolean).join(" · ")}export{p as LIVE_RUN_STATUSES,A as RESUMABLE_RUN_STATUSES,$ as STALLED_AFTER_MS,N as checkpointFrom,B as describeSpend,x as emptyRun,S as foldRun,v as isResumable,_ as priorWorkFor,E as runFromEvents,q as runState,O as spendOf};
package/src/team-store.js CHANGED
@@ -1,261 +1 @@
1
- // TEAM RUNS — the board every client can read, held here because the gateway is the one
2
- // address the extension and the desktop both have.
3
- //
4
- // A run happens in ONE client (its models, its tools, its guards), but the extension cannot
5
- // read the desktop's database and vice versa. So the running client APPENDS the run's
6
- // events here as they happen — planned, started, a finding, done — and any client can read
7
- // the run: list it, open its board, follow it live (SSE), and stop it. The store is the
8
- // truth about what a team did; the client that ran it is just the first reader.
9
- //
10
- // Events are the unit, applied to a run record as they arrive (the shape @chatpanel/events
11
- // team-run.js emits), so a reader that joins late replays and one that is watching tails.
12
- // A run whose writer went quiet is reported as such: `staleAfterMs` past its last event a
13
- // `running` run is marked stale, never silently kept "running" forever. Stop is a flag the
14
- // running client sees on its own SSE stream and honours; the store cannot kill anything.
15
- //
16
- // Encrypted at rest with the device key like memory and prefs — a board carries the user's
17
- // own findings — and bounded: the newest runs are kept, the oldest evicted.
18
-
19
- import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs';
20
- import { join, dirname } from 'node:path';
21
- import os from 'node:os';
22
- import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
23
- import { emptyBoardState } from './team-board.js';
24
- import { foldRun, emptyRun, checkpointFrom, isResumable, LIVE_RUN_STATUSES } from './team-record.js';
25
-
26
- const DIR = join(os.homedir(), '.chatpanel');
27
- const STORE_PATH = process.env.CHATPANEL_TEAMS_STORE || join(DIR, 'team-runs.enc');
28
- const KEY_PATH = process.env.CHATPANEL_HISTORY_KEY || join(DIR, 'history-key');
29
-
30
- export const MAX_RUNS = 200;
31
- export const MAX_EVENTS_PER_RUN = 2000;
32
- export const MAX_EVENT_BYTES = 64 * 1024;
33
- export const STALE_AFTER_MS = 5 * 60_000;
34
- const RUN_ID_RE = /^[a-zA-Z0-9_-]{4,64}$/;
35
- const LIVE = new Set(LIVE_RUN_STATUSES);
36
-
37
- export function loadOrCreateKey() {
38
- try { if (existsSync(KEY_PATH)) return Buffer.from(readFileSync(KEY_PATH, 'utf8').trim(), 'base64'); } catch { /* regenerate */ }
39
- const key = randomBytes(32);
40
- mkdirSync(dirname(KEY_PATH), { recursive: true, mode: 0o700 });
41
- writeFileSync(KEY_PATH, key.toString('base64'), { mode: 0o600 });
42
- return key;
43
- }
44
- function encrypt(key, buf) {
45
- const iv = randomBytes(12);
46
- const cipher = createCipheriv('aes-256-gcm', key, iv);
47
- const ct = Buffer.concat([cipher.update(buf), cipher.final()]);
48
- return { v: 1, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), ct: ct.toString('base64') };
49
- }
50
- function decrypt(key, env) {
51
- const d = createDecipheriv('aes-256-gcm', key, Buffer.from(env.iv, 'base64'));
52
- d.setAuthTag(Buffer.from(env.tag, 'base64'));
53
- return Buffer.concat([d.update(Buffer.from(env.ct, 'base64')), d.final()]);
54
- }
55
- const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
56
-
57
- /** Apply one event to a run record — the shared fold (team-record.js, vendored from @chatpanel/events). */
58
- export function applyEvent(run, ev) { return foldRun(run, ev); }
59
-
60
- export class TeamStore {
61
- constructor({ storePath = STORE_PATH, now = () => Date.now(), staleAfterMs = STALE_AFTER_MS, scorecards = null, engines = null } = {}) {
62
- this.scorecards = scorecards; // the agents' ledgers (scorecard-store.js), fed by task.scored
63
- this.engines = engines; // the engines' ledgers (engine-ledger-store.js), fed by task.routed / reappointed / handoff / scored
64
- this.path = storePath;
65
- this.now = now;
66
- this.staleAfterMs = staleAfterMs;
67
- this._key = null;
68
- this.runs = new Map(); // id -> { id, client, createdAt, events: [], ...folded record }
69
- this.watchers = new Map(); // id -> Set<fn(ev)>
70
- }
71
- load() {
72
- this._key = loadOrCreateKey();
73
- try {
74
- if (existsSync(this.path)) {
75
- const env = JSON.parse(readFileSync(this.path, 'utf8'));
76
- const doc = JSON.parse(decrypt(this._key, env).toString('utf8'));
77
- for (const r of Array.isArray(doc?.runs) ? doc.runs : []) if (r?.id) this.runs.set(r.id, r);
78
- }
79
- } catch { this.runs = new Map(); }
80
- return this;
81
- }
82
- save() {
83
- mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
84
- const env = encrypt(this._key, Buffer.from(JSON.stringify({ v: 1, runs: [...this.runs.values()] }), 'utf8'));
85
- const tmp = `${this.path}.${process.pid}.tmp`;
86
- writeFileSync(tmp, JSON.stringify(env), { mode: 0o600 });
87
- renameSync(tmp, this.path);
88
- }
89
- _fresh(id, { client = '' } = {}) {
90
- return { ...emptyRun({ id, client, now: this.now() }), events: [] };
91
- }
92
- _evict() {
93
- if (this.runs.size <= MAX_RUNS) return;
94
- const byAge = [...this.runs.values()].sort((a, b) => a.createdAt - b.createdAt);
95
- for (const r of byAge.slice(0, this.runs.size - MAX_RUNS)) this.runs.delete(r.id);
96
- }
97
- /** The record with liveness judged NOW, never as it was last written. */
98
- _view(run, { events = false } = {}) {
99
- const v = clone({ ...run, events: undefined });
100
- delete v.events;
101
- v.stale = LIVE.has(run.status) && this.now() - run.lastEventAt > this.staleAfterMs;
102
- // How long since the running client last wrote — a person who knows the process died
103
- // does not have to wait for the stale mark to pick the run up.
104
- v.quietMs = LIVE.has(run.status) ? Math.max(0, this.now() - run.lastEventAt) : 0;
105
- // Can a client pick this run up again? Not while its own client is live on it.
106
- v.resumable = isResumable(v);
107
- if (events) v.events = clone(run.events);
108
- return v;
109
- }
110
- create({ id, client, team, request } = {}) {
111
- if (!RUN_ID_RE.test(String(id || ''))) throw new Error('run id: 4–64 of [a-zA-Z0-9_-]');
112
- if (this.runs.has(id)) throw new Error(`run ${id} already exists`);
113
- const run = this._fresh(id, { client });
114
- run.team = String(team || '').slice(0, 64);
115
- run.request = String(request || '').slice(0, 4000);
116
- this.runs.set(id, run);
117
- this._evict();
118
- this.save();
119
- return this._view(run);
120
- }
121
- /** Append events (the runner's `emit` shape: `{ type, at, ...payload }`). Returns the view. */
122
- append(id, events) {
123
- const run = this.runs.get(String(id || ''));
124
- if (!run) throw new Error(`no run ${id}`);
125
- const list = Array.isArray(events) ? events : [events];
126
- let seq = run.events.length;
127
- let stored = 0;
128
- for (const e of list) {
129
- if (!e || typeof e !== 'object' || !e.type) continue;
130
- let bytes; try { bytes = Buffer.byteLength(JSON.stringify(e), 'utf8'); } catch { continue; }
131
- if (bytes > MAX_EVENT_BYTES) continue;
132
- const { type, at, runId: _r, ...payload } = e;
133
- // A STREAM IS NOT A FACT. A task's streamed text (`task.delta`) is folded into the record
134
- // — the task's live text — and handed to the tail so the other client reads along, but it
135
- // is never stored: the final text is on the record as a step. Deltas alone filled a run's
136
- // event log in three minutes, and the store then dropped the task.done, the writer's
137
- // start and the board that followed — a run that read "running" with a finished member.
138
- const stream = String(type) === 'task.delta';
139
- const ev = { seq: stream ? null : seq++, type: String(type), at: Number(at) || this.now(), payload };
140
- // At the cap the RECORD still moves — the fold keeps status, tasks and the board true —
141
- // only the replayable list stops growing, and says so.
142
- if (!stream) { if (run.events.length < MAX_EVENTS_PER_RUN) run.events.push(ev); else { ev.seq = null; run.eventsTruncated = true; seq -= 1; } }
143
- if (!stream) stored += 1;
144
- applyEvent(run, ev);
145
- // A finished task's fact goes to the member's scorecard — chained and attested there.
146
- if (this.scorecards && ev.type === 'task.scored') this.scorecards.fromRunEvent(ev, run);
147
- // …and to the engine's ledger: the call, or the decline / rotation that preceded it.
148
- if (this.engines && (ev.type === 'task.routed' || ev.type === 'task.reappointed' || ev.type === 'task.handoff' || ev.type === 'task.scored')) this.engines.fromRunEvent(ev, run);
149
- for (const fn of this.watchers.get(run.id) || []) { try { fn(ev); } catch { /* a dead watcher */ } }
150
- }
151
- // A batch of nothing but stream text does not rewrite the store — the live text is
152
- // persisted with the next fact (a step, a finding, the task's end).
153
- if (stored) this.save();
154
- return this._view(run);
155
- }
156
- get(id, opts) { const r = this.runs.get(String(id || '')); return r ? this._view(r, opts) : null; }
157
- /** Newest first, without boards — the list a lens shows. */
158
- list({ limit = 50, team = '' } = {}) {
159
- return [...this.runs.values()]
160
- .filter((r) => !team || r.team === team)
161
- .sort((a, b) => b.createdAt - a.createdAt)
162
- .slice(0, Math.max(1, Math.min(200, Number(limit) || 50)))
163
- .map((r) => { const v = this._view(r); return { ...v, board: undefined, threads: undefined, checkpoint: undefined, tasks: v.tasks.map((t) => ({ ...t, text: undefined, transcript: undefined })), findings: r.board.length, waiting: (r.threads?.threads || []).filter((t) => t.kind === 'ask' && t.status === 'waiting').length }; });
164
- }
165
- /** Ask the running client to stop. Recorded as an event, so watchers (the runner) see it. */
166
- /**
167
- * A person's answer to an ask, from ANY client: an answer post and the thread resolved,
168
- * appended as the events the running client's tail turns into the member's answer.
169
- * The post id is fixed here so the runner's own echo of it lands once.
170
- */
171
- answer(id, { threadId, text, by = 'person' } = {}) {
172
- const run = this.runs.get(String(id || ''));
173
- if (!run) throw new Error(`no run ${id}`);
174
- const thread = (run.threads?.threads || []).find((t) => t.id === threadId);
175
- if (!thread) throw new Error(`no thread ${threadId}`);
176
- if (thread.kind !== 'ask') throw new Error(`thread ${threadId} is not an ask`);
177
- const at = this.now();
178
- const postId = `ans_${randomBytes(4).toString('hex')}`;
179
- const post = { id: postId, threadId, by: String(by || 'person').slice(0, 40), kind: 'answer', text: String(text || '').slice(0, 4000), refs: [], replyTo: null, status: 'open', at };
180
- return this.append(id, [{ type: 'board.post', at, post }, { type: 'board.thread-status', at, threadId, status: 'resolved', answeredAt: at }]);
181
- }
182
- /** A person's decision on a post (approve / reject the draft, a finding), from any client. */
183
- decide(id, { postId, status, by = 'person' } = {}) {
184
- const run = this.runs.get(String(id || ''));
185
- if (!run) throw new Error(`no run ${id}`);
186
- if (!['approved', 'rejected', 'proposed', 'open'].includes(status)) throw new Error('status must be approved, rejected, proposed or open');
187
- if (!(run.threads?.posts || []).some((x) => x.id === postId)) throw new Error(`no post ${postId}`);
188
- const at = this.now();
189
- return this.append(id, [{ type: 'board.decision', at, postId, status, by: String(by || 'person').slice(0, 40) }]);
190
- }
191
- /** A person's own post in a thread (a note, a question), from any client. */
192
- post(id, { threadId, text, by = 'person', kind = 'note', replyTo = null } = {}) {
193
- const run = this.runs.get(String(id || ''));
194
- if (!run) throw new Error(`no run ${id}`);
195
- if (!(run.threads?.threads || []).some((t) => t.id === threadId)) throw new Error(`no thread ${threadId}`);
196
- const at = this.now();
197
- const post = { id: `pp_${randomBytes(4).toString('hex')}`, threadId, by: String(by || 'person').slice(0, 40), kind: ['note', 'question', 'decision'].includes(kind) ? kind : 'note', text: String(text || '').slice(0, 4000), refs: [], replyTo: replyTo || null, status: 'open', at };
198
- return this.append(id, [{ type: 'board.post', at, post }]);
199
- }
200
- /**
201
- * A person takes a thread off the board, from any client: the thread and its posts leave the
202
- * record, and the running client's tail applies the same event to its live board. A waiting
203
- * ask stays — the member behind it is blocked on an answer, not on tidiness.
204
- */
205
- removeThread(id, { threadId, by = 'person' } = {}) {
206
- const run = this.runs.get(String(id || ''));
207
- if (!run) throw new Error(`no run ${id}`);
208
- const thread = (run.threads?.threads || []).find((t) => t.id === threadId);
209
- if (!thread) throw new Error(`no thread ${threadId}`);
210
- if (thread.kind === 'ask' && thread.status === 'waiting') throw new Error('an ask that is waiting cannot be removed — answer it, or stop the run');
211
- return this.append(id, [{ type: 'board.thread-removed', at: this.now(), threadId, by: String(by || 'person').slice(0, 40) }]);
212
- }
213
- /** The checkpoint a client resumes from — the runner's own when the run ended with one, else built from the record. */
214
- checkpoint(id) {
215
- const run = this.runs.get(String(id || ''));
216
- if (!run) throw new Error(`no run ${id}`);
217
- return checkpointFrom(this._view(run));
218
- }
219
- /** A person hands a task to another model, from any client: the running client's tail acts on it. */
220
- handoff(id, { taskId, model, by = 'person', reason = '' } = {}) {
221
- const run = this.runs.get(String(id || ''));
222
- if (!run) throw new Error(`no run ${id}`);
223
- if (!run.tasks.some((t) => t.id === taskId)) throw new Error(`no task ${taskId}`);
224
- if (!model) throw new Error('a model is required');
225
- return this.append(id, [{ type: 'task.handoff-requested', at: this.now(), taskId, model: String(model).slice(0, 120), by: String(by || 'person').slice(0, 40), reason: String(reason || '').slice(0, 400) }]);
226
- }
227
- /** A client is taking a run over (resume): the record says so, and the old client's stop no longer applies. */
228
- claim(id, { client = '' } = {}) {
229
- const run = this.runs.get(String(id || ''));
230
- if (!run) throw new Error(`no run ${id}`);
231
- run.client = String(client || run.client || '').slice(0, 40);
232
- run.stopRequested = null;
233
- this.save();
234
- return this._view(run);
235
- }
236
- stop(id) {
237
- const run = this.runs.get(String(id || ''));
238
- if (!run) return null;
239
- if (!LIVE.has(run.status)) return this._view(run);
240
- return this.append(id, [{ type: 'run.stop-requested', at: this.now() }]);
241
- }
242
- /** Events from `after` (a seq) onward, for a late reader's replay. */
243
- eventsSince(id, after = -1) {
244
- const run = this.runs.get(String(id || ''));
245
- if (!run) return [];
246
- return run.events.filter((e) => e.seq > after).map(clone);
247
- }
248
- watch(id, fn) {
249
- if (!this.watchers.has(id)) this.watchers.set(id, new Set());
250
- this.watchers.get(id).add(fn);
251
- return () => this.watchers.get(id)?.delete(fn);
252
- }
253
- remove(id) {
254
- const had = this.runs.delete(String(id || ''));
255
- if (had) this.save();
256
- return had;
257
- }
258
- get size() { return this.runs.size; }
259
- }
260
-
261
- export function createTeamStore(opts) { return new TeamStore(opts).load(); }
1
+ import{readFileSync as m,writeFileSync as y,existsSync as v,mkdirSync as E,renameSync as $}from"node:fs";import{join as w,dirname as _}from"node:path";import x from"node:os";import{randomBytes as f,createCipheriv as N,createDecipheriv as R}from"node:crypto";import"./team-board.js";import{foldRun as M,emptyRun as q,checkpointFrom as B,isResumable as O,LIVE_RUN_STATUSES as J}from"./team-record.js";const A=w(x.homedir(),".chatpanel"),z=process.env.CHATPANEL_TEAMS_STORE||w(A,"team-runs.enc"),d=process.env.CHATPANEL_HISTORY_KEY||w(A,"history-key"),b=200,L=2e3,H=64*1024,P=5*6e4,U=/^[a-zA-Z0-9_-]{4,64}$/,g=new Set(J);function j(){try{if(v(d))return Buffer.from(m(d,"utf8").trim(),"base64")}catch{}const o=f(32);return E(_(d),{recursive:!0,mode:448}),y(d,o.toString("base64"),{mode:384}),o}function C(o,t){const e=f(12),r=N("aes-256-gcm",o,e),n=Buffer.concat([r.update(t),r.final()]);return{v:1,iv:e.toString("base64"),tag:r.getAuthTag().toString("base64"),ct:n.toString("base64")}}function D(o,t){const e=R("aes-256-gcm",o,Buffer.from(t.iv,"base64"));return e.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([e.update(Buffer.from(t.ct,"base64")),e.final()])}const S=o=>o===void 0?void 0:JSON.parse(JSON.stringify(o));function F(o,t){return M(o,t)}class V{constructor({storePath:t=z,now:e=()=>Date.now(),staleAfterMs:r=P,scorecards:n=null,engines:s=null}={}){this.scorecards=n,this.engines=s,this.path=t,this.now=e,this.staleAfterMs=r,this._key=null,this.runs=new Map,this.watchers=new Map}load(){this._key=j();try{if(v(this.path)){const t=JSON.parse(m(this.path,"utf8")),e=JSON.parse(D(this._key,t).toString("utf8"));for(const r of Array.isArray(e?.runs)?e.runs:[])r?.id&&this.runs.set(r.id,r)}}catch{this.runs=new Map}return this}save(){E(_(this.path),{recursive:!0,mode:448});const t=C(this._key,Buffer.from(JSON.stringify({v:1,runs:[...this.runs.values()]}),"utf8")),e=`${this.path}.${process.pid}.tmp`;y(e,JSON.stringify(t),{mode:384}),$(e,this.path)}_fresh(t,{client:e=""}={}){return{...q({id:t,client:e,now:this.now()}),events:[]}}_evict(){if(this.runs.size<=b)return;const t=[...this.runs.values()].sort((e,r)=>e.createdAt-r.createdAt);for(const e of t.slice(0,this.runs.size-b))this.runs.delete(e.id)}_view(t,{events:e=!1}={}){const r=S({...t,events:void 0});return delete r.events,r.stale=g.has(t.status)&&this.now()-t.lastEventAt>this.staleAfterMs,r.quietMs=g.has(t.status)?Math.max(0,this.now()-t.lastEventAt):0,r.resumable=O(r),e&&(r.events=S(t.events)),r}create({id:t,client:e,team:r,request:n}={}){if(!U.test(String(t||"")))throw new Error("run id: 4–64 of [a-zA-Z0-9_-]");if(this.runs.has(t))throw new Error(`run ${t} already exists`);const s=this._fresh(t,{client:e});return s.team=String(r||"").slice(0,64),s.request=String(n||"").slice(0,4e3),this.runs.set(t,s),this._evict(),this.save(),this._view(s)}append(t,e){const r=this.runs.get(String(t||""));if(!r)throw new Error(`no run ${t}`);const n=Array.isArray(e)?e:[e];let s=r.events.length,a=0;for(const i of n){if(!i||typeof i!="object"||!i.type)continue;let u;try{u=Buffer.byteLength(JSON.stringify(i),"utf8")}catch{continue}if(u>H)continue;const{type:c,at:p,runId:Y,...k}=i,l=String(c)==="task.delta",h={seq:l?null:s++,type:String(c),at:Number(p)||this.now(),payload:k};l||(r.events.length<L?r.events.push(h):(h.seq=null,r.eventsTruncated=!0,s-=1)),l||(a+=1),F(r,h),this.scorecards&&h.type==="task.scored"&&this.scorecards.fromRunEvent(h,r),this.engines&&(h.type==="task.routed"||h.type==="task.reappointed"||h.type==="task.handoff"||h.type==="task.scored")&&this.engines.fromRunEvent(h,r);for(const T of this.watchers.get(r.id)||[])try{T(h)}catch{}}return a&&this.save(),this._view(r)}get(t,e){const r=this.runs.get(String(t||""));return r?this._view(r,e):null}list({limit:t=50,team:e=""}={}){return[...this.runs.values()].filter(r=>!e||r.team===e).sort((r,n)=>n.createdAt-r.createdAt).slice(0,Math.max(1,Math.min(200,Number(t)||50))).map(r=>{const n=this._view(r);return{...n,board:void 0,threads:void 0,checkpoint:void 0,tasks:n.tasks.map(s=>({...s,text:void 0,transcript:void 0})),findings:r.board.length,waiting:(r.threads?.threads||[]).filter(s=>s.kind==="ask"&&s.status==="waiting").length}})}answer(t,{threadId:e,text:r,by:n="person"}={}){const s=this.runs.get(String(t||""));if(!s)throw new Error(`no run ${t}`);const a=(s.threads?.threads||[]).find(p=>p.id===e);if(!a)throw new Error(`no thread ${e}`);if(a.kind!=="ask")throw new Error(`thread ${e} is not an ask`);const i=this.now(),c={id:`ans_${f(4).toString("hex")}`,threadId:e,by:String(n||"person").slice(0,40),kind:"answer",text:String(r||"").slice(0,4e3),refs:[],replyTo:null,status:"open",at:i};return this.append(t,[{type:"board.post",at:i,post:c},{type:"board.thread-status",at:i,threadId:e,status:"resolved",answeredAt:i}])}decide(t,{postId:e,status:r,by:n="person"}={}){const s=this.runs.get(String(t||""));if(!s)throw new Error(`no run ${t}`);if(!["approved","rejected","proposed","open"].includes(r))throw new Error("status must be approved, rejected, proposed or open");if(!(s.threads?.posts||[]).some(i=>i.id===e))throw new Error(`no post ${e}`);const a=this.now();return this.append(t,[{type:"board.decision",at:a,postId:e,status:r,by:String(n||"person").slice(0,40)}])}post(t,{threadId:e,text:r,by:n="person",kind:s="note",replyTo:a=null}={}){const i=this.runs.get(String(t||""));if(!i)throw new Error(`no run ${t}`);if(!(i.threads?.threads||[]).some(p=>p.id===e))throw new Error(`no thread ${e}`);const u=this.now(),c={id:`pp_${f(4).toString("hex")}`,threadId:e,by:String(n||"person").slice(0,40),kind:["note","question","decision"].includes(s)?s:"note",text:String(r||"").slice(0,4e3),refs:[],replyTo:a||null,status:"open",at:u};return this.append(t,[{type:"board.post",at:u,post:c}])}removeThread(t,{threadId:e,by:r="person"}={}){const n=this.runs.get(String(t||""));if(!n)throw new Error(`no run ${t}`);const s=(n.threads?.threads||[]).find(a=>a.id===e);if(!s)throw new Error(`no thread ${e}`);if(s.kind==="ask"&&s.status==="waiting")throw new Error("an ask that is waiting cannot be removed — answer it, or stop the run");return this.append(t,[{type:"board.thread-removed",at:this.now(),threadId:e,by:String(r||"person").slice(0,40)}])}checkpoint(t){const e=this.runs.get(String(t||""));if(!e)throw new Error(`no run ${t}`);return B(this._view(e))}handoff(t,{taskId:e,model:r,by:n="person",reason:s=""}={}){const a=this.runs.get(String(t||""));if(!a)throw new Error(`no run ${t}`);if(!a.tasks.some(i=>i.id===e))throw new Error(`no task ${e}`);if(!r)throw new Error("a model is required");return this.append(t,[{type:"task.handoff-requested",at:this.now(),taskId:e,model:String(r).slice(0,120),by:String(n||"person").slice(0,40),reason:String(s||"").slice(0,400)}])}claim(t,{client:e=""}={}){const r=this.runs.get(String(t||""));if(!r)throw new Error(`no run ${t}`);return r.client=String(e||r.client||"").slice(0,40),r.stopRequested=null,this.save(),this._view(r)}stop(t){const e=this.runs.get(String(t||""));return e?g.has(e.status)?this.append(t,[{type:"run.stop-requested",at:this.now()}]):this._view(e):null}eventsSince(t,e=-1){const r=this.runs.get(String(t||""));return r?r.events.filter(n=>n.seq>e).map(S):[]}watch(t,e){return this.watchers.has(t)||this.watchers.set(t,new Set),this.watchers.get(t).add(e),()=>this.watchers.get(t)?.delete(e)}remove(t){const e=this.runs.delete(String(t||""));return e&&(this.watchers.delete(String(t||"")),this.save()),e}get size(){return this.runs.size}}function tt(o){return new V(o).load()}export{L as MAX_EVENTS_PER_RUN,H as MAX_EVENT_BYTES,b as MAX_RUNS,P as STALE_AFTER_MS,V as TeamStore,F as applyEvent,tt as createTeamStore,j as loadOrCreateKey};