@chatpanel/gateway 0.6.110 → 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.
- package/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +1 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2296
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/README.md
CHANGED
|
@@ -273,10 +273,29 @@ prints what is running — the gateway (this) and the bridge (your agents + skil
|
|
|
273
273
|
can see the whole local runtime at a glance. The bridge is an optional companion; a missing
|
|
274
274
|
one is reported plainly, never as an error.
|
|
275
275
|
|
|
276
|
+
### What leaves your machine — and how to check
|
|
277
|
+
|
|
278
|
+
```bash
|
|
279
|
+
chatpanel-gateway --audit # or --audit --json
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
prints two lists. **Observed:** every host this gateway process has actually contacted
|
|
283
|
+
since it started — model upstreams, the entitlement check, model-weight downloads, the
|
|
284
|
+
update check — by hostname and port with a count and first/last seen (no paths, headers or
|
|
285
|
+
bodies are kept). **Declared:** every host the current configuration *allows*, each with
|
|
286
|
+
the reason, when it happens, what is sent, and the setting that turns it off. The same
|
|
287
|
+
data is `GET /audit` (admin-authenticated, like `/config`), which the extension's Gateway
|
|
288
|
+
tab shows.
|
|
289
|
+
|
|
290
|
+
The audit covers this process. It does not see the embedded bridge (a separate process)
|
|
291
|
+
or the CLI agents it runs — Claude Code, Codex and friends reach their own vendors with
|
|
292
|
+
your own logins — nor a client's calls that bypass the gateway. Any host that shows up in
|
|
293
|
+
your firewall or proxy log for this process and is not on the declared list is a bug:
|
|
294
|
+
security@chatpanel.net.
|
|
295
|
+
|
|
276
296
|
## How it fits with ChatPanel
|
|
277
297
|
|
|
278
|
-
The
|
|
279
|
-
the browser; the [bridge](https://github.com/chatpanel/chatpanel-bridge) lets the
|
|
298
|
+
The extension redacts inside the browser; the bridge lets the
|
|
280
299
|
browser drive local CLI agents. This gateway reuses the bridge to put the **same
|
|
281
300
|
redaction engine** ([`@chatpanel/pii`](https://github.com/chatpanel/chatpanel-pii))
|
|
282
301
|
in front of *any* agent — so non-browser tools get the privacy too, and the
|
|
@@ -311,5 +330,6 @@ agent's own multi-turn loop is blinded, not just the first prompt.
|
|
|
311
330
|
|
|
312
331
|
## License
|
|
313
332
|
|
|
314
|
-
|
|
315
|
-
|
|
333
|
+
[PolyForm Shield 1.0.0](LICENSE) — you may run and modify it for your own use, not to
|
|
334
|
+
build a competing product. The npm package and the binaries ship minified; what the
|
|
335
|
+
gateway does with your data is documented above and verifiable with `--audit`.
|
|
@@ -1,24 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// A compiled single-file binary cannot embed onnxruntime-node's native dylib, so
|
|
4
|
-
// NER runs on the onnxruntime-web WASM runtime instead. We embed that runtime's
|
|
5
|
-
// two files INTO the executable here (Bun's `with { type: 'file' }` copies the
|
|
6
|
-
// asset in and yields a runtime path to it), then hand their paths to the NER
|
|
7
|
-
// engine via a global. src/ner-engine.js sees the global, forces the WASM backend,
|
|
8
|
-
// and points ORT at these files. Everything else is the normal CLI.
|
|
9
|
-
//
|
|
10
|
-
// The npm/Node package uses bin/chatpanel-gateway.js instead, which keeps the
|
|
11
|
-
// faster native onnxruntime-node runtime.
|
|
12
|
-
|
|
13
|
-
import { pathToFileURL } from 'node:url';
|
|
14
|
-
import wasmFile from '../assets/ort-wasm-simd-threaded.wasm' with { type: 'file' };
|
|
15
|
-
import mjsFile from '../assets/ort-wasm-simd-threaded.mjs' with { type: 'file' };
|
|
16
|
-
|
|
17
|
-
globalThis.__CHATPANEL_WASM_PATHS__ = {
|
|
18
|
-
wasm: pathToFileURL(wasmFile).href,
|
|
19
|
-
mjs: pathToFileURL(mjsFile).href,
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
// Delegate to the normal CLI (start / --install / --version / …). The global is
|
|
23
|
-
// already set, so when the gateway starts NER the engine uses the embedded WASM.
|
|
24
|
-
await import('./chatpanel-gateway.js');
|
|
1
|
+
import{pathToFileURL as i}from"node:url";import m from"../assets/ort-wasm-simd-threaded.wasm";import t from"../assets/ort-wasm-simd-threaded.mjs";globalThis.__CHATPANEL_WASM_PATHS__={wasm:i(m).href,mjs:i(t).href},await import("./chatpanel-gateway.js");
|
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,98 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
// chatpanel-gateway mcp stdio MCP server exposing warm history as tools
|
|
6
|
-
// chatpanel-gateway tools list the same tools, from a shell — names and one-liners
|
|
7
|
-
// chatpanel-gateway tools schema <tool> one tool's full schema
|
|
8
|
-
// chatpanel-gateway call <tool> '<json>' run one tool (exit 0 ok · 1 tool error · 2 usage)
|
|
9
|
-
// chatpanel-gateway local show the local runtime — bridge + gateway, one view
|
|
10
|
-
// chatpanel-gateway connect point your CLI agents (Codex, Claude Code, …) at this server
|
|
11
|
-
// chatpanel-gateway --install register login auto-start + start now
|
|
12
|
-
// chatpanel-gateway --uninstall remove login auto-start
|
|
13
|
-
// chatpanel-gateway --stop stop the running gateway (before an npm update on Windows)
|
|
14
|
-
// chatpanel-gateway --status is auto-start registered?
|
|
15
|
-
// chatpanel-gateway --version print version
|
|
16
|
-
// chatpanel-gateway --bridge run the embedded bridge (the supervisor's child; not for hands)
|
|
17
|
-
// chatpanel-gateway --mcp-stdio <url> the embedded bridge's per-turn tool proxy (spawned by CLI agents; not for hands)
|
|
18
|
-
//
|
|
19
|
-
// Config comes from gateway.config.json / env (see src/config.js).
|
|
20
|
-
export {}; // mark as an ES module (all imports below are dynamic)
|
|
21
|
-
|
|
22
|
-
const arg = process.argv[2];
|
|
23
|
-
|
|
24
|
-
try {
|
|
25
|
-
if (arg === '--bridge') {
|
|
26
|
-
// THE EMBEDDED BRIDGE. The gateway carries @chatpanel/bridge and starts it as a child of
|
|
27
|
-
// itself (src/bridge-supervisor.js) when nothing answers on 4319 — one install, two
|
|
28
|
-
// processes. The flag is consumed here; what remains of argv is the bridge's own
|
|
29
|
-
// (`--version` for the supervisor's check). CHATPANEL_BRIDGE_EMBEDDED tells the bridge its
|
|
30
|
-
// execPath is the gateway, so it never self-updates over it.
|
|
31
|
-
process.env.CHATPANEL_BRIDGE_EMBEDDED = '1';
|
|
32
|
-
process.argv.splice(2, 1);
|
|
33
|
-
await import('@chatpanel/bridge/src/server.js');
|
|
34
|
-
} else if (arg === '--mcp-stdio') {
|
|
35
|
-
// THE EMBEDDED BRIDGE'S PER-TURN TOOL SERVER. The bridge hands every CLI agent (Claude
|
|
36
|
-
// Code, Codex, a custom CLI) its per-turn ChatPanel tools — `team`, page, notes — as a
|
|
37
|
-
// stdio MCP server whose command is "re-run me with --mcp-stdio <url>"; embedded, "me"
|
|
38
|
-
// is this bin. Refusing the flag made the proxy exit 2 and Claude Code report the
|
|
39
|
-
// ChatPanel tools as "Connection closed" — a saved team ran as one agent doing a web
|
|
40
|
-
// search. Bridge 0.11.22+ sends `--bridge --mcp-stdio`; this keeps the older embedded
|
|
41
|
-
// copy working too. Not the history `mcp` server above — that one proxies to the gateway.
|
|
42
|
-
process.env.CHATPANEL_BRIDGE_EMBEDDED = '1';
|
|
43
|
-
await import('@chatpanel/bridge/src/server.js');
|
|
44
|
-
} else if (arg === 'mcp') {
|
|
45
|
-
// Its own path: proxies to the running gateway over HTTP and must NOT import
|
|
46
|
-
// server.js (which would open a second handle on the warm SQLite store).
|
|
47
|
-
const { runMcpServer } = await import('../src/mcp.js');
|
|
48
|
-
await runMcpServer();
|
|
49
|
-
} else if (arg === 'tools' || arg === 'call') {
|
|
50
|
-
// MCP2CLI: the MCP tools as shell verbs, for agents that only have a shell. Same
|
|
51
|
-
// in-process dispatcher as `mcp`, same no-server.js rule.
|
|
52
|
-
const { runMcpCli } = await import('../src/mcp-cli.js');
|
|
53
|
-
process.exit(await runMcpCli(process.argv.slice(2)));
|
|
54
|
-
} else if (arg === 'local') {
|
|
55
|
-
// Read-only unified view of both services. No server.js import — just HTTP probes.
|
|
56
|
-
const { localStatus, formatLocalStatus } = await import('../src/local-status.js');
|
|
57
|
-
process.stdout.write(formatLocalStatus(await localStatus()));
|
|
58
|
-
} else if (arg === 'connect') {
|
|
59
|
-
const { connectAgents, formatConnect } = await import('../src/connect-agents.js');
|
|
60
|
-
const dryRun = process.argv.includes('--dry-run') || process.argv.includes('-n');
|
|
61
|
-
process.stdout.write(formatConnect(connectAgents({ dryRun }), { dryRun }));
|
|
62
|
-
} else {
|
|
63
|
-
const { start, VERSION } = await import('../src/server.js');
|
|
64
|
-
const { installService, uninstallService, serviceStatus, stopService } = await import('../src/service.js');
|
|
65
|
-
switch (arg) {
|
|
66
|
-
case '--stop':
|
|
67
|
-
// Before `npm i -g` on Windows: a running gateway holds onnxruntime's DLL, and npm's
|
|
68
|
-
// copy of the new one fails with EBUSY. Stop, install, `--install`.
|
|
69
|
-
stopService();
|
|
70
|
-
console.log('ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).');
|
|
71
|
-
break;
|
|
72
|
-
case '--version':
|
|
73
|
-
case '-v':
|
|
74
|
-
console.log(VERSION);
|
|
75
|
-
break;
|
|
76
|
-
case '--install':
|
|
77
|
-
installService();
|
|
78
|
-
console.log('ChatPanel Privacy Gateway: installed login auto-start and started it.');
|
|
79
|
-
break;
|
|
80
|
-
case '--uninstall':
|
|
81
|
-
uninstallService();
|
|
82
|
-
console.log('ChatPanel Privacy Gateway: removed login auto-start.');
|
|
83
|
-
break;
|
|
84
|
-
case '--status':
|
|
85
|
-
console.log(serviceStatus() ? 'installed (auto-start registered)' : 'not installed');
|
|
86
|
-
break;
|
|
87
|
-
case undefined:
|
|
88
|
-
start();
|
|
89
|
-
break;
|
|
90
|
-
default:
|
|
91
|
-
console.error(`unknown option: ${arg}\nUsage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|--install|--uninstall|--stop|--status|--version|--bridge]`);
|
|
92
|
-
process.exit(2);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
} catch (e) {
|
|
96
|
-
console.error(`error: ${e.message}`);
|
|
97
|
-
process.exit(1);
|
|
98
|
-
}
|
|
2
|
+
const e=process.argv[2];try{if(e==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(e==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(e==="mcp"){const{runMcpServer:t}=await import("../src/mcp.js");await t()}else if(e==="tools"||e==="call"){const{runMcpCli:t}=await import("../src/mcp-cli.js");process.exit(await t(process.argv.slice(2)))}else if(e==="--audit"){const{egressAudit:t,formatAudit:a}=await import("../src/egress.js"),{loadConfig:s}=await import("../src/config.js"),{readFileSync:i}=await import("node:fs"),{join:l}=await import("node:path"),c=await import("node:os"),g=s(),o=`http://127.0.0.1:${g.port||4320}`;let n=null,p=`no gateway running at ${o}`;try{const u=i(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||l(c.homedir(),".chatpanel","gateway-token"),"utf8").trim(),r=await fetch(`${o}/audit`,{headers:{authorization:`Bearer ${u}`},signal:AbortSignal.timeout(2500)});if(r.ok)n=await r.json();else if(r.status===404){const d=await fetch(`${o}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);p=`the gateway running at ${o}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else p=`the gateway at ${o} refused the audit (HTTP ${r.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!n){const u=JSON.parse(i(new URL("../package.json",import.meta.url),"utf8")).version;n={...t(g,{ledger:null,version:u}),observed:[]},console.log(`(${p}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(n,null,2)):console.log(a(n))}else if(e==="local"){const{localStatus:t,formatLocalStatus:a}=await import("../src/local-status.js");process.stdout.write(a(await t()))}else if(e==="connect"){const{connectAgents:t,formatConnect:a}=await import("../src/connect-agents.js"),s=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(a(t({dryRun:s}),{dryRun:s}))}else{const{start:t,VERSION:a}=await import("../src/server.js"),{installService:s,uninstallService:i,serviceStatus:l,stopService:c}=await import("../src/service.js");switch(e){case"--stop":c(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(a);break;case"--install":s(),console.log("ChatPanel Privacy Gateway: installed login auto-start and started it.");break;case"--uninstall":i(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(l()?"installed (auto-start registered)":"not installed");break;case void 0:t();break;default:console.error(`unknown option: ${e}
|
|
4
|
+
Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(t){console.error(`error: ${t.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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": {
|
|
@@ -10,12 +10,6 @@
|
|
|
10
10
|
"exports": {
|
|
11
11
|
".": "./src/server.js"
|
|
12
12
|
},
|
|
13
|
-
"scripts": {
|
|
14
|
-
"start": "node bin/chatpanel-gateway.js",
|
|
15
|
-
"test": "node scripts/run-tests.mjs",
|
|
16
|
-
"typecheck": "tsc -p tsconfig.json",
|
|
17
|
-
"build:bin": "bash scripts/build-binaries.sh"
|
|
18
|
-
},
|
|
19
13
|
"files": [
|
|
20
14
|
"src",
|
|
21
15
|
"bin",
|
package/src/access-log-store.js
CHANGED
|
@@ -1,45 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// The pure ring (createAccessLog, @chatpanel/events) is in-memory by design. But the gateway
|
|
4
|
-
// restarts often — every update — and an empty "which agent read what" panel after each
|
|
5
|
-
// restart reads as "nothing is set up" when plenty is. So we back the ring with a tiny file:
|
|
6
|
-
// load it at start, debounce-write it on change. This is SAFE to persist because every event
|
|
7
|
-
// is already metadata only — client, tool, ms, and a REDACTED note (a search query's text is
|
|
8
|
-
// never in it). 0600, capped, under ~/.chatpanel.
|
|
9
|
-
//
|
|
10
|
-
// Kept out of the pure events module on purpose: persistence is a platform concern (node:fs),
|
|
11
|
-
// and the shared contract must stay dependency-free and runnable in a browser.
|
|
12
|
-
|
|
13
|
-
import { createAccessLog, ACCESS_LOG_MAX } from './observability.js';
|
|
14
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
15
|
-
import { join, dirname } from 'node:path';
|
|
16
|
-
import os from 'node:os';
|
|
17
|
-
|
|
18
|
-
const PATH = process.env.CHATPANEL_ACCESS_LOG || join(os.homedir(), '.chatpanel', 'access-log.json');
|
|
19
|
-
|
|
20
|
-
export function createPersistentAccessLog({ max = ACCESS_LOG_MAX, path = PATH, persistMs = 1000 } = {}) {
|
|
21
|
-
const log = createAccessLog(max);
|
|
22
|
-
|
|
23
|
-
// Load prior events, oldest-first, so the ring keeps chronological order.
|
|
24
|
-
try {
|
|
25
|
-
const arr = JSON.parse(readFileSync(path, 'utf8'));
|
|
26
|
-
if (Array.isArray(arr)) for (const e of arr) if (e && typeof e === 'object') log.push(e);
|
|
27
|
-
} catch { /* no prior log, or unreadable — start empty */ }
|
|
28
|
-
|
|
29
|
-
let timer = null;
|
|
30
|
-
const persist = () => {
|
|
31
|
-
try {
|
|
32
|
-
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
33
|
-
// snapshot() is newest-first; store oldest-first so a reload preserves order.
|
|
34
|
-
writeFileSync(path, JSON.stringify(log.snapshot().reverse()), { mode: 0o600 });
|
|
35
|
-
} catch { /* best effort — telemetry must never break the gateway */ }
|
|
36
|
-
};
|
|
37
|
-
const schedule = () => { clearTimeout(timer); timer = setTimeout(persist, persistMs); if (timer.unref) timer.unref(); };
|
|
38
|
-
|
|
39
|
-
return {
|
|
40
|
-
push(evt) { const e = log.push(evt); schedule(); return e; },
|
|
41
|
-
snapshot: (n) => log.snapshot(n),
|
|
42
|
-
get size() { return log.size; },
|
|
43
|
-
clear() { log.clear(); persist(); },
|
|
44
|
-
};
|
|
45
|
-
}
|
|
1
|
+
import{createAccessLog as m,ACCESS_LOG_MAX as u}from"./observability.js";import{readFileSync as f,writeFileSync as p,mkdirSync as l}from"node:fs";import{join as A,dirname as h}from"node:path";import y from"node:os";const S=process.env.CHATPANEL_ACCESS_LOG||A(y.homedir(),".chatpanel","access-log.json");function O({max:n=u,path:t=S,persistMs:i=1e3}={}){const e=m(n);try{const r=JSON.parse(f(t,"utf8"));if(Array.isArray(r))for(const o of r)o&&typeof o=="object"&&e.push(o)}catch{}let s=null;const c=()=>{try{l(h(t),{recursive:!0,mode:448}),p(t,JSON.stringify(e.snapshot().reverse()),{mode:384})}catch{}},a=()=>{clearTimeout(s),s=setTimeout(c,i),s.unref&&s.unref()};return{push(r){const o=e.push(r);return a(),o},snapshot:r=>e.snapshot(r),get size(){return e.size},clear(){e.clear(),c()}}}export{O as createPersistentAccessLog};
|
package/src/agent.js
CHANGED
|
@@ -1,257 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
// An AGENT, as data — the pool an org recruits from. Nothing runs here.
|
|
3
|
-
//
|
|
4
|
-
// A team's roles were inlined: each carried its own prompt, tier and grants, so the same
|
|
5
|
-
// "researcher" existed once per team and an edit landed in one of them. An agent is the role
|
|
6
|
-
// definition promoted out of the team (F8 §8 A1, architecture-pillars.md §9): a persistent
|
|
7
|
-
// identity — name, purpose, prompt, skills, grants, egress class, ENGINE, memory namespace —
|
|
8
|
-
// with a scorecard the runner writes and the store attests (scorecard.js). One agent stands
|
|
9
|
-
// in many teams; a team's role says `agent: <id>` and `resolveTeam` fills the role from the
|
|
10
|
-
// pool at run time, so the runner (team-run.js) is unchanged.
|
|
11
|
-
//
|
|
12
|
-
// The engine is a field on the card, never a nav item: `model` / `harness` / `auto` /
|
|
13
|
-
// `assistant` (engine.js). The built-in ASSISTANT is the agent behind every plain chat: its
|
|
14
|
-
// engine is whichever model the chat is on, which is why `engineOf` takes the chat's model.
|
|
15
|
-
//
|
|
16
|
-
// Trust is derived, never declared (the team.js rule): `builtin` only when the host says so.
|
|
17
|
-
// Grants are the team's vocabulary (team.js GRANT_RE), including the work grants a harness
|
|
18
|
-
// engine may hold; `page` is never grantable. The pool is shared through the client-prefs
|
|
19
|
-
// document (`agents` section) like teams, skills and recipes.
|
|
1
|
+
import{normalizeGrants as k,GRANT_RE as E,TeamError as A,normalizeTeam as x,slugTeamName as I}from"./team.js";import{normalizeEngineSpec as l,validateEngineSpec as N,describeEngine as O,engineRef as $,tierOf as B}from"./engine.js";const _=/^[a-z][a-z0-9_-]{0,63}$/i,u=Object.freeze(["jobs","meetings","notes"]),m=Object.freeze(["redacted","delegated"]),j=32,g="assistant";class z extends Error{constructor(r,t){super(t),this.name="AgentError",this.code=r}}const d=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),h=(e,r,t)=>[...new Set((Array.isArray(e)?e:typeof e=="string"?e.split(/[,\s]+/):[]).map(o=>String(o||"").trim().slice(0,r)).filter(Boolean))].slice(0,t);function S(e){const r=[];if(!d(e))return{ok:!1,errors:["agent must be an object"]};_.test(String(e.id||""))||r.push("id: a short identifier (letters, digits, _ -)"),String(e.name||e.id||"").trim()||r.push("name: what to call it"),!String(e.prompt||"").trim()&&String(e.id)!==g&&r.push("prompt: what this agent does"),r.push(...N(e.engine,"engine"));const t=(Array.isArray(e.grants)?e.grants:[]).filter(o=>!E.test(String(o)));return t.length&&r.push(`grants: not grantable: ${t.join(", ")}${t.some(o=>/^page/.test(String(o)))?" (a tab is one person's; an agent may not act on it)":""}`),e.egress!==void 0&&e.egress!==null&&!m.includes(e.egress)&&r.push(`egress: one of ${m.join(", ")}`),e.appliesTo!==void 0&&(!Array.isArray(e.appliesTo)||e.appliesTo.some(o=>!u.includes(o)))&&r.push(`appliesTo: a list of ${u.join(", ")}`),e.skills!==void 0&&!Array.isArray(e.skills)&&typeof e.skills!="string"&&r.push("skills: a list of skill names"),{ok:r.length===0,errors:r}}function f(e,{builtin:r=!1}={}){const t=S(e);if(!t.ok)throw new z("INVALID",t.errors.join("; "));const o=String(e.id);return{id:o,name:String(e.name||o).trim().slice(0,60),purpose:String(e.purpose||"").trim().slice(0,300),prompt:String(e.prompt||"").trim().slice(0,8e3),skills:h(e.skills,80,j),grants:k(e.grants),engine:l(e.engine),...m.includes(e.egress)?{egress:e.egress}:{},appliesTo:Array.isArray(e.appliesTo)&&e.appliesTo.length?[...new Set(e.appliesTo.filter(i=>u.includes(i)))]:["jobs"],memoryScope:String(e.memoryScope||"").trim().slice(0,120)||`agent:${o}`,...e.workdir?{workdir:String(e.workdir).trim().slice(0,400)}:{},createdBy:String(e.createdBy||"person").slice(0,80),enabled:e.enabled!==!1,...e.origin&&d(e.origin)?{origin:{...e.origin}}:{},...r?{builtin:!0}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function Y(e,r){return Object.freeze(f(e,r))}function D({grants:e=["data","web","history","mcp"]}={}){return Y({id:g,name:"Assistant",purpose:"The chat itself: answers, uses the tools you connected, remembers what you tell it.",prompt:"",engine:"assistant",grants:e,appliesTo:["jobs","meetings","notes"],createdBy:"chatpanel"},{builtin:!0})}function P(e,{chatModel:r=null}={}){const t=e||{};if(t.engine!==void 0&&t.engine!==null){const i=l(t.engine);return i.kind!=="assistant"?i:r?l(typeof r=="string"?r:{kind:"model",providerId:r.providerId,model:r.model||r.id}):{kind:"auto",policy:{prefer:"balanced"}}}return t.model?l({kind:"model",model:t.model}):{kind:"auto",policy:{prefer:{cheap:"cheapest-that-clears",strong:"best-quality",balanced:"balanced"}[t.prefer]||"balanced"}}}function C(e,r){const t=e||{};return`${t.name||t.id} — ${O(t.engine,r)} · tools: ${(t.grants||["none"]).join(", ")}${t.skills?.length?` · skills: ${t.skills.join(", ")}`:""}`}function L(e){return I(e)}function J(e,r=[],{chatModel:t=null,targetFor:o=null}={}){const i=x(e),p=new Map((Array.isArray(r)?r:[]).filter(n=>n&&n.id).map(n=>[String(n.id),n])),b={},T=i.roles.map(n=>{if(!n.agent)return n;const c=p.get(n.agent)||(n.agent===g?D():null);if(!c)throw new A("NO_AGENT",`role "${n.id}" names agent "${n.agent}", which is not in the pool`);const s=f(c,{builtin:!!c.builtin});if(s.enabled===!1)throw new A("NO_AGENT",`agent "${s.id}" is disabled`);b[n.id]=s;const a=P(n.engine?{engine:n.engine}:s,{chatModel:t}),y=$(a)?o?o(a,s):a.kind==="harness"?a.harnessId:a.model:null,v=Array.isArray(n.grants)?s.grants.includes("none")?["none"]:k(n.grants.filter(w=>s.grants.includes(w)||w.startsWith("mcp:")&&s.grants.includes("mcp"))):s.grants,R=[s.prompt,n.prompt?`In this team: ${n.prompt}`:""].filter(Boolean).join(`
|
|
20
2
|
|
|
21
|
-
|
|
22
|
-
import { normalizeEngineSpec, validateEngineSpec, describeEngine, engineRef, tierOf } from './engine.js';
|
|
23
|
-
|
|
24
|
-
export const AGENT_ID_RE = /^[a-z][a-z0-9_-]{0,63}$/i;
|
|
25
|
-
export const APPLIES_TO = Object.freeze(['jobs', 'meetings', 'notes']);
|
|
26
|
-
export const EGRESS_CLASSES = Object.freeze(['redacted', 'delegated']);
|
|
27
|
-
export const MAX_SKILLS = 32;
|
|
28
|
-
export const ASSISTANT_ID = 'assistant';
|
|
29
|
-
|
|
30
|
-
export class AgentError extends Error {
|
|
31
|
-
constructor(code, message) { super(message); this.name = 'AgentError'; this.code = code; }
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
35
|
-
const list = (xs, n, max) => [...new Set((Array.isArray(xs) ? xs : typeof xs === 'string' ? xs.split(/[,\s]+/) : []).map((x) => String(x || '').trim().slice(0, n)).filter(Boolean))].slice(0, max);
|
|
36
|
-
|
|
37
|
-
export function validateAgent(agent) {
|
|
38
|
-
const errors = [];
|
|
39
|
-
if (!isRecord(agent)) return { ok: false, errors: ['agent must be an object'] };
|
|
40
|
-
if (!AGENT_ID_RE.test(String(agent.id || ''))) errors.push('id: a short identifier (letters, digits, _ -)');
|
|
41
|
-
if (!String(agent.name || agent.id || '').trim()) errors.push('name: what to call it');
|
|
42
|
-
if (!String(agent.prompt || '').trim() && String(agent.id) !== ASSISTANT_ID) errors.push('prompt: what this agent does');
|
|
43
|
-
errors.push(...validateEngineSpec(agent.engine, 'engine'));
|
|
44
|
-
const bad = (Array.isArray(agent.grants) ? agent.grants : []).filter((g) => !GRANT_RE.test(String(g)));
|
|
45
|
-
if (bad.length) errors.push(`grants: not grantable: ${bad.join(', ')}${bad.some((g) => /^page/.test(String(g))) ? ' (a tab is one person\'s; an agent may not act on it)' : ''}`);
|
|
46
|
-
if (agent.egress !== undefined && agent.egress !== null && !EGRESS_CLASSES.includes(agent.egress)) errors.push(`egress: one of ${EGRESS_CLASSES.join(', ')}`);
|
|
47
|
-
if (agent.appliesTo !== undefined && (!Array.isArray(agent.appliesTo) || agent.appliesTo.some((a) => !APPLIES_TO.includes(a)))) errors.push(`appliesTo: a list of ${APPLIES_TO.join(', ')}`);
|
|
48
|
-
if (agent.skills !== undefined && !Array.isArray(agent.skills) && typeof agent.skills !== 'string') errors.push('skills: a list of skill names');
|
|
49
|
-
return { ok: errors.length === 0, errors };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* The stored form. Defaults filled, grants normalized, engine normalized, trust derived. The
|
|
54
|
-
* memory namespace defaults to the agent's own (`agent:<id>`); a team may point several
|
|
55
|
-
* agents at one shared namespace by naming it.
|
|
56
|
-
*/
|
|
57
|
-
export function normalizeAgent(agent, { builtin = false } = {}) {
|
|
58
|
-
const v = validateAgent(agent);
|
|
59
|
-
if (!v.ok) throw new AgentError('INVALID', v.errors.join('; '));
|
|
60
|
-
const id = String(agent.id);
|
|
61
|
-
return {
|
|
62
|
-
id,
|
|
63
|
-
name: String(agent.name || id).trim().slice(0, 60),
|
|
64
|
-
purpose: String(agent.purpose || '').trim().slice(0, 300),
|
|
65
|
-
prompt: String(agent.prompt || '').trim().slice(0, 8000),
|
|
66
|
-
skills: list(agent.skills, 80, MAX_SKILLS),
|
|
67
|
-
grants: normalizeGrants(agent.grants),
|
|
68
|
-
engine: normalizeEngineSpec(agent.engine),
|
|
69
|
-
...(EGRESS_CLASSES.includes(agent.egress) ? { egress: agent.egress } : {}),
|
|
70
|
-
appliesTo: Array.isArray(agent.appliesTo) && agent.appliesTo.length ? [...new Set(agent.appliesTo.filter((a) => APPLIES_TO.includes(a)))] : ['jobs'],
|
|
71
|
-
memoryScope: String(agent.memoryScope || '').trim().slice(0, 120) || `agent:${id}`,
|
|
72
|
-
...(agent.workdir ? { workdir: String(agent.workdir).trim().slice(0, 400) } : {}),
|
|
73
|
-
createdBy: String(agent.createdBy || 'person').slice(0, 80),
|
|
74
|
-
enabled: agent.enabled !== false,
|
|
75
|
-
...(agent.origin && isRecord(agent.origin) ? { origin: { ...agent.origin } } : {}),
|
|
76
|
-
...(builtin ? { builtin: true } : {}),
|
|
77
|
-
...(agent.createdAt ? { createdAt: agent.createdAt } : {}),
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function defineAgent(agent, opts) { return Object.freeze(normalizeAgent(agent, opts)); }
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* The built-in Assistant — the agent behind every plain chat. Its engine is the chat's model
|
|
85
|
-
* (`engineOf` resolves it); its grants are whatever the chat has; it applies everywhere.
|
|
86
|
-
*/
|
|
87
|
-
export function assistantAgent({ grants = ['data', 'web', 'history', 'mcp'] } = {}) {
|
|
88
|
-
return defineAgent({
|
|
89
|
-
id: ASSISTANT_ID, name: 'Assistant', purpose: 'The chat itself: answers, uses the tools you connected, remembers what you tell it.',
|
|
90
|
-
prompt: '', engine: 'assistant', grants, appliesTo: ['jobs', 'meetings', 'notes'], createdBy: 'chatpanel',
|
|
91
|
-
}, { builtin: true });
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* WHAT RUNS this agent's turns, resolved: the Assistant's engine is the chat's model (the
|
|
96
|
-
* host passes `chatModel` as `{ providerId?, model }` or a string), which is why the
|
|
97
|
-
* Assistant has no engine of its own. Everything else returns its normalized spec. A legacy
|
|
98
|
-
* role (no `engine`) reads as `model` when it pins one, else `auto` at its tier.
|
|
99
|
-
*/
|
|
100
|
-
export function engineOf(agentOrRole, { chatModel = null } = {}) {
|
|
101
|
-
const a = agentOrRole || {};
|
|
102
|
-
if (a.engine !== undefined && a.engine !== null) {
|
|
103
|
-
const s = normalizeEngineSpec(a.engine);
|
|
104
|
-
if (s.kind !== 'assistant') return s;
|
|
105
|
-
if (chatModel) return normalizeEngineSpec(typeof chatModel === 'string' ? chatModel : { kind: 'model', providerId: chatModel.providerId, model: chatModel.model || chatModel.id });
|
|
106
|
-
return { kind: 'auto', policy: { prefer: 'balanced' } };
|
|
107
|
-
}
|
|
108
|
-
if (a.model) return normalizeEngineSpec({ kind: 'model', model: a.model });
|
|
109
|
-
const prefer = { cheap: 'cheapest-that-clears', strong: 'best-quality', balanced: 'balanced' }[a.prefer] || 'balanced';
|
|
110
|
-
return { kind: 'auto', policy: { prefer } };
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** The capability strip's first column (§8): what kind of thing this agent is, in a word. */
|
|
114
|
-
export function describeAgent(agent, opts) {
|
|
115
|
-
const a = agent || {};
|
|
116
|
-
return `${a.name || a.id} — ${describeEngine(a.engine, opts)} · tools: ${(a.grants || ['none']).join(', ')}${a.skills?.length ? ` · skills: ${a.skills.join(', ')}` : ''}`;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export function slugAgentId(name) { return slugTeamName(name); }
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* A team as the runner needs it: every role that says `agent` is filled from the pool —
|
|
123
|
-
* prompt, grants, skills, engine, working directory — and the role's own fields narrow it.
|
|
124
|
-
*
|
|
125
|
-
* • prompt the agent's, then the role's ("In this team: …") when the role adds one
|
|
126
|
-
* • grants the agent's, narrowed to the role's when the role lists any (a team may not
|
|
127
|
-
* widen an agent; it may lend less)
|
|
128
|
-
* • engine the role's override when it has one, else the agent's, with the Assistant
|
|
129
|
-
* resolved to `chatModel`; `prefer` follows for today's appointers
|
|
130
|
-
* • model what `callModel` is handed — `targetFor(engine)` when the host maps engines
|
|
131
|
-
* to its target ids (the extension's endpoint ids, the desktop's gateway ids),
|
|
132
|
-
* else the harness id or the model name
|
|
133
|
-
*
|
|
134
|
-
* A role naming an agent not in the pool throws NO_AGENT: a team is not run with a hole in
|
|
135
|
-
* it. Returns the normalized team plus `agents` — the resolved cards, by role id.
|
|
136
|
-
*/
|
|
137
|
-
export function resolveTeam(team, pool = [], { chatModel = null, targetFor = null } = {}) {
|
|
138
|
-
const t = normalizeTeam(team);
|
|
139
|
-
const byId = new Map((Array.isArray(pool) ? pool : []).filter((a) => a && a.id).map((a) => [String(a.id), a]));
|
|
140
|
-
const agents = {};
|
|
141
|
-
const roles = t.roles.map((r) => {
|
|
142
|
-
if (!r.agent) return r;
|
|
143
|
-
const raw = byId.get(r.agent) || (r.agent === ASSISTANT_ID ? assistantAgent() : null);
|
|
144
|
-
if (!raw) throw new TeamError('NO_AGENT', `role "${r.id}" names agent "${r.agent}", which is not in the pool`);
|
|
145
|
-
const a = normalizeAgent(raw, { builtin: !!raw.builtin });
|
|
146
|
-
if (a.enabled === false) throw new TeamError('NO_AGENT', `agent "${a.id}" is disabled`);
|
|
147
|
-
agents[r.id] = a;
|
|
148
|
-
const engine = engineOf(r.engine ? { engine: r.engine } : a, { chatModel });
|
|
149
|
-
const ref = engineRef(engine);
|
|
150
|
-
const target = ref ? (targetFor ? targetFor(engine, a) : (engine.kind === 'harness' ? engine.harnessId : engine.model)) : null;
|
|
151
|
-
const grants = !Array.isArray(r.grants) ? a.grants
|
|
152
|
-
: a.grants.includes('none') ? ['none']
|
|
153
|
-
: normalizeGrants(r.grants.filter((g) => a.grants.includes(g) || (g.startsWith('mcp:') && a.grants.includes('mcp'))));
|
|
154
|
-
const prompt = [a.prompt, r.prompt ? `In this team: ${r.prompt}` : ''].filter(Boolean).join('\n\n').slice(0, 8000);
|
|
155
|
-
return {
|
|
156
|
-
...r,
|
|
157
|
-
name: r.name === r.id ? a.name : r.name,
|
|
158
|
-
prompt,
|
|
159
|
-
grants,
|
|
160
|
-
engine,
|
|
161
|
-
prefer: engine.kind === 'auto' ? tierOf(engine) : r.prefer,
|
|
162
|
-
...(target ? { model: r.model || target } : {}),
|
|
163
|
-
...(a.skills.length ? { skills: [...a.skills] } : {}),
|
|
164
|
-
...(a.workdir ? { workdir: a.workdir } : {}),
|
|
165
|
-
...(a.egress ? { egress: a.egress } : {}),
|
|
166
|
-
...(a.memoryScope ? { memoryScope: a.memoryScope } : {}),
|
|
167
|
-
};
|
|
168
|
-
});
|
|
169
|
-
return { ...t, roles, agents };
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
// ── The standing org and the editor's form ────────────────────────────────────────────────
|
|
173
|
-
//
|
|
174
|
-
// "ChatPanel Engineering" (architecture-pillars.md §12.2) — the first standing agents,
|
|
175
|
-
// offered as starters the way `research` and `review` are for teams. Every Implementer is
|
|
176
|
-
// this ONE card with a different working directory: the org repo's `agents/*.json` (§14.3)
|
|
177
|
-
// is where a company keeps one per repo. Engines are `auto` / `harness:<id>` so a starter
|
|
178
|
-
// does not name a provider a person may not have; the Harness engines say `claude` because
|
|
179
|
-
// that is the bridge's id for Claude Code and the pilot's choice — change it on the card.
|
|
180
|
-
|
|
181
|
-
export const STARTER_AGENTS = Object.freeze([
|
|
182
|
-
// The EXECUTIVE holds a goal (project-run.js): it posts the jobs, recruits for each from
|
|
183
|
-
// the pool, runs the recruited as a team, reads what came back, posts the follow-ups, asks
|
|
184
|
-
// the stakeholder where the gate says a person decides, and closes when done-when holds.
|
|
185
|
-
// A person is the stakeholder by default; this is the manager they delegate the running to.
|
|
186
|
-
{ id: 'executive', name: 'Executive', purpose: 'Runs a project: posts the jobs for the goal, recruits from the pool, reads the results, posts follow-ups, asks before spending or changing scope, closes when done-when holds.',
|
|
187
|
-
prompt: 'You are the Executive. You hold one goal and its done-when. Break the goal into jobs a stranger could act on, each naming the skills and tools it needs; prefer jobs that run at the same time and use dependsOn only when one truly needs another\'s result. Read every result against done-when as written — say it holds only when it does on the results as they are, not as they could be. Post follow-up jobs only for what would move done-when. Say plainly what was not found. You never do a job yourself and never create an agent, tool or skill without a person\'s approval.',
|
|
188
|
-
skills: ['planning', 'management'], grants: ['none'], engine: { kind: 'auto', policy: { prefer: 'best-quality' } }, appliesTo: ['jobs'] },
|
|
189
|
-
{ id: 'architect', name: 'Architect', purpose: 'Reads the docs and the repos; writes the project page and the jobs.',
|
|
190
|
-
prompt: 'You are the Architect. Read the feature doc, ROADMAP.md, naming-revamp.md and architecture-pillars.md before deciding anything. Write the project page (goal, done-when, budget) and post one job per repo that must change, saying which repo and what the guard is. Propose a new agent type only when no one in the pool fits. Never run a shell.',
|
|
191
|
-
skills: [], grants: ['data', 'history'], engine: { kind: 'auto', policy: { prefer: 'best-quality' } }, appliesTo: ['jobs'] },
|
|
192
|
-
{ id: 'implementer', name: 'Implementer', purpose: 'Builds one job on a branch in one repo; runs the guard; posts on the thread. Never pushes to main, never publishes.',
|
|
193
|
-
prompt: 'You are an Implementer. Work only in the repository you were given, on the branch named for this job. Read the job thread first. Make the change, run the repository\'s guard (tools/test-*.mjs or npm test) until it passes, commit with a message that says what and why, and post a summary with the diff stat on the job thread. Do not push to main, do not publish, do not touch another repository.',
|
|
194
|
-
skills: [], grants: ['shell', 'fs:write', 'scm:read', 'scm:push', 'scm:pr'], engine: { kind: 'harness', harnessId: 'claude' }, appliesTo: ['jobs'] },
|
|
195
|
-
{ id: 'reviewer', name: 'Reviewer', purpose: 'Reads the branch diff; posts findings on the thread. Approve or reject is a person\'s.',
|
|
196
|
-
prompt: 'You are the Reviewer. Read the diff of the job\'s branch against its base. Post each finding as a reply on the job thread: what, where (file:line), why it matters, what to do instead. Do not edit files. Do not approve or reject — say what you found and let a person decide.',
|
|
197
|
-
skills: ['review'], grants: ['shell', 'scm:read'], engine: { kind: 'harness', harnessId: 'claude' }, appliesTo: ['jobs'] },
|
|
198
|
-
{ id: 'tester', name: 'Tester', purpose: 'Runs the repository\'s guard on the branch; reports the result. No writes.',
|
|
199
|
-
prompt: 'You are the Tester. Check out the job\'s branch in its worktree and run the repository\'s guard (tools/test-*.mjs, npm test, the build). Report pass/fail with the failing output verbatim. Do not change any file.',
|
|
200
|
-
skills: [], grants: ['shell', 'scm:read'], engine: { kind: 'harness', harnessId: 'claude' }, appliesTo: ['jobs'] },
|
|
201
|
-
{ id: 'librarian', name: 'Librarian', purpose: 'Before every job: what was already done for this, and where.',
|
|
202
|
-
prompt: 'You are the Librarian. Before a job starts, search the runs, boards, briefs and docs for work that already covers it. Reply on the job thread with "already done in …" pointers and what could be reused or extended. Never do the job yourself.',
|
|
203
|
-
skills: [], grants: ['data', 'history'], engine: { kind: 'auto', policy: { prefer: 'cheapest-that-clears' } }, appliesTo: ['jobs'] },
|
|
204
|
-
{ id: 'scribe', name: 'Scribe', purpose: 'Writes what the run taught into the roadmap and the status row — proposed, a person lands it.',
|
|
205
|
-
prompt: 'You are the Scribe. From the run\'s board and scorecards, write the "what this run taught" paragraph for the feature doc, the ROADMAP.md entry and the IMPLEMENTATION-STATUS.md row. Post them as a proposal on the thread; a person lands them. Say plainly what did not work.',
|
|
206
|
-
skills: [], grants: ['data', 'history'], engine: { kind: 'auto', policy: { prefer: 'balanced' } }, appliesTo: ['jobs', 'notes'] },
|
|
207
|
-
{ id: 'release', name: 'Release', purpose: 'Version bump and changelog on the merged branch; asks before publish or push.',
|
|
208
|
-
prompt: 'You are Release. On the merged branch: bump the version, write the changelog line, run the guard. Before `npm publish` or any `git push`, stop and ask on the thread — a person answers. Never publish or push without that answer.',
|
|
209
|
-
skills: [], grants: ['shell', 'fs:write', 'scm:read', 'scm:push'], engine: { kind: 'harness', harnessId: 'claude' }, appliesTo: ['jobs'] },
|
|
210
|
-
]);
|
|
211
|
-
|
|
212
|
-
/** Fresh copies — a starter is a template, never the stored record. */
|
|
213
|
-
export function starterAgents() {
|
|
214
|
-
return STARTER_AGENTS.map((a) => JSON.parse(JSON.stringify(a)));
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/** A blank agent for the editor. */
|
|
218
|
-
export function blankAgent() {
|
|
219
|
-
return { id: '', name: '', purpose: '', prompt: '', skills: [], grants: ['none'], engine: { kind: 'auto', policy: { prefer: 'balanced' } }, appliesTo: ['jobs'], memoryScope: '' };
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* The editor's form → an agent, or the errors. Grants and skills come as text ("web, data",
|
|
224
|
-
* "review, graphify"); the engine as the form's own shape (`{ kind, model, providerId,
|
|
225
|
-
* harnessId, prefer }`) or a string; a blank id is slugged from the name.
|
|
226
|
-
*/
|
|
227
|
-
export function agentFromForm(form) {
|
|
228
|
-
const f = form || {};
|
|
229
|
-
const id = String(f.id || '').trim() || slugAgentId(f.name);
|
|
230
|
-
const engine = isRecord(f.engine)
|
|
231
|
-
? (f.engine.kind === 'auto' ? { kind: 'auto', policy: { prefer: f.engine.prefer || f.engine.policy?.prefer || 'balanced', ...(f.engine.policy || {}) } } : f.engine)
|
|
232
|
-
: f.engine;
|
|
233
|
-
const agent = {
|
|
234
|
-
id,
|
|
235
|
-
name: String(f.name || '').trim() || id,
|
|
236
|
-
purpose: String(f.purpose || '').trim(),
|
|
237
|
-
prompt: String(f.prompt || ''),
|
|
238
|
-
skills: list(f.skills, 80, MAX_SKILLS),
|
|
239
|
-
grants: list(f.grants, 80, 32).length ? list(f.grants, 80, 32) : ['none'],
|
|
240
|
-
engine,
|
|
241
|
-
...(f.egress ? { egress: f.egress } : {}),
|
|
242
|
-
appliesTo: Array.isArray(f.appliesTo) && f.appliesTo.length ? f.appliesTo : ['jobs'],
|
|
243
|
-
...(f.memoryScope ? { memoryScope: f.memoryScope } : {}),
|
|
244
|
-
...(f.workdir ? { workdir: f.workdir } : {}),
|
|
245
|
-
createdBy: f.createdBy || 'person',
|
|
246
|
-
enabled: f.enabled !== false,
|
|
247
|
-
...(f.origin && isRecord(f.origin) ? { origin: f.origin } : {}),
|
|
248
|
-
...(f.createdAt ? { createdAt: f.createdAt } : {}),
|
|
249
|
-
};
|
|
250
|
-
const v = validateAgent(agent);
|
|
251
|
-
return v.ok ? { ok: true, agent: normalizeAgent(agent) } : { ok: false, errors: v.errors };
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/** Which agents apply to jobs — the pool a job board recruits from. */
|
|
255
|
-
export function poolFor(agents, surface = 'jobs') {
|
|
256
|
-
return (Array.isArray(agents) ? agents : []).filter((a) => a && a.enabled !== false && (Array.isArray(a.appliesTo) ? a.appliesTo : ['jobs']).includes(surface));
|
|
257
|
-
}
|
|
3
|
+
`).slice(0,8e3);return{...n,name:n.name===n.id?s.name:n.name,prompt:R,grants:v,engine:a,prefer:a.kind==="auto"?B(a):n.prefer,...y?{model:n.model||y}:{},...s.skills.length?{skills:[...s.skills]}:{},...s.workdir?{workdir:s.workdir}:{},...s.egress?{egress:s.egress}:{},...s.memoryScope?{memoryScope:s.memoryScope}:{}}});return{...i,roles:T,agents:b}}const G=Object.freeze([{id:"executive",name:"Executive",purpose:"Runs a project: posts the jobs for the goal, recruits from the pool, reads the results, posts follow-ups, asks before spending or changing scope, closes when done-when holds.",prompt:"You are the Executive. You hold one goal and its done-when. Break the goal into jobs a stranger could act on, each naming the skills and tools it needs; prefer jobs that run at the same time and use dependsOn only when one truly needs another's result. Read every result against done-when as written — say it holds only when it does on the results as they are, not as they could be. Post follow-up jobs only for what would move done-when. Say plainly what was not found. You never do a job yourself and never create an agent, tool or skill without a person's approval.",skills:["planning","management"],grants:["none"],engine:{kind:"auto",policy:{prefer:"best-quality"}},appliesTo:["jobs"]},{id:"architect",name:"Architect",purpose:"Reads the docs and the repos; writes the project page and the jobs.",prompt:"You are the Architect. Read the feature doc, ROADMAP.md, naming-revamp.md and architecture-pillars.md before deciding anything. Write the project page (goal, done-when, budget) and post one job per repo that must change, saying which repo and what the guard is. Propose a new agent type only when no one in the pool fits. Never run a shell.",skills:[],grants:["data","history"],engine:{kind:"auto",policy:{prefer:"best-quality"}},appliesTo:["jobs"]},{id:"implementer",name:"Implementer",purpose:"Builds one job on a branch in one repo; runs the guard; posts on the thread. Never pushes to main, never publishes.",prompt:"You are an Implementer. Work only in the repository you were given, on the branch named for this job. Read the job thread first. Make the change, run the repository's guard (tools/test-*.mjs or npm test) until it passes, commit with a message that says what and why, and post a summary with the diff stat on the job thread. Do not push to main, do not publish, do not touch another repository.",skills:[],grants:["shell","fs:write","scm:read","scm:push","scm:pr"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]},{id:"reviewer",name:"Reviewer",purpose:"Reads the branch diff; posts findings on the thread. Approve or reject is a person's.",prompt:"You are the Reviewer. Read the diff of the job's branch against its base. Post each finding as a reply on the job thread: what, where (file:line), why it matters, what to do instead. Do not edit files. Do not approve or reject — say what you found and let a person decide.",skills:["review"],grants:["shell","scm:read"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]},{id:"tester",name:"Tester",purpose:"Runs the repository's guard on the branch; reports the result. No writes.",prompt:"You are the Tester. Check out the job's branch in its worktree and run the repository's guard (tools/test-*.mjs, npm test, the build). Report pass/fail with the failing output verbatim. Do not change any file.",skills:[],grants:["shell","scm:read"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]},{id:"librarian",name:"Librarian",purpose:"Before every job: what was already done for this, and where.",prompt:'You are the Librarian. Before a job starts, search the runs, boards, briefs and docs for work that already covers it. Reply on the job thread with "already done in …" pointers and what could be reused or extended. Never do the job yourself.',skills:[],grants:["data","history"],engine:{kind:"auto",policy:{prefer:"cheapest-that-clears"}},appliesTo:["jobs"]},{id:"scribe",name:"Scribe",purpose:"Writes what the run taught into the roadmap and the status row — proposed, a person lands it.",prompt:`You are the Scribe. From the run's board and scorecards, write the "what this run taught" paragraph for the feature doc, the ROADMAP.md entry and the IMPLEMENTATION-STATUS.md row. Post them as a proposal on the thread; a person lands them. Say plainly what did not work.`,skills:[],grants:["data","history"],engine:{kind:"auto",policy:{prefer:"balanced"}},appliesTo:["jobs","notes"]},{id:"release",name:"Release",purpose:"Version bump and changelog on the merged branch; asks before publish or push.",prompt:"You are Release. On the merged branch: bump the version, write the changelog line, run the guard. Before `npm publish` or any `git push`, stop and ask on the thread — a person answers. Never publish or push without that answer.",skills:[],grants:["shell","fs:write","scm:read","scm:push"],engine:{kind:"harness",harnessId:"claude"},appliesTo:["jobs"]}]);function M(){return G.map(e=>JSON.parse(JSON.stringify(e)))}function V(){return{id:"",name:"",purpose:"",prompt:"",skills:[],grants:["none"],engine:{kind:"auto",policy:{prefer:"balanced"}},appliesTo:["jobs"],memoryScope:""}}function K(e){const r=e||{},t=String(r.id||"").trim()||L(r.name),o=d(r.engine)&&r.engine.kind==="auto"?{kind:"auto",policy:{prefer:r.engine.prefer||r.engine.policy?.prefer||"balanced",...r.engine.policy||{}}}:r.engine,i={id:t,name:String(r.name||"").trim()||t,purpose:String(r.purpose||"").trim(),prompt:String(r.prompt||""),skills:h(r.skills,80,j),grants:h(r.grants,80,32).length?h(r.grants,80,32):["none"],engine:o,...r.egress?{egress:r.egress}:{},appliesTo:Array.isArray(r.appliesTo)&&r.appliesTo.length?r.appliesTo:["jobs"],...r.memoryScope?{memoryScope:r.memoryScope}:{},...r.workdir?{workdir:r.workdir}:{},createdBy:r.createdBy||"person",enabled:r.enabled!==!1,...r.origin&&d(r.origin)?{origin:r.origin}:{},...r.createdAt?{createdAt:r.createdAt}:{}},p=S(i);return p.ok?{ok:!0,agent:f(i)}:{ok:!1,errors:p.errors}}function U(e,r="jobs"){return(Array.isArray(e)?e:[]).filter(t=>t&&t.enabled!==!1&&(Array.isArray(t.appliesTo)?t.appliesTo:["jobs"]).includes(r))}export{_ as AGENT_ID_RE,u as APPLIES_TO,g as ASSISTANT_ID,z as AgentError,m as EGRESS_CLASSES,j as MAX_SKILLS,G as STARTER_AGENTS,K as agentFromForm,D as assistantAgent,V as blankAgent,Y as defineAgent,C as describeAgent,P as engineOf,f as normalizeAgent,U as poolFor,J as resolveTeam,L as slugAgentId,M as starterAgents,S as validateAgent};
|
package/src/anthropic.js
CHANGED
|
@@ -1,84 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
// as the OpenAI adapter — collect in-place text segments from the request,
|
|
3
|
-
// restore tokens in a non-streaming response. Streaming is handled generically.
|
|
1
|
+
import{segment as n}from"./redact.js";import{restoreDeep as f}from"./stream.js";function c(t){return/\/messages$/.test(t)}function u(t,s){return!s||!t||(typeof t.system=="string"?t.system+=`
|
|
4
2
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
export function matches(pathname) {
|
|
9
|
-
return /\/messages$/.test(pathname);
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
// Append a (non-redacted) instruction to the system prompt.
|
|
13
|
-
export function injectSystemNote(body, note) {
|
|
14
|
-
if (!note || !body) return body;
|
|
15
|
-
if (typeof body.system === 'string') body.system += `\n\n${note}`;
|
|
16
|
-
else if (Array.isArray(body.system)) body.system.push({ type: 'text', text: note });
|
|
17
|
-
else body.system = note;
|
|
18
|
-
return body;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// Push segments for a content field that may be a string or an array of blocks
|
|
22
|
-
// ({type:'text',text}, {type:'tool_result',content}, …).
|
|
23
|
-
function collectContent(content, segs) {
|
|
24
|
-
if (typeof content === 'string') {
|
|
25
|
-
// Can't set a primitive in place; caller wraps string content separately.
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
if (!Array.isArray(content)) return;
|
|
29
|
-
for (const block of content) {
|
|
30
|
-
if (!block) continue;
|
|
31
|
-
if (block.type === 'text' && typeof block.text === 'string') {
|
|
32
|
-
segs.push(segment(() => block.text, (v) => { block.text = v; }));
|
|
33
|
-
} else if (block.type === 'tool_result') {
|
|
34
|
-
collectContent(block.content, segs);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function collectSegments(body, redactionCfg) {
|
|
40
|
-
const segs = [];
|
|
41
|
-
|
|
42
|
-
// Top-level system prompt: string or array of {type:'text',text} blocks.
|
|
43
|
-
if (redactionCfg.redactSystem !== false && body) {
|
|
44
|
-
if (typeof body.system === 'string') {
|
|
45
|
-
segs.push(segment(() => body.system, (v) => { body.system = v; }));
|
|
46
|
-
} else if (Array.isArray(body.system)) {
|
|
47
|
-
collectContent(body.system, segs);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
for (const m of Array.isArray(body?.messages) ? body.messages : []) {
|
|
52
|
-
if (!m) continue;
|
|
53
|
-
if (typeof m.content === 'string') {
|
|
54
|
-
segs.push(segment(() => m.content, (v) => { m.content = v; }));
|
|
55
|
-
} else {
|
|
56
|
-
collectContent(m.content, segs);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
return segs;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// Extract the conversation for the bridge backend. Anthropic carries the system
|
|
63
|
-
// prompt at the top level (string or text blocks) — flatten it to a string.
|
|
64
|
-
export function toTurn(body) {
|
|
65
|
-
let system = '';
|
|
66
|
-
if (typeof body?.system === 'string') system = body.system;
|
|
67
|
-
else if (Array.isArray(body?.system)) {
|
|
68
|
-
system = body.system.filter((b) => b?.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n');
|
|
69
|
-
}
|
|
70
|
-
return { messages: Array.isArray(body?.messages) ? body.messages : [], system };
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// Restore a buffered response: text blocks + tool_use input objects.
|
|
74
|
-
export function restoreResponse(json, vault) {
|
|
75
|
-
for (const block of json?.content || []) {
|
|
76
|
-
if (!block) continue;
|
|
77
|
-
if (block.type === 'text' && typeof block.text === 'string') {
|
|
78
|
-
block.text = restoreDeep(block.text, vault);
|
|
79
|
-
} else if (block.type === 'tool_use' && block.input) {
|
|
80
|
-
block.input = restoreDeep(block.input, vault);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
return json;
|
|
84
|
-
}
|
|
3
|
+
${s}`:Array.isArray(t.system)?t.system.push({type:"text",text:s}):t.system=s),t}function i(t,s){if(typeof t!="string"&&Array.isArray(t))for(const e of t)e&&(e.type==="text"&&typeof e.text=="string"?s.push(n(()=>e.text,r=>{e.text=r})):e.type==="tool_result"&&i(e.content,s))}function y(t,s){const e=[];s.redactSystem!==!1&&t&&(typeof t.system=="string"?e.push(n(()=>t.system,r=>{t.system=r})):Array.isArray(t.system)&&i(t.system,e));for(const r of Array.isArray(t?.messages)?t.messages:[])r&&(typeof r.content=="string"?e.push(n(()=>r.content,m=>{r.content=m})):i(r.content,e));return e}function a(t){let s="";return typeof t?.system=="string"?s=t.system:Array.isArray(t?.system)&&(s=t.system.filter(e=>e?.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
4
|
+
`)),{messages:Array.isArray(t?.messages)?t.messages:[],system:s}}function l(t,s){for(const e of t?.content||[])e&&(e.type==="text"&&typeof e.text=="string"?e.text=f(e.text,s):e.type==="tool_use"&&e.input&&(e.input=f(e.input,s)));return t}export{y as collectSegments,u as injectSystemNote,c as matches,l as restoreResponse,a as toTurn};
|