@chatpanel/bridge 0.11.16 → 0.11.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.11.16",
3
+ "version": "0.11.19",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -26,9 +26,14 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
26
26
  // the invocation contract it validates against, and `reach.js` is the ladder that caps a
27
27
  // paired phone. `reach.js` exists as its own module for exactly this reason — the ladder is
28
28
  // three strings, and taking it out of `router.js` would have vendored 50 KB of model routing.
29
+ // `scm-connection.js` (architecture-pillars.md §14) is the third group: the connection
30
+ // record a client keeps, the remote → connection match, a job's branch name and the
31
+ // process-scoped credential environment — dependency-free, and the bridge is the one
32
+ // process that hands a token to git.
29
33
  const FILES = [
30
34
  'scopes.js', 'skill-manifest.js', 'skill-scan.js',
31
35
  'ref.js', 'event.js', 'view.js', 'capability.js', 'reach.js',
36
+ 'scm-connection.js',
32
37
  ];
33
38
 
34
39
  function pkgDir() {
@@ -0,0 +1,160 @@
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
+ }
@@ -166,7 +166,7 @@ export async function chat({ messages, system, options, images }, emit, { signal
166
166
  const args = structured ? [...baseArgs, '--output-format', 'stream-json'] : baseArgs;
167
167
  let child;
168
168
  try {
169
- child = spawn('agy', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env }, ...spawnGroupOpts });
169
+ child = spawn('agy', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(options.runEnv || {}) }, ...spawnGroupOpts });
170
170
  } catch (e) {
171
171
  return reject(new Error(`Failed to start agy: ${e.message}`));
172
172
  }
