@chatpanel/gateway 0.6.110 → 0.8.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 (81) 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 +2 -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/policy.js +2 -0
  47. package/src/prefs-store.js +1 -149
  48. package/src/project-store.js +1 -139
  49. package/src/project.js +1 -171
  50. package/src/recruit.js +3 -424
  51. package/src/recruiting.js +1 -93
  52. package/src/redact.js +2 -123
  53. package/src/responses.js +2 -80
  54. package/src/router.js +1 -292
  55. package/src/rrf.js +1 -93
  56. package/src/scorecard-store.js +1 -92
  57. package/src/scorecard.js +1 -336
  58. package/src/search-index.js +2 -134
  59. package/src/secure-fetch.js +1 -58
  60. package/src/sentencepiece.js +1 -184
  61. package/src/server.js +10 -2296
  62. package/src/service.js +11 -189
  63. package/src/shape.js +5 -121
  64. package/src/sqlite-store.js +3 -212
  65. package/src/stream.js +5 -182
  66. package/src/structured.js +4 -902
  67. package/src/stt-engine.js +1 -486
  68. package/src/stt-models.js +1 -144
  69. package/src/subject-kinds.js +1 -6
  70. package/src/subject-name.js +1 -97
  71. package/src/team-board.js +6 -338
  72. package/src/team-record.js +1 -226
  73. package/src/team-store.js +1 -261
  74. package/src/team.js +1 -303
  75. package/src/toolrelay.js +3 -122
  76. package/src/tts-engine.js +1 -453
  77. package/src/tts-models.js +1 -254
  78. package/src/tts-remote.js +1 -109
  79. package/src/tts-voice-resolve.js +1 -78
  80. package/src/tts-voices.js +1 -192
  81. package/src/update.js +1 -305
