@chatpanel/gateway 0.6.100 → 0.6.102

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.100",
3
+ "version": "0.6.102",
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": {
@@ -112,6 +112,10 @@ export async function ensureBridge(cfg, {
112
112
  waitForSiblingMs = 2500,
113
113
  now = Date.now,
114
114
  setTimer = setTimeout,
115
+ // The watch on an ADOPTED bridge: its own timer seam (a test's immediate `setTimer` would
116
+ // spin it), unref'd so a pending watch never keeps the process alive.
117
+ setWatch = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
118
+ watchEveryMs = 10_000,
115
119
  } = {}) {
116
120
  const url = String(cfg?.bridge?.url || DEFAULT_BRIDGE_URL).replace(/\/$/, '');
117
121
  const state = { mode: 'off', version: null, pid: null, restarts: 0, why: '', child: null, stopping: false, backoff: 0 };
@@ -131,12 +135,43 @@ export async function ensureBridge(cfg, {
131
135
  const plan = planBridge({ managed, cfgUrl: url, healthy, standalone, embeddedVersion });
132
136
 
133
137
  if (plan.action === 'off') { settle('off', plan.why); return controller(); }
134
- if (plan.action === 'adopt') { settle('adopted', plan.why, { version: healthy.version }); return controller(); }
135
138
 
136
- const spec = plan.action === 'spawn-embedded'
137
- ? { ...emb, env: { CHATPANEL_BRIDGE_EMBEDDED: '1' }, mode: 'embedded', version: embeddedVersion }
138
- : { program: plan.path, args: [], env: {}, mode: 'standalone', version: standalone?.version || null };
139
+ // What WE would run, decided once and kept: an adopted bridge that goes away is replaced
140
+ // by this without re-planning from scratch.
141
+ const specFor = (p) => (p.action === 'spawn-embedded'
142
+ ? { ...emb, env: { CHATPANEL_BRIDGE_EMBEDDED: '1' }, mode: 'embedded', version: p.version || embeddedVersion }
143
+ : { program: p.path, args: [], env: {}, mode: 'standalone', version: standalone?.version || null });
144
+ let spec = plan.action === 'adopt' ? null : specFor(plan);
139
145
  let startedAt = 0;
146
+ let watch = null;
147
+ let misses = 0;
148
+
149
+ // AN ADOPTED BRIDGE IS WATCHED, NOT TRUSTED FOREVER. The gateway carries the bridge: when
150
+ // the one it adopted goes away — the desktop app that ran it quit, an old login unit was
151
+ // removed, a standalone was stopped — the port is quiet and every agent turn fails with
152
+ // "bridge unreachable" until someone restarts the gateway. Two missed probes (a refused
153
+ // port counts at once) and ours starts.
154
+ const adopt = (why, ver) => {
155
+ settle('adopted', why, { version: ver || null });
156
+ misses = 0;
157
+ const tick = async () => {
158
+ if (state.stopping || state.mode !== 'adopted') return;
159
+ const h = await probe(url);
160
+ if (h) { misses = 0; state.version = h.version || state.version; watch = setWatch(tick, watchEveryMs); return; }
161
+ misses += 1;
162
+ if (misses < 2) { watch = setWatch(tick, Math.min(watchEveryMs, 3000)); return; }
163
+ if (!spec) {
164
+ const ev = embeddedVersion || version(emb.program, emb.args);
165
+ const p = planBridge({ managed, cfgUrl: url, healthy: null, standalone, embeddedVersion: ev });
166
+ if (p.action === 'off') { settle('off', `the adopted bridge went away and ${p.why}`); return; }
167
+ spec = specFor({ ...p, version: ev });
168
+ }
169
+ log(` bridge : the adopted bridge at ${url} went away — ${spec.mode === 'embedded' ? `starting the embedded bridge (v${spec.version || '?'})` : `starting the installed bridge (v${spec.version || '?'})`}`);
170
+ settle(spec.mode, `the adopted bridge went away; ${spec.mode} bridge started in its place`, { version: spec.version });
171
+ start();
172
+ };
173
+ watch = setWatch(tick, watchEveryMs);
174
+ };
140
175
 
141
176
  const start = () => {
142
177
  if (state.stopping) return;
@@ -155,7 +190,7 @@ export async function ensureBridge(cfg, {
155
190
  // The port may have been taken by a bridge someone else started while ours came up —
156
191
  // that is not a failure to restart from, it is a bridge to adopt.
157
192
  const other = await probe(url);
158
- if (other) { settle('adopted', `a bridge already answers at ${url} (v${other.version || '?'}) — ours stepped aside`, { version: other.version }); return; }
193
+ if (other) { adopt(`a bridge already answers at ${url} (v${other.version || '?'}${other.managedBy ? `, run by ${other.managedBy}` : ''}) — ours stepped aside`, other.version); return; }
159
194
  if (now() - startedAt > STABLE_MS) state.backoff = 0;
160
195
  const delay = BACKOFF_MS[Math.min(state.backoff, BACKOFF_MS.length - 1)];
161
196
  state.backoff += 1; state.restarts += 1;
@@ -163,6 +198,7 @@ export async function ensureBridge(cfg, {
163
198
  setTimer(start, delay);
164
199
  });
165
200
  };
201
+ if (plan.action === 'adopt') { adopt(plan.why, healthy.version); return controller(); }
166
202
  settle(spec.mode, plan.why, { version: spec.version });
167
203
  start();
168
204
  return controller();
@@ -170,7 +206,7 @@ export async function ensureBridge(cfg, {
170
206
  function controller() {
171
207
  return {
172
208
  status: () => ({ mode: state.mode, version: state.version, pid: state.pid, restarts: state.restarts, why: state.why }),
173
- stop: () => { state.stopping = true; if (state.child && !state.child.killed) { try { state.child.kill('SIGTERM'); } catch { /* gone */ } } },
209
+ stop: () => { state.stopping = true; if (watch) { clearTimeout(watch); watch = null; } if (state.child && !state.child.killed) { try { state.child.kill('SIGTERM'); } catch { /* gone */ } } },
174
210
  };
175
211
  }
176
212
  }
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.100';
66
+ export const VERSION = '0.6.102';
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.
package/src/team-board.js CHANGED
@@ -235,7 +235,7 @@ export function createBoard({ now = () => Date.now(), newId = null, state = null
235
235
  function asFinding(st) {
236
236
  return (p) => {
237
237
  const t = st.threads.find((x) => x.id === p.threadId);
238
- return { id: p.id, kind: p.finding?.kind || 'claim', text: p.text, refs: p.refs || [], confidence: p.finding?.confidence ?? null, role: p.by, taskId: t?.taskId || null, at: p.at, status: p.status };
238
+ return { id: p.id, kind: p.finding?.kind || 'claim', text: p.text, refs: p.refs || [], confidence: p.finding?.confidence ?? null, role: p.by, taskId: t?.taskId || null, at: p.at, status: p.status, ...(p.finding?.prior ? { prior: true } : {}) };
239
239
  };
240
240
  }
241
241
 
@@ -133,9 +133,61 @@ export function spendOf(run, { now = Date.now() } = {}) {
133
133
  const cap = run?.usage?.cap || run?.budget || null;
134
134
  if (!cap || !Object.keys(cap).length) return null;
135
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);
136
+ // The clock runs while the client is writing, and STOPS where it stopped: a run whose
137
+ // record says `running` because its client died (or its end never landed) is not still
138
+ // spending — it read "18m13s / 5m00s" and counting for a member that had finished.
139
+ const st = runState(run, { now });
140
+ 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);
137
141
  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 };
142
+ const over = BUDGET_KEYS.filter((k) => cap[k] && (spent[k] || 0) >= cap[k]);
143
+ return { cap, spent, pct, exhausted: run?.usage?.exhausted || over[0] || null, over };
144
+ }
145
+ const BUDGET_KEYS = ['tokens', 'calls', 'usd', 'ms'];
146
+
147
+ export const STALLED_AFTER_MS = 2 * 60_000;
148
+
149
+ /**
150
+ * What a run IS right now, for a person: the record's status read against the clock. A
151
+ * record that says `running` with no event for minutes is STALLED — its client stopped
152
+ * writing (died, or its end never landed) — not running. `{ key, label, tone, detail }`;
153
+ * `tone` is the chip: on · warn · ok · err · muted.
154
+ */
155
+ export function runState(run, { now = Date.now(), stalledAfterMs = STALLED_AFTER_MS } = {}) {
156
+ const s = String(run?.status || 'planning');
157
+ const quiet = Number.isFinite(run?.quietMs) ? run.quietMs : Math.max(0, now - (Number(run?.lastEventAt) || now));
158
+ 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`; };
159
+ if (s === 'waiting') return { key: 'waiting', label: 'waiting on you', tone: 'warn', detail: '' };
160
+ if (LIVE_RUN_STATUSES.includes(s)) {
161
+ 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` };
162
+ return { key: 'running', label: s === 'merging' ? 'merging' : s === 'planning' ? 'planning' : 'running', tone: 'on', detail: `last event ${agoText(quiet)} ago` };
163
+ }
164
+ if (s === 'completed') return { key: 'done', label: 'done', tone: 'ok', detail: '' };
165
+ if (s === 'partial') return { key: 'partial', label: 'done with failures', tone: 'warn', detail: 'a member failed; the rest merged' };
166
+ if (s === 'answered') return { key: 'answered', label: 'answered — resume to continue', tone: 'warn', detail: '' };
167
+ if (s === 'over-budget') return { key: 'over-budget', label: 'over budget', tone: 'err', detail: 'stopped with what it had' };
168
+ if (s === 'stopped') return { key: 'stopped', label: 'stopped', tone: 'muted', detail: '' };
169
+ if (s === 'failed') return { key: 'failed', label: 'failed', tone: 'err', detail: '' };
170
+ return { key: s, label: s, tone: 'muted', detail: '' };
171
+ }
172
+
173
+ /**
174
+ * Earlier runs whose work a new run should read before repeating it (§12.2.6, the librarian's
175
+ * first step): the same team (or any, when `team` is empty), a request that says the same
176
+ * thing (word overlap ≥ `minSimilarity`), findings on the record, not the run itself, newest
177
+ * first. `runs` is the store's list (`findings` is a count there). Returns
178
+ * `[{ id, at, similarity, findings }]`; the host fetches the record for the findings.
179
+ */
180
+ export function priorWorkFor(runs, { team = '', request = '', excludeId = null, minSimilarity = 0.6, maxAgeMs = 7 * 24 * 3600_000, now = Date.now(), limit = 3 } = {}) {
181
+ const words = (t) => new Set(String(t || '').toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter((w) => w.length > 2));
182
+ const want = words(request);
183
+ if (!want.size) return [];
184
+ 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); };
185
+ return (runs || [])
186
+ .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)
187
+ .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 }))
188
+ .filter((r) => r.similarity >= minSimilarity)
189
+ .sort((a, b) => b.similarity - a.similarity || b.at - a.at)
190
+ .slice(0, limit);
139
191
  }
140
192
 
141
193
  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`; };
@@ -145,10 +197,11 @@ const num = (n) => (Number(n) || 0).toLocaleString('en-US');
145
197
  export function describeSpend(spend) {
146
198
  if (!spend?.cap) return '';
147
199
  const { cap, spent } = spend;
200
+ const over = (k) => ((spend.over || []).includes(k) ? ' (over)' : '');
148
201
  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)}` : '',
202
+ cap.tokens ? `${num(spent.tokens)} / ${num(cap.tokens)} tokens${over('tokens')}` : '',
203
+ cap.calls ? `${num(spent.calls)} / ${num(cap.calls)} calls${over('calls')}` : '',
204
+ cap.usd ? `$${(Number(spent.usd) || 0).toFixed(2)} / $${Number(cap.usd).toFixed(2)}${over('usd')}` : '',
205
+ cap.ms ? `${secs(spent.ms)} / ${secs(cap.ms)}${over('ms')}` : '',
153
206
  ].filter(Boolean).join(' · ');
154
207
  }