@@ -171,10 +171,10 @@ export function claudeMcpConfig(mcp) {
171
171
  // Spawn claude (however it resolves) and stream its stream-json output via
172
172
  // `emit`. Resolves with { streamedAny, resultText } once it closes 0. Returns
173
173
  // null (no spawn) when claude can't be resolved, so the caller can fall back.
174
- function runClaude({ prompt, args, cwd, emit, signal }) {
174
+ function runClaude({ prompt, args, cwd, env = null, emit, signal }) {
175
175
  const spec = resolveClaude();
176
176
  if (!spec) return null;
177
- const [bin, argv, opts] = buildSpawnSpec(spec, args, cwd);
177
+ const [bin, argv, opts] = buildSpawnSpec(spec, args, cwd, env);
178
178
 
179
179
  return new Promise((resolve, reject) => {
180
180
  let child;
@@ -413,7 +413,7 @@ export async function chat({ messages, system, options, images }, emit, { signal
413
413
  // Never let caller-supplied extras re-open the read-only boundary the mode flags
414
414
  // above establish (shared sanitizer — see args.js).
415
415
  pushExtraArgs(args, options.extraArgs, FORBIDDEN.claude, emit);
416
- const run = runClaude({ prompt, args, cwd, emit, signal });
416
+ const run = runClaude({ prompt, args, cwd, env: options.runEnv || null, emit, signal });
417
417
  if (run === null) {
418
418
  cleanup(); // SDK fallback doesn't take images yet
419
419
  return sdkChat({ messages, system, options }, emit, { signal });
@@ -39,6 +39,11 @@ const REASONING = process.env.CHATPANEL_CODEX_EFFORT ?? 'low'; // '' → respect
39
39
  // straight from that file, plus a few common ids. The picker still accepts any
40
40
  // free-text value, so an out-of-date curated entry is harmless.
41
41
  const CODEX_KNOWN = ['gpt-5-codex', 'gpt-5', 'o3', 'o4-mini'];
42
+ // Set once Codex has reported that its managed requirements forbid approval_policy=never;
43
+ // cleared only by a bridge restart, which is when a policy could plausibly have changed.
44
+ let approvalPolicyBlocked = false;
45
+ export function resetApprovalPolicy() { approvalPolicyBlocked = false; }
46
+
42
47
  export async function listModels() {
43
48
  const set = new Set();
44
49
  try {
@@ -234,7 +239,7 @@ function runCodex({ args, cwd, env, prompt, outFile, emit, signal }) {
234
239
  /* no message file */
235
240
  }
236
241
  unlink(outFile).catch(() => {});
237
- resolve({ code, stderr, text, streamed });
242
+ resolve({ code, stderr, text, streamed, policyBlocked: !!evState.policyBlocked });
238
243
  });
239
244
 
240
245
  child.stdin.write(prompt);
@@ -265,7 +270,11 @@ export async function chat({ messages, system, options, images }, emit, { signal
265
270
  args.push('--dangerously-bypass-approvals-and-sandbox');
266
271
  } else {
267
272
  const sandbox = options.permissionMode === 'acceptEdits' ? 'workspace-write' : 'read-only';
268
- args.push('-s', sandbox, '-c', 'approval_policy=never');
273
+ args.push('-s', sandbox);
274
+ // `never` is what a headless run needs — but an organisation can pin approval_policy
275
+ // through Codex's managed requirements, and then every turn opened with a paragraph
276
+ // of warning and fell back to OnRequest anyway. Once Codex has said so, stop asking.
277
+ if (!approvalPolicyBlocked) args.push('-c', 'approval_policy=never');
269
278
  }
270
279
  if (REASONING) args.push('-c', `model_reasoning_effort=${REASONING}`);
271
280
  // Ask Codex to emit reasoning SUMMARIES so the panel can stream the model's thinking.
@@ -288,7 +297,7 @@ export async function chat({ messages, system, options, images }, emit, { signal
288
297
 
289
298
  // Default: use the user's skills/config. Opt-out → isolated home.
290
299
  const useLocal = options.useLocalConfig !== false;
291
- const env = { ...process.env };
300
+ const env = { ...process.env, ...(options.runEnv || {}) };
292
301
  if (!useLocal) {
293
302
  const home = ensureIsolatedHome();
294
303
  if (home) env.CODEX_HOME = home;
@@ -303,6 +312,7 @@ export async function chat({ messages, system, options, images }, emit, { signal
303
312
 
304
313
  try {
305
314
  let result = await attempt();
315
+ if (result.policyBlocked) approvalPolicyBlocked = true;
306
316
 
307
317
  // The failure this exists for: one of the user's OWN MCP servers could not authenticate
308
318
  // or could not be reached, and took a turn with it that never needed that server. Drop it
@@ -418,8 +428,19 @@ export function forwardEvent(ev, emit, state = { started: new Set(), reasoned: n
418
428
  }
419
429
 
420
430
  if (itype === 'error' || t === 'error') {
421
- const msg = item.message || ev.message || '';
422
- if (msg) emit({ type: 'status', text: `Codex: ${String(msg).slice(0, 300)}` });
431
+ const msg = String(item.message || ev.message || '');
432
+ if (!msg) return;
433
+ // The managed-requirements warning: long, per turn, and about a flag WE pass. Say it
434
+ // once in a sentence, and remember (see buildArgs) so the next turn does not earn it.
435
+ if (/approval_policy.*(disallowed|not in the allowed set)/i.test(msg)) {
436
+ state.policyBlocked = true;
437
+ if (!state.policyNoted) {
438
+ state.policyNoted = true;
439
+ emit({ type: 'status', text: 'Codex: your organisation pins approval_policy, so Codex will ask before actions it cannot run on its own. ChatPanel will stop passing its own setting.' });
440
+ }
441
+ return;
442
+ }
443
+ emit({ type: 'status', text: `Codex: ${msg.slice(0, 300)}` });
423
444
  return;
424
445
  }
425
446
 
@@ -570,7 +570,7 @@ export async function runSpec(spec, { messages, system, options = {}, images },
570
570
  args.push(...imageTokens); // stdin prompt: image tokens go on argv
571
571
  }
572
572
 
573
- const [bin, argv, opts] = buildSpawnSpec(resolved, args, cwd);
573
+ const [bin, argv, opts] = buildSpawnSpec(resolved, args, cwd, options.runEnv || null);
574
574
  // Discourage CLIs from colourizing output (kiro-cli etc.) when piped.
575
575
  opts.env = { ...(opts.env || process.env), NO_COLOR: '1', FORCE_COLOR: '0', CLICOLOR: '0', TERM: 'dumb' };
576
576
 
package/src/env.js CHANGED
@@ -226,7 +226,10 @@ function commandInWsl(name) {
226
226
 
227
227
  // Turn a launch spec + CLI args into a concrete [bin, argv, opts] for spawn().
228
228
  // `cwd` is the resolved working dir (a Windows path on win32), or null for home.
229
- export function buildSpawnSpec(spec, args, cwd) {
229
+ export function buildSpawnSpec(spec, args, cwd, env = null) {
230
+ // `env` is what ONE run adds — a git credential scoped to a host, the pre-push leash
231
+ // (connections.js, worktree.js). Merged over the process env, never into it.
232
+ const runEnv = env && typeof env === 'object' && Object.keys(env).length ? { ...process.env, ...env } : process.env;
230
233
  if (spec.kind === 'wsl') {
231
234
  // Run inside WSL's login shell so nvm/etc. PATH resolves the tool. The
232
235
  // `exec <cmd> "$@"` + 'chatpanel' ($0) trick passes our args through as a
@@ -237,13 +240,13 @@ export function buildSpawnSpec(spec, args, cwd) {
237
240
  if (wslCwd) pre.push('--cd', wslCwd); // else: run in WSL home
238
241
  }
239
242
  const argv = [...pre, '-e', 'bash', '-lic', `exec ${spec.command} "$@"`, 'chatpanel', ...args];
240
- return ['wsl.exe', argv, { stdio: ['pipe', 'pipe', 'pipe'], env: process.env, windowsHide: true, ...spawnGroupOpts }];
243
+ return ['wsl.exe', argv, { stdio: ['pipe', 'pipe', 'pipe'], env: runEnv, windowsHide: true, ...spawnGroupOpts }];
241
244
  }
242
245
  // Every spawned CLI leads its own process group, so Stop can signal the whole tree. An
243
246
  // agent CLI is not one process — it runs shell commands and tools of its own — and killing
244
247
  // only the pid we hold leaves those running after the user has stopped the turn.
245
248
  const opts = {
246
- cwd: cwd || os.homedir(), stdio: ['pipe', 'pipe', 'pipe'], env: process.env, windowsHide: true,
249
+ cwd: cwd || os.homedir(), stdio: ['pipe', 'pipe', 'pipe'], env: runEnv, windowsHide: true,
247
250
  ...spawnGroupOpts,
248
251
  };
249
252
  if (spec.kind === 'script') return [process.execPath, [spec.script, ...args], opts];
@@ -0,0 +1,188 @@
1
+ // GENERATED — do not edit.
2
+ // Source of truth: chatpanel-events/scm-connection.js (npm @chatpanel/events).
3
+ // Edit there, then run: npm run sync:events
4
+ //
5
+ // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
+ // curl one-liner install cannot fail on someone's registry, and so the compiled
7
+ // single-file binary has nothing to resolve.
8
+
9
+ // An SCM CONNECTION — how a harness engine reaches the organisation's source-control hub —
10
+ // and the two names a job gets in it: its branch and its worktree directory.
11
+ // (architecture-pillars.md §14: the repository is the source of truth.)
12
+ //
13
+ // ChatPanel is not a git host and not a git client. The harness runs `git`, `gh`, `glab`;
14
+ // ChatPanel brings the CREDENTIAL, the WORKTREE, the BRANCH NAME and the RECORD. This module
15
+ // is the pure part: what a connection record holds, how a remote URL maps to one, what a
16
+ // job's branch is called, and the environment that hands a token to git for ONE process
17
+ // without writing it anywhere.
18
+ //
19
+ // THE TOKEN IS NEVER IN THE RECORD. A connection stores a `secretRef` — the name under which
20
+ // the machine's keychain (or the bridge's secret store) holds the token. The record travels
21
+ // with the client-prefs document (`connections` section) so both clients show the same
22
+ // connections; the secret does not travel, and `normalizeConnection` REFUSES a record that
23
+ // carries one, so a settings export, a sync, or a prompt can never carry it either.
24
+
25
+ export const SCM_KINDS = Object.freeze(['github', 'github-enterprise', 'gitlab', 'bitbucket', 'gitea', 'azure-devops', 'git']);
26
+ export const CONNECTION_ID_RE = /^[a-z][a-z0-9_-]{0,63}$/i;
27
+ export const SECRET_REF_RE = /^[a-zA-Z0-9_.:@/-]{1,200}$/;
28
+ const SECRET_FIELDS = ['token', 'password', 'secret', 'pat', 'apiKey', 'key'];
29
+ const DEFAULT_HOST = { github: 'github.com', gitlab: 'gitlab.com', bitbucket: 'bitbucket.org', 'azure-devops': 'dev.azure.com' };
30
+
31
+ export class ScmError extends Error {
32
+ constructor(code, message) { super(message); this.name = 'ScmError'; this.code = code; }
33
+ }
34
+
35
+ const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
36
+
37
+ /** The host a connection serves: its baseUrl's, or the kind's public host. */
38
+ export function hostOf(conn) {
39
+ const url = String(conn?.baseUrl || '').trim();
40
+ if (url) { try { return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).host.toLowerCase(); } catch { return url.toLowerCase().replace(/^https?:\/\//, '').split('/')[0]; } }
41
+ return DEFAULT_HOST[conn?.kind] || '';
42
+ }
43
+
44
+ export function validateConnection(conn) {
45
+ const errors = [];
46
+ if (!isRecord(conn)) return { ok: false, errors: ['connection must be an object'] };
47
+ if (!CONNECTION_ID_RE.test(String(conn.id || ''))) errors.push('id: a short identifier (letters, digits, _ -)');
48
+ if (!SCM_KINDS.includes(conn.kind)) errors.push(`kind: one of ${SCM_KINDS.join(', ')}`);
49
+ const needsHost = ['github-enterprise', 'gitea', 'git'].includes(conn.kind);
50
+ if (needsHost && !String(conn.baseUrl || '').trim()) errors.push('baseUrl: the hub\'s URL');
51
+ if (conn.baseUrl && !/^(https?:\/\/)?[a-z0-9.-]+(:\d+)?(\/[^\s]*)?$/i.test(String(conn.baseUrl).trim())) errors.push('baseUrl: a host or URL');
52
+ const leaked = SECRET_FIELDS.filter((k) => conn[k] !== undefined && conn[k] !== null && conn[k] !== '');
53
+ if (leaked.length) errors.push(`${leaked.join(', ')}: a connection never stores a secret — store it in the keychain and reference it by secretRef`);
54
+ if (conn.secretRef !== undefined && conn.secretRef !== null && conn.secretRef !== '' && !SECRET_REF_RE.test(String(conn.secretRef))) errors.push('secretRef: a keychain / secret-store name');
55
+ if (conn.reach !== undefined && !Array.isArray(conn.reach)) errors.push('reach: a list of remotes or owners this connection may be used for');
56
+ return { ok: errors.length === 0, errors };
57
+ }
58
+
59
+ /** The stored form. Throws on a record that carries a secret. */
60
+ export function normalizeConnection(conn) {
61
+ const v = validateConnection(conn);
62
+ if (!v.ok) throw new ScmError('INVALID', v.errors.join('; '));
63
+ const id = String(conn.id);
64
+ return {
65
+ id,
66
+ kind: conn.kind,
67
+ label: String(conn.label || conn.name || '').trim().slice(0, 80) || `${conn.kind} · ${hostOf(conn) || id}`,
68
+ ...(conn.baseUrl ? { baseUrl: String(conn.baseUrl).trim().replace(/\/+$/, '') } : {}),
69
+ // The secret's NAME — `chatpanel:scm:<id>` by default — under which the keychain holds it.
70
+ secretRef: String(conn.secretRef || '').trim() || `chatpanel:scm:${id}`,
71
+ ...(conn.username ? { username: String(conn.username).trim().slice(0, 80) } : {}),
72
+ // Which remotes it may be used for: `owner/*`, `owner/name`, or a host. Empty = any on its host.
73
+ reach: (Array.isArray(conn.reach) ? conn.reach : []).map((r) => String(r).trim().toLowerCase()).filter(Boolean).slice(0, 64),
74
+ enabled: conn.enabled !== false,
75
+ ...(conn.createdAt ? { createdAt: conn.createdAt } : {}),
76
+ };
77
+ }
78
+
79
+ /**
80
+ * A remote URL, read: `{ host, owner, name, protocol }` for https, ssh (`git@host:o/n.git`,
81
+ * `ssh://git@host/o/n`) and plain `host/o/n`. Credentials in the URL are dropped, never
82
+ * returned. Null for what cannot be read.
83
+ */
84
+ export function parseRemote(url) {
85
+ const s = String(url || '').trim();
86
+ if (!s) return null;
87
+ let m = /^(?:ssh:\/\/)?(?:[\w.-]+@)?([a-z0-9.-]+)(?::\d+)?[:/]+([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(s.replace(/^https?:\/\/(?:[^@/]+@)?/i, ''));
88
+ if (m && !/^https?:/i.test(s)) return { host: m[1].toLowerCase(), owner: m[2], name: m[3], protocol: /^ssh:|^[\w.-]+@/.test(s) ? 'ssh' : 'plain' };
89
+ try {
90
+ const u = new URL(s);
91
+ const parts = u.pathname.replace(/\.git$/, '').split('/').filter(Boolean);
92
+ if (parts.length < 2) return null;
93
+ // Azure DevOps: /org/project/_git/repo; GitLab subgroups: /a/b/c/repo — owner is all but the last.
94
+ const name = parts.at(-1);
95
+ const owner = parts.slice(0, -1).filter((p) => p !== '_git').join('/');
96
+ return { host: u.host.toLowerCase(), owner, name, protocol: u.protocol.replace(':', '') };
97
+ } catch { return null; }
98
+ }
99
+
100
+ /**
101
+ * The connection to use for a remote: enabled, same host, and — when the connection lists
102
+ * a reach — the remote's `owner/name` or `owner/*` in it. The most specific reach wins.
103
+ */
104
+ export function connectionFor(remote, connections = []) {
105
+ const r = typeof remote === 'string' ? parseRemote(remote) : remote;
106
+ if (!r) return null;
107
+ const slug = `${r.owner}/${r.name}`.toLowerCase();
108
+ let best = null; let bestScore = -1;
109
+ for (const c of connections || []) {
110
+ if (!c || c.enabled === false) continue;
111
+ if (hostOf(c) !== r.host) continue;
112
+ const reach = Array.isArray(c.reach) ? c.reach : [];
113
+ let score = reach.length ? -1 : 0;
114
+ for (const x of reach) {
115
+ if (x === slug) score = Math.max(score, 3);
116
+ else if (x.endsWith('/*') && slug.startsWith(x.slice(0, -1))) score = Math.max(score, 2);
117
+ else if (x === r.host) score = Math.max(score, 1);
118
+ }
119
+ if (score > bestScore) { best = c; bestScore = score; }
120
+ }
121
+ return best;
122
+ }
123
+
124
+ const slug = (s) => String(s || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 48) || 'x';
125
+
126
+ /** A job's branch: `cp/<project>/<job>` — one branch per job, always under `cp/`, never a protected name. */
127
+ export function branchFor(projectId, jobId) { return `cp/${slug(projectId)}/${slug(jobId)}`; }
128
+
129
+ /** A job's worktree directory under the bridge's worktree root: `<project>/<job>`. */
130
+ export function worktreeDirFor(projectId, jobId) { return `${slug(projectId)}/${slug(jobId)}`; }
131
+
132
+ /**
133
+ * The environment that hands ONE process the token, scoped to the connection's host:
134
+ * git's `credential.<url>.helper` set through `GIT_CONFIG_*` (never a file, never the
135
+ * command line), a helper that reads the token from the environment, terminal prompts
136
+ * off, and the hub CLIs' own variables (`GH_TOKEN` / `GH_HOST`, `GITLAB_TOKEN`) so `gh` and
137
+ * `glab` work in the same process. The caller spawns with `{ ...process.env, ...env }` and
138
+ * the token dies with the process.
139
+ */
140
+ export function credentialEnv(conn, token, { username = null } = {}) {
141
+ const c = conn || {};
142
+ const host = hostOf(c);
143
+ if (!host || !token) return {};
144
+ const user = username || c.username || ({ github: 'x-access-token', 'github-enterprise': 'x-access-token', gitlab: 'oauth2', bitbucket: 'x-token-auth', gitea: 'oauth2', 'azure-devops': 'pat' }[c.kind] || 'token');
145
+ const env = {
146
+ GIT_TERMINAL_PROMPT: '0',
147
+ GIT_CONFIG_COUNT: '2',
148
+ GIT_CONFIG_KEY_0: `credential.https://${host}.helper`,
149
+ // A shell helper: on `get`, answer from the environment. Nothing is written anywhere.
150
+ GIT_CONFIG_VALUE_0: '!f() { if [ "$1" = get ]; then printf "username=%s\\npassword=%s\\n" "$CHATPANEL_SCM_USER" "$CHATPANEL_SCM_TOKEN"; fi; }; f',
151
+ GIT_CONFIG_KEY_1: `credential.https://${host}.useHttpPath`,
152
+ GIT_CONFIG_VALUE_1: 'false',
153
+ CHATPANEL_SCM_USER: user,
154
+ CHATPANEL_SCM_TOKEN: String(token),
155
+ };
156
+ if (c.kind === 'github' || c.kind === 'github-enterprise') {
157
+ env.GH_TOKEN = String(token);
158
+ if (c.kind === 'github-enterprise') { env.GH_ENTERPRISE_TOKEN = String(token); env.GH_HOST = host; }
159
+ }
160
+ if (c.kind === 'gitlab') { env.GITLAB_TOKEN = String(token); env.GITLAB_HOST = host; }
161
+ return env;
162
+ }
163
+
164
+ /** One line a person reads: "GitHub · github.com · acme/*". */
165
+ export function describeConnection(conn) {
166
+ const c = conn || {};
167
+ const kindLabel = { github: 'GitHub', 'github-enterprise': 'GitHub Enterprise', gitlab: 'GitLab', bitbucket: 'Bitbucket', gitea: 'Gitea', 'azure-devops': 'Azure DevOps', git: 'Git' }[c.kind] || c.kind;
168
+ return `${kindLabel} · ${hostOf(c)}${c.reach?.length ? ` · ${c.reach.join(', ')}` : ''}${c.enabled === false ? ' (off)' : ''}`;
169
+ }
170
+
171
+ export function blankConnection() { return { id: '', kind: 'github', label: '', baseUrl: '', reach: [], username: '' }; }
172
+
173
+ /** The editor's form → a connection, or the errors. The token is NOT part of the form's record: the host stores it separately. */
174
+ export function connectionFromForm(form) {
175
+ const f = form || {};
176
+ const id = String(f.id || '').trim() || slug(f.label || `${f.kind}-${hostOf(f)}`);
177
+ const conn = {
178
+ id, kind: f.kind || 'github', label: String(f.label || '').trim(),
179
+ ...(f.baseUrl ? { baseUrl: String(f.baseUrl).trim() } : {}),
180
+ ...(f.username ? { username: String(f.username).trim() } : {}),
181
+ ...(f.secretRef ? { secretRef: String(f.secretRef).trim() } : {}),
182
+ reach: String(Array.isArray(f.reach) ? f.reach.join(',') : f.reach || '').split(/[,\s]+/).map((x) => x.trim()).filter(Boolean),
183
+ enabled: f.enabled !== false,
184
+ ...(f.createdAt ? { createdAt: f.createdAt } : {}),
185
+ };
186
+ const v = validateConnection(conn);
187
+ return v.ok ? { ok: true, connection: normalizeConnection(conn) } : { ok: false, errors: v.errors };
188
+ }
@@ -54,7 +54,31 @@ export function restoreToolArgs(value, vault) {
54
54
  // [[LOCATION_1]] token as redacted and REFUSE to use it for a lookup ("I can't see
55
55
  // your real city") — the opposite of what we want. Weak models call the tool blindly
56
56
  // and it works (the harness restores the real value), so the note levels them up.
57
- export function placeholderToolNote({ toolData = 'real' } = {}) {
57
+ //
58
+ // `ownTools`: the model is a relayed CLI agent that brings tools of ITS OWN (Codex's web
59
+ // search, a shell, files). Those run on the far side of the harness and receive the
60
+ // placeholder LITERALLY — a search for "[[ORG_1]] stock price" finds nothing, and the agent
61
+ // reports that "the lookup did not resolve the company". Seen exactly so, on the desktop:
62
+ // Codex chose its own web search over ChatPanel's `find` on one turn and answered from
63
+ // nothing. The extra sentence says which tools restore and which do not, so the choice is
64
+ // no longer a coin toss.
65
+ /**
66
+ * The note for a turn with NO tools armed. The model still meets `[[LOCATION_1]]` in the
67
+ * conversation, and a coding agent told nothing about it stops to ask what the "unresolved
68
+ * placeholder" means — exactly what a redaction layer must never cause. So: treat it as a
69
+ * concrete value, write around it, echo it exactly; the real value is restored on the way
70
+ * back. Short, because there is nothing to call.
71
+ */
72
+ export function placeholderNote() {
73
+ return 'PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], '
74
+ + '[[LOCATION_1]], [[ORG_1]] that stand in for the user\'s real private data. Treat each one as '
75
+ + 'a CONCRETE, specific value you already have — not missing or unknown information. Do not ask '
76
+ + 'what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason '
77
+ + 'and write with the placeholder exactly as written; the real value is restored in your answer '
78
+ + 'automatically.';
79
+ }
80
+
81
+ export function placeholderToolNote({ toolData = 'real', ownTools = false } = {}) {
58
82
  const intro =
59
83
  'PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], '
60
84
  + '[[LOCATION_1]], [[ORG_1]] that stand in for the user\'s real private data. ';
@@ -82,7 +106,15 @@ export function placeholderToolNote({ toolData = 'real' } = {}) {
82
106
  + 'Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup '
83
107
  + 'will work. The real values are restored in your final answer automatically, so write your '
84
108
  + 'answer using the placeholders too.';
85
- return intro + remote + rules;
109
+ const own = ownTools
110
+ ? ' ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. Any tool you bring '
111
+ + 'yourself — your own web search, shell, file or code tools — receives the placeholder '
112
+ + 'text literally and will find nothing. So for ANY lookup that involves a placeholder, '
113
+ + 'call the listed tool (for example `find` with action `web_search` or `history_search`) '
114
+ + 'rather than your own. Prefer the listed tools for lookups in general — the user sees '
115
+ + 'those as steps — and keep your own tools for what the listed ones cannot do.'
116
+ : '';
117
+ return intro + remote + rules + own;
86
118
  }
87
119
 
88
120
  // Tools whose results come from the PUBLIC web rather than from the user's own machine or
package/src/scm.js ADDED
@@ -0,0 +1,76 @@
1
+ // scm.js — what a run did in a git checkout, said on the record.
2
+ //
3
+ // The repository is the source of truth for a project that is code (architecture-pillars.md
4
+ // §14): the board holds the conversation, the job board the intent, but what an agent DID
5
+ // lives in branches and commits in the hub the organisation already uses. The bridge adds
6
+ // no git client — the coding agents know `git` — but it is the one process that knows
7
+ // where the agent worked and can look before and after, so it reports: which repo, which
8
+ // branch, HEAD when the run started, HEAD when it ended, and how many commits lie between.
9
+ // The runner puts that on the task and on the agent's scorecard, where a merged PR will be
10
+ // the one outcome fact that does not come from a judge.
11
+ //
12
+ // Read-only, never writes, never fails a run: a directory that is not a checkout, or a
13
+ // machine without git, is `null` and nothing is announced. Every call is bounded by a short
14
+ // timeout — `git` on a network filesystem must not stall a chat.
15
+
16
+ import { execFile } from 'node:child_process';
17
+
18
+ const GIT_TIMEOUT_MS = 2500;
19
+
20
+ /** One git query; '' on any failure (no git, not a repo, timed out). */
21
+ function git(dir, args, { exec = execFile } = {}) {
22
+ return new Promise((resolve) => {
23
+ let done = false;
24
+ const finish = (v) => { if (!done) { done = true; resolve(v); } };
25
+ try {
26
+ exec('git', ['-C', dir, ...args], { timeout: GIT_TIMEOUT_MS, windowsHide: true, maxBuffer: 1 << 20 }, (err, stdout) => finish(err ? '' : String(stdout || '').trim()));
27
+ } catch { finish(''); }
28
+ });
29
+ }
30
+
31
+ /**
32
+ * The checkout at `dir`, or null. `{ repo, remote, branch, head, dirty }` — `repo` is the
33
+ * worktree's top level, `remote` the origin URL when there is one (with any credential
34
+ * stripped: a token in a URL is not something to put on a record), `branch` the current one
35
+ * ('HEAD' when detached), `head` the full commit, `dirty` whether anything is uncommitted.
36
+ */
37
+ export async function gitState(dir, opts = {}) {
38
+ if (!dir) return null;
39
+ const repo = await git(dir, ['rev-parse', '--show-toplevel'], opts);
40
+ if (!repo) return null;
41
+ const [branch, head, remote, status] = await Promise.all([
42
+ git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'], opts),
43
+ git(dir, ['rev-parse', 'HEAD'], opts),
44
+ git(dir, ['remote', 'get-url', 'origin'], opts),
45
+ git(dir, ['status', '--porcelain', '--untracked-files=no'], opts),
46
+ ]);
47
+ return {
48
+ repo,
49
+ ...(remote ? { remote: stripCredential(remote) } : {}),
50
+ branch: branch || 'HEAD',
51
+ ...(head ? { head } : {}),
52
+ dirty: status.length > 0,
53
+ };
54
+ }
55
+
56
+ /** `https://user:token@host/…` → `https://host/…`. */
57
+ export function stripCredential(url) {
58
+ return String(url || '').replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]+@/i, '$1');
59
+ }
60
+
61
+ /**
62
+ * What the run changed: the state after, plus `commits` — how many lie between the HEAD it
63
+ * started at and the HEAD it ended at (0 when unchanged or unknowable). `before` is what
64
+ * `gitState` returned at the start; a run that began outside a checkout can still end in
65
+ * one (an agent that cloned), so `after` is read regardless.
66
+ */
67
+ export async function gitDelta(dir, before, opts = {}) {
68
+ const after = await gitState(dir, opts);
69
+ if (!after) return null;
70
+ let commits = 0;
71
+ if (before?.head && after.head && before.head !== after.head) {
72
+ const n = await git(dir, ['rev-list', '--count', `${before.head}..${after.head}`], opts);
73
+ commits = Number(n) || 0;
74
+ }
75
+ return { ...after, ...(before?.head ? { headBefore: before.head } : {}), commits };
76
+ }
package/src/server.js CHANGED
@@ -10,11 +10,19 @@
10
10
  // {type:'tool', name, summary}
11
11
  // {type:'status'|'reasoning', text?}
12
12
  // {type:'workdir', path, isDefault} where this run writes
13
+ // {type:'scm', phase:'before'|'after', repo, remote?, branch, head, commits?}
14
+ // the checkout it worked in, when it is one
15
+ // {type:'workspace', path, branch, base, created, connection?}
16
+ // the worktree the run was given (options.workspace)
13
17
  // {type:'done', text?} (text only if not streamed)
14
18
  // {type:'error', error}
15
19
  // POST /v1/chat/completions, /v1/completions, /v1/responses
16
20
  // → OpenAI-compatible text adapters for the local agents
17
21
  // POST /v1/messages → Anthropic-compatible text adapter for the local agents
22
+ // GET /connections → SCM connections on this machine (records; never a token)
23
+ // POST /connections → { connection, token? } save one; the token goes to the keychain
24
+ // POST /connections/<id>/test { remote? } · POST /connections/<id>/delete
25
+ // GET /worktrees → the job worktrees the bridge made · POST /worktrees/remove
18
26
  // GET /skills → skill packages on disk (name + description + files)
19
27
  // GET /skills/<name> → one skill, SKILL.md body included
20
28
  // GET /skills/<name>/file/<path> → one reference/template/asset from that package
@@ -40,6 +48,9 @@ import { installService, uninstallService, serviceStatus, restartService } from
40
48
  import { skillIndex, listRecords, readRecord, readPackageFile, skillsHealth, quarantinedSkills } from './skills.js';
41
49
  import { capabilityToolSpecs, runCapabilityTool } from './mcp-capabilities.js';
42
50
  import { DEFAULT_WORKSPACE, isDefaultWorkdir, resolveWorkdir, writeScopeNote } from './workdir.js';
51
+ import { gitState, gitDelta } from './scm.js';
52
+ import { listConnections, putConnection, removeConnection, runEnvFor, testConnection, secretBackend } from './connections.js';
53
+ import { worktreeFor, listWorktrees, removeWorktree, withHook, WORKTREE_ROOT } from './worktree.js';
43
54
  import { AGENT_CLIS, enrichPath, enrichAgentEnv, findAgentBin, resolveCommand } from './env.js';
44
55
  import { stripHidden } from './sanitize.js';
45
56
  import { checkForUpdate, selfUpdate } from './update.js';
@@ -67,7 +78,7 @@ import {
67
78
  // Hardcoded (not read from package.json) so it survives Bun's single-file
68
79
  // --compile, where package.json isn't on a readable FS. CI fails the publish if
69
80
  // this drifts from package.json, so the two can't silently diverge.
70
- const VERSION = '0.11.16';
81
+ const VERSION = '0.11.19';
71
82
  const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
72
83
  const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
73
84
 
@@ -336,6 +347,10 @@ const PRIVILEGED_POST = new Set([
336
347
  '/channels/unpair',
337
348
  '/channels/settings',
338
349
  '/channels/disconnect',
350
+ // An SCM connection holds a token for this machine's git; a worktree is a checkout the
351
+ // bridge makes. Both are as privileged as /chat.
352
+ '/connections',
353
+ '/worktrees',
339
354
  ]);
340
355
  // /channels is NOT here, for the same reason /skills is not, and it was a regression to add
341
356
  // it: a privileged GET is unreachable from the extension. The panel holds `<all_urls>`, so
@@ -445,6 +460,8 @@ async function handleHealth(res) {
445
460
  json(res, 200, {
446
461
  ok: true, version: VERSION, agents, update,
447
462
  workspace: DEFAULT_WORKSPACE,
463
+ // Where job worktrees go and where a connection's token is kept — additive.
464
+ worktrees: WORKTREE_ROOT, secretBackend: secretBackend(),
448
465
  // WHO STARTED THIS PROCESS — additive. ChatPanel Desktop sets CHATPANEL_MANAGED_BY=desktop on
449
466
  // the login service it registers; a client can then say so instead of offering install.sh.
450
467
  ...(process.env.CHATPANEL_MANAGED_BY ? { managedBy: String(process.env.CHATPANEL_MANAGED_BY).slice(0, 32) } : {}),
@@ -573,18 +590,48 @@ async function handleChat(req, res) {
573
590
  // a temp folder the OS clears on its own schedule. Now there is one answer and it is
574
591
  // announced. Additive: a client that does not know `workdir` ignores it, and the same
575
592
  // information is repeated as a `status` line, which every client already renders.
593
+ // AND WHICH CHECKOUT, when the directory is one (scm.js): the repo, branch and HEAD before
594
+ // the agent starts, and after it ends what moved — so the team runner can put "worked on
595
+ // cp/p/j, 2 commits" on the task and the agent's record, not "it said it committed".
596
+ // A JOB'S WORKTREE, when the run names one (architecture-pillars.md §14.2):
597
+ // options.workspace = { repo, projectId, jobId, base? } → a checkout of its own on
598
+ // cp/<project>/<job>, which becomes the working directory. A worktree that cannot be
599
+ // made ends the run here — an Implementer must not fall back to the main checkout.
600
+ let workspace = null;
601
+ if (body.options?.workspace && typeof body.options.workspace === 'object') {
602
+ const w = body.options.workspace;
603
+ workspace = await worktreeFor({ repo: w.repo, projectId: w.projectId, jobId: w.jobId, base: w.base || null });
604
+ if (workspace.error) { emit({ type: 'error', error: `workspace: ${workspace.error}` }); endRun(runId); if (!res.writableEnded) res.end(); return; }
605
+ }
606
+ const workdir = workspace ? workspace.path : resolveWorkdir(body.options?.workingDir);
607
+ let scmBefore = null;
576
608
  {
577
- const dir = resolveWorkdir(body.options?.workingDir);
578
- const chosen = !isDefaultWorkdir(body.options?.workingDir);
609
+ const dir = workdir;
610
+ const chosen = !!workspace || !isDefaultWorkdir(body.options?.workingDir);
579
611
  const scope = writeScopeNote(body.agent, body.options?.permissionMode, dir);
580
612
  emit({ type: 'workdir', path: dir, isDefault: !chosen, writeScope: scope || undefined });
581
613
  emit({ type: 'status', text: `Working in ${dir}${chosen ? '' : ' (default)'}` });
582
614
  if (scope) emit({ type: 'status', text: scope });
615
+ scmBefore = await gitState(dir);
616
+ if (scmBefore) emit({ type: 'scm', phase: 'before', ...scmBefore });
617
+ }
618
+ // THE CREDENTIAL AND THE LEASH, for this process only (connections.js, worktree.js): the
619
+ // token of the connection that matches the checkout's remote, scoped to its host in the
620
+ // spawned process's environment; the pre-push hook that keeps a push on the job's own
621
+ // branch, or refuses every push when the role has no scm:push. Nothing is written to the
622
+ // repository or the user's git config. Said on the stream, minus the secret.
623
+ let runEnv = null;
624
+ if (scmBefore || workspace) {
625
+ const grants = Array.isArray(body.options?.grants) ? body.options.grants : [];
626
+ const { env, connection } = runEnvFor({ remote: scmBefore?.remote || null, grants, branch: workspace?.branch || null, connectionId: body.options?.connectionId || null });
627
+ runEnv = withHook(env);
628
+ if (workspace) emit({ type: 'workspace', path: workspace.path, branch: workspace.branch, base: workspace.base, created: workspace.created, repo: workspace.repo, ...(connection ? { connection } : {}) });
629
+ if (connection) emit({ type: 'status', text: `Git credential: ${connection.kind} · ${connection.host}${connection.hasSecret ? '' : ' (no token stored)'} · push: ${env.CHATPANEL_SCM_PUSH === 'own' ? `${workspace?.branch} only` : env.CHATPANEL_SCM_PUSH}` });
583
630
  }
584
631
 
585
632
  // Browser-tools relay: when the extension sends page-tool specs, host an MCP
586
633
  // server for this turn and tell the engine to point the CLI at it.
587
- const options = { ...(body.options || {}) };
634
+ const options = { ...(body.options || {}), ...(workspace ? { workingDir: workspace.path } : {}), ...(runEnv ? { runEnv } : {}) };
588
635
  let session = null;
589
636
  if (body.pageTools?.specs?.length) {
590
637
  session = createSession(safeEmit, body.pageTools.specs);
@@ -610,12 +657,51 @@ async function handleChat(req, res) {
610
657
  log('error', `${body.agent} chat failed: ${e?.message || e}`);
611
658
  emit({ type: 'error', error: e?.message || String(e) });
612
659
  } finally {
660
+ // What the run left in the checkout — said before the stream closes, so a client that
661
+ // already has the answer still gets the commits. A run that was cancelled is looked at
662
+ // too: the commits it made before Stop are real.
663
+ if (!closed) {
664
+ const after = await gitDelta(workdir, scmBefore).catch(() => null);
665
+ if (after) safeEmit({ type: 'scm', phase: 'after', ...after });
666
+ }
613
667
  endRun(runId);
614
668
  if (session) deleteSession(session.id);
615
669
  if (!res.writableEnded) res.end();
616
670
  }
617
671
  }
618
672
 
673
+ // --- SCM connections and job worktrees (architecture-pillars.md §14) ---------------------
674
+ // GET is open like /skills (the panel's GET carries no Origin); every write is a POST and
675
+ // privileged. A token arrives in a POST body once, goes to the keychain, and is never
676
+ // returned — a client learns only `hasSecret`.
677
+ async function handleConnections(req, res, pathname) {
678
+ if (req.method === 'GET' && pathname === '/connections') return json(res, 200, { ok: true, connections: listConnections(), secretBackend: secretBackend() });
679
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
680
+ const body = await readBody(req);
681
+ if (pathname === '/connections') {
682
+ try { return json(res, 200, { ok: true, connection: putConnection(body.connection || body, { token: body.token || null }) }); }
683
+ catch (e) { return json(res, 400, { error: String(e?.message || e) }); }
684
+ }
685
+ const m = /^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(pathname);
686
+ if (!m) return json(res, 404, { error: 'Not found' });
687
+ if (m[2] === 'delete') return json(res, 200, { ok: removeConnection(m[1]) });
688
+ return json(res, 200, testConnection(m[1], body.remote || ''));
689
+ }
690
+ async function handleWorktrees(req, res, pathname) {
691
+ if (req.method === 'GET' && pathname === '/worktrees') return json(res, 200, { ok: true, root: WORKTREE_ROOT, worktrees: await listWorktrees() });
692
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
693
+ const body = await readBody(req);
694
+ if (pathname === '/worktrees') {
695
+ const r = await worktreeFor({ repo: body.repo, projectId: body.projectId, jobId: body.jobId, base: body.base || null });
696
+ return json(res, r.error ? 400 : 200, r.error ? { error: r.error } : { ok: true, ...r });
697
+ }
698
+ if (pathname === '/worktrees/remove') {
699
+ const r = await removeWorktree({ projectId: body.projectId, jobId: body.jobId, force: !!body.force });
700
+ return json(res, r.ok ? 200 : 400, r);
701
+ }
702
+ return json(res, 404, { error: 'Not found' });
703
+ }
704
+
619
705
  async function runCompatibleAgent(config, onDelta, res) {
620
706
  const target = ENGINES[config.agent];
621
707
  if (!target || target.hidden) throw new CompatError(`Unknown ChatPanel agent "${config.agent}"`, 400, 'model');
@@ -1162,6 +1248,8 @@ const server = createServer(async (req, res) => {
1162
1248
  extraDirs,
1163
1249
  );
1164
1250
  }
1251
+ if (url.pathname === '/connections' || url.pathname.startsWith('/connections/')) return handleConnections(req, res, url.pathname);
1252
+ if (url.pathname === '/worktrees' || url.pathname.startsWith('/worktrees/')) return handleWorktrees(req, res, url.pathname);
1165
1253
  if (req.method === 'GET' && url.pathname === '/v1/models') return handleCompatibleModels(res);
1166
1254
  if (req.method === 'GET' && url.pathname.startsWith('/v1/models/')) {
1167
1255
  return handleCompatibleModels(res, decodeURIComponent(url.pathname.slice('/v1/models/'.length)));
@@ -0,0 +1,146 @@
1
+ // worktree.js — a checkout per job, and the hook that keeps its pushes on its own branch.
2
+ //
3
+ // An Implementer works in a WORKTREE of the repository (architecture-pillars.md §14.2):
4
+ // `git worktree add` under ~/.chatpanel/worktrees/<project>/<job> on the branch
5
+ // `cp/<project>/<job>`, from the base the job names (the repo's default branch when it
6
+ // names none). Two jobs on one repo never share a working directory; the main checkout is
7
+ // never touched; a person can open the directory and look. The bridge adds no git client —
8
+ // `git` does the work, bounded, and a failure is reported, never hidden.
9
+ //
10
+ // THE PRE-PUSH HOOK is how "push your own branch" is enforced without inspecting what the
11
+ // agent types: the run's environment sets `core.hooksPath` to a directory the bridge
12
+ // owns, whose `pre-push` refuses any ref that is not the job's branch (and every push when
13
+ // the role has no `scm:push`). The repository's own pre-push, if it has one, still runs
14
+ // after ours. This is process-scoped like the credential: the hook is not installed in the
15
+ // repository and does not survive the run.
16
+
17
+ import { execFile } from 'node:child_process';
18
+ import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync, realpathSync } from 'node:fs';
19
+ import { join, resolve } from 'node:path';
20
+ import os from 'node:os';
21
+ import { branchFor, worktreeDirFor } from './events/scm-connection.js';
22
+
23
+ export const WORKTREE_ROOT = process.env.CHATPANEL_WORKTREES || join(os.homedir(), '.chatpanel', 'worktrees');
24
+ export const HOOKS_DIR = process.env.CHATPANEL_GIT_HOOKS || join(os.homedir(), '.chatpanel', 'git-hooks');
25
+ const GIT_TIMEOUT_MS = 60_000; // a worktree add checks files out; a network filesystem is slow
26
+
27
+ const PRE_PUSH = `#!/bin/sh
28
+ # ChatPanel's pre-push — process-scoped through core.hooksPath for one agent run.
29
+ # Refuses every push when CHATPANEL_SCM_PUSH=none, and any ref but the job's own branch
30
+ # when CHATPANEL_SCM_PUSH=own. Then runs the repository's own pre-push, if there is one.
31
+ mode="\${CHATPANEL_SCM_PUSH:-any}"
32
+ own="\${CHATPANEL_SCM_BRANCH:-}"
33
+ if [ "$mode" = "none" ]; then
34
+ echo "chatpanel: this role has no scm:push grant — the push was refused" >&2
35
+ exit 1
36
+ fi
37
+ if [ "$mode" = "own" ]; then
38
+ while read -r local_ref local_sha remote_ref remote_sha; do
39
+ [ -z "$local_ref" ] && continue
40
+ case "$remote_ref" in
41
+ "refs/heads/$own") ;;
42
+ *) echo "chatpanel: this job may push only its own branch ($own), not \${remote_ref#refs/heads/}" >&2; exit 1 ;;
43
+ esac
44
+ done
45
+ fi
46
+ repo_hook="$(git rev-parse --git-common-dir 2>/dev/null)/hooks/pre-push"
47
+ if [ -x "$repo_hook" ]; then exec "$repo_hook" "$@"; fi
48
+ exit 0
49
+ `;
50
+
51
+ /** The hooks directory, written once; the env that points one process's git at it. */
52
+ export function hookEnv() {
53
+ try {
54
+ mkdirSync(HOOKS_DIR, { recursive: true, mode: 0o700 });
55
+ const p = join(HOOKS_DIR, 'pre-push');
56
+ if (!existsSync(p) || readFileSync(p, 'utf8') !== PRE_PUSH) { writeFileSync(p, PRE_PUSH, { mode: 0o755 }); chmodSync(p, 0o755); }
57
+ } catch { return {}; }
58
+ return { CHATPANEL_GIT_HOOKS_KEY: 'core.hooksPath', CHATPANEL_GIT_HOOKS_VALUE: HOOKS_DIR };
59
+ }
60
+
61
+ /**
62
+ * Merge the hook into a credential env (events/scm-connection.js `credentialEnv`) — both
63
+ * use GIT_CONFIG_COUNT, so the hook's pair is appended at the next index.
64
+ */
65
+ export function withHook(env) {
66
+ const h = hookEnv();
67
+ if (!h.CHATPANEL_GIT_HOOKS_KEY) return env;
68
+ const n = Number(env.GIT_CONFIG_COUNT) || 0;
69
+ const { CHATPANEL_GIT_HOOKS_KEY: k, CHATPANEL_GIT_HOOKS_VALUE: v } = h;
70
+ return { ...env, GIT_CONFIG_COUNT: String(n + 1), [`GIT_CONFIG_KEY_${n}`]: k, [`GIT_CONFIG_VALUE_${n}`]: v };
71
+ }
72
+
73
+ function git(dir, args, { exec = execFile, env = process.env } = {}) {
74
+ return new Promise((resolve) => {
75
+ let done = false;
76
+ const finish = (v) => { if (!done) { done = true; resolve(v); } };
77
+ try {
78
+ exec('git', ['-C', dir, ...args], { timeout: GIT_TIMEOUT_MS, windowsHide: true, maxBuffer: 1 << 22, env }, (err, stdout, stderr) => finish({ ok: !err, out: String(stdout || '').trim(), err: err ? String(stderr || err.message || '').trim() : '' }));
79
+ } catch (e) { finish({ ok: false, out: '', err: String(e?.message || e) }); }
80
+ });
81
+ }
82
+
83
+ /** The repository's default branch as the remote says, else `main`/`master` if either exists, else HEAD. */
84
+ export async function defaultBase(repo, opts) {
85
+ const sym = await git(repo, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], opts);
86
+ if (sym.ok && sym.out) return sym.out; // origin/main
87
+ for (const b of ['main', 'master']) { const r = await git(repo, ['rev-parse', '--verify', '--quiet', `refs/heads/${b}`], opts); if (r.ok) return b; }
88
+ return 'HEAD';
89
+ }
90
+
91
+ /**
92
+ * The worktree for a job — created on first use, reused after. `repo` is a local checkout
93
+ * the person already has (the clone the org's Repo record points at); `base` a branch,
94
+ * tag or commit. Returns `{ path, branch, base, created, repo }` or `{ error }`.
95
+ */
96
+ export async function worktreeFor({ repo, projectId, jobId, base = null, root = WORKTREE_ROOT }, opts = {}) {
97
+ const dir = resolve(String(repo || ''));
98
+ if (!dir || !existsSync(dir)) return { error: `no such repository: ${repo || '(blank)'}` };
99
+ const top = await git(dir, ['rev-parse', '--show-toplevel'], opts);
100
+ if (!top.ok || !top.out) return { error: `${dir} is not a git checkout` };
101
+ const branch = branchFor(projectId, jobId);
102
+ const path = join(root, worktreeDirFor(projectId, jobId));
103
+ // Already there and registered to this repo → reuse.
104
+ const list = await git(top.out, ['worktree', 'list', '--porcelain'], opts);
105
+ const known = list.ok && list.out.split('\n').some((l) => l.startsWith('worktree ') && samePath(l.slice(9), path));
106
+ if (known && existsSync(path)) {
107
+ const cur = await git(path, ['rev-parse', '--abbrev-ref', 'HEAD'], opts);
108
+ return { path, branch: cur.ok ? cur.out : branch, base: base || null, created: false, repo: top.out };
109
+ }
110
+ const from = base || await defaultBase(top.out, opts);
111
+ mkdirSync(resolve(path, '..'), { recursive: true });
112
+ const exists = await git(top.out, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], opts);
113
+ const add = exists.ok
114
+ ? await git(top.out, ['worktree', 'add', path, branch], opts)
115
+ : await git(top.out, ['worktree', 'add', '-b', branch, path, from], opts);
116
+ if (!add.ok) return { error: `git worktree add failed: ${add.err.slice(0, 300)}` };
117
+ return { path, branch, base: from, created: true, repo: top.out };
118
+ }
119
+
120
+ const samePath = (a, b) => { try { return realpathSync(a) === realpathSync(b); } catch { return resolve(a) === resolve(b); } };
121
+
122
+ /** Every worktree the bridge made, from the root directory, with what git says about each. */
123
+ export async function listWorktrees({ root = WORKTREE_ROOT } = {}, opts = {}) {
124
+ const out = [];
125
+ if (!existsSync(root)) return out;
126
+ const { readdirSync } = await import('node:fs');
127
+ for (const p of readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory())) {
128
+ for (const j of readdirSync(join(root, p.name), { withFileTypes: true }).filter((d) => d.isDirectory())) {
129
+ const path = join(root, p.name, j.name);
130
+ const [branch, top] = await Promise.all([git(path, ['rev-parse', '--abbrev-ref', 'HEAD'], opts), git(path, ['rev-parse', '--git-common-dir'], opts)]);
131
+ out.push({ project: p.name, job: j.name, path, branch: branch.ok ? branch.out : null, repo: top.ok ? resolve(path, top.out).replace(/\/\.git$/, '') : null });
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** Remove a job's worktree (`git worktree remove`); the branch stays — it is the record. */
138
+ export async function removeWorktree({ projectId, jobId, root = WORKTREE_ROOT, force = false }, opts = {}) {
139
+ const path = join(root, worktreeDirFor(projectId, jobId));
140
+ if (!existsSync(path)) return { ok: false, error: 'no such worktree' };
141
+ const top = await git(path, ['rev-parse', '--git-common-dir'], opts);
142
+ if (!top.ok) return { ok: false, error: `${path} is not a worktree` };
143
+ const repo = resolve(path, top.out).replace(/\/\.git$/, '');
144
+ const r = await git(repo, ['worktree', 'remove', ...(force ? ['--force'] : []), path], opts);
145
+ return r.ok ? { ok: true, path } : { ok: false, error: r.err.slice(0, 300) };
146
+ }