package/src/team.js CHANGED
@@ -1,303 +1 @@
1
- // VENDORED from @chatpanel/events/team.js — edit there, then copy over.
2
- // A team, as data — roles with grants, a merge policy, a budget. Nothing runs here.
3
- //
4
- // The Notes co-writer swarm was one team, hard-wired: a planner, four roles appointed per
5
- // model, a shared board. The desktop was about to copy it, and every client would then hold
6
- // its own answer to "what is a researcher allowed to touch". So a team is declared once, in
7
- // this shape, and shared through the client-prefs document like a skill or a recipe: defined
8
- // in one client, invokable in the other at its next open.
9
- //
10
- // Two invariants are enforced here rather than trusted:
11
- // • A role's GRANTS name tool groups, never tools — and `page` is not grantable. A tab is
12
- // one person's; a team member acting on it is the one thing every guard was written to
13
- // stop. `none` is a legitimate grant: a writer needs no tools.
14
- // • A team has a BUDGET, or it is not a team (F8 O1). `validateTeam` refuses one without.
15
- //
16
- // Trust is derived, never declared (the skill-manifest rule): a stored `builtin` cannot
17
- // survive an `origin`, and a team a client stores as trusted is stored as nothing of the kind.
18
-
19
- import { validateBudget, normalizeBudget } from './budget.js';
20
- import { normalizeEngineSpec, validateEngineSpec, tierOf } from './engine.js';
21
-
22
- export const TEAM_NAME_RE = /^[a-z][a-z0-9_-]{0,63}$/i;
23
- export const ROLE_ID_RE = /^[a-z][a-z0-9_-]{0,31}$/i;
24
- export const ROLE_MODES = Object.freeze(['model', 'subagent', 'recipe']);
25
- export const ROLE_PREFERS = Object.freeze(['cheap', 'balanced', 'strong']);
26
- export const MERGE_POLICIES = Object.freeze(['judge', 'converge', 'concat', 'first']);
27
- export const PLAN_MODES = Object.freeze(['fixed', 'planner']);
28
- /**
29
- * The tool groups a role may hold. `mcp:<server>` narrows to one server; `mcp` is all of them.
30
- *
31
- * The work grants (architecture-pillars.md §14.2) are for an agent whose engine is a harness
32
- * running in a checkout: `shell` and `fs:write` say so explicitly instead of riding along
33
- * with the harness; `scm:read` reads the repo and its hub, `scm:push` pushes ITS OWN branch
34
- * (`cp/<project>/<job>`), `scm:pr` opens a pull request, and `scm:merge` is held by the
35
- * Gate — grantable only where the org's `gate.json` allows it. A chat-model role that holds
36
- * one of these holds nothing: only a harness engine can use them, and the bridge enforces it.
37
- */
38
- export const GRANTABLE = Object.freeze(['none', 'data', 'web', 'mcp', 'history', 'shell', 'fs:write', 'scm:read', 'scm:push', 'scm:pr', 'scm:merge']);
39
- export const WORK_GRANTS = Object.freeze(['shell', 'fs:write', 'scm:read', 'scm:push', 'scm:pr', 'scm:merge']);
40
- export const GRANT_RE = /^(none|data|web|history|mcp|mcp:[a-zA-Z0-9_.:-]{1,64}|shell|fs:write|scm:(read|push|pr|merge))$/;
41
- export const MAX_ROLES = 8;
42
- /** A role that stands for an agent from the pool: `agent` names it (agent.js `AGENT_ID_RE`). */
43
- export const AGENT_REF_RE = /^[a-z][a-z0-9_-]{0,63}$/i;
44
-
45
- export class TeamError extends Error {
46
- constructor(code, message) { super(message); this.name = 'TeamError'; this.code = code; }
47
- }
48
-
49
- const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
50
-
51
- /** A role's grants, normalized: `none` alone means no tools; duplicates and `page` are dropped. */
52
- export function normalizeGrants(grants) {
53
- const list = (Array.isArray(grants) ? grants : typeof grants === 'string' ? [grants] : []).map((g) => String(g || '').trim()).filter(Boolean);
54
- const ok = [...new Set(list.filter((g) => GRANT_RE.test(g)))];
55
- if (!ok.length || ok.includes('none')) return ['none'];
56
- return ok;
57
- }
58
-
59
- export function validateTeam(team) {
60
- const errors = [];
61
- if (!isRecord(team)) return { ok: false, errors: ['team must be an object'] };
62
- if (!TEAM_NAME_RE.test(String(team.name || ''))) errors.push('name: a short identifier (letters, digits, _ -)');
63
- if (!Array.isArray(team.roles) || !team.roles.length) errors.push('roles: a non-empty array');
64
- else {
65
- if (team.roles.length > MAX_ROLES) errors.push(`roles: at most ${MAX_ROLES}`);
66
- const seen = new Set();
67
- team.roles.forEach((r, i) => {
68
- const w = `roles[${i}]`;
69
- if (!isRecord(r)) { errors.push(`${w}: must be an object`); return; }
70
- if (!ROLE_ID_RE.test(String(r.id || ''))) errors.push(`${w}.id: a short identifier`);
71
- else if (seen.has(r.id)) errors.push(`${w}.id: duplicate "${r.id}"`);
72
- seen.add(r.id);
73
- if (r.mode !== undefined && !ROLE_MODES.includes(r.mode)) errors.push(`${w}.mode: one of ${ROLE_MODES.join(', ')}`);
74
- if (r.prefer !== undefined && !ROLE_PREFERS.includes(r.prefer)) errors.push(`${w}.prefer: one of ${ROLE_PREFERS.join(', ')}`);
75
- if ((r.mode || 'model') === 'recipe' && !r.recipe) errors.push(`${w}.recipe: a recipe name is required in recipe mode`);
76
- if (r.agent !== undefined && r.agent !== null && !AGENT_REF_RE.test(String(r.agent))) errors.push(`${w}.agent: an agent id`);
77
- // A role that stands for an agent takes its prompt from the pool (agent.js resolveTeam);
78
- // a role that stands for nobody must say what it does.
79
- if ((r.mode || 'model') !== 'recipe' && !r.agent && !String(r.prompt || '').trim()) errors.push(`${w}.prompt: what this role does`);
80
- errors.push(...validateEngineSpec(r.engine, `${w}.engine`));
81
- const bad = (Array.isArray(r.grants) ? r.grants : []).filter((g) => !GRANT_RE.test(String(g)));
82
- if (bad.length) errors.push(`${w}.grants: not grantable: ${bad.join(', ')}${bad.some((g) => /^page/.test(String(g))) ? ' (a tab is one person\'s; a team may not act on it)' : ''}`);
83
- });
84
- }
85
- if (team.merge !== undefined && !MERGE_POLICIES.includes(team.merge)) errors.push(`merge: one of ${MERGE_POLICIES.join(', ')}`);
86
- if (team.plan !== undefined && !PLAN_MODES.includes(team.plan)) errors.push(`plan: one of ${PLAN_MODES.join(', ')}`);
87
- if (team.judge !== undefined && team.judge !== null && !(Array.isArray(team.roles) && team.roles.some((r) => r?.id === team.judge))) errors.push('judge: must name one of the roles');
88
- const b = validateBudget(team.budget);
89
- if (!b.ok) errors.push(...b.errors.map((e) => `budget: ${e}`));
90
- return { ok: errors.length === 0, errors };
91
- }
92
-
93
- /**
94
- * The stored form. Defaults filled, grants normalized, trust derived: `builtin` only when the
95
- * host says so, never from the record.
96
- */
97
- export function normalizeTeam(team, { builtin = false } = {}) {
98
- const v = validateTeam(team);
99
- if (!v.ok) throw new TeamError('INVALID', v.errors.join('; '));
100
- return {
101
- name: String(team.name),
102
- description: String(team.description || '').trim().slice(0, 300),
103
- plan: PLAN_MODES.includes(team.plan) ? team.plan : 'fixed',
104
- merge: MERGE_POLICIES.includes(team.merge) ? team.merge : (team.judge ? 'judge' : 'concat'),
105
- judge: team.judge || null,
106
- roles: team.roles.map((r) => ({
107
- id: String(r.id),
108
- name: String(r.name || r.id).slice(0, 60),
109
- mode: ROLE_MODES.includes(r.mode) ? r.mode : 'model',
110
- prefer: ROLE_PREFERS.includes(r.prefer) ? r.prefer : (r.engine ? tierOf(r.engine) : 'balanced'),
111
- ...(r.model ? { model: String(r.model) } : {}),
112
- ...(r.agent ? { agent: String(r.agent) } : {}),
113
- ...(r.engine ? { engine: normalizeEngineSpec(r.engine) } : {}),
114
- prompt: String(r.prompt || '').trim().slice(0, 4000),
115
- // A role that stands for an agent holds the agent's grants unless it narrows them: no
116
- // list means "the agent's", so the key is left out rather than stored as `none`.
117
- ...(r.agent && !(Array.isArray(r.grants) && r.grants.length) ? {} : { grants: normalizeGrants(r.grants) }),
118
- ...(r.recipe ? { recipe: String(r.recipe) } : {}),
119
- ...(Array.isArray(r.dependsOn) ? { dependsOn: r.dependsOn.map(String).filter((d) => d !== r.id) } : {}),
120
- // What agent.js resolveTeam fills from the pool; kept so the runner's roles carry it.
121
- ...(Array.isArray(r.skills) && r.skills.length ? { skills: r.skills.map(String).slice(0, 32) } : {}),
122
- ...(r.workdir ? { workdir: String(r.workdir).slice(0, 400) } : {}),
123
- ...(r.egress === 'redacted' || r.egress === 'delegated' ? { egress: r.egress } : {}),
124
- ...(r.memoryScope ? { memoryScope: String(r.memoryScope).slice(0, 120) } : {}),
125
- })),
126
- budget: normalizeBudget(team.budget),
127
- enabled: team.enabled !== false,
128
- ...(team.origin && isRecord(team.origin) ? { origin: { ...team.origin } } : {}),
129
- ...(builtin ? { builtin: true } : {}),
130
- ...(team.createdAt ? { createdAt: team.createdAt } : {}),
131
- };
132
- }
133
-
134
- export function defineTeam(team) { return Object.freeze(normalizeTeam(team)); }
135
-
136
- /** Which of a client's tool groups a role may hold — `(groupId, serverId?) => boolean`. */
137
- export function grantAllows(grants, groupId, serverId = '') {
138
- const g = normalizeGrants(grants);
139
- if (g.includes('none')) return false;
140
- if (groupId === 'page') return false;
141
- if (groupId === 'mcp') return g.includes('mcp') || (!!serverId && g.includes(`mcp:${serverId}`));
142
- return g.includes(groupId);
143
- }
144
-
145
- /**
146
- * The SCM ladder: `merge` ⊃ `pr` ⊃ `push` ⊃ `read` — a role that may open a PR may push the
147
- * branch the PR is from, and anyone who may push may read. `push` is the role's OWN branch
148
- * only; the bridge names it (`cp/<project>/<job>`) and refuses any other.
149
- */
150
- const SCM_LADDER = ['read', 'push', 'pr', 'merge'];
151
- export function scmAllows(grants, action) {
152
- const g = normalizeGrants(grants);
153
- const want = SCM_LADDER.indexOf(String(action || '').replace(/^scm:/, ''));
154
- if (want < 0 || g.includes('none')) return false;
155
- const held = Math.max(-1, ...g.filter((x) => x.startsWith('scm:')).map((x) => SCM_LADDER.indexOf(x.slice(4))));
156
- return held >= want;
157
- }
158
-
159
- /** One line a person reads per role: name · tier/model · grants · mode. */
160
- export function describeRole(r) {
161
- const who = r.model || r.prefer || 'balanced';
162
- const grants = (r.grants || ['none']).join(', ');
163
- return `${r.name || r.id}${r.agent ? ` (agent: ${r.agent})` : ''} — ${who}${r.mode && r.mode !== 'model' ? ` (${r.mode})` : ''} · tools: ${grants}`;
164
- }
165
-
166
- // ── Starters and the editor's form ───────────────────────────────────────────────────────
167
- //
168
- // A team is usually proposed in conversation, but a person's first team should not depend
169
- // on a model deciding to propose one. Both clients' Settings → Teams offer these as "Add
170
- // starter" and edit them on the same form as a blank team; `teamFromForm` is the one shaping
171
- // of that form into a team, so a field's meaning does not differ between clients.
172
-
173
- export const STARTER_TEAMS = Object.freeze([
174
- {
175
- name: 'research',
176
- description: 'Research a question from the web and your own notes, then write it up.',
177
- plan: 'fixed', merge: 'judge', judge: 'writer',
178
- roles: [
179
- { id: 'researcher', prompt: 'Research the request thoroughly. Search the web and the user\'s own history. Report each fact as a finding with where it came from; note disagreements between sources.', prefer: 'balanced', grants: ['web', 'data'] },
180
- { id: 'writer', prompt: 'Write the answer the user asked for from the board\'s findings, citing them. Say plainly what was not found.', prefer: 'strong', grants: ['none'] },
181
- ],
182
- budget: { tokens: 40000, ms: 300000 },
183
- },
184
- {
185
- name: 'review',
186
- description: 'Two independent reads of a draft, reconciled into one set of comments.',
187
- plan: 'fixed', merge: 'converge',
188
- roles: [
189
- { id: 'editor', prompt: 'Read the draft as an editor: structure, clarity, what is missing. One finding per issue, with the passage it refers to.', prefer: 'strong', grants: ['none'] },
190
- { id: 'checker', prompt: 'Read the draft as a fact-checker: every claim that could be wrong, with what you checked against. Use the user\'s history and the web.', prefer: 'balanced', grants: ['data', 'web'] },
191
- ],
192
- budget: { tokens: 30000, ms: 240000 },
193
- },
194
- // ── The engineering teams (architecture-pillars.md §12.2) — roles stand for the standing
195
- // agents in agent.js STARTER_AGENTS; a role's prompt is the agent's, its engine the agent's.
196
- // A feature that crosses repos recruits one Implementer per repo (the role says which via
197
- // its prompt); these starters name one.
198
- {
199
- name: 'feature',
200
- description: 'Architect plans, an Implementer builds on a branch, Reviewer and Tester check, Scribe writes it up. The Architect judges.',
201
- plan: 'planner', merge: 'judge', judge: 'architect',
202
- roles: [
203
- { id: 'architect', agent: 'architect' },
204
- { id: 'implementer', agent: 'implementer', dependsOn: ['architect'] },
205
- { id: 'reviewer', agent: 'reviewer', dependsOn: ['implementer'] },
206
- { id: 'tester', agent: 'tester', dependsOn: ['implementer'] },
207
- { id: 'scribe', agent: 'scribe', dependsOn: ['reviewer', 'tester'] },
208
- ],
209
- budget: { tokens: 400000, ms: 3600000 },
210
- },
211
- {
212
- name: 'fix',
213
- description: 'One Implementer fixes it on a branch, the Tester runs the guard, the Scribe notes it.',
214
- plan: 'fixed', merge: 'concat',
215
- roles: [
216
- { id: 'implementer', agent: 'implementer' },
217
- { id: 'tester', agent: 'tester', dependsOn: ['implementer'] },
218
- { id: 'scribe', agent: 'scribe', dependsOn: ['tester'] },
219
- ],
220
- budget: { tokens: 150000, ms: 1800000 },
221
- },
222
- {
223
- name: 'docs',
224
- description: 'The Architect decides what the docs should say; the Scribe proposes the text.',
225
- plan: 'fixed', merge: 'concat',
226
- roles: [
227
- { id: 'architect', agent: 'architect' },
228
- { id: 'scribe', agent: 'scribe', dependsOn: ['architect'] },
229
- ],
230
- budget: { tokens: 80000, ms: 900000 },
231
- },
232
- {
233
- name: 'release',
234
- description: 'The Tester runs the guard on the merged branch, Release bumps and asks before publishing, the Scribe records the version.',
235
- plan: 'fixed', merge: 'concat',
236
- roles: [
237
- { id: 'tester', agent: 'tester' },
238
- { id: 'release', agent: 'release', dependsOn: ['tester'] },
239
- { id: 'scribe', agent: 'scribe', dependsOn: ['release'] },
240
- ],
241
- budget: { tokens: 60000, ms: 1800000 },
242
- },
243
- ]);
244
-
245
- /**
246
- * A name as typed → the identifier a `/command` needs: "Research Team" → "research-team".
247
- * Used by the tool's save and by the form, so a model that names a team in prose is not
248
- * bounced for it; what cannot be shaped (nothing left) still fails validation.
249
- */
250
- export function slugTeamName(name) {
251
- return String(name || '').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[^a-z]+/, '').replace(/-+$/, '').slice(0, 64);
252
- }
253
-
254
- /** Fresh copies — a starter is a template, never the stored record. */
255
- export function starterTeams() {
256
- return STARTER_TEAMS.map((t) => ({ ...t, roles: t.roles.map((r) => ({ ...r, ...(r.grants ? { grants: [...r.grants] } : {}), ...(r.dependsOn ? { dependsOn: [...r.dependsOn] } : {}) })), budget: { ...t.budget } }));
257
- }
258
-
259
- /** A blank team for the editor: one role, the smallest budget that is still a budget. */
260
- export function blankTeam() {
261
- return { name: '', description: '', plan: 'fixed', merge: 'concat', judge: null, roles: [{ id: 'role1', prompt: '', prefer: 'balanced', grants: ['none'] }], budget: { tokens: 20000, ms: 300000 } };
262
- }
263
-
264
- /**
265
- * The editor's form → a team, or the errors. Grants come as text ("web, data, mcp:srv"),
266
- * the budget as numbers that may be blank; a blank judge under `merge: judge` is the last
267
- * role, which is the writer in every starter.
268
- */
269
- const grantsText = (g) => String(Array.isArray(g) ? g.join(',') : g || '').split(/[,\s]+/).map((x) => x.trim()).filter(Boolean);
270
- export function teamFromForm(form) {
271
- const roles = (Array.isArray(form.roles) ? form.roles : []).map((r) => ({
272
- id: String(r.id || '').trim(),
273
- name: String(r.name || '').trim() || undefined,
274
- prompt: String(r.prompt || ''),
275
- prefer: r.prefer || 'balanced',
276
- ...(r.model ? { model: String(r.model) } : {}),
277
- ...(r.agent ? { agent: String(r.agent).trim() } : {}),
278
- ...(r.engine ? { engine: r.engine } : {}),
279
- ...(Array.isArray(r.dependsOn) ? { dependsOn: r.dependsOn.map(String) } : {}),
280
- // Blank grants on a role that stands for an agent mean "the agent's"; on any other role
281
- // they mean none.
282
- ...(grantsText(r.grants).length ? { grants: grantsText(r.grants) } : r.agent ? {} : { grants: ['none'] }),
283
- }));
284
- const budget = {};
285
- for (const k of ['tokens', 'calls', 'ms', 'usd']) {
286
- const v = Number(form.budget?.[k]);
287
- if (form.budget?.[k] !== '' && form.budget?.[k] != null && Number.isFinite(v) && v > 0) budget[k] = v;
288
- }
289
- const merge = form.merge || 'concat';
290
- const team = {
291
- name: slugTeamName(form.name),
292
- description: String(form.description || '').trim(),
293
- plan: form.plan || 'fixed',
294
- merge,
295
- judge: merge === 'judge' ? (form.judge || roles[roles.length - 1]?.id || null) : null,
296
- roles,
297
- budget,
298
- enabled: form.enabled !== false,
299
- ...(form.createdAt ? { createdAt: form.createdAt } : {}),
300
- };
301
- const v = validateTeam(team);
302
- return v.ok ? { ok: true, team: normalizeTeam(team) } : { ok: false, errors: v.errors };
303
- }
1
+ import{validateBudget as y,normalizeBudget as x}from"./budget.js";import{normalizeEngineSpec as O,validateEngineSpec as j,tierOf as $}from"./engine.js";const k=/^[a-z][a-z0-9_-]{0,63}$/i,E=/^[a-z][a-z0-9_-]{0,31}$/i,c=Object.freeze(["model","subagent","recipe"]),l=Object.freeze(["cheap","balanced","strong"]),p=Object.freeze(["judge","converge","concat","first"]),g=Object.freeze(["fixed","planner"]),N=Object.freeze(["none","data","web","mcp","history","shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),M=Object.freeze(["shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),f=/^(none|data|web|history|mcp|mcp:[a-zA-Z0-9_.:-]{1,64}|shell|fs:write|scm:(read|push|pr|merge))$/,h=8,R=/^[a-z][a-z0-9_-]{0,63}$/i;class T extends Error{constructor(t,i){super(i),this.name="TeamError",this.code=t}}const u=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function m(e){const t=(Array.isArray(e)?e:typeof e=="string"?[e]:[]).map(n=>String(n||"").trim()).filter(Boolean),i=[...new Set(t.filter(n=>f.test(n)))];return!i.length||i.includes("none")?["none"]:i}function b(e){const t=[];if(!u(e))return{ok:!1,errors:["team must be an object"]};if(k.test(String(e.name||""))||t.push("name: a short identifier (letters, digits, _ -)"),!Array.isArray(e.roles)||!e.roles.length)t.push("roles: a non-empty array");else{e.roles.length>h&&t.push(`roles: at most ${h}`);const n=new Set;e.roles.forEach((s,o)=>{const r=`roles[${o}]`;if(!u(s)){t.push(`${r}: must be an object`);return}E.test(String(s.id||""))?n.has(s.id)&&t.push(`${r}.id: duplicate "${s.id}"`):t.push(`${r}.id: a short identifier`),n.add(s.id),s.mode!==void 0&&!c.includes(s.mode)&&t.push(`${r}.mode: one of ${c.join(", ")}`),s.prefer!==void 0&&!l.includes(s.prefer)&&t.push(`${r}.prefer: one of ${l.join(", ")}`),(s.mode||"model")==="recipe"&&!s.recipe&&t.push(`${r}.recipe: a recipe name is required in recipe mode`),s.agent!==void 0&&s.agent!==null&&!R.test(String(s.agent))&&t.push(`${r}.agent: an agent id`),(s.mode||"model")!=="recipe"&&!s.agent&&!String(s.prompt||"").trim()&&t.push(`${r}.prompt: what this role does`),t.push(...j(s.engine,`${r}.engine`));const a=(Array.isArray(s.grants)?s.grants:[]).filter(d=>!f.test(String(d)));a.length&&t.push(`${r}.grants: not grantable: ${a.join(", ")}${a.some(d=>/^page/.test(String(d)))?" (a tab is one person's; a team may not act on it)":""}`)})}e.merge!==void 0&&!p.includes(e.merge)&&t.push(`merge: one of ${p.join(", ")}`),e.plan!==void 0&&!g.includes(e.plan)&&t.push(`plan: one of ${g.join(", ")}`),e.judge!==void 0&&e.judge!==null&&!(Array.isArray(e.roles)&&e.roles.some(n=>n?.id===e.judge))&&t.push("judge: must name one of the roles");const i=y(e.budget);return i.ok||t.push(...i.errors.map(n=>`budget: ${n}`)),{ok:t.length===0,errors:t}}function S(e,{builtin:t=!1}={}){const i=b(e);if(!i.ok)throw new T("INVALID",i.errors.join("; "));return{name:String(e.name),description:String(e.description||"").trim().slice(0,300),plan:g.includes(e.plan)?e.plan:"fixed",merge:p.includes(e.merge)?e.merge:e.judge?"judge":"concat",judge:e.judge||null,roles:e.roles.map(n=>({id:String(n.id),name:String(n.name||n.id).slice(0,60),mode:c.includes(n.mode)?n.mode:"model",prefer:l.includes(n.prefer)?n.prefer:n.engine?$(n.engine):"balanced",...n.model?{model:String(n.model)}:{},...n.agent?{agent:String(n.agent)}:{},...n.engine?{engine:O(n.engine)}:{},prompt:String(n.prompt||"").trim().slice(0,4e3),...n.agent&&!(Array.isArray(n.grants)&&n.grants.length)?{}:{grants:m(n.grants)},...n.recipe?{recipe:String(n.recipe)}:{},...Array.isArray(n.dependsOn)?{dependsOn:n.dependsOn.map(String).filter(s=>s!==n.id)}:{},...Array.isArray(n.skills)&&n.skills.length?{skills:n.skills.map(String).slice(0,32)}:{},...n.workdir?{workdir:String(n.workdir).slice(0,400)}:{},...n.egress==="redacted"||n.egress==="delegated"?{egress:n.egress}:{},...n.memoryScope?{memoryScope:String(n.memoryScope).slice(0,120)}:{}})),budget:x(e.budget),enabled:e.enabled!==!1,...e.origin&&u(e.origin)?{origin:{...e.origin}}:{},...t?{builtin:!0}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function D(e){return Object.freeze(S(e))}function G(e,t,i=""){const n=m(e);return n.includes("none")||t==="page"?!1:t==="mcp"?n.includes("mcp")||!!i&&n.includes(`mcp:${i}`):n.includes(t)}const w=["read","push","pr","merge"];function B(e,t){const i=m(e),n=w.indexOf(String(t||"").replace(/^scm:/,""));return n<0||i.includes("none")?!1:Math.max(-1,...i.filter(o=>o.startsWith("scm:")).map(o=>w.indexOf(o.slice(4))))>=n}function F(e){const t=e.model||e.prefer||"balanced",i=(e.grants||["none"]).join(", ");return`${e.name||e.id}${e.agent?` (agent: ${e.agent})`:""} — ${t}${e.mode&&e.mode!=="model"?` (${e.mode})`:""} · tools: ${i}`}const z=Object.freeze([{name:"research",description:"Research a question from the web and your own notes, then write it up.",plan:"fixed",merge:"judge",judge:"writer",roles:[{id:"researcher",prompt:"Research the request thoroughly. Search the web and the user's own history. Report each fact as a finding with where it came from; note disagreements between sources.",prefer:"balanced",grants:["web","data"]},{id:"writer",prompt:"Write the answer the user asked for from the board's findings, citing them. Say plainly what was not found.",prefer:"strong",grants:["none"]}],budget:{tokens:4e4,ms:3e5}},{name:"review",description:"Two independent reads of a draft, reconciled into one set of comments.",plan:"fixed",merge:"converge",roles:[{id:"editor",prompt:"Read the draft as an editor: structure, clarity, what is missing. One finding per issue, with the passage it refers to.",prefer:"strong",grants:["none"]},{id:"checker",prompt:"Read the draft as a fact-checker: every claim that could be wrong, with what you checked against. Use the user's history and the web.",prefer:"balanced",grants:["data","web"]}],budget:{tokens:3e4,ms:24e4}},{name:"feature",description:"Architect plans, an Implementer builds on a branch, Reviewer and Tester check, Scribe writes it up. The Architect judges.",plan:"planner",merge:"judge",judge:"architect",roles:[{id:"architect",agent:"architect"},{id:"implementer",agent:"implementer",dependsOn:["architect"]},{id:"reviewer",agent:"reviewer",dependsOn:["implementer"]},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["reviewer","tester"]}],budget:{tokens:4e5,ms:36e5}},{name:"fix",description:"One Implementer fixes it on a branch, the Tester runs the guard, the Scribe notes it.",plan:"fixed",merge:"concat",roles:[{id:"implementer",agent:"implementer"},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["tester"]}],budget:{tokens:15e4,ms:18e5}},{name:"docs",description:"The Architect decides what the docs should say; the Scribe proposes the text.",plan:"fixed",merge:"concat",roles:[{id:"architect",agent:"architect"},{id:"scribe",agent:"scribe",dependsOn:["architect"]}],budget:{tokens:8e4,ms:9e5}},{name:"release",description:"The Tester runs the guard on the merged branch, Release bumps and asks before publishing, the Scribe records the version.",plan:"fixed",merge:"concat",roles:[{id:"tester",agent:"tester"},{id:"release",agent:"release",dependsOn:["tester"]},{id:"scribe",agent:"scribe",dependsOn:["release"]}],budget:{tokens:6e4,ms:18e5}}]);function _(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/,"").slice(0,64)}function I(){return z.map(e=>({...e,roles:e.roles.map(t=>({...t,...t.grants?{grants:[...t.grants]}:{},...t.dependsOn?{dependsOn:[...t.dependsOn]}:{}})),budget:{...e.budget}}))}function q(){return{name:"",description:"",plan:"fixed",merge:"concat",judge:null,roles:[{id:"role1",prompt:"",prefer:"balanced",grants:["none"]}],budget:{tokens:2e4,ms:3e5}}}const A=e=>String(Array.isArray(e)?e.join(","):e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean);function C(e){const t=(Array.isArray(e.roles)?e.roles:[]).map(r=>({id:String(r.id||"").trim(),name:String(r.name||"").trim()||void 0,prompt:String(r.prompt||""),prefer:r.prefer||"balanced",...r.model?{model:String(r.model)}:{},...r.agent?{agent:String(r.agent).trim()}:{},...r.engine?{engine:r.engine}:{},...Array.isArray(r.dependsOn)?{dependsOn:r.dependsOn.map(String)}:{},...A(r.grants).length?{grants:A(r.grants)}:r.agent?{}:{grants:["none"]}})),i={};for(const r of["tokens","calls","ms","usd"]){const a=Number(e.budget?.[r]);e.budget?.[r]!==""&&e.budget?.[r]!=null&&Number.isFinite(a)&&a>0&&(i[r]=a)}const n=e.merge||"concat",s={name:_(e.name),description:String(e.description||"").trim(),plan:e.plan||"fixed",merge:n,judge:n==="judge"&&(e.judge||t[t.length-1]?.id)||null,roles:t,budget:i,enabled:e.enabled!==!1,...e.createdAt?{createdAt:e.createdAt}:{}},o=b(s);return o.ok?{ok:!0,team:S(s)}:{ok:!1,errors:o.errors}}export{R as AGENT_REF_RE,N as GRANTABLE,f as GRANT_RE,h as MAX_ROLES,p as MERGE_POLICIES,g as PLAN_MODES,E as ROLE_ID_RE,c as ROLE_MODES,l as ROLE_PREFERS,z as STARTER_TEAMS,k as TEAM_NAME_RE,T as TeamError,M as WORK_GRANTS,q as blankTeam,D as defineTeam,F as describeRole,G as grantAllows,m as normalizeGrants,S as normalizeTeam,B as scmAllows,_ as slugTeamName,I as starterTeams,C as teamFromForm,b as validateTeam};
package/src/toolrelay.js CHANGED
@@ -1,123 +1,4 @@
1
- // Tool-call relay for the bridge backend.
2
- //
3
- // The bridge relays a CLI agent's tool calls MID-SESSION: it emits a
4
- // `tool_request` over the /chat SSE and pauses the agent until a POST /tool-result
5
- // arrives. OpenAI function-calling is the opposite — the model returns `tool_calls`,
6
- // the response ENDS, and the client re-requests with results. To bridge the two we
7
- // keep the codex /chat stream OPEN across the OpenAI round-trip:
8
- //
9
- // 1. open bridge /chat with the client's tools as pageTools.specs
10
- // 2. read SSE; on `tool_request` → emit OpenAI tool_calls, finish_reason:tool_calls,
11
- // and PARK the session (reader stays open; codex is paused on the bridge side)
12
- // 3. on the client's follow-up request (carrying the tool result + tool_call_id) →
13
- // POST /tool-result to the bridge and RESUME reading the same stream
14
- //
15
- // Tool args are restored on the way out (so the client runs on real values) and
16
- // the result is redacted on the way back (so codex only sees placeholders).
1
+ import{randomUUID as p}from"node:crypto";import{restoreDeep as m,redactText as y,createVault as g}from"@chatpanel/pii";const s=new Map,b=(e,t)=>`gwtr_${e}_${t}`;function w(e){const t=/^gwtr_([^_]+)_(.+)$/.exec(String(e||""));return t?{gwId:t[1],toolId:t[2]}:null}function _(e){return(Array.isArray(e)?e:[]).filter(t=>t&&t.type==="function"&&t.function?.name).map(t=>({name:t.function.name,description:t.function.description||"",parameters:t.function.parameters||{type:"object",properties:{}}}))}const x=2e5;function h({vault:e,redactOpts:t,bridgeUrl:r,token:n,harness:a=null,idleMs:c=x}){const i=p().slice(0,8),l={id:i,reader:null,decoder:new TextDecoder,buf:"",bridgeSessionId:null,toolId:null,vault:e||g(),redactOpts:t||{tier:"basic"},bridgeUrl:r,token:n,harness:a,done:!1,idleMs:c,ttl:null,startedAt:Date.now(),rounds:0};return s.set(i,l),u(i),l}const D=e=>s.get(e);function u(e){const t=s.get(e);t&&(t.ttl&&clearTimeout(t.ttl),t.ttl=setTimeout(()=>S(e),t.idleMs),typeof t.ttl.unref=="function"&&t.ttl.unref())}function S(e){const t=s.get(e);if(t?.ttl&&clearTimeout(t.ttl),t?.reader)try{t.reader.cancel()}catch{}s.delete(e)}async function O(e,t){for(;;){let r;for(;(r=e.buf.indexOf(`
17
2
 
18
- import { randomUUID } from 'node:crypto';
19
- import { restoreDeep, redactText, createVault } from '@chatpanel/pii';
20
-
21
- const sessions = new Map(); // gwSessionId -> { reader, decoder, buf, bridgeSessionId, toolId, vault, redactOpts, bridgeUrl, token }
22
-
23
- // Encode/decode the gateway session into the OpenAI tool_call id so the client
24
- // echoes it back on the follow-up request, letting us find the parked session.
25
- const encodeToolCallId = (gwId, toolId) => `gwtr_${gwId}_${toolId}`;
26
- export function parseToolCallId(id) {
27
- const m = /^gwtr_([^_]+)_(.+)$/.exec(String(id || ''));
28
- return m ? { gwId: m[1], toolId: m[2] } : null;
29
- }
30
-
31
- // Map OpenAI `tools` → the bridge's pageTools.specs ({ name, description, parameters }).
32
- export function toolsToSpecs(tools) {
33
- return (Array.isArray(tools) ? tools : [])
34
- .filter((t) => t && t.type === 'function' && t.function?.name)
35
- .map((t) => ({ name: t.function.name, description: t.function.description || '', parameters: t.function.parameters || { type: 'object', properties: {} } }));
36
- }
37
-
38
- // A parked session lives while something is happening on it. The limit is IDLE time —
39
- // re-armed on every tool result the client brings back and every chunk the agent sends —
40
- // not time since the turn began: a flat 135 s from the start killed every relayed turn
41
- // with more than a handful of tool rounds, at 135.1 s exactly, and the client read the
42
- // empty resume as "the model returned no answer". A team member's turn is many rounds.
43
- export const RELAY_IDLE_MS = 200_000; // longer than the bridge's own idle (180 s), which is the authority
44
-
45
- export function createRelaySession({ vault, redactOpts, bridgeUrl, token, harness = null, idleMs = RELAY_IDLE_MS }) {
46
- const id = randomUUID().slice(0, 8);
47
- const s = { id, reader: null, decoder: new TextDecoder(), buf: '', bridgeSessionId: null, toolId: null, vault: vault || createVault(), redactOpts: redactOpts || { tier: 'basic' }, bridgeUrl, token, harness, done: false, idleMs, ttl: null, startedAt: Date.now(), rounds: 0 };
48
- sessions.set(id, s);
49
- touchRelaySession(id);
50
- return s;
51
- }
52
- export const getRelaySession = (id) => sessions.get(id);
53
- /** Something happened on the session: the idle clock starts over. */
54
- export function touchRelaySession(id) {
55
- const s = sessions.get(id);
56
- if (!s) return;
57
- if (s.ttl) clearTimeout(s.ttl);
58
- s.ttl = setTimeout(() => endRelaySession(id), s.idleMs);
59
- if (typeof s.ttl.unref === 'function') s.ttl.unref();
60
- }
61
- export function endRelaySession(id) {
62
- const s = sessions.get(id);
63
- if (s?.ttl) clearTimeout(s.ttl);
64
- if (s?.reader) { try { s.reader.cancel(); } catch { /* ignore */ } }
65
- sessions.delete(id);
66
- }
67
-
68
- // Drain one SSE event block ("data: {json}\n\n") at a time from the held reader,
69
- // dispatching to handlers until a tool_request parks us or the stream is done.
70
- // handlers: { onText(restorableText), onToolRequest({name, restoredArgs, toolId, bridgeSessionId}), onDone(), onError(err) }
71
- // Returns 'parked' (hit a tool_request) or 'done'.
72
- export async function pumpBridgeStream(s, handlers) {
73
- for (;;) {
74
- let nl;
75
- while ((nl = s.buf.indexOf('\n\n')) !== -1) {
76
- const block = s.buf.slice(0, nl);
77
- s.buf = s.buf.slice(nl + 2);
78
- for (const line of block.split('\n')) {
79
- const t = line.trim();
80
- if (!t.startsWith('data:')) continue;
81
- const payload = t.slice(5).trim();
82
- if (!payload || payload === '[DONE]') continue;
83
- let evt; try { evt = JSON.parse(payload); } catch { continue; }
84
- // Anything the bridge sends is life: an agent running its own tools for two minutes
85
- // sends only status events, and a session that counts only text and tool requests
86
- // as activity ended those turns mid-work.
87
- touchRelaySession(s.id);
88
- if (evt.type === 'delta' && typeof evt.text === 'string') {
89
- handlers.onText(evt.text);
90
- } else if (evt.type === 'tool_request') {
91
- s.bridgeSessionId = evt.session; s.toolId = evt.id;
92
- // ② via the shared harness: real values so the CLIENT runs the tool on
93
- // them, or the redacted token kept for remote MCP under "redact remote".
94
- const restoredArgs = s.harness
95
- ? s.harness.toTool(evt.name, evt.input ?? {})
96
- : restoreDeep(evt.input ?? {}, s.vault);
97
- handlers.onToolRequest({ name: evt.name, restoredArgs, toolId: encodeToolCallId(s.id, evt.id) });
98
- return 'parked';
99
- } else if (evt.type === 'done') {
100
- s.done = true; handlers.onDone?.(); return 'done';
101
- } else if (evt.type === 'error') {
102
- handlers.onError?.(new Error(evt.error || 'bridge error')); return 'done';
103
- }
104
- // status / reasoning / tool (summary) events are ignored
105
- }
106
- }
107
- const { done, value } = await s.reader.read();
108
- if (done) { s.done = true; handlers.onDone?.(); return 'done'; }
109
- s.buf += s.decoder.decode(value, { stream: true });
110
- }
111
- }
112
-
113
- // Deliver a client's tool result back to the parked codex session: redact it (so
114
- // codex sees placeholders) and POST /tool-result; the bridge then resumes the run.
115
- export async function deliverToolResult(s, content) {
116
- const redacted = redactText(typeof content === 'string' ? content : JSON.stringify(content), s.vault, s.redactOpts);
117
- const res = await fetch(`${s.bridgeUrl.replace(/\/$/, '')}/tool-result`, {
118
- method: 'POST',
119
- headers: { 'content-type': 'application/json', ...(s.token ? { authorization: `Bearer ${s.token}` } : {}) },
120
- body: JSON.stringify({ session: s.bridgeSessionId, id: s.toolId, result: redacted }),
121
- });
122
- if (!res.ok) throw new Error(`bridge /tool-result HTTP ${res.status}`);
123
- }
3
+ `))!==-1;){const c=e.buf.slice(0,r);e.buf=e.buf.slice(r+2);for(const i of c.split(`
4
+ `)){const l=i.trim();if(!l.startsWith("data:"))continue;const d=l.slice(5).trim();if(!d||d==="[DONE]")continue;let o;try{o=JSON.parse(d)}catch{continue}if(u(e.id),o.type==="delta"&&typeof o.text=="string")t.onText(o.text);else if(o.type==="tool_request"){e.bridgeSessionId=o.session,e.toolId=o.id;const f=e.harness?e.harness.toTool(o.name,o.input??{}):m(o.input??{},e.vault);return t.onToolRequest({name:o.name,restoredArgs:f,toolId:b(e.id,o.id)}),"parked"}else{if(o.type==="done")return e.done=!0,t.onDone?.(),"done";if(o.type==="error")return t.onError?.(new Error(o.error||"bridge error")),"done"}}}const{done:n,value:a}=await e.reader.read();if(n)return e.done=!0,t.onDone?.(),"done";e.buf+=e.decoder.decode(a,{stream:!0})}}async function R(e,t){const r=y(typeof t=="string"?t:JSON.stringify(t),e.vault,e.redactOpts),n=await fetch(`${e.bridgeUrl.replace(/\/$/,"")}/tool-result`,{method:"POST",headers:{"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:JSON.stringify({session:e.bridgeSessionId,id:e.toolId,result:r})});if(!n.ok)throw new Error(`bridge /tool-result HTTP ${n.status}`)}export{x as RELAY_IDLE_MS,h as createRelaySession,R as deliverToolResult,S as endRelaySession,D as getRelaySession,w as parseToolCallId,O as pumpBridgeStream,_ as toolsToSpecs,u as touchRelaySession};