@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,150 +1 @@
1
- // The engines' ledgers — every fact the runner and a host observed about a MODEL or a
2
- // HARNESS, chained and attested here (model-ledger.js), one chain per engine key.
3
- //
4
- // The scorecard store's twin. A scorecard says what an AGENT did; a ledger says how an
5
- // ENGINE behaved while doing it — did it answer, how fast, how much, was the JSON valid, was
6
- // the verdict good. The facts come from the run store's fold (a finished task is a `call`,
7
- // a re-appointment is a `declined` on the engine that was left, a hand-off a
8
- // `rotated-from`), from a host that timed its own chat calls (`POST /v1/engines/:key/entries`),
9
- // and from a person (a rating on a task lands on the engine that served it; a price they
10
- // typed). Nothing is ever edited. The same store key attests both stores, under its own
11
- // label, so a scorecard's mark cannot be replayed as a ledger's.
12
- //
13
- // Read: `GET /v1/engines` (every card), `GET /v1/engines/:key/card` (the card, the chain
14
- // on request, whether it verifies). The card is what a client feeds `applyCard` — observed
15
- // quality, latency and cost over the name-based guess once there is enough history.
16
-
17
- import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs';
18
- import { join, dirname } from 'node:path';
19
- import os from 'node:os';
20
- import { createHmac, webcrypto } from 'node:crypto';
21
- import { makeLedgerEntry, verifyChain, attest, verifyAttested, summarizeEngine, ledgerKey, LEDGER_ENTRY_KINDS, DECLINE_REASONS } from './model-ledger.js';
22
- import { normalizeEngine } from './scorecard.js';
23
-
24
- const DIR = join(os.homedir(), '.chatpanel');
25
- const STORE_PATH = process.env.CHATPANEL_ENGINES_STORE || join(DIR, 'engines.json');
26
- const MAX_ENTRIES_PER_ENGINE = 20000;
27
-
28
- /** Why an engine declined, read from the error the runner recorded. */
29
- export function declineReasonOf(error) {
30
- const m = String(error || '');
31
- if (/rate|429|overloaded|capacity|too many/i.test(m)) return 'rate';
32
- if (/401|403|unauthori[sz]ed|no api key|invalid.*key|forbidden|not configured/i.test(m)) return 'auth';
33
- if (/credit|quota|billing|insufficient|402/i.test(m)) return 'credits';
34
- if (/timed? ?out|ETIMEDOUT|deadline/i.test(m)) return 'timeout';
35
- if (/context|too long|maximum.*tokens|token limit/i.test(m)) return 'context';
36
- if (/not[_ ]found|404|not deployed|unavailable|does not exist|unknown model|ECONNREFUSED|could ?n.t reach|closed the connection|exited|502|503|500/i.test(m)) return 'unavailable';
37
- return 'other';
38
- }
39
-
40
- export class EngineLedgerStore {
41
- constructor({ storePath = STORE_PATH, key = null, now = () => Date.now() } = {}) {
42
- this.path = storePath;
43
- this.now = now;
44
- this._mark = key ? createHmac('sha256', key).update('chatpanel:engine-ledger:attest:v1').digest() : null;
45
- this.chains = new Map(); // key -> [entries]
46
- this._routed = new Map(); // `${runId}/${taskId}` -> the engine last routed to (for declines and rotations)
47
- this._queue = Promise.resolve();
48
- }
49
- load() {
50
- try {
51
- if (existsSync(this.path)) {
52
- const doc = JSON.parse(readFileSync(this.path, 'utf8'));
53
- for (const [k, entries] of Object.entries(doc?.chains || {})) if (Array.isArray(entries)) this.chains.set(k, entries);
54
- }
55
- } catch { this.chains = new Map(); }
56
- return this;
57
- }
58
- save() {
59
- mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
60
- const tmp = `${this.path}.${process.pid}.tmp`;
61
- writeFileSync(tmp, JSON.stringify({ v: 1, chains: Object.fromEntries(this.chains) }), { mode: 0o600 });
62
- renameSync(tmp, this.path);
63
- }
64
- /** Append one fact to an engine's chain: made, chained, attested, saved. Serialised per store. */
65
- append(fact) {
66
- const run = async () => {
67
- const engine = normalizeEngine(fact?.engine);
68
- if (!engine) throw new Error('model-ledger: engine required');
69
- if (!LEDGER_ENTRY_KINDS.includes(fact?.kind)) throw new Error(`model-ledger: kind must be one of ${LEDGER_ENTRY_KINDS.join(', ')}`);
70
- const key = ledgerKey(engine);
71
- const chain = this.chains.get(key) || [];
72
- if (chain.length >= MAX_ENTRIES_PER_ENGINE) throw new Error('model-ledger: chain is full');
73
- let entry = await makeLedgerEntry({ ...fact, engine, at: fact.at || this.now() }, chain.at(-1) || null, { now: this.now, subtle: webcrypto.subtle });
74
- if (this._mark) entry = await attest(entry, this._mark, { subtle: webcrypto.subtle });
75
- chain.push(entry);
76
- this.chains.set(key, chain);
77
- this.save();
78
- return entry;
79
- };
80
- const p = this._queue.then(run, run);
81
- this._queue = p.catch(() => {});
82
- return p;
83
- }
84
- /** The card, and on request the chain and whether it verifies. */
85
- async get(key, { entries = false, minCalls, now } = {}) {
86
- const chain = this.chains.get(String(key || '')) || [];
87
- const out = { key: String(key || ''), card: summarizeEngine(chain, { minCalls, now: now || this.now() }) };
88
- if (entries) {
89
- out.entries = chain;
90
- out.verified = await verifyChain(chain, { subtle: webcrypto.subtle });
91
- out.attested = this._mark ? await verifyAttested(chain, this._mark, { subtle: webcrypto.subtle }) : { ok: false, attested: 0, of: chain.length };
92
- }
93
- return out;
94
- }
95
- /** Every engine's card, without the chains. */
96
- list({ minCalls, now } = {}) {
97
- return [...this.chains.entries()].map(([key, chain]) => summarizeEngine(chain, { minCalls, now: now || this.now() })).filter((c) => c.key);
98
- }
99
- /**
100
- * A run store event, as the fold sees it. `task.routed` is remembered per task; a later
101
- * `task.reappointed` is a decline on what was routed before it, `task.handoff` a rotation,
102
- * and `task.scored` the call itself (the harness's or the model's whole task).
103
- */
104
- fromRunEvent(ev, run) {
105
- const type = String(ev?.type || '');
106
- const p = ev?.payload && typeof ev.payload === 'object' ? ev.payload : {};
107
- const runId = run?.id || p.runId || '';
108
- const slot = `${runId}/${p.taskId || ''}`;
109
- if (type === 'task.routed') {
110
- const engine = normalizeEngine(p.engine);
111
- if (engine) this._routed.set(slot, engine);
112
- return null;
113
- }
114
- if (type === 'task.reappointed' || type === 'task.handoff') {
115
- const from = this._routed.get(slot);
116
- if (!from) return null;
117
- const fact = type === 'task.reappointed'
118
- ? { engine: from, kind: 'declined', at: ev.at, runId, taskId: p.taskId, declined: { reason: declineReasonOf(p.error), error: p.error } }
119
- : { engine: from, kind: 'rotated-from', at: ev.at, runId, taskId: p.taskId, rotated: { to: p.to ? { id: p.to } : undefined, reason: p.reason || `handed off by ${p.by || 'a person'}` } };
120
- return this.append(fact).catch(() => null);
121
- }
122
- if (type === 'task.scored') {
123
- const engine = normalizeEngine(p.engine);
124
- if (!engine) return null;
125
- const ok = p.outcome !== 'task.failed';
126
- return this.append({
127
- engine, kind: 'call', at: ev.at, runId, taskId: p.taskId, agentId: p.agentId,
128
- call: { ok, totalMs: p.size?.ms, tokens: p.size?.tokens || undefined, empty: !ok && /no answer|did not answer|returned nothing|empty/i.test(String(p.error || '')) },
129
- refs: p.refs,
130
- }).catch(() => null);
131
- }
132
- return null;
133
- }
134
- /**
135
- * A rating a person gave an AGENT'S task (scorecard-store.js) lands on the engine that
136
- * served it too: `chain` is the agent's scorecard, `entry` the rating just appended.
137
- */
138
- fromRating(chain, entry) {
139
- if (!entry?.rating || !Array.isArray(chain)) return null;
140
- const r = entry.rating;
141
- const task = r.about != null ? chain.find((e) => e.seq === r.about)
142
- : entry.taskId ? chain.find((e) => (e.kind === 'task.done' || e.kind === 'task.failed') && e.taskId === entry.taskId && (!entry.runId || e.runId === entry.runId))
143
- : entry.runId ? (() => { const xs = chain.filter((e) => (e.kind === 'task.done' || e.kind === 'task.failed') && e.runId === entry.runId); return xs.length === 1 ? xs[0] : null; })() : null;
144
- if (!task?.engine) return null;
145
- return this.append({ engine: task.engine, kind: 'rating', at: entry.at, runId: task.runId, taskId: task.taskId, agentId: entry.agentId, rating: { by: r.by, score: r.score, jobKind: entry.jobKind, agentId: entry.agentId } }).catch(() => null);
146
- }
147
- }
148
-
149
- export function createEngineLedgerStore(opts) { return new EngineLedgerStore(opts).load(); }
150
- export { DECLINE_REASONS };
1
+ import{readFileSync as p,writeFileSync as g,existsSync as m,mkdirSync as k,renameSync as I}from"node:fs";import{join as c,dirname as E}from"node:path";import w from"node:os";import{createHmac as y,webcrypto as u}from"node:crypto";import{makeLedgerEntry as b,verifyChain as S,attest as _,verifyAttested as N,summarizeEngine as h,ledgerKey as R,LEDGER_ENTRY_KINDS as f,DECLINE_REASONS as x}from"./model-ledger.js";import{normalizeEngine as l}from"./scorecard.js";const A=c(w.homedir(),".chatpanel"),O=process.env.CHATPANEL_ENGINES_STORE||c(A,"engines.json"),v=2e4;function j(a){const t=String(a||"");return/rate|429|overloaded|capacity|too many/i.test(t)?"rate":/401|403|unauthori[sz]ed|no api key|invalid.*key|forbidden|not configured/i.test(t)?"auth":/credit|quota|billing|insufficient|402/i.test(t)?"credits":/timed? ?out|ETIMEDOUT|deadline/i.test(t)?"timeout":/context|too long|maximum.*tokens|token limit/i.test(t)?"context":/not[_ ]found|404|not deployed|unavailable|does not exist|unknown model|ECONNREFUSED|could ?n.t reach|closed the connection|exited|502|503|500/i.test(t)?"unavailable":"other"}class T{constructor({storePath:t=O,key:n=null,now:i=()=>Date.now()}={}){this.path=t,this.now=i,this._mark=n?y("sha256",n).update("chatpanel:engine-ledger:attest:v1").digest():null,this.chains=new Map,this._routed=new Map,this._queue=Promise.resolve()}load(){try{if(m(this.path)){const t=JSON.parse(p(this.path,"utf8"));for(const[n,i]of Object.entries(t?.chains||{}))Array.isArray(i)&&this.chains.set(n,i)}}catch{this.chains=new Map}return this}save(){k(E(this.path),{recursive:!0,mode:448});const t=`${this.path}.${process.pid}.tmp`;g(t,JSON.stringify({v:1,chains:Object.fromEntries(this.chains)}),{mode:384}),I(t,this.path)}append(t){const n=async()=>{const e=l(t?.engine);if(!e)throw new Error("model-ledger: engine required");if(!f.includes(t?.kind))throw new Error(`model-ledger: kind must be one of ${f.join(", ")}`);const r=R(e),s=this.chains.get(r)||[];if(s.length>=v)throw new Error("model-ledger: chain is full");let o=await b({...t,engine:e,at:t.at||this.now()},s.at(-1)||null,{now:this.now,subtle:u.subtle});return this._mark&&(o=await _(o,this._mark,{subtle:u.subtle})),s.push(o),this.chains.set(r,s),this.save(),o},i=this._queue.then(n,n);return this._queue=i.catch(()=>{}),i}async get(t,{entries:n=!1,minCalls:i,now:e}={}){const r=this.chains.get(String(t||""))||[],s={key:String(t||""),card:h(r,{minCalls:i,now:e||this.now()})};return n&&(s.entries=r,s.verified=await S(r,{subtle:u.subtle}),s.attested=this._mark?await N(r,this._mark,{subtle:u.subtle}):{ok:!1,attested:0,of:r.length}),s}list({minCalls:t,now:n}={}){return[...this.chains.entries()].map(([i,e])=>h(e,{minCalls:t,now:n||this.now()})).filter(i=>i.key)}fromRunEvent(t,n){const i=String(t?.type||""),e=t?.payload&&typeof t.payload=="object"?t.payload:{},r=n?.id||e.runId||"",s=`${r}/${e.taskId||""}`;if(i==="task.routed"){const o=l(e.engine);return o&&this._routed.set(s,o),null}if(i==="task.reappointed"||i==="task.handoff"){const o=this._routed.get(s);if(!o)return null;const d=i==="task.reappointed"?{engine:o,kind:"declined",at:t.at,runId:r,taskId:e.taskId,declined:{reason:j(e.error),error:e.error}}:{engine:o,kind:"rotated-from",at:t.at,runId:r,taskId:e.taskId,rotated:{to:e.to?{id:e.to}:void 0,reason:e.reason||`handed off by ${e.by||"a person"}`}};return this.append(d).catch(()=>null)}if(i==="task.scored"){const o=l(e.engine);if(!o)return null;const d=e.outcome!=="task.failed";return this.append({engine:o,kind:"call",at:t.at,runId:r,taskId:e.taskId,agentId:e.agentId,call:{ok:d,totalMs:e.size?.ms,tokens:e.size?.tokens||void 0,empty:!d&&/no answer|did not answer|returned nothing|empty/i.test(String(e.error||""))},refs:e.refs}).catch(()=>null)}return null}fromRating(t,n){if(!n?.rating||!Array.isArray(t))return null;const i=n.rating,e=i.about!=null?t.find(r=>r.seq===i.about):n.taskId?t.find(r=>(r.kind==="task.done"||r.kind==="task.failed")&&r.taskId===n.taskId&&(!n.runId||r.runId===n.runId)):n.runId?(()=>{const r=t.filter(s=>(s.kind==="task.done"||s.kind==="task.failed")&&s.runId===n.runId);return r.length===1?r[0]:null})():null;return e?.engine?this.append({engine:e.engine,kind:"rating",at:n.at,runId:e.runId,taskId:e.taskId,agentId:n.agentId,rating:{by:i.by,score:i.score,jobKind:n.jobKind,agentId:n.agentId}}).catch(()=>null):null}}function C(a){return new T(a).load()}export{x as DECLINE_REASONS,T as EngineLedgerStore,C as createEngineLedgerStore,j as declineReasonOf};
package/src/engine.js CHANGED
@@ -1,132 +1 @@
1
- // VENDORED from @chatpanel/events/engine.js — edit there, then copy over.
2
- // An ENGINE — what actually runs an agent's turns — as a declaration, and its one-line label.
3
- //
4
- // The model is a variable, not a constant (architecture-pillars.md §13). An agent card names
5
- // the engine it runs on, and there are four ways to say it:
6
- //
7
- // { kind: 'model', providerId?, model } an endpoint the client calls; `providerId` is
8
- // the endpoint / gateway destination, because the
9
- // same model at two providers is two engines
10
- // { kind: 'harness', harnessId, model? } a CLI coding agent the bridge runs (Claude
11
- // Code, Codex, …) — ChatPanel delegates a whole
12
- // task to it; `model` is what it was asked to run
13
- // { kind: 'auto', policy } the recruiter picks, by policy, from the
14
- // engine cards (§13.4) — the default
15
- // { kind: 'assistant' } the built-in Assistant: whatever model the chat
16
- // is on right now (`engineOf` resolves it)
17
- //
18
- // The RECORD keeps a flatter shape — `{ kind: 'model'|'harness', id, model? }`, see
19
- // scorecard.js `normalizeEngine` — because a record says what DID run, and `auto` and
20
- // `assistant` never run anything themselves. `engineRef` maps a spec to that shape once a
21
- // choice was made, so the scorecard's `byEngine` and the model ledger key the same way.
22
- //
23
- // Pure, dependency-free; team.js and agent.js both import from here, never from each other.
24
-
25
- export const ENGINE_KINDS = Object.freeze(['model', 'harness', 'auto', 'assistant']);
26
- export const ROUTE_PREFERS = Object.freeze(['cheapest-that-clears', 'best-quality', 'fastest', 'balanced']);
27
- export const HARNESS_ID_RE = /^[a-zA-Z0-9_.:@+-]{1,120}$/;
28
-
29
- const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
30
- const str = (v, n = 200) => (v == null || v === '' ? undefined : String(v).trim().slice(0, n) || undefined);
31
- const num = (v) => { const n = Number(v); return v === '' || v == null || !Number.isFinite(n) ? undefined : n; };
32
- const refs = (xs) => (Array.isArray(xs) ? [...new Set(xs.map((x) => str(typeof x === 'string' ? x : engineKeyOf(x), 200)).filter(Boolean))] : undefined);
33
-
34
- /** A routing policy, normalized: an unknown preference is `balanced`; floors and ceilings are numbers or absent. */
35
- export function normalizePolicy(p) {
36
- const src = isRecord(p) ? p : {};
37
- const floor = {}; const ceiling = {};
38
- const q = num(src.floor?.quality); if (q !== undefined) floor.quality = Math.max(0, Math.min(1, q));
39
- const av = num(src.floor?.availability); if (av !== undefined) floor.availability = Math.max(0, Math.min(1, av));
40
- const c = num(src.ceiling?.costPerTask); if (c !== undefined && c >= 0) ceiling.costPerTask = c;
41
- const l = num(src.ceiling?.latencyMs); if (l !== undefined && l >= 0) ceiling.latencyMs = Math.round(l);
42
- const allow = refs(src.allow); const deny = refs(src.deny);
43
- return {
44
- prefer: ROUTE_PREFERS.includes(src.prefer) ? src.prefer : 'balanced',
45
- ...(Object.keys(floor).length ? { floor } : {}),
46
- ...(Object.keys(ceiling).length ? { ceiling } : {}),
47
- ...(allow?.length ? { allow } : {}),
48
- ...(deny?.length ? { deny } : {}),
49
- };
50
- }
51
-
52
- /**
53
- * An engine spec as stored. A string is read the obvious way — `assistant`, `auto`, a
54
- * `harness:<id>` / `model:<id>` prefix, or a bare model id — because a person types these
55
- * and a model proposes them in prose. Anything unreadable is `auto`, the honest default.
56
- */
57
- export function normalizeEngineSpec(e) {
58
- if (e == null || e === '') return { kind: 'auto', policy: normalizePolicy() };
59
- if (typeof e === 'string') {
60
- const s = e.trim();
61
- if (s === 'assistant' || s === 'auto') return s === 'assistant' ? { kind: 'assistant' } : { kind: 'auto', policy: normalizePolicy() };
62
- const m = /^(model|harness):(.+)$/.exec(s);
63
- if (m) return m[1] === 'harness' ? { kind: 'harness', harnessId: m[2].trim() } : { kind: 'model', model: m[2].trim() };
64
- return { kind: 'model', model: s };
65
- }
66
- if (!isRecord(e)) return { kind: 'auto', policy: normalizePolicy() };
67
- const kind = ENGINE_KINDS.includes(e.kind) ? e.kind : (e.harnessId ? 'harness' : e.model ? 'model' : e.policy ? 'auto' : 'auto');
68
- if (kind === 'assistant') return { kind };
69
- if (kind === 'auto') return { kind, policy: normalizePolicy(e.policy) };
70
- if (kind === 'harness') {
71
- const harnessId = str(e.harnessId || e.id, 120);
72
- if (!harnessId) return { kind: 'auto', policy: normalizePolicy() };
73
- const model = str(e.model, 200);
74
- return { kind, harnessId, ...(model ? { model } : {}) };
75
- }
76
- const model = str(e.model || e.id, 200);
77
- if (!model) return { kind: 'auto', policy: normalizePolicy() };
78
- const providerId = str(e.providerId || e.destination || e.endpointId, 120);
79
- return { kind: 'model', ...(providerId ? { providerId } : {}), model };
80
- }
81
-
82
- /** Is this a spec a validator should accept? Returns the errors, with a prefix. */
83
- export function validateEngineSpec(e, where = 'engine') {
84
- const errors = [];
85
- if (e == null || e === '') return errors;
86
- if (typeof e === 'string') return errors; // every string reads as something
87
- if (!isRecord(e)) return [`${where}: a string or an object`];
88
- if (e.kind !== undefined && !ENGINE_KINDS.includes(e.kind)) errors.push(`${where}.kind: one of ${ENGINE_KINDS.join(', ')}`);
89
- if (e.kind === 'harness' && !str(e.harnessId || e.id)) errors.push(`${where}.harnessId: which harness`);
90
- if (e.kind === 'harness' && str(e.harnessId || e.id) && !HARNESS_ID_RE.test(String(e.harnessId || e.id).trim())) errors.push(`${where}.harnessId: a short identifier`);
91
- if (e.kind === 'model' && !str(e.model || e.id)) errors.push(`${where}.model: which model`);
92
- if (e.kind === 'auto' && e.policy !== undefined && !isRecord(e.policy)) errors.push(`${where}.policy: an object`);
93
- if (e.kind === 'auto' && isRecord(e.policy) && e.policy.prefer !== undefined && !ROUTE_PREFERS.includes(e.policy.prefer)) errors.push(`${where}.policy.prefer: one of ${ROUTE_PREFERS.join(', ')}`);
94
- return errors;
95
- }
96
-
97
- /**
98
- * The record's shape for a spec that names something concrete — `{ kind, id, model? }`,
99
- * the same fields scorecard.js keys `byEngine` on and the model ledger is keyed by. `auto`
100
- * and `assistant` have no ref: nothing ran yet.
101
- */
102
- export function engineRef(spec) {
103
- const s = normalizeEngineSpec(spec);
104
- if (s.kind === 'harness') return { kind: 'harness', id: s.harnessId, ...(s.model ? { model: s.model } : {}) };
105
- if (s.kind === 'model') return s.providerId ? { kind: 'model', id: s.providerId, model: s.model } : { kind: 'model', id: s.model };
106
- return null;
107
- }
108
-
109
- /** The ledger key of a spec, or null when it names nothing concrete. Same key as `engineKey` in scorecard.js. */
110
- export function engineKeyOf(spec) {
111
- const r = engineRef(spec);
112
- return r ? `${r.kind}:${r.id}${r.model && r.model !== r.id ? `/${r.model}` : ''}` : null;
113
- }
114
-
115
- /** One phrase a person reads on a card: "Claude Code", "gpt-4o at openrouter", "auto · cheapest that clears", "the chat's model". */
116
- export function describeEngine(spec, { harnessName = (id) => id, providerName = (id) => id } = {}) {
117
- const s = normalizeEngineSpec(spec);
118
- if (s.kind === 'assistant') return 'the chat’s model';
119
- if (s.kind === 'auto') return `auto · ${s.policy.prefer.replace(/-/g, ' ')}`;
120
- if (s.kind === 'harness') return `${harnessName(s.harnessId)}${s.model ? ` (${s.model})` : ''}`;
121
- return `${s.model}${s.providerId ? ` at ${providerName(s.providerId)}` : ''}`;
122
- }
123
-
124
- /**
125
- * The role tier today's appointers understand (`cheap` / `balanced` / `strong`) for a spec:
126
- * the bridge to `prefer` until the recruiter routes by card (§13.4, step 5).
127
- */
128
- export function tierOf(spec) {
129
- const s = normalizeEngineSpec(spec);
130
- if (s.kind !== 'auto') return 'balanced';
131
- return { 'best-quality': 'strong', 'cheapest-that-clears': 'cheap', fastest: 'cheap', balanced: 'balanced' }[s.policy.prefer] || 'balanced';
132
- }
1
+ const f=Object.freeze(["model","harness","auto","assistant"]),p=Object.freeze(["cheapest-that-clears","best-quality","fastest","balanced"]),$=/^[a-zA-Z0-9_.:@+-]{1,120}$/,a=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),s=(n,i=200)=>n==null||n===""?void 0:String(n).trim().slice(0,i)||void 0,l=n=>{const i=Number(n);return n===""||n==null||!Number.isFinite(i)?void 0:i},k=n=>Array.isArray(n)?[...new Set(n.map(i=>s(typeof i=="string"?i:I(i),200)).filter(Boolean))]:void 0;function d(n){const i=a(n)?n:{},t={},e={},r=l(i.floor?.quality);r!==void 0&&(t.quality=Math.max(0,Math.min(1,r)));const o=l(i.floor?.availability);o!==void 0&&(t.availability=Math.max(0,Math.min(1,o)));const c=l(i.ceiling?.costPerTask);c!==void 0&&c>=0&&(e.costPerTask=c);const u=l(i.ceiling?.latencyMs);u!==void 0&&u>=0&&(e.latencyMs=Math.round(u));const h=k(i.allow),y=k(i.deny);return{prefer:p.includes(i.prefer)?i.prefer:"balanced",...Object.keys(t).length?{floor:t}:{},...Object.keys(e).length?{ceiling:e}:{},...h?.length?{allow:h}:{},...y?.length?{deny:y}:{}}}function m(n){if(n==null||n==="")return{kind:"auto",policy:d()};if(typeof n=="string"){const r=n.trim();if(r==="assistant"||r==="auto")return r==="assistant"?{kind:"assistant"}:{kind:"auto",policy:d()};const o=/^(model|harness):(.+)$/.exec(r);return o?o[1]==="harness"?{kind:"harness",harnessId:o[2].trim()}:{kind:"model",model:o[2].trim()}:{kind:"model",model:r}}if(!a(n))return{kind:"auto",policy:d()};const i=f.includes(n.kind)?n.kind:n.harnessId?"harness":n.model?"model":(n.policy,"auto");if(i==="assistant")return{kind:i};if(i==="auto")return{kind:i,policy:d(n.policy)};if(i==="harness"){const r=s(n.harnessId||n.id,120);if(!r)return{kind:"auto",policy:d()};const o=s(n.model,200);return{kind:i,harnessId:r,...o?{model:o}:{}}}const t=s(n.model||n.id,200);if(!t)return{kind:"auto",policy:d()};const e=s(n.providerId||n.destination||n.endpointId,120);return{kind:"model",...e?{providerId:e}:{},model:t}}function b(n,i="engine"){const t=[];return n==null||n===""||typeof n=="string"?t:a(n)?(n.kind!==void 0&&!f.includes(n.kind)&&t.push(`${i}.kind: one of ${f.join(", ")}`),n.kind==="harness"&&!s(n.harnessId||n.id)&&t.push(`${i}.harnessId: which harness`),n.kind==="harness"&&s(n.harnessId||n.id)&&!$.test(String(n.harnessId||n.id).trim())&&t.push(`${i}.harnessId: a short identifier`),n.kind==="model"&&!s(n.model||n.id)&&t.push(`${i}.model: which model`),n.kind==="auto"&&n.policy!==void 0&&!a(n.policy)&&t.push(`${i}.policy: an object`),n.kind==="auto"&&a(n.policy)&&n.policy.prefer!==void 0&&!p.includes(n.policy.prefer)&&t.push(`${i}.policy.prefer: one of ${p.join(", ")}`),t):[`${i}: a string or an object`]}function g(n){const i=m(n);return i.kind==="harness"?{kind:"harness",id:i.harnessId,...i.model?{model:i.model}:{}}:i.kind==="model"?i.providerId?{kind:"model",id:i.providerId,model:i.model}:{kind:"model",id:i.model}:null}function I(n){const i=g(n);return i?`${i.kind}:${i.id}${i.model&&i.model!==i.id?`/${i.model}`:""}`:null}function x(n,{harnessName:i=e=>e,providerName:t=e=>e}={}){const e=m(n);return e.kind==="assistant"?"the chat’s model":e.kind==="auto"?`auto · ${e.policy.prefer.replace(/-/g," ")}`:e.kind==="harness"?`${i(e.harnessId)}${e.model?` (${e.model})`:""}`:`${e.model}${e.providerId?` at ${t(e.providerId)}`:""}`}function E(n){const i=m(n);return i.kind!=="auto"?"balanced":{"best-quality":"strong","cheapest-that-clears":"cheap",fastest:"cheap",balanced:"balanced"}[i.policy.prefer]||"balanced"}export{f as ENGINE_KINDS,$ as HARNESS_ID_RE,p as ROUTE_PREFERS,x as describeEngine,I as engineKeyOf,g as engineRef,m as normalizeEngineSpec,d as normalizePolicy,E as tierOf,b as validateEngineSpec};
@@ -1,84 +1 @@
1
- // Online entitlement re-validation. The gateway stores one offline-signed
2
- // entitlement token and verifies it offline (entitlement.js). On an interval it also
3
- // re-checks online: it polls the worker's /entitlement for the token's install_id and
4
- // either refreshes the stored token (still entitled) or clears it (worker reports
5
- // valid:false), dropping the gateway to Free. Network/worker errors never revoke
6
- // (fail-open); the offline `exp` still bounds the token's lifetime.
7
-
8
- import { persistConfig, configPath } from './configstore.js';
9
-
10
- // Same worker the extension/bridge use. Overridable for self-hosted/test.
11
- const API_BASE = (process.env.CHATPANEL_API_BASE || 'https://api.chatpanel.net').replace(/\/+$/, '');
12
- const CHECK_INTERVAL_MS = 60 * 60 * 1000; // 1h — online re-check interval
13
- const FIRST_CHECK_DELAY_MS = 30 * 1000; // let the server settle before first poll
14
- const MIN_RECHECK_MS = 2 * 60 * 1000; // throttle on-demand (/status) re-checks
15
-
16
- let lastCheckAt = 0;
17
-
18
- // The token payload carries { typ, plan, install_id, sub, exp }; we only need the
19
- // install_id to ask the worker whether that seat is still entitled.
20
- function installIdFromToken(token) {
21
- try {
22
- const head = String(token).split('.')[0];
23
- const json = Buffer.from(head.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
24
- const p = JSON.parse(json);
25
- return typeof p.install_id === 'string' && p.install_id ? p.install_id : null;
26
- } catch {
27
- return null;
28
- }
29
- }
30
-
31
- async function revalidate(cfg) {
32
- lastCheckAt = Date.now();
33
- const token = cfg.pro?.entitlementToken;
34
- if (!token) return;
35
- const installId = installIdFromToken(token);
36
- if (!installId) return; // legacy/opaque token — leave the offline exp to bound it
37
-
38
- let data;
39
- try {
40
- const r = await fetch(`${API_BASE}/entitlement?install_id=${encodeURIComponent(installId)}`, {
41
- signal: AbortSignal.timeout(8000),
42
- });
43
- if (!r.ok) return; // worker hiccup → fail-open, retry next interval
44
- data = await r.json();
45
- } catch {
46
- return; // offline / network error → fail-open (never revoke a paying user)
47
- }
48
-
49
- if (data && data.valid && typeof data.token === 'string' && data.token) {
50
- // Still entitled — adopt the freshly-signed token so Pro never lapses while paid.
51
- if (data.token !== token) {
52
- cfg.pro.entitlementToken = data.token;
53
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
54
- }
55
- } else if (data && data.valid === false) {
56
- // Worker reports the token is no longer valid → clear it and drop to Free.
57
- cfg.pro.entitlementToken = '';
58
- try { persistConfig(cfg, configPath()); } catch { /* best effort */ }
59
- console.log('[gateway] entitlement no longer valid — Pro deactivated (refund/revoke/seat lost).');
60
- }
61
- }
62
-
63
- // On-demand, throttled re-check — fire-and-forget from a hot path (the extension's
64
- // /status poll) so deactivation shows up within ~minutes of opening the gateway
65
- // tab, not just on the hourly tick. Never awaited; safe to call often.
66
- export function maybeRevalidate(cfg) {
67
- if (process.env.CHATPANEL_NO_REVALIDATE) return;
68
- if (!cfg.pro?.entitlementToken) return;
69
- if (Date.now() - lastCheckAt < MIN_RECHECK_MS) return;
70
- lastCheckAt = Date.now(); // claim the slot before the async hop (avoid stampede)
71
- revalidate(cfg).catch(() => {});
72
- }
73
-
74
- // Start the periodic re-check. Timers are unref'd so they never keep the process
75
- // alive on their own. Returns a handle with stop() for clean shutdown.
76
- export function startEntitlementRefresh(cfg) {
77
- if (process.env.CHATPANEL_NO_REVALIDATE) return { stop() {} };
78
- const tick = () => { revalidate(cfg).catch(() => {}); };
79
- const first = setTimeout(tick, FIRST_CHECK_DELAY_MS);
80
- const iv = setInterval(tick, CHECK_INTERVAL_MS);
81
- if (typeof first.unref === 'function') first.unref();
82
- if (typeof iv.unref === 'function') iv.unref();
83
- return { stop() { clearTimeout(first); clearInterval(iv); } };
84
- }
1
+ import{persistConfig as a,configPath as s}from"./configstore.js";const c=(process.env.CHATPANEL_API_BASE||"https://api.chatpanel.net").replace(/\/+$/,""),f=3600*1e3,u=30*1e3,p=120*1e3;let r=0;function _(e){try{const n=String(e).split(".")[0],o=Buffer.from(n.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),t=JSON.parse(o);return typeof t.install_id=="string"&&t.install_id?t.install_id:null}catch{return null}}async function l(e){r=Date.now();const n=e.pro?.entitlementToken;if(!n)return;const o=_(n);if(!o)return;let t;try{const i=await fetch(`${c}/entitlement?install_id=${encodeURIComponent(o)}`,{signal:AbortSignal.timeout(8e3)});if(!i.ok)return;t=await i.json()}catch{return}if(t&&t.valid&&typeof t.token=="string"&&t.token){if(t.token!==n){e.pro.entitlementToken=t.token;try{a(e,s())}catch{}}}else if(t&&t.valid===!1){e.pro.entitlementToken="";try{a(e,s())}catch{}console.log("[gateway] entitlement no longer valid — Pro deactivated (refund/revoke/seat lost).")}}function d(e){process.env.CHATPANEL_NO_REVALIDATE||e.pro?.entitlementToken&&(Date.now()-r<p||(r=Date.now(),l(e).catch(()=>{})))}function m(e){if(process.env.CHATPANEL_NO_REVALIDATE)return{stop(){}};const n=()=>{l(e).catch(()=>{})},o=setTimeout(n,u),t=setInterval(n,f);return typeof o.unref=="function"&&o.unref(),typeof t.unref=="function"&&t.unref(),{stop(){clearTimeout(o),clearInterval(t)}}}export{d as maybeRevalidate,m as startEntitlementRefresh};
@@ -1,76 +1 @@
1
- // Offline entitlement verification. The license server signs an ECDSA P-256 token;
2
- // the gateway ships the matching public key and verifies it locally. Gates paid
3
- // features such as custom "bring your own CLI" agents.
4
- //
5
- // Token format (identical to the extension's, extension/js/license.js):
6
- // token = base64url(JSON payload) + "." + base64url(raw ECDSA signature)
7
- // signed over UTF-8(head); payload = { typ:'ent', plan, install_id, sub, exp }
8
- //
9
- // Keep ENTITLEMENT_PUBLIC_JWK in sync with the extension's copy.
10
-
11
- import { webcrypto } from 'node:crypto';
12
-
13
- const ENTITLEMENT_PUBLIC_JWK = {
14
- kty: 'EC',
15
- crv: 'P-256',
16
- x: 'CmgKLC4e3xDMvwhbjVqF7jbDe1JhC1KKQi8JN3qVX_4',
17
- y: 'r40l6fQiyCcJYqW-SvB4VoSyn4F36yhSt82ZAOSo78E',
18
- };
19
-
20
- const PRO_PLANS = new Set(['pro', 'team']);
21
-
22
- const b64urlToBytes = (s) => {
23
- const norm = s.replace(/-/g, '+').replace(/_/g, '/');
24
- return new Uint8Array(Buffer.from(norm, 'base64'));
25
- };
26
-
27
- let keyPromise = null;
28
- function publicKey() {
29
- if (!keyPromise) {
30
- keyPromise = webcrypto.subtle.importKey(
31
- 'jwk',
32
- ENTITLEMENT_PUBLIC_JWK,
33
- { name: 'ECDSA', namedCurve: 'P-256' },
34
- false,
35
- ['verify'],
36
- );
37
- }
38
- return keyPromise;
39
- }
40
-
41
- // Verify a server entitlement token. Returns its payload, or null. Checks the
42
- // ECDSA signature (unforgeable without the private key), the token type, and
43
- // expiry. install_id binding is the extension's concern — for the bridge gate the
44
- // signature is what matters.
45
- export async function verifyEntitlement(token) {
46
- if (!token || typeof token !== 'string' || token.indexOf('.') < 0) return null;
47
- const [head, sig] = token.split('.');
48
- const enc = new TextEncoder();
49
- let ok = false;
50
- try {
51
- ok = await webcrypto.subtle.verify(
52
- { name: 'ECDSA', hash: 'SHA-256' },
53
- await publicKey(),
54
- b64urlToBytes(sig),
55
- enc.encode(head),
56
- );
57
- } catch {
58
- return null;
59
- }
60
- if (!ok) return null;
61
- let payload;
62
- try {
63
- payload = JSON.parse(new TextDecoder().decode(b64urlToBytes(head)));
64
- } catch {
65
- return null;
66
- }
67
- if (payload.typ !== 'ent') return null;
68
- if (payload.exp && Date.now() > payload.exp) return null;
69
- return payload;
70
- }
71
-
72
- // True when `token` is a valid, unexpired Pro (or Team) entitlement.
73
- export async function isProEntitled(token) {
74
- const p = await verifyEntitlement(token);
75
- return !!(p && PRO_PLANS.has(p.plan));
76
- }
1
+ import{webcrypto as o}from"node:crypto";const u={kty:"EC",crv:"P-256",x:"CmgKLC4e3xDMvwhbjVqF7jbDe1JhC1KKQi8JN3qVX_4",y:"r40l6fQiyCcJYqW-SvB4VoSyn4F36yhSt82ZAOSo78E"},s=new Set(["pro","team"]),a=e=>{const t=e.replace(/-/g,"+").replace(/_/g,"/");return new Uint8Array(Buffer.from(t,"base64"))};let r=null;function y(){return r||(r=o.subtle.importKey("jwk",u,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])),r}async function f(e){if(!e||typeof e!="string"||e.indexOf(".")<0)return null;const[t,i]=e.split("."),c=new TextEncoder;let l=!1;try{l=await o.subtle.verify({name:"ECDSA",hash:"SHA-256"},await y(),a(i),c.encode(t))}catch{return null}if(!l)return null;let n;try{n=JSON.parse(new TextDecoder().decode(a(t)))}catch{return null}return n.typ!=="ent"||n.exp&&Date.now()>n.exp?null:n}async function m(e){const t=await f(e);return!!(t&&s.has(t.plan))}export{m as isProEntitled,f as verifyEntitlement};