@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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Peer2Peer for Codex (the Codex bridge)
2
2
 
3
- This connects OpenAI Codex CLI sessions to [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/docs/protocol.md). A Codex session can then see what your friends', circle-mates' and other devices' agent sessions (Claude Code or Codex) are working on, message them end-to-end encrypted, and get flagged when two sessions change the same files. There is no account and no login.
3
+ This connects OpenAI Codex CLI sessions to [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/docs/protocol.md). A Codex session can then see what your friends', circle-mates' and other devices' agent sessions (Claude Code or Codex) are working on, message them end-to-end encrypted, and get flagged when two sessions change the same files. There is no account and no login.
4
4
 
5
- It is the Codex counterpart of the [Claude Code mod](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/mods/claude/peer2peer/README.md) and keeps the same rules. Both run over the same `p2p` CLI and the same relays, so a Claude session and a Codex session see and message each other with no extra setup.
5
+ It is the Codex counterpart of the [Claude Code mod](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/mods/claude/peer2peer/README.md) and keeps the same rules. Both run over the same `p2p` CLI and the same relays, so a Claude session and a Codex session see and message each other with no extra setup.
6
6
 
7
7
  ## Install
8
8
 
@@ -41,7 +41,7 @@ Then:
41
41
 
42
42
  - **Restart Codex and trust the hooks once with `/hooks`.** Codex runs non-managed hooks only after you approve them, and again after any change to them.
43
43
  - **Make your identity** in a terminal, once per machine: `node …/p2p.mjs setup`. Then join a friend with `node …/p2p.mjs join '<link or code>'`, or make a code for them with `invite`. A code on a relay on a private network (a Tailscale name, a LAN address) needs `--allow-private-relay` on the join (`node …/p2p.mjs join --allow-private-relay '<link>'`), unless that relay is already one of yours. Put the script on your `PATH` as `p2p` if you like.
