@chatpanel/bridge 0.11.23 → 0.11.25

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 (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -463
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
@@ -1,160 +1 @@
1
- // connections.js — the SCM connections this machine holds, and the token behind each.
2
- //
3
- // A connection RECORD (events/scm-connection.js) is the hub, its host, a secret's name and
4
- // a reach; it is shared between the clients through the gateway's prefs document. The
5
- // TOKEN is the one thing that never travels: it lives here, in the machine's keychain (macOS
6
- // `security`), or — where there is no keychain — in a file only this user can read. The
7
- // bridge is the process that spawns the coding agents, so it is the one that hands the
8
- // token to git: for ONE run, in that process's environment, scoped to the connection's
9
- // host, with a pre-push hook that keeps the push on the job's own branch (worktree.js).
10
- //
11
- // Nothing here logs a token, returns one over HTTP, or puts one on a command line.
12
-
13
- import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs';
14
- import { execFileSync } from 'node:child_process';
15
- import { join } from 'node:path';
16
- import os from 'node:os';
17
- import { normalizeConnection, connectionFor, credentialEnv, hostOf, parseRemote, describeConnection } from './events/scm-connection.js';
18
-
19
- const DIR = join(os.homedir(), '.chatpanel');
20
- const RECORDS_PATH = process.env.CHATPANEL_CONNECTIONS_PATH || join(DIR, 'connections.json');
21
- const SECRETS_PATH = process.env.CHATPANEL_SECRETS_PATH || join(DIR, 'secrets.json');
22
- const KEYCHAIN_ACCOUNT = 'chatpanel';
23
-
24
- // ── The secret store: keychain where there is one, a 0600 file where there is not ────────
25
-
26
- function keychainAvailable() {
27
- return process.platform === 'darwin' && !/^(0|false|no|off)$/i.test(process.env.CHATPANEL_USE_KEYCHAIN || '');
28
- }
29
- function security(args, input) {
30
- return execFileSync('security', args, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000, input, windowsHide: true });
31
- }
32
-
33
- function readSecretsFile() {
34
- try { return existsSync(SECRETS_PATH) ? JSON.parse(readFileSync(SECRETS_PATH, 'utf8')) || {} : {}; } catch { return {}; }
35
- }
36
- function writeSecretsFile(doc) {
37
- mkdirSync(DIR, { recursive: true, mode: 0o700 });
38
- const tmp = `${SECRETS_PATH}.${process.pid}.tmp`;
39
- writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 });
40
- renameSync(tmp, SECRETS_PATH);
41
- }
42
-
43
- /** Where a secret would be kept on this machine — reported, never the secret. */
44
- export function secretBackend() { return keychainAvailable() ? 'keychain' : 'file'; }
45
-
46
- export function setSecret(ref, token) {
47
- const r = String(ref || '').trim(); const t = String(token || '');
48
- if (!r) throw new Error('secretRef required');
49
- if (!t) return deleteSecret(r);
50
- if (keychainAvailable()) {
51
- // -U updates in place; the password goes over stdin-less argv of `security`, which is
52
- // the documented way and stays inside the loopback of this machine. The keychain item
53
- // is this user's, under the "chatpanel" account, named by the ref.
54
- try { security(['add-generic-password', '-a', KEYCHAIN_ACCOUNT, '-s', r, '-w', t, '-U']); return 'keychain'; }
55
- catch (e) { throw new Error(`keychain refused: ${String(e?.stderr || e?.message || e).trim().slice(0, 200)}`); }
56
- }
57
- const doc = readSecretsFile(); doc[r] = t; writeSecretsFile(doc); return 'file';
58
- }
59
-
60
- export function getSecret(ref) {
61
- const r = String(ref || '').trim();
62
- if (!r) return null;
63
- if (keychainAvailable()) {
64
- try { return security(['find-generic-password', '-a', KEYCHAIN_ACCOUNT, '-s', r, '-w']).replace(/\n$/, '') || null; } catch { /* not there, or file below */ }
65
- }
66
- const v = readSecretsFile()[r];
67
- return typeof v === 'string' && v ? v : null;
68
- }
69
-
70
- export function hasSecret(ref) { return getSecret(ref) != null; }
71
-
72
- export function deleteSecret(ref) {
73
- const r = String(ref || '').trim();
74
- if (!r) return false;
75
- let any = false;
76
- if (keychainAvailable()) { try { security(['delete-generic-password', '-a', KEYCHAIN_ACCOUNT, '-s', r]); any = true; } catch { /* was not there */ } }
77
- const doc = readSecretsFile();
78
- if (r in doc) { delete doc[r]; writeSecretsFile(doc); any = true; }
79
- return any;
80
- }
81
-
82
- // ── The records ───────────────────────────────────────────────────────────────────────────
83
-
84
- function readRecords() {
85
- try { const doc = existsSync(RECORDS_PATH) ? JSON.parse(readFileSync(RECORDS_PATH, 'utf8')) : null; return Array.isArray(doc?.connections) ? doc.connections : []; } catch { return []; }
86
- }
87
- function writeRecords(list) {
88
- mkdirSync(DIR, { recursive: true, mode: 0o700 });
89
- const tmp = `${RECORDS_PATH}.${process.pid}.tmp`;
90
- writeFileSync(tmp, JSON.stringify({ v: 1, connections: list }), { mode: 0o600 });
91
- renameSync(tmp, RECORDS_PATH);
92
- }
93
-
94
- /** Every connection, as a client may see it: the record plus whether a token is held. Never the token. */
95
- export function listConnections() {
96
- return readRecords().map((c) => ({ ...c, hasSecret: hasSecret(c.secretRef), label: c.label || describeConnection(c) }));
97
- }
98
-
99
- /**
100
- * Save a connection; a `token` (optional) goes to the secret store under the record's
101
- * `secretRef` and is not in what comes back. A record that carries a token field of its
102
- * own is refused by `normalizeConnection` — that is the events contract, enforced here too.
103
- */
104
- export function putConnection(record, { token = null } = {}) {
105
- const conn = normalizeConnection({ ...record, createdAt: record?.createdAt || Date.now() });
106
- const list = readRecords().filter((c) => c.id !== conn.id);
107
- list.push(conn);
108
- writeRecords(list);
109
- let stored = null;
110
- if (token) stored = setSecret(conn.secretRef, token);
111
- return { ...conn, hasSecret: hasSecret(conn.secretRef), ...(stored ? { secretStoredIn: stored } : {}) };
112
- }
113
-
114
- export function removeConnection(id) {
115
- const list = readRecords();
116
- const conn = list.find((c) => c.id === String(id || ''));
117
- if (!conn) return false;
118
- writeRecords(list.filter((c) => c.id !== conn.id));
119
- deleteSecret(conn.secretRef);
120
- return true;
121
- }
122
-
123
- /**
124
- * The environment a run gets for the checkout at `remote` — the matched connection's token,
125
- * scoped to its host, plus what the pre-push hook reads (worktree.js): the branch a push may
126
- * touch, and whether pushing is granted at all. `grants` are the role's (team.js): no
127
- * `scm:push` → the hook refuses every push; `scm:push` → the job's branch only. Without a
128
- * matching connection there is no token and the agent works as the user's own git does.
129
- */
130
- export function runEnvFor({ remote = null, grants = [], branch = null, connectionId = null } = {}) {
131
- const list = readRecords();
132
- const conn = connectionId ? list.find((c) => c.id === connectionId && c.enabled !== false) || null : (remote ? connectionFor(remote, list) : null);
133
- const token = conn ? getSecret(conn.secretRef) : null;
134
- const env = conn && token ? credentialEnv(conn, token) : {};
135
- const g = Array.isArray(grants) ? grants.map(String) : [];
136
- const canPush = g.some((x) => x === 'scm:push' || x === 'scm:pr' || x === 'scm:merge');
137
- env.CHATPANEL_SCM_PUSH = canPush ? (branch ? 'own' : 'any') : 'none';
138
- if (branch) env.CHATPANEL_SCM_BRANCH = String(branch);
139
- return { env, connection: conn ? { id: conn.id, kind: conn.kind, host: hostOf(conn), hasSecret: !!token } : null };
140
- }
141
-
142
- /** For `POST /connections/:id/test`: can this connection read `remote`? Runs `git ls-remote` with the run env, never prints the token. */
143
- export function testConnection(id, remote) {
144
- const conn = readRecords().find((c) => c.id === String(id || ''));
145
- if (!conn) return { ok: false, reason: 'no such connection' };
146
- const token = getSecret(conn.secretRef);
147
- if (!token) return { ok: false, reason: 'no token stored' };
148
- const r = parseRemote(remote || (conn.reach.find((x) => !x.endsWith('/*') && x.includes('/')) ? `https://${hostOf(conn)}/${conn.reach.find((x) => !x.endsWith('/*') && x.includes('/'))}` : ''));
149
- if (!r) return { ok: false, reason: 'give a repository to test against (owner/name or a URL)' };
150
- if (r.host !== hostOf(conn)) return { ok: false, reason: `${r.host} is not this connection's host (${hostOf(conn)})` };
151
- const url = `https://${r.host}/${r.owner}/${r.name}.git`;
152
- try {
153
- const out = execFileSync('git', ['ls-remote', '--symref', url, 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15000, windowsHide: true, env: { ...process.env, ...credentialEnv(conn, token) } });
154
- const head = /^ref: refs\/heads\/(\S+)\tHEAD/m.exec(out)?.[1] || null;
155
- return { ok: true, remote: url, defaultBranch: head };
156
- } catch (e) {
157
- const msg = String(e?.stderr || e?.message || e).replace(new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '***').trim().slice(0, 300);
158
- return { ok: false, reason: msg || 'git ls-remote failed' };
159
- }
160
- }
1
+ import{readFileSync as C,writeFileSync as w,existsSync as E,mkdirSync as R,renameSync as H}from"node:fs";import{execFileSync as k}from"node:child_process";import{join as S}from"node:path";import x from"node:os";import{normalizeConnection as O,connectionFor as F,credentialEnv as N,hostOf as l,parseRemote as L,describeConnection as D}from"./events/scm-connection.js";const f=S(x.homedir(),".chatpanel"),d=process.env.CHATPANEL_CONNECTIONS_PATH||S(f,"connections.json"),p=process.env.CHATPANEL_SECRETS_PATH||S(f,"secrets.json"),h="chatpanel";function m(){return process.platform==="darwin"&&!/^(0|false|no|off)$/i.test(process.env.CHATPANEL_USE_KEYCHAIN||"")}function g(n,t){return k("security",n,{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:5e3,input:t,windowsHide:!0})}function y(){try{return E(p)?JSON.parse(C(p,"utf8"))||{}:{}}catch{return{}}}function $(n){R(f,{recursive:!0,mode:448});const t=`${p}.${process.pid}.tmp`;w(t,JSON.stringify(n),{mode:384}),H(t,p)}function M(){return m()?"keychain":"file"}function U(n,t){const e=String(n||"").trim(),r=String(t||"");if(!e)throw new Error("secretRef required");if(!r)return T(e);if(m())try{return g(["add-generic-password","-a",h,"-s",e,"-w",r,"-U"]),"keychain"}catch(o){throw new Error(`keychain refused: ${String(o?.stderr||o?.message||o).trim().slice(0,200)}`)}const i=y();return i[e]=r,$(i),"file"}function A(n){const t=String(n||"").trim();if(!t)return null;if(m())try{return g(["find-generic-password","-a",h,"-s",t,"-w"]).replace(/\n$/,"")||null}catch{}const e=y()[t];return typeof e=="string"&&e?e:null}function v(n){return A(n)!=null}function T(n){const t=String(n||"").trim();if(!t)return!1;let e=!1;if(m())try{g(["delete-generic-password","-a",h,"-s",t]),e=!0}catch{}const r=y();return t in r&&(delete r[t],$(r),e=!0),e}function a(){try{const n=E(d)?JSON.parse(C(d,"utf8")):null;return Array.isArray(n?.connections)?n.connections:[]}catch{return[]}}function _(n){R(f,{recursive:!0,mode:448});const t=`${d}.${process.pid}.tmp`;w(t,JSON.stringify({v:1,connections:n}),{mode:384}),H(t,d)}function W(){return a().map(n=>({...n,hasSecret:v(n.secretRef),label:n.label||D(n)}))}function Y(n,{token:t=null}={}){const e=O({...n,createdAt:n?.createdAt||Date.now()}),r=a().filter(o=>o.id!==e.id);r.push(e),_(r);let i=null;return t&&(i=U(e.secretRef,t)),{...e,hasSecret:v(e.secretRef),...i?{secretStoredIn:i}:{}}}function q(n){const t=a(),e=t.find(r=>r.id===String(n||""));return e?(_(t.filter(r=>r.id!==e.id)),T(e.secretRef),!0):!1}function z({remote:n=null,grants:t=[],branch:e=null,connectionId:r=null}={}){const i=a(),o=r?i.find(u=>u.id===r&&u.enabled!==!1)||null:n?F(n,i):null,s=o?A(o.secretRef):null,c=o&&s?N(o,s):{},P=(Array.isArray(t)?t.map(String):[]).some(u=>u==="scm:push"||u==="scm:pr"||u==="scm:merge");return c.CHATPANEL_SCM_PUSH=P?e?"own":"any":"none",e&&(c.CHATPANEL_SCM_BRANCH=String(e)),{env:c,connection:o?{id:o.id,kind:o.kind,host:l(o),hasSecret:!!s}:null}}function G(n,t){const e=a().find(s=>s.id===String(n||""));if(!e)return{ok:!1,reason:"no such connection"};const r=A(e.secretRef);if(!r)return{ok:!1,reason:"no token stored"};const i=L(t||(e.reach.find(s=>!s.endsWith("/*")&&s.includes("/"))?`https://${l(e)}/${e.reach.find(s=>!s.endsWith("/*")&&s.includes("/"))}`:""));if(!i)return{ok:!1,reason:"give a repository to test against (owner/name or a URL)"};if(i.host!==l(e))return{ok:!1,reason:`${i.host} is not this connection's host (${l(e)})`};const o=`https://${i.host}/${i.owner}/${i.name}.git`;try{const s=k("git",["ls-remote","--symref",o,"HEAD"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:15e3,windowsHide:!0,env:{...process.env,...N(e,r)}}),c=/^ref: refs\/heads\/(\S+)\tHEAD/m.exec(s)?.[1]||null;return{ok:!0,remote:o,defaultBranch:c}}catch(s){return{ok:!1,reason:String(s?.stderr||s?.message||s).replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"***").trim().slice(0,300)||"git ls-remote failed"}}}export{T as deleteSecret,A as getSecret,v as hasSecret,W as listConnections,Y as putConnection,q as removeConnection,z as runEnvFor,M as secretBackend,U as setSecret,G as testConnection};
package/src/connectors.js CHANGED
@@ -1,100 +1 @@
1
- // What an agent can already reach, read from its own configuration.
2
- //
3
- // A CLI agent brings connectors ChatPanel cannot see: a Slack MCP, a Jira MCP, a filesystem.
4
- // ChatPanel relays its own tools to that agent and says a great deal about them — all of it
5
- // restrictive, because each line was written to stop one substitution — so an agent asked
6
- // about an internal thread read the page, saw the reference, and told the user to go and look
7
- // it up, while holding a connector that reaches it.
8
- //
9
- // Knowing the names turns a guess into a fact. It lets the harness say "you have slack
10
- // connected — use it" instead of listing connectors the agent may not have, and lets routing
11
- // treat "can reach Slack" as a capability rather than a hope.
12
- //
13
- // NAMES ONLY, AND NEVER THE CREDENTIALS. A server's name is what the agent already knows and
14
- // what a prompt needs; its URL, argv and env are what a leak would be made of. This reads
15
- // config files that belong to the user's own agents and returns a list of strings.
16
- //
17
- // CONFIGURED, NOT PROVEN. A server listed here may still fail to start. That is honest and
18
- // useful — it is exactly what the agent itself will try — and probing for real would cost a
19
- // process spawn per agent on every health poll.
20
-
21
- import { readFile } from 'node:fs/promises';
22
- import os from 'node:os';
23
- import path from 'node:path';
24
-
25
- /** Read a file and parse it as JSON, or null. Missing and malformed are the same answer. */
26
- async function readJson(file) {
27
- try { return JSON.parse(await readFile(file, 'utf8')); } catch { return null; }
28
- }
29
-
30
- /** Every key of a `{ mcpServers: { name: {...} } }` block, wherever it appears. */
31
- function fromMcpServers(obj) {
32
- const m = obj && typeof obj === 'object' ? obj.mcpServers || obj.mcp_servers : null;
33
- return m && typeof m === 'object' ? Object.keys(m) : [];
34
- }
35
-
36
- /**
37
- * `[mcp_servers.NAME]` table headers out of a TOML file.
38
- *
39
- * Deliberately a regex rather than a TOML parser: the bridge is zero-runtime-dependency by
40
- * design, and the only thing wanted here is the set of table names. Anything this misses
41
- * simply is not reported, which is the safe direction — a missing name costs a sentence in a
42
- * prompt, an invented one sends an agent looking for a connector it does not have.
43
- */
44
- function fromToml(text) {
45
- const out = [];
46
- const re = /^\s*\[\s*mcp_servers\s*\.\s*([A-Za-z0-9._-]+)\s*\]/gm;
47
- for (const m of String(text || '').matchAll(re)) out.push(m[1]);
48
- return out;
49
- }
50
-
51
- async function readToml(file) {
52
- try { return fromToml(await readFile(file, 'utf8')); } catch { return []; }
53
- }
54
-
55
- const home = () => os.homedir();
56
- const configHome = () => process.env.XDG_CONFIG_HOME || path.join(home(), '.config');
57
-
58
- // Where each agent keeps the list. One entry per agent id in the /health registry; an agent
59
- // with no entry simply reports nothing, which is what an unknown agent should do.
60
- const SOURCES = {
61
- claude: async () => {
62
- const [main, project] = await Promise.all([
63
- readJson(path.join(home(), '.claude.json')),
64
- readJson(path.join(process.cwd(), '.mcp.json')),
65
- ]);
66
- return [...fromMcpServers(main), ...fromMcpServers(project)];
67
- },
68
- codex: async () => readToml(path.join(process.env.CODEX_HOME || path.join(home(), '.codex'), 'config.toml')),
69
- opencode: async () => {
70
- for (const f of [
71
- path.join(configHome(), 'opencode', 'opencode.json'),
72
- path.join(home(), 'Library', 'Application Support', 'opencode', 'opencode.jsonc'),
73
- ]) {
74
- const j = await readJson(f);
75
- const names = [...fromMcpServers(j), ...(j && j.mcp && typeof j.mcp === 'object' ? Object.keys(j.mcp) : [])];
76
- if (names.length) return names;
77
- }
78
- return [];
79
- },
80
- };
81
-
82
- /**
83
- * The connector names an agent is configured with — deduped, sorted, and bounded.
84
- *
85
- * Bounded because this rides in a health response and then into a system prompt: a user with
86
- * forty servers should cost a line, not a paragraph. Sorted so the value is stable across
87
- * polls and a settings page does not reorder itself.
88
- */
89
- export async function connectorsFor(agentId, { max = 24 } = {}) {
90
- const read = SOURCES[agentId];
91
- if (!read) return [];
92
- try {
93
- const names = await read();
94
- return [...new Set(names.filter((n) => typeof n === 'string' && n && n.length <= 64))].sort().slice(0, max);
95
- } catch {
96
- // A config we cannot read is a config we say nothing about. Never a reason to fail a
97
- // health check the extension needs in order to show the agent at all.
98
- return [];
99
- }
100
- }
1
+ import{readFile as p}from"node:fs/promises";import m from"node:os";import t from"node:path";async function i(o){try{return JSON.parse(await p(o,"utf8"))}catch{return null}}function a(o){const n=o&&typeof o=="object"?o.mcpServers||o.mcp_servers:null;return n&&typeof n=="object"?Object.keys(n):[]}function f(o){const n=[],e=/^\s*\[\s*mcp_servers\s*\.\s*([A-Za-z0-9._-]+)\s*\]/gm;for(const c of String(o||"").matchAll(e))n.push(c[1]);return n}async function u(o){try{return f(await p(o,"utf8"))}catch{return[]}}const r=()=>m.homedir(),l=()=>process.env.XDG_CONFIG_HOME||t.join(r(),".config"),y={claude:async()=>{const[o,n]=await Promise.all([i(t.join(r(),".claude.json")),i(t.join(process.cwd(),".mcp.json"))]);return[...a(o),...a(n)]},codex:async()=>u(t.join(process.env.CODEX_HOME||t.join(r(),".codex"),"config.toml")),opencode:async()=>{for(const o of[t.join(l(),"opencode","opencode.json"),t.join(r(),"Library","Application Support","opencode","opencode.jsonc")]){const n=await i(o),e=[...a(n),...n&&n.mcp&&typeof n.mcp=="object"?Object.keys(n.mcp):[]];if(e.length)return e}return[]}};async function g(o,{max:n=24}={}){const e=y[o];if(!e)return[];try{const c=await e();return[...new Set(c.filter(s=>typeof s=="string"&&s&&s.length<=64))].sort().slice(0,n)}catch{return[]}}export{g as connectorsFor};
@@ -1,236 +1,6 @@
1
- // Antigravity engine — drives the Antigravity CLI (`agy -p`) using your local
2
- // login. This replaces Gemini CLI as the default Google-model agent (the Gemini
3
- // CLI is being deprecated for individual users).
4
- //
5
- // agy -p "<prompt>" → run one prompt non-interactively, print the answer, exit
6
- // agy --model <id> → pick the model agy models → list models
7
- //
8
- // Images: Antigravity has no image flag, but it READS image files referenced by
9
- // path in the prompt (vision) — same approach as Claude Code. We write the image
10
- // into the workspace (cwd), grant read access with --add-dir, and reference the
11
- // path so the model opens it.
1
+ import{spawn as N,spawnSync as P}from"node:child_process";import{writeFileSync as F,unlinkSync as z}from"node:fs";import"node:os";import I from"node:path";import{findAgentBin as O}from"../env.js";import{buildCliPrompt as R}from"./prompt.js";import{summarizeCliError as U}from"../cli-errors.js";import{killOnAbort as j,spawnGroupOpts as B}from"../proc.js";import{pushExtraArgs as G,FORBIDDEN as H}from"./args.js";import{resolveWorkdir as J}from"../workdir.js";const D=Number(process.env.CHATPANEL_AGY_TIMEOUT_MS)||18e4;async function at(){try{const p=O("agy")||"agy",l=P(p,["models"],{encoding:"utf8",timeout:15e3}),e=[],a=new Set;for(const r of String(l.stdout||"").split(`
2
+ `)){const n=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(n)&&!/^(name|model|models|id|provider|available)$/i.test(n)&&!a.has(n)&&(a.add(n),e.push(n),e.length>=100))break}return e}catch{return[]}}const C=()=>({started:new Set,finalText:""});function K(p,l,e=C()){const a=String(p||"").trim();if(!a)return{streamed:!1};let r;try{r=JSON.parse(a)}catch{return l({type:"delta",text:`${a}
3
+ `}),{streamed:!0}}const n=r.event||r.type||"";if(n==="init")return l({type:"status",text:"Antigravity working"}),{streamed:!1};if(n==="result"){const s=r.result||{};return e.finalText=typeof s.response=="string"?s.response:"",s.status&&s.status!=="SUCCESS"&&l({type:"status",text:`Antigravity: ${s.status}`}),{streamed:!1}}if(n!=="step_update")return{streamed:!1};const o=r.step_update||{};if(o.step_type==="tool"){const s=`agy_${o.step_index??e.started.size}`,i=o.tool_info&&typeof o.tool_info=="object"?o.tool_info:{},m=o.tool_name||i.name||"tool";if(e.started.has(s)||(e.started.add(s),l({type:"tool",name:m,phase:"start",callId:s,input:i.parameters&&typeof i.parameters=="object"?i.parameters:{}})),o.state==="DONE"){const d=!!i.error||o.state==="ERROR",y=i.output==null?"":typeof i.output=="string"?i.output:JSON.stringify(i.output);l({type:"tool",name:m,phase:"done",callId:s,status:d?`error: ${String(i.error||"failed").slice(0,80)}`:"ok",result:String(d?i.error||"":y).slice(0,4e3)})}return{streamed:!1}}return o.step_type==="agent_response"&&typeof o.text_delta=="string"&&o.text_delta?(l({type:"delta",text:o.text_delta}),{streamed:!0}):{streamed:!1}}let w=!1,L=0;async function it(){if(Date.now()-L>(w?3e4:4e3)){L=Date.now();try{w=!!O("agy")}catch{w=!1}}return w?{ok:!0}:{ok:!1,reason:"agy not found on PATH. Install Antigravity, then run `agy` once to sign in."}}function W(p,l){const e=[];for(let a=0;a<(p?.length||0);a++){const r=/^data:([^;]+);base64,(.+)$/s.exec(p[a]?.dataUrl||"");if(!r)continue;const n=(r[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",o=I.join(l,`chatpanel-img-${Date.now()}-${a}.${n}`);try{F(o,Buffer.from(r[2],"base64")),e.push(o)}catch{}}return e}async function lt({messages:p,system:l,options:e,images:a},r,{signal:n}={}){const o=J(e.workingDir),s=W(a,o),i=()=>s.forEach(t=>{try{z(t)}catch{}});let m=R(p,l);s.length&&(m+=`
12
4
 
13
- import { spawn, spawnSync } from 'node:child_process';
14
- import { mkdirSync, writeFileSync, unlinkSync } from 'node:fs';
15
- import os from 'node:os';
16
- import path from 'node:path';
17
- import { findAgentBin } from '../env.js';
18
- import { buildCliPrompt } from './prompt.js';
19
- import { summarizeCliError } from '../cli-errors.js';
20
- import { killOnAbort, spawnGroupOpts } from '../proc.js';
21
- import { pushExtraArgs, FORBIDDEN } from './args.js';
22
- import { resolveWorkdir } from '../workdir.js';
23
-
24
- const IDLE_MS = Number(process.env.CHATPANEL_AGY_TIMEOUT_MS) || 180_000;
25
-
26
- // `agy models` lists available models. Parse ids best-effort; free text is still
27
- // accepted by the picker, and [] just means "type a model or use the default".
28
- export async function listModels() {
29
- try {
30
- const bin = findAgentBin('agy') || 'agy';
31
- const r = spawnSync(bin, ['models'], { encoding: 'utf8', timeout: 15000 });
32
- const ids = [];
33
- const seen = new Set();
34
- for (const line of String(r.stdout || '').split('\n')) {
35
- const tok = line.trim().split(/\s+/)[0] || '';
36
- if (!/^[A-Za-z0-9][\w./:-]{1,79}$/.test(tok)) continue;
37
- if (/^(name|model|models|id|provider|available)$/i.test(tok)) continue;
38
- if (seen.has(tok)) continue;
39
- seen.add(tok);
40
- ids.push(tok);
41
- if (ids.length >= 100) break;
42
- }
43
- return ids;
44
- } catch {
45
- return [];
46
- }
47
- }
48
-
49
- export const newAgyState = () => ({ started: new Set(), finalText: '' });
50
-
51
- // Translate one `agy --output-format stream-json` line into the bridge's streaming
52
- // vocabulary. Schema, captured from agy 1.2.2:
53
- // {event:'init', init:{cwd, tools:[…]}}
54
- // {event:'step_update', step_update:{ step_index, state:'ACTIVE'|'DONE',
55
- // step_type:'user_input'|'agent_response'|'tool', text_delta?, tool_name?,
56
- // tool_info:{ name, parameters, output? }, usage? }}
57
- // {event:'result', result:{ status:'SUCCESS', response, usage }}
58
- // Returns { streamed } — whether a piece of the ANSWER went out (tool activity does not
59
- // count, so a run that only ran tools still gets its final text from `result`).
60
- export function forwardAgyLine(line, emit, state = newAgyState()) {
61
- const t = String(line || '').trim();
62
- if (!t) return { streamed: false };
63
- let ev;
64
- try { ev = JSON.parse(t); } catch {
65
- // Not JSON: the CLI printed something for a human (a warning, a banner). Show it.
66
- emit({ type: 'delta', text: `${t}\n` });
67
- return { streamed: true };
68
- }
69
- const kind = ev.event || ev.type || '';
70
- if (kind === 'init') { emit({ type: 'status', text: 'Antigravity working' }); return { streamed: false }; }
71
- if (kind === 'result') {
72
- const res = ev.result || {};
73
- state.finalText = typeof res.response === 'string' ? res.response : '';
74
- if (res.status && res.status !== 'SUCCESS') emit({ type: 'status', text: `Antigravity: ${res.status}` });
75
- return { streamed: false };
76
- }
77
- if (kind !== 'step_update') return { streamed: false };
78
- const st = ev.step_update || {};
79
- if (st.step_type === 'tool') {
80
- const id = `agy_${st.step_index ?? state.started.size}`;
81
- const info = st.tool_info && typeof st.tool_info === 'object' ? st.tool_info : {};
82
- const name = st.tool_name || info.name || 'tool';
83
- if (!state.started.has(id)) {
84
- state.started.add(id);
85
- emit({ type: 'tool', name, phase: 'start', callId: id, input: info.parameters && typeof info.parameters === 'object' ? info.parameters : {} });
86
- }
87
- if (st.state === 'DONE') {
88
- const failed = !!info.error || st.state === 'ERROR';
89
- const output = info.output == null ? '' : typeof info.output === 'string' ? info.output : JSON.stringify(info.output);
90
- emit({ type: 'tool', name, phase: 'done', callId: id, status: failed ? `error: ${String(info.error || 'failed').slice(0, 80)}` : 'ok', result: String(failed ? info.error || '' : output).slice(0, 4000) });
91
- }
92
- return { streamed: false };
93
- }
94
- if (st.step_type === 'agent_response' && typeof st.text_delta === 'string' && st.text_delta) {
95
- emit({ type: 'delta', text: st.text_delta });
96
- return { streamed: true };
97
- }
98
- return { streamed: false };
99
- }
100
-
101
- let installed = false;
102
- let lastProbe = 0;
103
- export async function available() {
104
- // Cache a positive result; keep re-probing (throttled) while not found so it
105
- // self-heals once agy appears on PATH — never cache a negative forever.
106
- // Re-probe in both directions (see codex.js): an uninstalled CLI must stop reporting itself
107
- // available without waiting for a bridge restart.
108
- if (Date.now() - lastProbe > (installed ? 30_000 : 4000)) {
109
- lastProbe = Date.now();
110
- try {
111
- installed = !!findAgentBin('agy');
112
- } catch {
113
- installed = false;
114
- }
115
- }
116
- return installed
117
- ? { ok: true }
118
- : { ok: false, reason: 'agy not found on PATH. Install Antigravity, then run `agy` once to sign in.' };
119
- }
120
-
121
- function writeImages(images, dir) {
122
- const files = [];
123
- for (let i = 0; i < (images?.length || 0); i++) {
124
- const m = /^data:([^;]+);base64,(.+)$/s.exec(images[i]?.dataUrl || '');
125
- if (!m) continue;
126
- const ext = (m[1].split('/')[1] || 'png').replace(/[^a-z0-9]/gi, '').slice(0, 5) || 'png';
127
- const file = path.join(dir, `chatpanel-img-${Date.now()}-${i}.${ext}`);
128
- try {
129
- writeFileSync(file, Buffer.from(m[2], 'base64'));
130
- files.push(file);
131
- } catch {
132
- /* skip unwritable */
133
- }
134
- }
135
- return files;
136
- }
137
-
138
- export async function chat({ messages, system, options, images }, emit, { signal } = {}) {
139
- const cwd = resolveWorkdir(options.workingDir);
140
-
141
- // Images: write into the cwd (workspace) and reference with `@<file>` — agy
142
- // reads @-referenced files (incl. images) inline as multimodal input, so no
143
- // read-tool approval is needed in headless `-p` mode. (Confirmed working.)
144
- const imageFiles = writeImages(images, cwd);
145
- const cleanup = () => imageFiles.forEach((f) => { try { unlinkSync(f); } catch { /* gone */ } });
146
- let prompt = buildCliPrompt(messages, system);
147
- if (imageFiles.length) {
148
- prompt += `\n\nThe user attached image(s): ${imageFiles.map((f) => '@' + path.basename(f)).join(' ')}`;
149
- }
150
-
151
- // `-p` runs one prompt non-interactively. --model picks the model.
152
- // --dangerously-skip-permissions auto-approves tool use (headless has no human
153
- // approver) only when the user opted into bypassPermissions.
154
- const baseArgs = ['-p', prompt];
155
- if (options.model) baseArgs.push('--model', options.model);
156
- if (options.permissionMode === 'bypassPermissions') baseArgs.push('--dangerously-skip-permissions');
157
- // Drop caller extras that would auto-approve tools (shared sanitizer).
158
- pushExtraArgs(baseArgs, options.extraArgs, FORBIDDEN.antigravity, emit);
159
-
160
- // STRUCTURED OUTPUT FIRST. agy 1.2+ streams `--output-format stream-json`: one NDJSON
161
- // event per line, with every tool step's name, parameters and output. Plain text — which
162
- // is all this engine ever read — has no tools in it at all, so a turn that ran six
163
- // commands showed the panel one answer and nothing else. An older agy that does not know
164
- // the flag exits non-zero naming it; we fall back to text once, out loud.
165
- const run = (structured) => new Promise((resolve, reject) => {
166
- const args = structured ? [...baseArgs, '--output-format', 'stream-json'] : baseArgs;
167
- let child;
168
- try {
169
- child = spawn('agy', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(options.runEnv || {}) }, ...spawnGroupOpts });
170
- } catch (e) {
171
- return reject(new Error(`Failed to start agy: ${e.message}`));
172
- }
173
-
174
- const detach = killOnAbort(child, signal); // Stop → terminate the agy child
175
-
176
- let out = '';
177
- let err = '';
178
- let buf = '';
179
- let streamed = false;
180
- const state = newAgyState();
181
- let idleTimer;
182
- const armIdle = () => {
183
- clearTimeout(idleTimer);
184
- idleTimer = setTimeout(() => {
185
- child.kill('SIGKILL');
186
- reject(new Error(`Antigravity timed out — no output for ${Math.round(IDLE_MS / 1000)}s.`));
187
- }, IDLE_MS);
188
- };
189
- armIdle();
190
-
191
- const forward = (line) => {
192
- const r = forwardAgyLine(line, emit, state);
193
- if (r.streamed) streamed = true;
194
- };
195
- child.stdout.on('data', (d) => {
196
- armIdle();
197
- const s = d.toString();
198
- out += s;
199
- if (!structured) { streamed = true; emit({ type: 'delta', text: s }); return; }
200
- buf += s;
201
- let nl;
202
- while ((nl = buf.indexOf('\n')) >= 0) {
203
- forward(buf.slice(0, nl));
204
- buf = buf.slice(nl + 1);
205
- }
206
- });
207
- child.stderr.on('data', (d) => { armIdle(); err += d.toString(); });
208
- child.on('error', (e) => {
209
- clearTimeout(idleTimer);
210
- detach();
211
- reject(new Error(`Failed to start agy: ${e.message}`));
212
- });
213
- child.on('close', (code) => {
214
- clearTimeout(idleTimer);
215
- detach();
216
- if (signal?.aborted) { resolve({ code: 0, aborted: true }); return; } // Stop pressed — end quietly
217
- if (structured && buf.trim()) forward(buf);
218
- resolve({ code, out, err, streamed, state });
219
- });
220
- });
221
-
222
- try {
223
- let r = await run(true);
224
- if (r.aborted) return;
225
- if (r.code !== 0 && !r.streamed && /output-format|unknown flag|flag provided but not defined/i.test(r.err)) {
226
- emit({ type: 'status', text: 'This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity.' });
227
- r = await run(false);
228
- if (r.aborted) return;
229
- }
230
- if (r.code !== 0) throw new Error(summarizeCliError('Antigravity', r.code, r.err, r.out));
231
- if (!r.streamed) emit({ type: 'delta', text: (r.state?.finalText || r.out).trim() || '(no output)' });
232
- emit({ type: 'done', text: '' });
233
- } finally {
234
- cleanup();
235
- }
236
- }
5
+ The user attached image(s): ${s.map(t=>"@"+I.basename(t)).join(" ")}`);const d=["-p",m];e.model&&d.push("--model",e.model),e.permissionMode==="bypassPermissions"&&d.push("--dangerously-skip-permissions"),G(d,e.extraArgs,H.antigravity,r);const y=t=>new Promise((v,x)=>{const M=t?[...d,"--output-format","stream-json"]:d;let f;try{f=N("agy",M,{cwd:o,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.runEnv||{}},...B})}catch(u){return x(new Error(`Failed to start agy: ${u.message}`))}const A=j(f,n);let k="",E="",c="",b=!1;const T=C();let g;const S=()=>{clearTimeout(g),g=setTimeout(()=>{f.kill("SIGKILL"),x(new Error(`Antigravity timed out — no output for ${Math.round(D/1e3)}s.`))},D)};S();const $=u=>{K(u,r,T).streamed&&(b=!0)};f.stdout.on("data",u=>{S();const h=u.toString();if(k+=h,!t){b=!0,r({type:"delta",text:h});return}c+=h;let _;for(;(_=c.indexOf(`
6
+ `))>=0;)$(c.slice(0,_)),c=c.slice(_+1)}),f.stderr.on("data",u=>{S(),E+=u.toString()}),f.on("error",u=>{clearTimeout(g),A(),x(new Error(`Failed to start agy: ${u.message}`))}),f.on("close",u=>{if(clearTimeout(g),A(),n?.aborted){v({code:0,aborted:!0});return}t&&c.trim()&&$(c),v({code:u,out:k,err:E,streamed:b,state:T})})});try{let t=await y(!0);if(t.aborted||t.code!==0&&!t.streamed&&/output-format|unknown flag|flag provided but not defined/i.test(t.err)&&(r({type:"status",text:"This Antigravity CLI has no structured output; showing its text only. Update it with `agy update` to see tool activity."}),t=await y(!1),t.aborted))return;if(t.code!==0)throw new Error(U("Antigravity",t.code,t.err,t.out));t.streamed||r({type:"delta",text:(t.state?.finalText||t.out).trim()||"(no output)"}),r({type:"done",text:""})}finally{i()}}export{it as available,lt as chat,K as forwardAgyLine,at as listModels,C as newAgyState};
@@ -1,47 +1 @@
1
- // Caller-supplied "extra CLI arguments" sanitizer (shared by every engine).
2
- //
3
- // The extension/model can pass free-form extraArgs to the agent CLI. A prompt-
4
- // injected model must NOT be able to smuggle a flag that re-opens the sandbox /
5
- // permission boundary the engine deliberately sets (e.g. Codex's
6
- // --dangerously-bypass-approvals-and-sandbox, Claude's --permission-mode). Since
7
- // these flags take values, partial filtering is unsafe — if ANY forbidden token is
8
- // present we drop the WHOLE extraArgs. Previously only claude.js did this; codex,
9
- // antigravity and custom pushed extraArgs unfiltered (this closes that gap).
10
-
11
- export function splitArgs(raw) {
12
- return String(raw || '').split(/\s+/).filter(Boolean);
13
- }
14
-
15
- // Per-engine escalation flags. Long flags use \b so `--flag=value` is caught too;
16
- // short flags are exact-matched so we don't over-block a benign token.
17
- export const FORBIDDEN = {
18
- claude: /^--?(permission-mode|allowed-?tools|disallowed-?tools|dangerously|add-dir|mcp-config|setting-sources|permission-prompt-tool)/i,
19
- // Codex: sandbox / approval escalation + `-c key=val` (can set approval_policy or
20
- // sandbox_mode in TOML) + `-C/--cd` (retarget the working dir).
21
- codex: /^(-s|-a|-c|-C)$|^--(dangerously[\w-]*|sandbox|ask-for-approval|full-auto|yolo|config|cd)\b/i,
22
- antigravity: /^--(dangerously[\w-]*|skip-permissions|trust-all-?tools|yolo|full-auto)\b/i,
23
- // Custom runs an arbitrary CLI, so only clearly-dangerous LONG flags are blocked
24
- // (no short-flag guesses that might collide with a benign tool option).
25
- custom: /^--(dangerously[\w-]*|skip-permissions|trust-all-?tools|no-sandbox|bypass|yolo|full-auto|permission-mode|allowed-?tools|disallowed-?tools|mcp-config)\b/i,
26
- // Copilot's escalation surface is its own family of --allow-* flags (which the
27
- // `custom` pattern above does NOT cover: "allow-all-tools" != "allowed-tools").
28
- // Also block re-targeting the working dir (-C / --add-dir) and injecting MCP
29
- // servers, since the engine sets those deliberately per turn.
30
- copilot: /^(-C)$|^--(allow-all[\w-]*|allow-tool|allow-url|allow-path|yolo|add-dir|additional-mcp-config|disable-builtin-mcps|deny-tool|deny-url|autopilot|mode)\b/i,
31
- };
32
-
33
- // Returns { args, blocked }. `blocked:true` => the whole extraArgs was dropped.
34
- export function sanitizeExtraArgs(raw, forbidden) {
35
- const tokens = splitArgs(raw);
36
- if (tokens.some((t) => forbidden.test(t))) return { args: [], blocked: true };
37
- return { args: tokens, blocked: false };
38
- }
39
-
40
- // Convenience for the engines: sanitize, push the safe tokens onto `args`, and emit
41
- // a status when something was dropped.
42
- export function pushExtraArgs(args, raw, forbidden, emit) {
43
- if (!raw) return;
44
- const { args: extra, blocked } = sanitizeExtraArgs(raw, forbidden);
45
- if (blocked) { try { emit?.({ type: 'status', text: '(ignored unsafe extraArgs)' }); } catch { /* ignore */ } return; }
46
- args.push(...extra);
47
- }
1
+ function i(o){return String(o||"").split(/\s+/).filter(Boolean)}const n={claude:/^--?(permission-mode|allowed-?tools|disallowed-?tools|dangerously|add-dir|mcp-config|setting-sources|permission-prompt-tool)/i,codex:/^(-s|-a|-c|-C)$|^--(dangerously[\w-]*|sandbox|ask-for-approval|full-auto|yolo|config|cd)\b/i,antigravity:/^--(dangerously[\w-]*|skip-permissions|trust-all-?tools|yolo|full-auto)\b/i,custom:/^--(dangerously[\w-]*|skip-permissions|trust-all-?tools|no-sandbox|bypass|yolo|full-auto|permission-mode|allowed-?tools|disallowed-?tools|mcp-config)\b/i,copilot:/^(-C)$|^--(allow-all[\w-]*|allow-tool|allow-url|allow-path|yolo|add-dir|additional-mcp-config|disable-builtin-mcps|deny-tool|deny-url|autopilot|mode)\b/i};function a(o,s){const t=i(o);return t.some(l=>s.test(l))?{args:[],blocked:!0}:{args:t,blocked:!1}}function d(o,s,t,l){if(!s)return;const{args:e,blocked:r}=a(s,t);if(r){try{l?.({type:"status",text:"(ignored unsafe extraArgs)"})}catch{}return}o.push(...e)}export{n as FORBIDDEN,d as pushExtraArgs,a as sanitizeExtraArgs,i as splitArgs};