@peer2peer/codex-bridge 0.1.0 → 0.1.1

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/dist/hook.js CHANGED
@@ -16,7 +16,8 @@
16
16
  // must exist in the repo.
17
17
  // Failing open is safe here (the hold rule lives in the bridge, and no
18
18
  // bridge means no messages): any error prints nothing and exits 0.
19
- import { isAbsolute } from "node:path";
19
+ import { lstatSync, readFileSync, statSync } from "node:fs";
20
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
20
21
  import { boundaryRefusal, editedFiles, MAX_COMMAND_PATHS, mutatingP2PVerb, namesP2PCli, resolveLike, shellPaths, touchesSecrets } from "./lib.js";
21
22
  import { ancestors, ask, findEntry, readEntries } from "./ipc.js";
22
23
  const SHELL_TOOLS = /^(bash|shell|local_shell|exec_command|unified_exec|container\.exec|powershell|write_stdin)$/i;
@@ -48,32 +49,129 @@ export function guard(toolName, input, binNames = [], ownSid) {
48
49
  return `Refused by Peer2Peer: ${boundary}.`;
49
50
  return null;
50
51
  }
52
+ /** Whether `d` is a bare git repository (projects.ts isBareRepo: HEAD, objects/ and refs/, or `bare = true`). */
53
+ function isBareRepo(d) {
54
+ if (basename(d) === ".git")
55
+ return false;
56
+ const st = (p) => {
57
+ try {
58
+ return statSync(p);
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ };
64
+ if (st(join(d, "HEAD"))?.isFile() && st(join(d, "objects"))?.isDirectory() && st(join(d, "refs"))?.isDirectory())
65
+ return true;
66
+ try {
67
+ const c = join(d, "config");
68
+ const cs = st(c);
69
+ return !!cs && cs.isFile() && cs.size <= 256 * 1024 && /^\s*bare\s*=\s*true\s*$/im.test(readFileSync(c, "utf8"));
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+ /**
76
+ * The marker of the nearest folder at or above each path that holds a `.git` (any kind), a
77
+ * `.p2p-private`, or is a bare repository (`<that folder>/.git` then), and each of `maybe` that
78
+ * exists: the bridge binds them too, so a shared folder above never covers a repository once its
79
+ * files are gone (projects.ts namedStop). Metadata only; git is never run. The same rules as the
80
+ * Claude mod's MARKER_PROBE.
81
+ */
82
+ export function markerPaths(paths, maybe = []) {
83
+ const out = new Set();
84
+ const exists = (p) => {
85
+ try {
86
+ statSync(p);
87
+ return true;
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ };
93
+ const there = (p) => {
94
+ try {
95
+ lstatSync(p);
96
+ return true;
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ };
102
+ for (const m of maybe)
103
+ if (isAbsolute(m) && exists(m))
104
+ out.add(m);
105
+ for (const p of new Set([...paths, ...maybe])) {
106
+ if (!isAbsolute(p))
107
+ continue;
108
+ let cur = resolve(p);
109
+ for (let i = 0; i < 4096; i++) {
110
+ try {
111
+ if (!statSync(cur).isDirectory())
112
+ cur = dirname(cur);
113
+ break;
114
+ }
115
+ catch {
116
+ const up = dirname(cur);
117
+ if (up === cur)
118
+ break;
119
+ cur = up;
120
+ }
121
+ }
122
+ for (let i = 0; i < 4096; i++) {
123
+ if (there(join(cur, ".git")) || isBareRepo(cur)) {
124
+ out.add(join(cur, ".git"));
125
+ break;
126
+ }
127
+ if (there(join(cur, ".p2p-private"))) {
128
+ out.add(join(cur, ".p2p-private"));
129
+ break;
130
+ }
131
+ const up = dirname(cur);
132
+ if (up === cur)
133
+ break;
134
+ cur = up;
135
+ }
136
+ }
137
+ return [...out];
138
+ }
51
139
  /**
52
140
  * The paths a tool call names outside its folder (a shell command's absolute, ~ and .. paths; the
53
141
  * files an apply_patch or edit names), resolved: the bridge binds each one's project (projects.ts).
142
+ * Plus the repository marker each one (and the cwd) is under, and a program's word that names a
143
+ * file that exists (markerPaths).
54
144
  */
55
145
  export function touchedPaths(toolName, input, cwd, home) {
56
146
  const out = [];
57
- let over = false;
147
+ const maybe = [];
148
+ // Why it is private (the CLI's OverWhy words): a path that can't be placed, or too many.
149
+ const why = new Set();
58
150
  if (SHELL_TOOLS.test(toolName)) {
59
151
  // No folder to resolve against: what it names can't be placed, so private.
60
152
  if (!cwd)
61
- over = true;
153
+ why.add("unresolved");
62
154
  else {
63
155
  const r = shellPaths(commandOf(input), cwd, home);
64
156
  out.push(...r.paths);
65
- over ||= r.over;
157
+ maybe.push(...(r.maybe ?? []));
158
+ for (const w of r.why ?? [])
159
+ why.add(w);
66
160
  }
67
161
  }
68
162
  for (const f of editedFiles(toolName, input)) {
69
163
  if (cwd || isAbsolute(f))
70
164
  out.push(resolveLike(cwd ?? "/", f));
71
165
  else
72
- over = true;
166
+ why.add("unresolved");
73
167
  }
74
- if (out.length > MAX_COMMAND_PATHS)
75
- over = true;
76
- return { paths: out.slice(0, MAX_COMMAND_PATHS), over };
168
+ // (The cwd's own marker only beside other paths: a call that names none needn't reach the bridge, and
169
+ // the CLI never covers a session folder that is gone from above: projects.ts projectOf.)
170
+ const extras = out.length + maybe.length > 0 ? markerPaths([...(cwd && isAbsolute(cwd) ? [cwd] : []), ...out], maybe) : [];
171
+ const all = [...new Set([...out, ...extras])];
172
+ if (all.length > MAX_COMMAND_PATHS)
173
+ why.add("folders");
174
+ return { paths: all.slice(0, MAX_COMMAND_PATHS), over: why.size > 0, ...(why.size > 0 ? { why: [...why] } : {}) };
77
175
  }
78
176
  /** Runs one hook: the JSON to print (empty for nothing). */
79
177
  export async function runHook(event, stdin, deps) {
@@ -109,7 +207,7 @@ export async function runHook(event, stdin, deps) {
109
207
  const t = entry ? touchedPaths(String(payload.tool_name ?? ""), payload.tool_input, cwd, deps.homeDir) : { paths: [], over: false };
110
208
  if (entry && (t.paths.length > 0 || t.over)) {
111
209
  // The bridge must hear it before the call runs: if it can't be told, the call doesn't run.
112
- const told = await ask(entry.sock, { op: "hook", report: { event: "PreToolUse", ...(sessionId ? { sessionId } : {}), ...(cwd ? { cwd } : {}), mode: {}, dirs: t.paths, ...(t.over ? { over: true } : {}) } }, 8_000)
210
+ const told = await ask(entry.sock, { op: "hook", report: { event: "PreToolUse", ...(sessionId ? { sessionId } : {}), ...(cwd ? { cwd } : {}), mode: {}, dirs: t.paths, ...(t.over ? { over: true, overWhy: t.why ?? [] } : {}) } }, 8_000)
113
211
  .then((r) => r?.ok === true)
114
212
  .catch(() => false);
115
213
  if (!told) {
package/dist/lib.d.ts CHANGED
@@ -75,6 +75,7 @@ export type Target = {
75
75
  } | {
76
76
  kind: "refused";
77
77
  reason: string;
78
+ code?: "no-label";
78
79
  };
79
80
  /**
80
81
  * What `--to` the CLI gets for a model's `to`. Only a `p2p:` address or a
@@ -91,11 +92,27 @@ export declare function eventAddress(event: {
91
92
  from: {
92
93
  userId: string;
93
94
  address: string;
95
+ self?: boolean;
94
96
  };
95
97
  own: string;
96
98
  sid: string;
97
99
  ref: string;
100
+ fromRef?: unknown;
98
101
  }, peers: readonly PeerRow[]): string;
102
+ /**
103
+ * Where a delivery notice to a received message goes: a peer's own session by its ref, else the peer;
104
+ * one of this user's own sessions only by the sending session's ref (this device's record), else
105
+ * nowhere ("": never this session's own address, never the bare address).
106
+ */
107
+ export declare function replyToOf(event: {
108
+ from: {
109
+ userId: string;
110
+ self?: boolean;
111
+ };
112
+ own: string;
113
+ ref: string;
114
+ fromRef?: unknown;
115
+ }): string;
99
116
  /**
100
117
  * What the bridge knows of this Codex session's own mode, from Codex itself
101
118
  * (never from a peer). Every field may be unknown (undefined or null):
@@ -170,6 +187,7 @@ export declare function capHeld<T extends {
170
187
  from: {
171
188
  userId: string;
172
189
  };
190
+ bucket?: string;
173
191
  }>(list: readonly T[]): T[];
174
192
  /** Turns peers may start: per sender and in all, in a sliding window. */
175
193
  export declare const TURN_WINDOW_MS: number;
@@ -306,6 +324,8 @@ export declare function screenMessage(o: {
306
324
  mode: ModeClass;
307
325
  autoDeliver: AutoDeliver;
308
326
  refused?: string | undefined;
327
+ ownAgent?: boolean;
328
+ elsewhere?: boolean;
309
329
  }): Screen;
310
330
  /** What a tool call's `_meta["x-codex-turn-metadata"]` says: the thread and the sandbox. */
311
331
  export declare function fromToolMeta(meta: unknown): {
@@ -328,24 +348,68 @@ export declare const LITERAL = "\uE000";
328
348
  * parts join into one word (`''x1` and `"x"1` are `x1`), backslashes escape, `$'…'` is
329
349
  * ANSI-C quoted, and `;`, `|`, `&`, `(`, `)`, `<`, `>` and newlines separate words. Expansions
330
350
  * (`$X`, `$(…)`, backticks) stay as text. Linear in the length, with no cap on the number of words
331
- * (a cap would let padding hide what follows it). Best effort: no aliases, no globbing.
351
+ * (a cap would let padding hide what follows it). Best effort: no aliases, no globbing. With
352
+ * `starts`: the index of each word that begins a simple command (the first word, and the first
353
+ * after an unquoted `;`, `|`, `&`, `(`, `)` or newline).
332
354
  */
333
- export declare function shellTokens(command: string, markLiteral?: boolean): string[];
355
+ export declare function shellTokens(command: string, markLiteral?: boolean, substs?: string[], starts?: Set<number>): string[];
334
356
  /** `p` made absolute against `cwd` (POSIX or Windows separators), `.` and `..` resolved. Linear: no regex over the input. */
335
357
  export declare function resolveLike(cwd: string, p: string): string;
336
358
  /** At most this many folders one command may name; past it the session is private (`over`). */
337
359
  export declare const MAX_COMMAND_PATHS = 256;
360
+ /** Why a command makes a session private: a path it couldn't resolve, or more folders than one command may name. */
361
+ export type PathsOverWhy = 'unresolved' | 'folders';
338
362
  /**
339
- * The folders a shell command names: absolute, `~` and relative paths (anything with a separator,
340
- * or starting with `.` or `~`), an option's value (`--file=/x`) too, each resolved (relative ones
341
- * against `cwd`, a file to its folder, `$HOME`/`${HOME}` and `$PWD`/`${PWD}` expanded). A path
342
- * built any other way (`$X/y`, `$(…)`, backticks) can't be resolved, so the session is `over`
343
- * (private), and so it is past MAX_COMMAND_PATHS. URLs are not paths.
363
+ * What a front end knows of the model's shell, for shellPaths: variables whose value it knows (as
364
+ * the shell sees them), and `untrusted` once the session touched the files Claude Code runs before
365
+ * each command (then no variable is known).
366
+ */
367
+ export interface ShellContext {
368
+ vars?: Readonly<Record<string, string | undefined>>;
369
+ untrusted?: boolean;
370
+ }
371
+ /**
372
+ * What shellPaths found. `maybe`: what the words it read as a program (sed's script, jq's filter)
373
+ * would name if they were paths: the front end binds each one that exists (a file named like a
374
+ * program is still that file).
344
375
  */
345
- export declare function shellPaths(command: string, cwd: string, home?: string): {
376
+ export interface ShellPaths {
346
377
  paths: string[];
347
378
  over: boolean;
348
- };
379
+ why?: PathsOverWhy[];
380
+ sticky?: true;
381
+ maybe?: string[];
382
+ }
383
+ /**
384
+ * The paths a shell command names: absolute, `~` and relative paths (anything with a separator,
385
+ * or starting with `.` or `~`), an option's value (`--file=/x`) too, each resolved (relative ones
386
+ * against `cwd` and every folder the command moves to) and the absolute paths written inside a
387
+ * program or quoted phrase. A path is passed as written (`/src/secret.repo` stays itself): the CLI
388
+ * maps a file to its folder.
389
+ *
390
+ * The folders it moves to, read per simple command: `cd`/`pushd`/`chdir` (none: `$HOME`), `git -C`,
391
+ * `make -C`, `tar -C`, `env -C`, `sudo -D` and the like. Each binds, and relative paths resolve
392
+ * against each one (and against the ones before it). One it can't place (`cd -`, `cd $X`, `popd`
393
+ * with no `pushd`) is `unresolved`.
394
+ *
395
+ * Variables expand only when the front end knows their value as the shell sees it: `$HOME`,
396
+ * `$PWD`, and `ctx.vars` (the mod's `$CLAUDE_JOB_DIR`), and only when the command doesn't set
397
+ * them itself (`HOME=…`, `export`, `read`, `cd` for `$PWD`, eval, source). Any other expansion
398
+ * (`$X/y`, `$(…)/y`, backticks) in a path's first segment can't be resolved: the session is `over`
399
+ * (private), `why` `unresolved`; further in, the folder before it binds. A bare `$X` or `$(…)`
400
+ * names no path. A `$(…)` or backtick command is read for its own paths.
401
+ *
402
+ * A program's text (programWords: only for a simple command's command word) isn't a path, unless
403
+ * it has a `..` segment or a shell expansion; what it would name otherwise is `maybe`.
404
+ *
405
+ * Device files (`/dev/null`, `/dev/fd/1`) are skipped. A command that could delete a repository's
406
+ * `.git` or `.p2p-private` without naming it (find -delete, xargs, dotglob, inline code) also
407
+ * names `<folder>/.git` for each folder, so a shared folder above never covers it afterwards
408
+ * (projects.ts projectOf). Past MAX_COMMAND_PATHS: `over`, `why` `folders`. URLs are not paths.
409
+ * `sticky`: the command touched the files Claude Code runs before each command (pass `untrusted`
410
+ * from then on).
411
+ */
412
+ export declare function shellPaths(command: string, cwd: string, home?: string, ctx?: ShellContext, depth?: number): ShellPaths;
349
413
  /** Whether a command runs interpreter code given inline, or anything under a pseudo-terminal wrapper (by its words: linear). */
350
414
  export declare function hidesCommand(command: string): 'interpreter' | 'pty' | null;
351
415
  /** Commands naming p2p longer than this are refused unread. */