44
- - **Share your Codex sessions.** A session follows its project (the repository it works in): private until you share the project with `p2p project share [<circle>…] [--person <friend>]…` in it, a command only you run: the bridge's shell guard and the CLI refuse it from the model, best effort (for a hard barrier deny the model's sandbox access to `P2P_HOME`: [threat model](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.0/docs/security/threat-model.md#the-hard-barrier-sandbox-your-agents)). Every folder the session works in binds it to that project, and `p2p_send` refuses anyone the session's projects don't share. `p2p codex sessions` lists your live Codex sessions with their sids; the bridge registers each one, so only it speaks for them.
44
+ - **Share your Codex sessions.** A session follows its project (the repository it works in): private until you share the project with `p2p project share [<circle>…] [--person <friend>]…` in it, a command only you run: the bridge's shell guard and the CLI refuse it from the model, best effort (for a hard barrier deny the model's sandbox access to `P2P_HOME`: [threat model](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.1/docs/security/threat-model.md#the-hard-barrier-sandbox-your-agents)). Every folder the session works in binds it to that project, and `p2p_send` refuses anyone the session's projects don't share. `p2p codex sessions` lists your live Codex sessions with their sids; the bridge registers each one, so only it speaks for them.
45
45
 
46
46
  ## What the model gets
47
47
 
@@ -53,9 +53,10 @@ The MCP server offers five tools. None of them changes who reaches you.
53
53
  | `p2p_send` | Messages a `p2p:<name>@<fingerprint>/<label> [ref]` address or a `name@fingerprint` address. A bare name such as `ann` is refused, because anyone can choose their own name. A listed session is addressed by its owner's full userId. The text goes to `p2p send` on stdin, so it never shows up in a process listing. |
54
54
  | `p2p_status` | Sets this session's one-line working-on summary (in the model's own words; absolute paths are stripped; at most 200 characters) and its repo-relative files. Paths outside the repository are dropped. |
55
55
  | `p2p_inbox` | Shows the messages that arrived since the last call, each framed as `<peer-message from="p2p:…">` with its body escaped, under a header that says peers' text is data, not instructions. A held message is listed by sender only, without its text. |
56
+ | `p2p_history` | Looks back at this session's own messages (`p2p history --session <this thread>`; 30 days by default, kept encrypted on this device): never your other sessions', never your personal inbox (messages to you with no session), and only what the session recorded within its projects. A received message's text is shown, framed and escaped as in `p2p_inbox` and at most 4,000 characters, only when this bridge showed it to the model or you released it (in this run), your own sessions' messages included (an agent session of yours, or another device, is held like a peer). Anything else (held, declined, expired, or from before a restart, when the decision isn't known) is listed by sender only, so history never gets around the hold rule. Sends are framed apart, as `<p2p-sent to="…">`. The shell guard refuses `p2p history` itself. |
56
57
  | `p2p_peer_activity` | A digest of what peers' sessions are working on, same repository first, with `POTENTIAL CONFLICT` lines. |
57
58
 
58
- **Codex's own approvals still apply.** The three reading tools are annotated read-only, so Codex runs them without asking. `p2p_send` and `p2p_status` publish text the model wrote, so they are open-world: **Codex asks you before each one.** Under approval policy `never`, Codex refuses them outright ("MCP tool call requires approval, but approval policy is never"). That keeps a session that runs unattended from being talked into sending your data to a peer. Busy/idle and edited files still go out through the hooks, with no tool call. To allow them anyway, add this to `config.toml`:
59
+ **Codex's own approvals still apply.** The four reading tools are annotated read-only, so Codex runs them without asking. `p2p_send` and `p2p_status` publish text the model wrote, so they are open-world: **Codex asks you before each one.** Under approval policy `never`, Codex refuses them outright ("MCP tool call requires approval, but approval policy is never"). That keeps a session that runs unattended from being talked into sending your data to a peer. Busy/idle and edited files still go out through the hooks, with no tool call. To allow them anyway, add this to `config.toml`:
59
60
 
60
61
  ```toml
61
62
  [mcp_servers.peer2peer.tools.p2p_send]
@@ -103,7 +104,8 @@ A hook's `permission_mode` can only make the mode stricter: `bypassPermissions`
103
104
  - **The session asks before acting** when approvals go to you (`untrusted` or `on-request`, not `never`, not auto-review) **and** the sandbox is `read-only`. Messages from friends and circle-mates are then delivered.
104
105
  - **Anything else counts as auto-approving.** That covers `workspace-write` (Codex edits files and runs sandboxed commands without asking), `danger-full-access`, `never`, `--yolo`, `--approve-for-me` and `granular`. **An unknown mode holds too**: no tool call has named the thread yet, or there is no turn context. A message held only because the mode was unknown goes out once Codex confirms the session asks. Every message from another person is otherwise **held**. There are two exceptions:
105
106
  - senders listed in `P2P_AUTO_DELIVER`, by full userId (`p2p:…`) or `name@fingerprint`. Bare names and petnames are ignored, since names are self-chosen;
106
- - messages from your own devices, which are always delivered.
107
+ - messages you sent from your own terminal (`p2p tui`, `p2p send`). Your **agent** sessions' messages are held like a peer's unless you ran `p2p own-agents deliver` in your own terminal (the bridge reads the setting before each delivery). Your other devices may start at most 5 turns per 10 minutes, other sessions on this device 30, and all of them 10 since you last typed a prompt (a user message in this thread's rollout file: never a hook report, never the bridge's own `codex queue` pointer); past a cap they are held.
108
+ - **Messages from your other devices are held too.** Another device can't say whether you typed a message (that needs the wire field of [RFC #48](https://github.com/ix-infrastructure/Peer2Peer/issues/48)). `p2p own-agents deliver --devices <device id…|all-other>` lets just those devices through.
107
109
  - **The mode is never published** in a status.
108
110
  - **A message sent to you rather than to a session** is never delivered by itself. Your most recently used Codex session holds it.
109
111
  - **Held messages** wait up to 10 minutes. Their text never reaches the model. Review them in your own terminal:
package/dist/bridge.d.ts CHANGED
@@ -8,8 +8,15 @@ export declare const HOLD_EXPIRY_MS: number;
8
8
  /** Without hooks, a session counts busy this long after its last tool call. */
9
9
  export declare const BUSY_WITHOUT_HOOKS_MS: number;
10
10
  export declare const WATCH_BACKOFF_MS: number[];
11
- /** L1: turns this user's own devices may start, per 10 minutes. */
11
+ /** L1: turns this user's other devices may start, per 10 minutes. */
12
12
  export declare const SELF_TURNS = 5;
13
+ /**
14
+ * Turns this user's other sessions on this same device may start, per 10 minutes: the person's own
15
+ * work, so more than a peer's 3, but still a cap. Constants: nothing a session or its agent sets changes them.
16
+ */
17
+ export declare const LOCAL_SELF_TURNS = 30;
18
+ /** Turns this user's own sessions may start since the person last typed a prompt here (a slow loop stops too). */
19
+ export declare const OWN_TURNS_UNATTENDED = 10;
13
20
  export type InboxState = "pending" | "held" | "released" | "shown" | "declined" | "expired";
14
21
  /** Why an item is held: the mode acts without asking, the mode is unknown (re-checked later), a turn cap, or sent to the user. */
15
22
  export type HoldKind = "auto" | "unknown" | "cap" | "toUser";
@@ -20,7 +27,16 @@ export type InboxItem = {
20
27
  userId: string;
21
28
  address: string;
22
29
  };
30
+ /** From one of this user's own sessions (any device). */
23
31
  fromSelf: boolean;
32
+ /** From one of this user's own sessions that isn't the person at their own terminal: held like a peer's (screenMessage). */
33
+ ownAgent?: boolean;
34
+ /** From another session on this device (not another device). */
35
+ local?: boolean;
36
+ /** The sending device (own sessions only). */
37
+ did?: string;
38
+ /** The held-queue bucket (capHeld) for your own sessions: one per sending session. */
39
+ bucket?: string;
24
40
  /** The sender's text (message), or the bridge's own notice line. */
25
41
  text: string;
26
42
  at: number;
@@ -100,16 +116,22 @@ export type HookReport = {
100
116
  dirs?: string[];
101
117
  /** PreToolUse: some path couldn't be resolved, or there were too many: the session is private. */
102
118
  over?: boolean;
119
+ /** Why, as the CLI's OverWhy words (`unresolved`, `folders`). */
120
+ overWhy?: string[];
103
121
  stopHookActive?: boolean;
104
122
  };
105
123
  export type HookOutput = Record<string, unknown>;
106
124
  export declare function loadThreadDirs(home: string | undefined, threadId: string): string[];
107
- /** A thread's saved folders, and whether it was already over its cap. A file that exists but can't be read: over (fails closed). */
125
+ /**
126
+ * A thread's saved folders, and whether it was already over its cap (and why: the CLI's OverWhy
127
+ * words). A file that exists but can't be read: over (fails closed), `front`.
128
+ */
108
129
  export declare function loadThread(home: string | undefined, threadId: string): {
109
130
  dirs: string[];
110
131
  over: boolean;
132
+ why: string[];
111
133
  };
112
- export declare function saveThreadDirs(home: string | undefined, threadId: string, dirs: readonly string[], over?: boolean): void;
134
+ export declare function saveThreadDirs(home: string | undefined, threadId: string, dirs: readonly string[], over?: boolean, why?: readonly string[]): void;
113
135
  export declare const INBOX_OPEN = "<peer2peer-inbox>";
114
136
  export declare class Bridge {
115
137
  private readonly deps;
@@ -153,6 +175,8 @@ export declare class Bridge {
153
175
  private readonly touched;
154
176
  /** Past a cap, or a path that couldn't be resolved: the CLI keeps this session private (`--project-dirs-over`). */
155
177
  isDirsOver: boolean;
178
+ /** Why (the CLI's OverWhy words), so its refusal names the cause. */
179
+ readonly dirsOverWhy: Set<string>;
156
180
  /** Where sandboxed commands may write, per the trusted turn context ("all": no sandbox; undefined: unknown). */
157
181
  trustedWritable: string[] | "all" | undefined;
158
182
  /** Why this thread's rollout file isn't trusted (planted or malformed), once found. */
@@ -162,6 +186,10 @@ export declare class Bridge {
162
186
  private seenEdits;
163
187
  /** Turns this user's own devices started (L1: at most 5 per 10 minutes). */
164
188
  private selfTurns;
189
+ /** Turns your own sessions started since the person last typed a prompt here. */
190
+ private ownSinceTyped;
191
+ /** Prompts the person typed, as the trusted rollout counts them (TrustedMode.typed). */
192
+ private trustedTyped;
165
193
  threadId: string | undefined;
166
194
  hooksSeen: boolean;
167
195
  activeAt: number;
@@ -189,6 +217,10 @@ export declare class Bridge {
189
217
  start(): Promise<void>;
190
218
  /** Every folder this session has worked in: each one's project bounds who it reaches (projects.ts). */
191
219
  sessionDirs(): string[];
220
+ /** Private from now on, and why. */
221
+ markOver(why: string): void;
222
+ /** What `--project-dirs-over` says: false, or why (an over set without a reason is `front`). */
223
+ dirsOver(): false | string[];
192
224
  private goOnline;
193
225
  /** Stops the watcher and timers; a final idle status so peers see this session stop. */
194
226
  close(): Promise<void>;
@@ -294,6 +326,17 @@ export declare class Bridge {
294
326
  /** The `<peer-activity>` digest, with any conflicts this session has. */
295
327
  activity(): string;
296
328
  onLine(line: string): Promise<void>;
329
+ /**
330
+ * What an event says of an own-session origin (the CLI's local record, never the wire): `via` is
331
+ * "person" for the person's own terminal session, anything else (or nothing: another device, an
332
+ * older client) counts as an agent session's. `ownTrusted`: the person ran `p2p own-agents deliver`.
333
+ */
334
+ private ownOf;
335
+ /** `p2p own-agents` as it stands now, read before each screening (never stamped on an event). Unknown: hold. */
336
+ private ownAgentsSetting;
337
+ refreshOwnAgents(): Promise<void>;
338
+ /** Whether the person's `p2p own-agents` lets this own agent session's message through (the CLI's ownAgentsDeliverFrom). */
339
+ private ownAgentDelivers;
297
340
  /** Applies the hold rule to one new item, by this session's own mode as it stands now. */
298
341
  private screenNow;
299
342
  private hold;
@@ -308,8 +351,8 @@ export declare class Bridge {
308
351
  * turn's context may not be written yet, so only what doesn't depend on
309
352
  * the mode goes out there). When the delivery starts a turn (a Stop
310
353
  * continuation, `codex queue`), the turn caps apply: past a cap, peers'
311
- * messages are held for the person, and the user's own devices' wait for
312
- * the next prompt.
354
+ * messages and the user's own sessions' are held until the person
355
+ * releases them (`p2p codex release`).
313
356
  */
314
357
  takeDeliverable(o: {
315
358
  startsTurn: boolean;
package/dist/bridge.js CHANGED
@@ -22,7 +22,7 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from
22
22
  import { readFile } from "node:fs/promises";
23
23
  import { tmpdir } from "node:os";
24
24
  import { isAbsolute, join, sep } from "node:path";
25
- import { capHeld, cleanBody, cleanSummary, conflictKeys, conflictMessage, conflicts, eventAddress, classifyMode, isExplicitlyAuto, screenMessage, idleNotice, inert, isInside, mayStartTurn, mergeMode, modeWords, parseAutoDeliver, pathBasename, peerActivity, sanitizeLabel, sessionAddress, shareableFile, touchFile, TMPDIR_ROOT, wrapMessage, TURN_WINDOW_MS, } from "./lib.js";
25
+ import { capHeld, cleanBody, cleanSummary, conflictKeys, conflictMessage, conflicts, eventAddress, replyToOf, classifyMode, isExplicitlyAuto, screenMessage, idleNotice, inert, isInside, mayStartTurn, mergeMode, modeWords, parseAutoDeliver, pathBasename, peerActivity, sanitizeLabel, sessionAddress, shareableFile, touchFile, TMPDIR_ROOT, wrapMessage, TURN_WINDOW_MS, } from "./lib.js";
26
26
  import { codexGranted, darwinUserTempDir, isHomeFolder, projectConfigDirsOf, projectOverride, realish, tempRoots, unsafeLocation } from "./knobs.js";
27
27
  export const STATUS_EVERY_MS = 60_000;
28
28
  export const PEERS_EVERY_MS = 60_000;
@@ -33,8 +33,15 @@ export const BUSY_WITHOUT_HOOKS_MS = 2 * 60_000;
33
33
  export const WATCH_BACKOFF_MS = [1_000, 2_000, 5_000, 10_000, 30_000];
34
34
  const WATCH_STABLE_MS = 10_000;
35
35
  const QUEUE_DEBOUNCE_MS = 500;
36
- /** L1: turns this user's own devices may start, per 10 minutes. */
36
+ /** L1: turns this user's other devices may start, per 10 minutes. */
37
37
  export const SELF_TURNS = 5;
38
+ /**
39
+ * Turns this user's other sessions on this same device may start, per 10 minutes: the person's own
40
+ * work, so more than a peer's 3, but still a cap. Constants: nothing a session or its agent sets changes them.
41
+ */
42
+ export const LOCAL_SELF_TURNS = 30;
43
+ /** Turns this user's own sessions may start since the person last typed a prompt here (a slow loop stops too). */
44
+ export const OWN_TURNS_UNATTENDED = 10;
38
45
  const FINAL_STATUS_TIMEOUT_MS = 8_000;
39
46
  export const realClock = {
40
47
  now: () => Date.now(),
@@ -63,34 +70,41 @@ function threadDirsFile(home, threadId) {
63
70
  export function loadThreadDirs(home, threadId) {
64
71
  return loadThread(home, threadId).dirs;
65
72
  }
66
- /** A thread's saved folders, and whether it was already over its cap. A file that exists but can't be read: over (fails closed). */
73
+ /**
74
+ * A thread's saved folders, and whether it was already over its cap (and why: the CLI's OverWhy
75
+ * words). A file that exists but can't be read: over (fails closed), `front`.
76
+ */
67
77
  export function loadThread(home, threadId) {
68
78
  const f = threadDirsFile(home, threadId);
69
79
  if (!f)
70
- return { dirs: [], over: false };
80
+ return { dirs: [], over: false, why: [] };
71
81
  let text;
72
82
  try {
73
83
  text = readFileSync(f, "utf8");
74
84
  }
75
85
  catch (e) {
76
- return { dirs: [], over: e.code !== "ENOENT" };
86
+ const over = e.code !== "ENOENT";
87
+ return { dirs: [], over, why: over ? ["front"] : [] };
77
88
  }
78
89
  try {
79
90
  const v = JSON.parse(text);
80
91
  const dirs = Array.isArray(v.dirs) ? v.dirs.filter((x) => typeof x === "string" && isAbsolute(x)) : [];
81
- return { dirs: dirs.slice(0, 512), over: v.over === true || dirs.length > 512 };
92
+ const over = v.over === true || dirs.length > 512;
93
+ const said = Array.isArray(v.why) ? v.why.filter((x) => typeof x === "string" && /^[a-z]{1,16}$/.test(x)).slice(0, 8) : [];
94
+ return { dirs: dirs.slice(0, 512), over, why: over ? (said.length ? said : dirs.length > 512 ? ["folders"] : ["front"]) : [] };
82
95
  }
83
96
  catch {
84
- return { dirs: [], over: true };
97
+ return { dirs: [], over: true, why: ["front"] };
85
98
  }
86
99
  }
87
- export function saveThreadDirs(home, threadId, dirs, over = false) {
100
+ export function saveThreadDirs(home, threadId, dirs, over = false, why = []) {
88
101
  const f = threadDirsFile(home, threadId);
89
102
  if (!f)
90
103
  return;
91
104
  try {
92
105
  mkdirSync(join(home, "codex-threads"), { recursive: true, mode: 0o700 });
93
- writeFileSync(f, JSON.stringify({ dirs: dirs.slice(0, 512), over: over || dirs.length > 512, at: Date.now() }), { mode: 0o600 });
106
+ const isOver = over || dirs.length > 512;
107
+ writeFileSync(f, JSON.stringify({ dirs: dirs.slice(0, 512), over: isOver, ...(isOver ? { why: [...new Set([...why, ...(dirs.length > 512 ? ["folders"] : [])])] } : {}), at: Date.now() }), { mode: 0o600 });
94
108
  }
95
109
  catch {
96
110
  // best effort: the session stays bound for this run either way
@@ -140,6 +154,8 @@ export class Bridge {
140
154
  touched = new Set();
141
155
  /** Past a cap, or a path that couldn't be resolved: the CLI keeps this session private (`--project-dirs-over`). */
142
156
  isDirsOver = false;
157
+ /** Why (the CLI's OverWhy words), so its refusal names the cause. */
158
+ dirsOverWhy = new Set();
143
159
  /** Where sandboxed commands may write, per the trusted turn context ("all": no sandbox; undefined: unknown). */
144
160
  trustedWritable;
145
161
  /** Why this thread's rollout file isn't trusted (planted or malformed), once found. */
@@ -149,6 +165,10 @@ export class Bridge {
149
165
  seenEdits = new Set();
150
166
  /** Turns this user's own devices started (L1: at most 5 per 10 minutes). */
151
167
  selfTurns = [];
168
+ /** Turns your own sessions started since the person last typed a prompt here. */
169
+ ownSinceTyped = 0;
170
+ /** Prompts the person typed, as the trusted rollout counts them (TrustedMode.typed). */
171
+ trustedTyped = 0;
152
172
  threadId;
153
173
  hooksSeen = false;
154
174
  activeAt = 0;
@@ -219,9 +239,18 @@ export class Bridge {
219
239
  sessionDirs() {
220
240
  const all = [...new Set([...(this.deps.projectDirs ?? []), this.deps.cwd, ...this.projectSeen, ...this.touched])];
221
241
  if (all.length > 512)
222
- this.isDirsOver = true;
242
+ this.markOver("folders");
223
243
  return all.slice(0, 512);
224
244
  }
245
+ /** Private from now on, and why. */
246
+ markOver(why) {
247
+ this.isDirsOver = true;
248
+ this.dirsOverWhy.add(why);
249
+ }
250
+ /** What `--project-dirs-over` says: false, or why (an over set without a reason is `front`). */
251
+ dirsOver() {
252
+ return this.isDirsOver ? (this.dirsOverWhy.size ? [...this.dirsOverWhy] : ["front"]) : false;
253
+ }
225
254
  async goOnline() {
226
255
  if (this.isOnline || this.stop.signal.aborted)
227
256
  return;
@@ -290,9 +319,9 @@ export class Bridge {
290
319
  continue;
291
320
  if (this.touched.size >= 512) {
292
321
  // Past the cap: private, never "the first 512".
293
- if (!this.isDirsOver)
322
+ if (!this.dirsOverWhy.has("folders"))
294
323
  added = true;
295
- this.isDirsOver = true;
324
+ this.markOver("folders");
296
325
  continue;
297
326
  }
298
327
  this.touched.add(d);
@@ -301,7 +330,7 @@ export class Bridge {
301
330
  if (!added)
302
331
  return;
303
332
  if (this.threadId)
304
- saveThreadDirs(this.deps.p2pHome, this.threadId, [...this.touched], this.isDirsOver);
333
+ saveThreadDirs(this.deps.p2pHome, this.threadId, [...this.touched], this.isDirsOver, [...this.dirsOverWhy]);
305
334
  this.announce();
306
335
  }
307
336
  /** The repo (the git toplevel's folder name), branch and label for `cwd`. */
@@ -359,7 +388,7 @@ export class Bridge {
359
388
  this.isAnnounceQueued = false;
360
389
  const summary = this.sharedSummary();
361
390
  const r = await this.deps.p2p
362
- .status({ session: this.sid, state: this.status, label: this.label, ...this.where(), ...(summary ? { summary } : {}), ...(this.shareStatus ? { files: this.files } : {}), projectDirs: this.sessionDirs(), projectDirsOver: this.isDirsOver })
391
+ .status({ session: this.sid, state: this.status, label: this.label, ...this.where(), ...(summary ? { summary } : {}), ...(this.shareStatus ? { files: this.files } : {}), projectDirs: this.sessionDirs(), projectDirsOver: this.dirsOver() })
363
392
  .catch(() => null);
364
393
  if (r && !r.ok)
365
394
  this.lastError = `status not shared: ${r.reason}`;
@@ -411,7 +440,8 @@ export class Bridge {
411
440
  for (const d of saved.dirs)
412
441
  this.touched.add(d);
413
442
  if (saved.over)
414
- this.isDirsOver = true;
443
+ for (const w of saved.why)
444
+ this.markOver(w);
415
445
  this.transcript = this.deps.transcript?.(info.threadId);
416
446
  this.deps.onChange?.();
417
447
  }
@@ -447,6 +477,12 @@ export class Bridge {
447
477
  }
448
478
  this.transcriptMode = t.mode;
449
479
  this.trustedSeq = t.seq;
480
+ // The person typed a prompt (the trusted rollout says so, never a hook report or our own queued
481
+ // pointer): own sessions may start their OWN_TURNS_UNATTENDED again.
482
+ if (typeof t.typed === "number" && t.typed > this.trustedTyped) {
483
+ this.trustedTyped = t.typed;
484
+ this.ownSinceTyped = 0;
485
+ }
450
486
  this.trustedWritable = t.writable;
451
487
  if (t.cwd) {
452
488
  this.trustedCwd = t.cwd;
@@ -681,7 +717,7 @@ export class Bridge {
681
717
  this.activityNotes.push(`POTENTIAL CONFLICT with ${sessionAddress(c.peer)}: you both changed ${c.files.map(inert).join(", ")}.`);
682
718
  // The file names go only where the status already goes; with status sharing off, nothing is sent.
683
719
  if (this.shareStatus && this.repo) {
684
- await this.deps.p2p.send({ fromSession: this.sid, to: `${c.peer.own} [${c.peer.ref}]`, text: conflictMessage(c.files, this.repo), projectDirs: this.sessionDirs(), projectDirsOver: this.isDirsOver }).catch(() => undefined);
720
+ await this.deps.p2p.send({ fromSession: this.sid, to: `${c.peer.own} [${c.peer.ref}]`, text: conflictMessage(c.files, this.repo), projectDirs: this.sessionDirs(), projectDirsOver: this.dirsOver() }).catch(() => undefined);
685
721
  }
686
722
  }
687
723
  }
@@ -741,15 +777,15 @@ export class Bridge {
741
777
  return;
742
778
  if (e.toSession !== undefined && e.toSession !== this.sid)
743
779
  return;
744
- const address = eventAddress({ from: e.from, own: e.own, sid: e.sid, ref: e.ref }, this.peers);
780
+ const address = eventAddress({ from: e.from, own: e.own, sid: e.sid, ref: e.ref, fromRef: e.fromRef }, this.peers);
745
781
  const item = {
746
782
  id: e.id,
747
783
  kind: "message",
748
784
  from: { userId: e.from.userId, address },
749
- fromSelf: e.from.self === true,
785
+ ...this.ownOf(e),
750
786
  text: cleanBody(e.text).slice(0, 64_000),
751
787
  at: typeof e.at === "number" ? e.at : this.clock.now(),
752
- replyTo: e.own === e.from.userId ? `${e.from.userId} [${e.ref}]` : e.from.userId,
788
+ replyTo: replyToOf({ from: e.from, own: e.own, ref: e.ref, fromRef: e.fromRef }),
753
789
  state: "pending",
754
790
  };
755
791
  if (this.inbox.some((one) => one.id === item.id))
@@ -765,8 +801,10 @@ export class Bridge {
765
801
  return;
766
802
  }
767
803
  this.inbox.push(item);
768
- // Screened by the mode Codex recorded last, not a stale copy of it.
804
+ // Screened by the mode Codex recorded last, and the person's `p2p own-agents` now: not stale copies.
769
805
  await this.refreshTrusted();
806
+ if (item.fromSelf)
807
+ await this.refreshOwnAgents();
770
808
  this.screenNow(item);
771
809
  this.scheduleQueue();
772
810
  return;
@@ -774,12 +812,14 @@ export class Bridge {
774
812
  case "p2p.idle": {
775
813
  if (!isSessionEvent || e.toSession !== this.sid || typeof e.reason !== "string")
776
814
  return;
777
- const address = eventAddress({ from: e.from, own: e.own, sid: e.sid, ref: e.ref }, this.peers);
815
+ const address = eventAddress({ from: e.from, own: e.own, sid: e.sid, ref: e.ref, fromRef: e.fromRef }, this.peers);
778
816
  const item = {
779
817
  id: e.id,
780
818
  kind: "notice",
781
819
  from: { userId: e.from.userId, address },
782
- fromSelf: e.from.self === true,
820
+ // An idle notice is the bridge's own line, never a sender's instruction: not held as an agent's, but it counts as an own turn.
821
+ ...this.ownOf(e),
822
+ ownAgent: false,
783
823
  text: idleNotice(address, e.reason),
784
824
  at: this.clock.now(),
785
825
  replyTo: e.from.userId,
@@ -805,11 +845,43 @@ export class Bridge {
805
845
  return;
806
846
  }
807
847
  }
848
+ /**
849
+ * What an event says of an own-session origin (the CLI's local record, never the wire): `via` is
850
+ * "person" for the person's own terminal session, anything else (or nothing: another device, an
851
+ * older client) counts as an agent session's. `ownTrusted`: the person ran `p2p own-agents deliver`.
852
+ */
853
+ ownOf(e) {
854
+ if (e.from?.self !== true)
855
+ return { fromSelf: false };
856
+ const ref = typeof e.fromRef === "string" && /^[0-9a-f]{6}$/.test(e.fromRef) ? e.fromRef : "elsewhere";
857
+ return {
858
+ fromSelf: true,
859
+ ownAgent: e.via !== "person",
860
+ local: this.who !== null && e.from.did === this.who.did,
861
+ bucket: `${e.from.userId}/${ref}`,
862
+ ...(typeof e.from.did === "string" ? { did: e.from.did } : {}),
863
+ };
864
+ }
865
+ /** `p2p own-agents` as it stands now, read before each screening (never stamped on an event). Unknown: hold. */
866
+ ownAgentsSetting = { ownAgents: "hold", devices: [] };
867
+ async refreshOwnAgents() {
868
+ const r = await this.deps.p2p.ownAgents().catch(() => undefined);
869
+ this.ownAgentsSetting = r?.ok ? r.value : { ownAgents: "hold", devices: [] };
870
+ }
871
+ /** Whether the person's `p2p own-agents` lets this own agent session's message through (the CLI's ownAgentsDeliverFrom). */
872
+ ownAgentDelivers(item) {
873
+ const s = this.ownAgentsSetting;
874
+ if (s.ownAgents === "deliver")
875
+ return true;
876
+ if (item.local || item.did === undefined)
877
+ return false;
878
+ return s.devices === "all-other" || (Array.isArray(s.devices) && s.devices.includes(item.did));
879
+ }
808
880
  /** Applies the hold rule to one new item, by this session's own mode as it stands now. */
809
881
  screenNow(item) {
810
882
  if (item.state !== "pending")
811
883
  return;
812
- const verdict = screenMessage({ fromSelf: item.fromSelf, fromUserId: item.from.userId, mode: this.modeClass(), autoDeliver: this.autoDeliver, refused: this.locationRefusal() });
884
+ const verdict = screenMessage({ fromSelf: item.fromSelf, ownAgent: item.ownAgent && !this.ownAgentDelivers(item), elsewhere: item.fromSelf && !item.local, fromUserId: item.from.userId, mode: this.modeClass(), autoDeliver: this.autoDeliver, refused: this.locationRefusal() });
813
885
  if (!verdict.deliver)
814
886
  this.hold(item, verdict.why, verdict.reason);
815
887
  }
@@ -838,9 +910,10 @@ export class Bridge {
838
910
  }
839
911
  }
840
912
  async notice(item, what) {
841
- if (item.kind !== "message" || !this.isOnline)
913
+ // One of your own sessions with no known sending session: nowhere to send it (replyToOf).
914
+ if (item.kind !== "message" || !this.isOnline || item.replyTo === "")
842
915
  return;
843
- await this.deps.p2p.send({ fromSession: this.sid, to: item.replyTo, text: `[Peer2Peer delivery notice] Your message to ${this.address} ${what}.`, projectDirs: this.sessionDirs(), projectDirsOver: this.isDirsOver }).catch(() => undefined);
916
+ await this.deps.p2p.send({ fromSession: this.sid, to: item.replyTo, text: `[Peer2Peer delivery notice] Your message to ${this.address} ${what}.`, projectDirs: this.sessionDirs(), projectDirsOver: this.dirsOver() }).catch(() => undefined);
844
917
  }
845
918
  async expireHeld() {
846
919
  const now = this.clock.now();
@@ -858,8 +931,8 @@ export class Bridge {
858
931
  * turn's context may not be written yet, so only what doesn't depend on
859
932
  * the mode goes out there). When the delivery starts a turn (a Stop
860
933
  * continuation, `codex queue`), the turn caps apply: past a cap, peers'
861
- * messages are held for the person, and the user's own devices' wait for
862
- * the next prompt.
934
+ * messages and the user's own sessions' are held until the person
935
+ * releases them (`p2p codex release`).
863
936
  */
864
937
  takeDeliverable(o) {
865
938
  const mode = this.modeClass(o.confirmed !== false);
@@ -875,7 +948,7 @@ export class Bridge {
875
948
  const isRescreen = item.state === "held" && item.holdKind === "unknown";
876
949
  if (item.state !== "pending" && !isRescreen)
877
950
  continue;
878
- const verdict = screenMessage({ fromSelf: item.fromSelf, fromUserId: item.from.userId, mode, autoDeliver: this.autoDeliver, refused });
951
+ const verdict = screenMessage({ fromSelf: item.fromSelf, ownAgent: item.ownAgent && !this.ownAgentDelivers(item), elsewhere: item.fromSelf && !item.local, fromUserId: item.from.userId, mode, autoDeliver: this.autoDeliver, refused });
879
952
  if (verdict.deliver)
880
953
  ready.push(item);
881
954
  // Unconfirmed at UserPromptSubmit: wait for PostToolUse or Stop rather than hold.
@@ -889,14 +962,30 @@ export class Bridge {
889
962
  let out = ready;
890
963
  if (o.startsTurn) {
891
964
  const now = this.clock.now();
892
- // L1: the user's own devices may start at most 5 turns per 10 minutes too.
893
- this.selfTurns = this.selfTurns.filter((at) => now - at < TURN_WINDOW_MS);
965
+ // L1: your other devices may start at most 5 turns per 10 minutes, other sessions on this device 30,
966
+ // and all of them together 10 since the person last typed here. Past a cap they are held (never
967
+ // deferred): the person releases them.
968
+ this.selfTurns = this.selfTurns.filter((one) => now - one.at < TURN_WINDOW_MS);
894
969
  const own = out.filter((one) => one.fromSelf && one.state !== "released");
895
970
  if (own.length > 0) {
896
- if (this.selfTurns.length >= SELF_TURNS)
971
+ const used = (local) => this.selfTurns.filter((one) => one.local === local).length;
972
+ const why = this.ownSinceTyped >= OWN_TURNS_UNATTENDED
973
+ ? `your own sessions already started ${OWN_TURNS_UNATTENDED} turns here since your user last typed`
974
+ : own.some((one) => !one.local) && used(false) >= SELF_TURNS
975
+ ? `your other devices already started ${SELF_TURNS} turns here in 10 minutes`
976
+ : own.some((one) => one.local) && used(true) >= LOCAL_SELF_TURNS
977
+ ? `your other sessions here already started ${LOCAL_SELF_TURNS} turns in 10 minutes`
978
+ : undefined;
979
+ if (why !== undefined) {
980
+ for (const one of own)
981
+ this.hold(one, why, "cap");
897
982
  out = out.filter((one) => !own.includes(one));
898
- else
899
- this.selfTurns.push(now);
983
+ }
984
+ else {
985
+ for (const local of new Set(own.map((one) => one.local === true)))
986
+ this.selfTurns.push({ at: now, local });
987
+ this.ownSinceTyped += 1;
988
+ }
900
989
  }
901
990
  const capped = out.filter((one) => one.state !== "released" && !one.fromSelf);
902
991
  const senders = [...new Set(capped.map((one) => one.from.userId))];
@@ -997,6 +1086,9 @@ export class Bridge {
997
1086
  async flushQueue() {
998
1087
  if (!this.deps.queue || !this.threadId || this.status !== "idle")
999
1088
  return;
1089
+ await this.refreshTrusted();
1090
+ if (this.inbox.some((one) => one.fromSelf && one.ownAgent && one.state === "pending"))
1091
+ await this.refreshOwnAgents();
1000
1092
  const before = new Map(this.inbox.map((one) => [one.id, one.state]));
1001
1093
  const items = this.takeDeliverable({ startsTurn: true });
1002
1094
  if (items.length === 0)
@@ -1017,6 +1109,8 @@ export class Bridge {
1017
1109
  async onHook(r) {
1018
1110
  this.hooksSeen = true;
1019
1111
  await this.refreshTrusted();
1112
+ if (this.inbox.some((one) => one.fromSelf && one.ownAgent && (one.state === "pending" || one.state === "held")))
1113
+ await this.refreshOwnAgents();
1020
1114
  if (r.mode && isExplicitlyAuto(r.mode))
1021
1115
  this.reportedAutoSeq = this.trustedSeq;
1022
1116
  // The cwd comes from where Codex started this server and from the trusted turn context, never from a report.
@@ -1033,6 +1127,9 @@ export class Bridge {
1033
1127
  }
1034
1128
  case "UserPromptSubmit": {
1035
1129
  this.activeAt = this.clock.now();
1130
+ // Not a reset of OWN_TURNS_UNATTENDED: a hook report is untrusted (a sandboxed command can send
1131
+ // one), and this hook also runs for the bridge's own `codex queue` turns. Only the rollout's
1132
+ // typed prompts reset it (refreshTrusted).
1036
1133
  this.deps.onChange?.();
1037
1134
  this.setStatus("busy");
1038
1135
  // Codex may run this hook before it records this turn's context: the mode isn't confirmed yet.
@@ -1043,11 +1140,16 @@ export class Bridge {
1043
1140
  return context("UserPromptSubmit", [items.length > 0 ? this.frame(items) : undefined, this.takeActivityNotes(), this.heldNote(), reminder]);
1044
1141
  }
1045
1142
  case "PreToolUse": {
1046
- if (r.over && !this.isDirsOver) {
1047
- this.isDirsOver = true;
1048
- if (this.threadId)
1049
- saveThreadDirs(this.deps.p2pHome, this.threadId, [...this.projectSeen, ...this.touched], true);
1050
- this.announce();
1143
+ if (r.over) {
1144
+ const before = this.dirsOverWhy.size;
1145
+ const was = this.isDirsOver;
1146
+ for (const w of r.overWhy?.length ? r.overWhy : ["front"])
1147
+ this.markOver(w);
1148
+ if (!was || this.dirsOverWhy.size !== before) {
1149
+ if (this.threadId)
1150
+ saveThreadDirs(this.deps.p2pHome, this.threadId, [...this.projectSeen, ...this.touched], true, [...this.dirsOverWhy]);
1151
+ this.announce();
1152
+ }
1051
1153
  }
1052
1154
  this.noteTouched(r.dirs ?? []);
1053
1155
  return {};
package/dist/hook.d.ts CHANGED
@@ -2,13 +2,24 @@
2
2
  export declare function commandOf(input: unknown): string;
3
3
  /** PreToolUse: the denial for a shell command the model may not run, or null. */
4
4
  export declare function guard(toolName: string, input: unknown, binNames?: readonly string[], ownSid?: string): string | null;
5
+ /**
6
+ * The marker of the nearest folder at or above each path that holds a `.git` (any kind), a
7
+ * `.p2p-private`, or is a bare repository (`<that folder>/.git` then), and each of `maybe` that
8
+ * exists: the bridge binds them too, so a shared folder above never covers a repository once its
9
+ * files are gone (projects.ts namedStop). Metadata only; git is never run. The same rules as the
10
+ * Claude mod's MARKER_PROBE.
11
+ */
12
+ export declare function markerPaths(paths: readonly string[], maybe?: readonly string[]): string[];
5
13
  /**
6
14
  * The paths a tool call names outside its folder (a shell command's absolute, ~ and .. paths; the
7
15
  * files an apply_patch or edit names), resolved: the bridge binds each one's project (projects.ts).
16
+ * Plus the repository marker each one (and the cwd) is under, and a program's word that names a
17
+ * file that exists (markerPaths).
8
18
  */
9
19
  export declare function touchedPaths(toolName: string, input: unknown, cwd: string | undefined, home: string | undefined): {
10
20
  paths: string[];
11
21
  over: boolean;
22
+ why?: string[];
12
23
  };
13
24
  export interface HookDeps {
14
25
  home: string;