@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
package/src/update.js CHANGED
@@ -1,216 +1 @@
1
- // In-app updater for the standalone binary.
2
- //
3
- // The bridge is a background service the user never opens, so the EXTENSION
4
- // surfaces "update available" (from /health) and offers a one-click Update that
5
- // calls POST /update. The bridge downloads the new binary, swaps it in, and the
6
- // service relaunches into the new version.
7
- //
8
- // Cross-platform swap + relaunch (users come from anywhere):
9
- // • macOS — atomic rename over the running file; KeepAlive relaunches on exit.
10
- // • Linux — atomic rename; `systemctl --user restart` relaunches.
11
- // • Windows — can't overwrite a running .exe, so we RENAME the running exe aside
12
- // and drop the new one in its place, then a detached helper waits for
13
- // this process to exit (freeing the port) and relaunches it.
14
- //
15
- // No-ops for npx/node installs — npm owns those; only compiled binaries self-update.
16
-
17
- import os from 'node:os';
18
- import path from 'node:path';
19
- import { chmod, rename, mkdir, readFile, writeFile } from 'node:fs/promises';
20
- import { isCompiledBinary } from './env.js';
21
-
22
- /** Started by the gateway from its own binary — never self-updates, never registers a service. */
23
- export function isEmbedded() { return process.env.CHATPANEL_BRIDGE_EMBEDDED === '1'; }
24
-
25
- const REPO = 'chatpanel/chatpanel-bridge';
26
- const LATEST_API = `https://api.github.com/repos/${REPO}/releases/latest`;
27
- const CHECK_EVERY_MS = 6 * 60 * 60 * 1000; // 6h
28
- const CACHE = path.join(os.homedir(), '.chatpanel', 'update-check.json');
29
- const UA = { 'User-Agent': 'chatpanel-bridge-updater' };
30
- // THIS CHECK RUNS INSIDE /health. Every client heartbeat — the extension, the desktop's
31
- // supervisor, the gateway's model list — waits on it. An un-timed fetch to GitHub therefore
32
- // made every one of them wait for a VPN to give up on api.github.com, and the desktop gives a
33
- // health answer 2.5s before calling the bridge dead. So: a short timeout, and after a failure
34
- // no retry for a while — a failed check that was re-attempted on every call kept the stall
35
- // going for as long as the network was bad.
36
- const FETCH_TIMEOUT_MS = Math.max(500, Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS) || 5000);
37
- const RETRY_AFTER_FAILURE_MS = 10 * 60 * 1000; // 10min
38
- let lastFailure = { at: 0, error: '' };
39
-
40
- /** Test seam: forget the last failure so the next unforced check reaches the network. */
41
- export function resetUpdateBackoff() { lastFailure = { at: 0, error: '' }; }
42
-
43
- // Release asset name for THIS platform (matches release-binaries.yml outputs).
44
- // macOS publishes arm64 only; Intel Macs use `npx` (managed → no self-update).
45
- function assetName() {
46
- if (process.platform === 'darwin') return process.arch === 'arm64' ? 'chatpanel-bridge-macos-arm64' : null;
47
- if (process.platform === 'linux') return 'chatpanel-bridge-linux-x64';
48
- if (process.platform === 'win32') return 'chatpanel-bridge-windows-x64.exe';
49
- return null;
50
- }
51
-
52
- function parseVersion(s = '') {
53
- const m = /(\d+(?:\.\d+){0,3})/.exec(s || '');
54
- return m ? m[1] : null;
55
- }
56
- // >0 if a is newer than b.
57
- function cmp(a, b) {
58
- const pa = String(a).split('.').map(Number);
59
- const pb = String(b).split('.').map(Number);
60
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
61
- const d = (pa[i] || 0) - (pb[i] || 0);
62
- if (d) return d > 0 ? 1 : -1;
63
- }
64
- return 0;
65
- }
66
-
67
- async function readCache() {
68
- try {
69
- return JSON.parse(await readFile(CACHE, 'utf8'));
70
- } catch {
71
- return null;
72
- }
73
- }
74
- async function writeCache(obj) {
75
- try {
76
- await mkdir(path.dirname(CACHE), { recursive: true });
77
- await writeFile(CACHE, JSON.stringify(obj));
78
- } catch {
79
- /* best effort */
80
- }
81
- }
82
-
83
- // Returns { current, latest, updateAvailable, mode, canSelfUpdate, assetUrl, npmCommand }.
84
- // mode 'binary' → compiled standalone build (macOS/Linux curl install, or the
85
- // optional Windows .exe). POST /update self-replaces in place.
86
- // mode 'npm' → npx/node install (the default on Windows). The bridge can't
87
- // swap its own files; the extension shows `npmCommand` instead.
88
- // Both report updateAvailable so the user always gets the notice — only the action
89
- // differs. Throttled to CHECK_EVERY_MS unless `force`.
90
- export async function checkForUpdate(current, { force = false } = {}) {
91
- const mode = isCompiledBinary() ? 'binary' : 'npm';
92
- const want = assetName();
93
-
94
- let latest = null;
95
- let assetUrl = null;
96
- // Whether `latest` is a real answer or yesterday's. GitHub's unauthenticated API is 60
97
- // requests/hour per IP, and a developer machine burns that easily — so the fallback below
98
- // is not rare, it fires regularly. Saying WHICH it is matters: acting on a stale "latest"
99
- // is how a forced check reported "already on the latest version" minutes after a newer one
100
- // was published, and how an earlier update landed on a version that was not the newest and
101
- // called it a success.
102
- let stale = false;
103
- let error = '';
104
- const cache = await readCache();
105
- const fallBackToCache = () => {
106
- latest = cache?.latest || null;
107
- assetUrl = cache?.assetUrl || null;
108
- stale = true;
109
- };
110
- if (!force && cache && Date.now() - cache.checkedAt < CHECK_EVERY_MS) {
111
- latest = cache.latest;
112
- assetUrl = cache.assetUrl;
113
- } else if (!force && lastFailure.at && Date.now() - lastFailure.at < RETRY_AFTER_FAILURE_MS) {
114
- // The network said no a moment ago. Asking again on every health poll would make every
115
- // poll as slow as the failure; the answer is what it was, and says so.
116
- error = lastFailure.error;
117
- fallBackToCache();
118
- } else {
119
- // An explicit timer, not AbortSignal.timeout: that one's timer is unref'd, so in a
120
- // process with nothing else to do (a test, a CLI one-shot) the loop can exit before it
121
- // fires and the fetch is neither answered nor abandoned.
122
- const ctl = new AbortController();
123
- const timer = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
124
- try {
125
- const res = await fetch(LATEST_API, {
126
- headers: { Accept: 'application/vnd.github+json', ...UA },
127
- signal: ctl.signal,
128
- });
129
- if (res.ok) {
130
- const data = await res.json();
131
- latest = parseVersion(data.tag_name) || parseVersion(data.name);
132
- assetUrl = want ? (data.assets || []).find((a) => a.name === want)?.browser_download_url || null : null;
133
- await writeCache({ checkedAt: Date.now(), latest, assetUrl });
134
- lastFailure = { at: 0, error: '' };
135
- } else {
136
- error = res.status === 403 ? 'GitHub rate limit (60/hour per IP) — try again later' : `HTTP ${res.status}`;
137
- lastFailure = { at: Date.now(), error };
138
- fallBackToCache();
139
- }
140
- } catch (e) {
141
- error = ctl.signal.aborted
142
- ? `GitHub did not answer within ${Math.round(FETCH_TIMEOUT_MS / 1000)}s`
143
- : e?.message || String(e);
144
- lastFailure = { at: Date.now(), error };
145
- fallBackToCache();
146
- } finally {
147
- clearTimeout(timer);
148
- }
149
- }
150
- const updateAvailable = !!latest && cmp(latest, current) > 0;
151
- // One-click in-place update is only possible for a compiled binary with a
152
- // matching release asset; npm installs update via the command.
153
- const canSelfUpdate = mode === 'binary' && !!assetUrl;
154
- return {
155
- current,
156
- latest,
157
- updateAvailable,
158
- mode,
159
- canSelfUpdate,
160
- assetUrl,
161
- stale,
162
- error,
163
- npmCommand: mode === 'npm' ? 'npm i -g @chatpanel/bridge@latest' : null,
164
- };
165
- }
166
-
167
- // Download the latest binary and swap it in. Does NOT restart — the caller sends
168
- // its HTTP response first, then triggers restartService(). Throws on any failure,
169
- // leaving the running binary untouched.
170
- export async function selfUpdate(current) {
171
- // A bridge the gateway runs from inside its own binary (CHATPANEL_BRIDGE_EMBEDDED=1) has
172
- // `process.execPath` = the GATEWAY binary. Swapping "itself" would overwrite the gateway
173
- // with a bridge — the one update this code must never perform.
174
- if (isEmbedded()) {
175
- throw new Error('This bridge runs inside the ChatPanel Gateway. Update the gateway instead (it carries the bridge).');
176
- }
177
- if (!isCompiledBinary()) {
178
- throw new Error('Self-update applies only to the standalone binary. Update the npm/npx version with npm.');
179
- }
180
- const info = await checkForUpdate(current, { force: true });
181
- // A forced check that fell back to the cache has not checked anything. Acting on it is how
182
- // an update reported success while installing a version that was already superseded, and how
183
- // it later refused with "already on the latest version" while a newer one sat published.
184
- // Say what actually happened and leave the binary alone.
185
- if (info.stale) {
186
- throw new Error(`Could not reach the update server${info.error ? ` (${info.error})` : ''}. `
187
- + 'Refusing to act on a stale check — try again in a few minutes.');
188
- }
189
- if (!info.assetUrl) throw new Error('No downloadable build for this platform — use `npx @chatpanel/bridge`.');
190
- if (!info.updateAvailable) throw new Error(`Already on the latest version (v${current}).`);
191
-
192
- const target = process.execPath; // the running binary's own path
193
- const dir = path.dirname(target);
194
- const tmp = path.join(dir, `.chatpanel-bridge.new-${Date.now()}`);
195
-
196
- const res = await fetch(info.assetUrl, { headers: UA });
197
- if (!res.ok || !res.body) throw new Error(`Download failed (${res.status}).`);
198
- const buf = Buffer.from(await res.arrayBuffer());
199
- if (buf.length < 1_000_000) throw new Error('Downloaded file looks too small — aborting to avoid a broken bridge.');
200
-
201
- await writeFile(tmp, buf);
202
- if (process.platform !== 'win32') await chmod(tmp, 0o755);
203
-
204
- if (process.platform === 'win32') {
205
- // A running .exe can't be overwritten, but it CAN be renamed. Move it aside,
206
- // drop the new one in place; the old (renamed) file is cleaned up after exit.
207
- const aside = path.join(dir, `chatpanel-bridge.old-${Date.now()}.exe`);
208
- await rename(target, aside);
209
- await rename(tmp, target);
210
- } else {
211
- // POSIX: atomic rename over the running file. The live process keeps the old
212
- // inode; the path now points at the new binary.
213
- await rename(tmp, target);
214
- }
215
- return { ok: true, from: current, to: info.latest };
216
- }
1
+ import x from"node:os";import d from"node:path";import{chmod as C,rename as m,mkdir as D,readFile as k,writeFile as b}from"node:fs/promises";import{isCompiledBinary as g}from"./env.js";function S(){return process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"}const v="chatpanel/chatpanel-bridge",M=`https://api.github.com/repos/${v}/releases/latest`,N=360*60*1e3,w=d.join(x.homedir(),".chatpanel","update-check.json"),E={"User-Agent":"chatpanel-bridge-updater"},y=Math.max(500,Number(process.env.CHATPANEL_UPDATE_TIMEOUT_MS)||5e3),P=600*1e3;let l={at:0,error:""};function J(){l={at:0,error:""}}function $(){return process.platform==="darwin"?process.arch==="arm64"?"chatpanel-bridge-macos-arm64":null:process.platform==="linux"?"chatpanel-bridge-linux-x64":process.platform==="win32"?"chatpanel-bridge-windows-x64.exe":null}function A(r=""){const e=/(\d+(?:\.\d+){0,3})/.exec(r||"");return e?e[1]:null}function H(r,e){const n=String(r).split(".").map(Number),o=String(e).split(".").map(Number);for(let t=0;t<Math.max(n.length,o.length);t++){const a=(n[t]||0)-(o[t]||0);if(a)return a>0?1:-1}return 0}async function R(){try{return JSON.parse(await k(w,"utf8"))}catch{return null}}async function B(r){try{await D(d.dirname(w),{recursive:!0}),await b(w,JSON.stringify(r))}catch{}}async function F(r,{force:e=!1}={}){const n=g()?"binary":"npm",o=$();let t=null,a=null,p=!1,s="";const c=await R(),u=()=>{t=c?.latest||null,a=c?.assetUrl||null,p=!0};if(!e&&c&&Date.now()-c.checkedAt<N)t=c.latest,a=c.assetUrl;else if(!e&&l.at&&Date.now()-l.at<P)s=l.error,u();else{const f=new AbortController,U=setTimeout(()=>f.abort(),y);try{const i=await fetch(M,{headers:{Accept:"application/vnd.github+json",...E},signal:f.signal});if(i.ok){const h=await i.json();t=A(h.tag_name)||A(h.name),a=o&&(h.assets||[]).find(_=>_.name===o)?.browser_download_url||null,await B({checkedAt:Date.now(),latest:t,assetUrl:a}),l={at:0,error:""}}else s=i.status===403?"GitHub rate limit (60/hour per IP) — try again later":`HTTP ${i.status}`,l={at:Date.now(),error:s},u()}catch(i){s=f.signal.aborted?`GitHub did not answer within ${Math.round(y/1e3)}s`:i?.message||String(i),l={at:Date.now(),error:s},u()}finally{clearTimeout(U)}}const T=!!t&&H(t,r)>0;return{current:r,latest:t,updateAvailable:T,mode:n,canSelfUpdate:n==="binary"&&!!a,assetUrl:a,stale:p,error:s,npmCommand:n==="npm"?"npm i -g @chatpanel/bridge@latest":null}}async function V(r){if(S())throw new Error("This bridge runs inside the ChatPanel Gateway. Update the gateway instead (it carries the bridge).");if(!g())throw new Error("Self-update applies only to the standalone binary. Update the npm/npx version with npm.");const e=await F(r,{force:!0});if(e.stale)throw new Error(`Could not reach the update server${e.error?` (${e.error})`:""}. Refusing to act on a stale check — try again in a few minutes.`);if(!e.assetUrl)throw new Error("No downloadable build for this platform — use `npx @chatpanel/bridge`.");if(!e.updateAvailable)throw new Error(`Already on the latest version (v${r}).`);const n=process.execPath,o=d.dirname(n),t=d.join(o,`.chatpanel-bridge.new-${Date.now()}`),a=await fetch(e.assetUrl,{headers:E});if(!a.ok||!a.body)throw new Error(`Download failed (${a.status}).`);const p=Buffer.from(await a.arrayBuffer());if(p.length<1e6)throw new Error("Downloaded file looks too small — aborting to avoid a broken bridge.");if(await b(t,p),process.platform!=="win32"&&await C(t,493),process.platform==="win32"){const s=d.join(o,`chatpanel-bridge.old-${Date.now()}.exe`);await m(n,s),await m(t,n)}else await m(t,n);return{ok:!0,from:r,to:e.latest}}export{F as checkForUpdate,S as isEmbedded,J as resetUpdateBackoff,V as selfUpdate};
package/src/workdir.js CHANGED
@@ -1,108 +1 @@
1
- // workdir.js — where an agent's files actually go.
2
- //
3
- // This existed five times with four different answers, none of them told to the user:
4
- //
5
- // claude (CLI) cwd: null → inherits the BRIDGE's cwd, which under launchd is `/`
6
- // claude (SDK) ~
7
- // codex /tmp/chatpanel-codex-scratch
8
- // antigravity /tmp/chatpanel-agy-scratch
9
- // custom cwd: null → `/` again
10
- //
11
- // So "the agent created a file and I cannot find it" was not user error. Depending on
12
- // which agent answered, the file was at the filesystem root, in the home directory, or in
13
- // a temp folder the OS deletes on its own schedule.
14
- //
15
- // One default, and it is neither `/` nor a temp directory: `~/.chatpanel/workspace`.
16
- // Persistent, predictable, obviously ChatPanel's, and somewhere a person can navigate to.
17
- // A user who wants files elsewhere sets Working directory on the agent — which is what
18
- // that field was always for; it just had an invisible and inconsistent fallback.
19
- //
20
- // The path is REPORTED, not just chosen: /health carries it so Settings can show what a
21
- // blank field resolves to, and every run announces it, because a default nobody can see
22
- // is the same problem in a nicer location.
23
-
24
- import { mkdirSync } from 'node:fs';
25
- import os from 'node:os';
26
- import path from 'node:path';
27
-
28
- /** Where files land when an agent has no Working directory set. */
29
- export const DEFAULT_WORKSPACE = path.join(os.homedir(), '.chatpanel', 'workspace');
30
-
31
- /**
32
- * Resolve an agent's working directory, creating it if needed.
33
- *
34
- * Always returns a real, absolute path — never null. Inheriting the bridge's own cwd is
35
- * what produced `/`, and a process spawned at `/` either refuses to write or writes
36
- * somewhere nobody will look.
37
- *
38
- * Creation failure is not fatal: the agent may not need to write at all, and refusing to
39
- * answer a question because a directory could not be made would be a worse failure than
40
- * the one it prevents. The caller still gets the path, and the CLI reports its own error
41
- * if it turns out to matter.
42
- */
43
- export function resolveWorkdir(workingDir) {
44
- const dir = workingDir && String(workingDir).trim()
45
- ? path.resolve(String(workingDir).trim())
46
- : DEFAULT_WORKSPACE;
47
- try {
48
- mkdirSync(dir, { recursive: true });
49
- } catch {
50
- /* reported by whatever tries to write */
51
- }
52
- return dir;
53
- }
54
-
55
- /** True when this run is using the default rather than a directory the user chose. */
56
- export function isDefaultWorkdir(workingDir) {
57
- return !(workingDir && String(workingDir).trim());
58
- }
59
-
60
- /**
61
- * How a path should read in a tool step.
62
- *
63
- * `path.basename` was used here, so a step said "foo.js" and left the user to guess which
64
- * of the four possible roots it meant. Relative-to-cwd says where it is without pasting an
65
- * absolute path into every line; anything OUTSIDE the working directory keeps its full
66
- * path, because that is exactly the case worth noticing.
67
- *
68
- * `impl` is the path flavour, injected so the Windows and POSIX rules can both be tested
69
- * on whichever machine happens to run the suite. The bridge ships to macOS, Linux AND
70
- * Windows, and a display rule that is only ever exercised on one of them is a display rule
71
- * that is wrong on the other two.
72
- */
73
- export function displayPath(filePath, cwd, impl = path) {
74
- const p = String(filePath || '');
75
- if (!p) return '';
76
- if (!cwd || !impl.isAbsolute(p)) return p;
77
- const rel = impl.relative(cwd, p);
78
- if (!rel) return '.';
79
- // Two ways out of the working directory, and Windows only has one of them in common
80
- // with POSIX: `..` for a sibling, and a wholly different ROOT (another drive, a UNC
81
- // share) for which `relative` hands back an absolute path rather than any `..` at all.
82
- if (rel.startsWith('..') || impl.isAbsolute(rel)) return p;
83
- return rel;
84
- }
85
-
86
- /**
87
- * Whether this engine+mode confines writes to the working directory, and how to say so.
88
- *
89
- * Codex's `acceptEdits` maps to `--sandbox workspace-write`, which permits writes ONLY
90
- * inside the cwd. That is correct sandboxing and it is also the most confusing failure the
91
- * bridge produces: the agent reports that it could not write a file, the user checks that
92
- * "auto-edit files" is on, and nothing anywhere mentions that the boundary is a DIRECTORY
93
- * rather than a permission. It bit hardest before there was a sensible default, when a
94
- * blank field meant a temp folder — so every attempt to edit a real project was outside
95
- * the sandbox by construction.
96
- *
97
- * Stated up front rather than detected on failure: a denial does not necessarily fail the
98
- * run (Codex reports it as a failed tool call and carries on), so there is no reliable
99
- * error to attach an explanation to.
100
- */
101
- export function writeScopeNote(engineId, permissionMode, cwd) {
102
- if (engineId !== 'codex') return '';
103
- if (permissionMode === 'bypassPermissions') return '';
104
- if (permissionMode !== 'acceptEdits') {
105
- return 'Codex is read-only in this mode — set Permissions to “auto-edit files” to let it write.';
106
- }
107
- return `Codex may only create or edit files inside ${cwd}. To work on another project, set this agent’s Working directory to it.`;
108
- }
1
+ import{mkdirSync as s}from"node:fs";import u from"node:os";import n from"node:path";const c=n.join(u.homedir(),".chatpanel","workspace");function p(t){const r=t&&String(t).trim()?n.resolve(String(t).trim()):c;try{s(r,{recursive:!0})}catch{}return r}function l(t){return!(t&&String(t).trim())}function m(t,r,e=n){const o=String(t||"");if(!o)return"";if(!r||!e.isAbsolute(o))return o;const i=e.relative(r,o);return i?i.startsWith("..")||e.isAbsolute(i)?o:i:"."}function h(t,r,e){return t!=="codex"||r==="bypassPermissions"?"":r!=="acceptEdits"?"Codex is read-only in this mode — set Permissions to “auto-edit files” to let it write.":`Codex may only create or edit files inside ${e}. To work on another project, set this agent’s Working directory to it.`}export{c as DEFAULT_WORKSPACE,m as displayPath,l as isDefaultWorkdir,p as resolveWorkdir,h as writeScopeNote};
package/src/worktree.js CHANGED
@@ -1,30 +1,4 @@
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
1
+ import{execFile as O}from"node:child_process";import{existsSync as m,mkdirSync as A,writeFileSync as C,chmodSync as v,readFileSync as $,realpathSync as y}from"node:fs";import{join as f,resolve as l}from"node:path";import E from"node:os";import{branchFor as g,worktreeDirFor as H}from"./events/scm-connection.js";const _=process.env.CHATPANEL_WORKTREES||f(E.homedir(),".chatpanel","worktrees"),w=process.env.CHATPANEL_GIT_HOOKS||f(E.homedir(),".chatpanel","git-hooks"),P=6e4,S=`#!/bin/sh
28
2
  # ChatPanel's pre-push — process-scoped through core.hooksPath for one agent run.
29
3
  # Refuses every push when CHATPANEL_SCM_PUSH=none, and any ref but the job's own branch
30
4
  # when CHATPANEL_SCM_PUSH=own. Then runs the repository's own pre-push, if there is one.
@@ -46,101 +20,5 @@ fi
46
20
  repo_hook="$(git rev-parse --git-common-dir 2>/dev/null)/hooks/pre-push"
47
21
  if [ -x "$repo_hook" ]; then exec "$repo_hook" "$@"; fi
48
22
  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
- }
23
+ `;function b(){try{A(w,{recursive:!0,mode:448});const e=f(w,"pre-push");(!m(e)||$(e,"utf8")!==S)&&(C(e,S,{mode:493}),v(e,493))}catch{return{}}return{CHATPANEL_GIT_HOOKS_KEY:"core.hooksPath",CHATPANEL_GIT_HOOKS_VALUE:w}}function D(e){const t=b();if(!t.CHATPANEL_GIT_HOOKS_KEY)return e;const n=Number(e.GIT_CONFIG_COUNT)||0,{CHATPANEL_GIT_HOOKS_KEY:i,CHATPANEL_GIT_HOOKS_VALUE:a}=t;return{...e,GIT_CONFIG_COUNT:String(n+1),[`GIT_CONFIG_KEY_${n}`]:i,[`GIT_CONFIG_VALUE_${n}`]:a}}function u(e,t,{exec:n=O,env:i=process.env}={}){return new Promise(a=>{let o=!1;const s=r=>{o||(o=!0,a(r))};try{n("git",["-C",e,...t],{timeout:P,windowsHide:!0,maxBuffer:1<<22,env:i},(r,c,h)=>s({ok:!r,out:String(c||"").trim(),err:r?String(h||r.message||"").trim():""}))}catch(r){s({ok:!1,out:"",err:String(r?.message||r)})}})}async function N(e,t){const n=await u(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"],t);if(n.ok&&n.out)return n.out;for(const i of["main","master"])if((await u(e,["rev-parse","--verify","--quiet",`refs/heads/${i}`],t)).ok)return i;return"HEAD"}async function M({repo:e,projectId:t,jobId:n,base:i=null,root:a=_},o={}){const s=l(String(e||""));if(!s||!m(s))return{error:`no such repository: ${e||"(blank)"}`};const r=await u(s,["rev-parse","--show-toplevel"],o);if(!r.ok||!r.out)return{error:`${s} is not a git checkout`};const c=g(t,n),h=f(a,H(t,n)),k=await u(r.out,["worktree","list","--porcelain"],o);if(k.ok&&k.out.split(`
24
+ `).some(p=>p.startsWith("worktree ")&&x(p.slice(9),h))&&m(h)){const p=await u(h,["rev-parse","--abbrev-ref","HEAD"],o);return{path:h,branch:p.ok?p.out:c,base:i||null,created:!1,repo:r.out}}const d=i||await N(r.out,o);A(l(h,".."),{recursive:!0});const T=(await u(r.out,["rev-parse","--verify","--quiet",`refs/heads/${c}`],o)).ok?await u(r.out,["worktree","add",h,c],o):await u(r.out,["worktree","add","-b",c,h,d],o);return T.ok?{path:h,branch:c,base:d,created:!0,repo:r.out}:{error:`git worktree add failed: ${T.err.slice(0,300)}`}}const x=(e,t)=>{try{return y(e)===y(t)}catch{return l(e)===l(t)}};async function W({root:e=_}={},t={}){const n=[];if(!m(e))return n;const{readdirSync:i}=await import("node:fs");for(const a of i(e,{withFileTypes:!0}).filter(o=>o.isDirectory()))for(const o of i(f(e,a.name),{withFileTypes:!0}).filter(s=>s.isDirectory())){const s=f(e,a.name,o.name),[r,c]=await Promise.all([u(s,["rev-parse","--abbrev-ref","HEAD"],t),u(s,["rev-parse","--git-common-dir"],t)]);n.push({project:a.name,job:o.name,path:s,branch:r.ok?r.out:null,repo:c.ok?l(s,c.out).replace(/\/\.git$/,""):null})}return n}async function j({projectId:e,jobId:t,root:n=_,force:i=!1},a={}){const o=f(n,H(e,t));if(!m(o))return{ok:!1,error:"no such worktree"};const s=await u(o,["rev-parse","--git-common-dir"],a);if(!s.ok)return{ok:!1,error:`${o} is not a worktree`};const r=l(o,s.out).replace(/\/\.git$/,""),c=await u(r,["worktree","remove",...i?["--force"]:[],o],a);return c.ok?{ok:!0,path:o}:{ok:!1,error:c.err.slice(0,300)}}export{w as HOOKS_DIR,_ as WORKTREE_ROOT,N as defaultBase,b as hookEnv,W as listWorktrees,j as removeWorktree,D as withHook,M as worktreeFor};