@chatpanel/gateway 0.6.98 → 0.6.100

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.6.98",
3
+ "version": "0.6.100",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/server.js CHANGED
@@ -63,7 +63,7 @@ import * as openai from './openai.js';
63
63
  import * as responses from './responses.js';
64
64
  import * as anthropic from './anthropic.js';
65
65
 
66
- export const VERSION = '0.6.98';
66
+ export const VERSION = '0.6.100';
67
67
 
68
68
  // WARM search tier — SQLite + FTS5 record store (falls back to an encrypted-JSON
69
69
  // store if SQLite can't load), fed by the extension's ingest sync + backup-ingest.
@@ -1061,7 +1061,8 @@ export function createGateway(cfg = loadConfig()) {
1061
1061
  // duplicates are dropped by seq, so nothing lands in the gap.
1062
1062
  let last = Number.isFinite(after) ? after : -1;
1063
1063
  sendEv({ seq: -1, type: 'hello', at: Date.now(), payload: { run: teamStore.get(id), after: last } });
1064
- const off = teamStore.watch(id, (ev) => { if (ev.seq > last) { last = ev.seq; sendEv(ev); } });
1064
+ // A stream event (a task's text delta) has no seq: it is never stored, so it is passed live and never replayed.
1065
+ const off = teamStore.watch(id, (ev) => { if (ev.seq == null) sendEv(ev); else if (ev.seq > last) { last = ev.seq; sendEv(ev); } });
1065
1066
  for (const ev of teamStore.eventsSince(id, last)) { last = ev.seq; sendEv(ev); }
1066
1067
  const beat = setInterval(() => { try { res.write(': keep-alive\n\n'); } catch { /* closed */ } }, 25_000);
1067
1068
  res.on('close', () => { off(); clearInterval(beat); });
package/src/team-board.js CHANGED
@@ -78,7 +78,9 @@ export const THREAD_KINDS = Object.freeze(['task', 'ask', 'discussion', 'proposa
78
78
  // `failed`: the task behind the thread ended without an answer (every model on the roster
79
79
  // tried, or a hard error) — not `resolved`, which read as "done" on the board.
80
80
  export const THREAD_STATUSES = Object.freeze(['open', 'waiting', 'resolved', 'failed', 'approved', 'rejected']);
81
- export const POST_KINDS = Object.freeze(['finding', 'note', 'question', 'answer', 'draft', 'decision']);
81
+ // `request`: a member asks for a piece of its task to be done by someone else — the runner
82
+ // turns it into a sub-task with its own thread (team-subtask.js).
83
+ export const POST_KINDS = Object.freeze(['finding', 'note', 'question', 'answer', 'draft', 'decision', 'request']);
82
84
  export const POST_STATUSES = Object.freeze(['open', 'proposed', 'approved', 'rejected']);
83
85
  export const ASK_TYPES = Object.freeze(['info', 'budget', 'permission', 'direction']);
84
86
  export const RUNNER = 'runner';
@@ -111,7 +113,7 @@ export function foldBoard(state, ev) {
111
113
  if (x) { x.status = p.status; x.decidedBy = p.by; x.decidedAt = p.at ?? ev?.at; }
112
114
  } else if (type === 'board.thread-status' && p.threadId) {
113
115
  const t = s.threads.find((x) => x.id === p.threadId);
114
- if (t) { t.status = p.status; if (p.status !== 'waiting') t.waitingOn = null; }
116
+ if (t) { t.status = p.status; if (p.status !== 'waiting') t.waitingOn = null; if (p.holder) t.holder = p.holder; }
115
117
  }
116
118
  return s;
117
119
  }
@@ -133,22 +135,25 @@ export function createBoard({ now = () => Date.now(), newId = null, state = null
133
135
 
134
136
  const api = {
135
137
  /** Open a thread. A task's thread is opened once; asking for it again returns it. */
136
- openThread({ id = null, taskId = null, kind = 'discussion', title = '', by = RUNNER, status = 'open', ask = null } = {}) {
138
+ openThread({ id = null, taskId = null, kind = 'discussion', title = '', by = RUNNER, status = 'open', ask = null, parent = null, holder = null } = {}) {
137
139
  if (kind === 'task' && taskId) { const had = threadForTask(taskId); if (had) return had; }
138
- const thread = { id: id || mk('th'), kind: THREAD_KINDS.includes(kind) ? kind : 'discussion', taskId, title: clip(title, 200), by, status: THREAD_STATUSES.includes(status) ? status : 'open', at: now(), posts: 0, ...(ask ? { ask } : {}) };
140
+ // `parent`: the task this one was requested from (a sub-task's thread hangs under its
141
+ // parent's on the board); `holder`: the member that took it.
142
+ const thread = { id: id || mk('th'), kind: THREAD_KINDS.includes(kind) ? kind : 'discussion', taskId, title: clip(title, 200), by, status: THREAD_STATUSES.includes(status) ? status : 'open', at: now(), posts: 0, ...(ask ? { ask } : {}), ...(parent ? { parent } : {}), ...(holder ? { holder } : {}) };
139
143
  st.threads.push(thread);
140
144
  say('board.thread', { thread: { ...thread } });
141
145
  return thread;
142
146
  },
143
147
  /** A post in a thread; `replyTo` makes it a reply. */
144
- post({ id = null, threadId, by, kind = 'note', text = '', refs = [], replyTo = null, status = 'open', finding = null, ask = null } = {}) {
148
+ /** `proposal` rides on a draft a person decides on — `{ kind: 'agent', agent, jobId }` (§15.2): the card the host creates when the post is approved. */
149
+ post({ id = null, threadId, by, kind = 'note', text = '', refs = [], replyTo = null, status = 'open', finding = null, ask = null, proposal = null } = {}) {
145
150
  const t = threadOf(threadId);
146
151
  if (!t) throw new Error(`no thread ${threadId}`);
147
152
  if (id && postOf(id)) return postOf(id);
148
153
  const post = {
149
154
  id: id || mk('p'), threadId, by: String(by || RUNNER), kind: POST_KINDS.includes(kind) ? kind : 'note',
150
155
  text: clip(text, MAX_POST_TEXT), refs: refsOf(refs), replyTo, status: POST_STATUSES.includes(status) ? status : 'open', at: now(),
151
- ...(finding ? { finding } : {}), ...(ask ? { ask } : {}),
156
+ ...(finding ? { finding } : {}), ...(ask ? { ask } : {}), ...(proposal && typeof proposal === 'object' ? { proposal } : {}),
152
157
  };
153
158
  st.posts.push(post);
154
159
  t.lastAt = post.at; t.lastBy = post.by; t.posts = (t.posts || 0) + 1;
@@ -284,7 +289,7 @@ function threadedLines(state, { taskIds, role }) {
284
289
  for (const t of threads) {
285
290
  const own = posts.filter((x) => x.threadId === t.id && x.status !== 'rejected');
286
291
  if (!own.length) continue;
287
- out.push(`## ${t.kind}${t.by && t.by !== RUNNER ? ` by ${t.by}` : ''}: ${t.title}${t.status === 'resolved' && t.kind === 'ask' ? ' (answered)' : ''}`);
292
+ out.push(`## ${t.kind}${t.by && t.by !== RUNNER ? ` by ${t.by}` : ''}: ${t.title}${t.holder ? ` (held by ${t.holder})` : ''}${t.status === 'resolved' && t.kind === 'ask' ? ' (answered)' : ''}`);
288
293
  const line = (x, depth) => {
289
294
  const tag = [x.kind === 'finding' ? (x.finding?.kind || 'claim') : x.kind, x.by, x.finding?.confidence != null ? `${Math.round(x.finding.confidence * 100)}%` : null, x.status === 'approved' ? 'APPROVED' : x.status === 'proposed' ? 'proposed' : null, x.kind === 'decision' || x.by === PERSON ? 'SETTLED' : null].filter(Boolean).join(' · ');
290
295
  out.push(`${' '.repeat(depth)}- [${tag}] ${x.text}${x.refs?.length ? ` (refs: ${x.refs.join(', ')})` : ''}`);
@@ -15,7 +15,7 @@ export const RESUMABLE_RUN_STATUSES = Object.freeze(['waiting', 'stopped', 'fail
15
15
  const TASK_TEXT_MAX = 20_000;
16
16
 
17
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: [], board: [], threads: emptyBoardState(), checkpoint: null, proposal: null, usage: null, stopRequested: null, startedAt: null, endedAt: null };
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
19
  }
20
20
 
21
21
  const taskOf = (run, id) => run.tasks.find((x) => x.id === id);
@@ -36,9 +36,24 @@ export function foldRun(run, ev) {
36
36
  case 'plan.ready':
37
37
  run.plan = { by: p.by || 'fixed', tasks: Array.isArray(p.tasks) ? p.tasks : [] };
38
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' : 'pending', findings: taskOf(run, t.id)?.findings || 0 }));
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 || '' } : {}) }));
40
40
  run.status = 'running';
41
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
+ 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; }
52
+ 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; }
53
+ 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; }
54
+ 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; }
55
+ case 'task.nudged': { const t = taskOf(run, p.taskId); if (t) t.nudged = [...(t.nudged || []), { grants: p.grants || [], at }]; break; }
56
+ 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;
42
57
  case 'task.started': { const t = taskOf(run, p.taskId); if (t) { t.status = 'running'; t.startedAt = at; t.error = null; } run.status = 'running'; break; }
43
58
  case 'task.model': { const t = taskOf(run, p.taskId); if (t) { t.model = p.model; t.attempts = [...(t.attempts || []), { model: p.model, at, attempt: p.attempt }]; } break; }
44
59
  case 'task.step': { const t = taskOf(run, p.taskId); if (t && Array.isArray(p.steps)) t.transcript = [...(t.transcript || []), ...p.steps]; break; }
@@ -50,7 +65,14 @@ export function foldRun(run, ev) {
50
65
  break;
51
66
  case 'task.waiting': { const t = taskOf(run, p.taskId); if (t) { t.status = 'waiting'; t.waitingOn = p.threadId; } break; }
52
67
  case 'task.done':
53
- case 'task.failed': { const t = taskOf(run, p.taskId); if (t) { t.status = p.status || (type === 'task.done' ? 'ok' : 'failed'); t.error = p.error || null; t.ms = p.ms; t.endedAt = at; } break; }
68
+ case 'task.failed': {
69
+ const t = taskOf(run, p.taskId);
70
+ if (t) { t.status = p.status || (type === 'task.done' ? 'ok' : 'failed'); t.error = p.error || null; t.ms = p.ms; t.endedAt = at; }
71
+ // A job posting's outcome is the sub-task's (§15.2.5): taken by, finished how.
72
+ const j = run.jobs.find((x) => x.taskId === p.taskId);
73
+ if (j) { j.status = type === 'task.done' ? 'done' : 'failed'; j.endedAt = at; }
74
+ break;
75
+ }
54
76
  case 'run.merging': run.status = 'merging'; break;
55
77
  case 'run.waiting': run.status = 'running'; break;
56
78
  case 'run.usage': run.usage = p.usage || run.usage; break;
@@ -101,3 +123,32 @@ export function isResumable(run) {
101
123
  if (RESUMABLE_RUN_STATUSES.includes(run.status)) return true;
102
124
  return !!run.stale && LIVE_RUN_STATUSES.includes(run.status); // its client went away mid-run
103
125
  }
126
+
127
+ /**
128
+ * The run's spend against its cap, as a board shows it: the record's last `run.usage` (or
129
+ * nothing spent yet) with `ms` measured LIVE for a run still going — the stored figure is as
130
+ * of the last task's end, and a board read "0 s" through a ten-minute research task.
131
+ */
132
+ export function spendOf(run, { now = Date.now() } = {}) {
133
+ const cap = run?.usage?.cap || run?.budget || null;
134
+ if (!cap || !Object.keys(cap).length) return null;
135
+ const spent = { tokens: 0, calls: 0, usd: 0, ms: 0, ...(run?.usage?.spent || {}) };
136
+ if (LIVE_RUN_STATUSES.includes(run?.status) && run?.startedAt) spent.ms = Math.max(spent.ms || 0, now - run.startedAt);
137
+ 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;
138
+ return { cap, spent, pct, exhausted: run?.usage?.exhausted || null };
139
+ }
140
+
141
+ 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`; };
142
+ const num = (n) => (Number(n) || 0).toLocaleString('en-US');
143
+
144
+ /** One line: `1,240 / 40,000 tokens · 3 / 20 calls · 2m10s / 15m00s`. Only the capped dimensions. */
145
+ export function describeSpend(spend) {
146
+ if (!spend?.cap) return '';
147
+ const { cap, spent } = spend;
148
+ return [
149
+ cap.tokens ? `${num(spent.tokens)} / ${num(cap.tokens)} tokens` : '',
150
+ cap.calls ? `${num(spent.calls)} / ${num(cap.calls)} calls` : '',
151
+ cap.usd ? `$${(Number(spent.usd) || 0).toFixed(2)} / $${Number(cap.usd).toFixed(2)}` : '',
152
+ cap.ms ? `${secs(spent.ms)} / ${secs(cap.ms)}` : '',
153
+ ].filter(Boolean).join(' · ');
154
+ }
package/src/team-store.js CHANGED
@@ -124,14 +124,23 @@ export class TeamStore {
124
124
  if (!run) throw new Error(`no run ${id}`);
125
125
  const list = Array.isArray(events) ? events : [events];
126
126
  let seq = run.events.length;
127
+ let stored = 0;
127
128
  for (const e of list) {
128
129
  if (!e || typeof e !== 'object' || !e.type) continue;
129
130
  let bytes; try { bytes = Buffer.byteLength(JSON.stringify(e), 'utf8'); } catch { continue; }
130
131
  if (bytes > MAX_EVENT_BYTES) continue;
131
- if (run.events.length >= MAX_EVENTS_PER_RUN) break;
132
132
  const { type, at, runId: _r, ...payload } = e;
133
- const ev = { seq: seq++, type: String(type), at: Number(at) || this.now(), payload };
134
- run.events.push(ev);
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;
135
144
  applyEvent(run, ev);
136
145
  // A finished task's fact goes to the member's scorecard — chained and attested there.
137
146
  if (this.scorecards && ev.type === 'task.scored') this.scorecards.fromRunEvent(ev, run);
@@ -139,7 +148,9 @@ export class TeamStore {
139
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);
140
149
  for (const fn of this.watchers.get(run.id) || []) { try { fn(ev); } catch { /* a dead watcher */ } }
141
150
  }
142
- this.save();
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();
143
154
  return this._view(run);
144
155
  }
145
156
  get(id, opts) { const r = this.runs.get(String(id || '')); return r ? this._view(r, opts) : null; }