@peer2peer/codex-bridge 0.0.0-stage → 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/lib.d.ts ADDED
@@ -0,0 +1,438 @@
1
+ export declare const P2P_PREFIX = "p2p:";
2
+ /**
3
+ * A peer's own text, on one line and unable to close or open the block it
4
+ * sits in: no `<`/`>`, no control or format characters, whitespace folded.
5
+ */
6
+ export declare function inert(text: string): string;
7
+ /** Peer text capped at `max` characters, after it was made inert. */
8
+ export declare function inertMax(text: string, max: number): string;
9
+ /** A session label as the bridge sends it: `[a-z0-9._-]`, at most 40. */
10
+ export declare function sanitizeLabel(raw: string): string;
11
+ /** A peer's label as it appears inside an address: inert, no spaces, slashes or brackets. */
12
+ export declare function addressLabel(label: string): string;
13
+ /** Message text with control and format characters gone; line breaks and tabs kept. */
14
+ export declare function cleanBody(text: string): string;
15
+ /** The one-line preview: the message's first non-empty line, inert. */
16
+ export declare function firstLine(text: string, max?: number): string;
17
+ /** Peer-written text, inert, quoted and labelled as data from that peer. */
18
+ export declare function peerData(address: string, text: string): string;
19
+ export declare const MESSAGE_TAG = "peer-message";
20
+ /**
21
+ * A message as the model reads it. Every `&`, `<` and `>` in the body is
22
+ * escaped, so a sender can neither close the frame (in any spelling) nor
23
+ * open a forged one inside it. The header says, outside the sender's
24
+ * control, that the body is data from that peer.
25
+ */
26
+ export declare function wrapMessage(from: string, text: string, at?: number): string;
27
+ /** What an address names: a user (display address or userId), and optionally a label and a ref. */
28
+ export type ParsedAddress = {
29
+ user: string;
30
+ label?: string;
31
+ ref?: string;
32
+ };
33
+ /**
34
+ * `p2p:<name>@<fp>[/<label>] [ref]`, the same without the prefix, or
35
+ * `p2p:<userId-b32> [ref]`; null for anything else (a bare name).
36
+ */
37
+ export declare function parseAddress(to: string): ParsedAddress | null;
38
+ /** A session as `p2p ls --json` lists it (packages/p2p `PeerRow`). */
39
+ export type PeerRow = {
40
+ own: string;
41
+ sid: string;
42
+ ref: string;
43
+ address: string;
44
+ self: boolean;
45
+ thisDevice: boolean;
46
+ live: boolean;
47
+ ageSec?: number;
48
+ state: "busy" | "idle";
49
+ label: string;
50
+ repo?: string;
51
+ branch?: string;
52
+ mode?: string;
53
+ summary?: string;
54
+ files?: string[];
55
+ circle?: string;
56
+ };
57
+ /** The address a session is reached at: `p2p:<name>@<fp>/<label> [ref]`. */
58
+ export declare function sessionAddress(peer: {
59
+ address: string;
60
+ label?: string;
61
+ ref?: string;
62
+ }): string;
63
+ /** Sessions a send may name: everything listed but this very session. */
64
+ export declare function reachable(peers: readonly PeerRow[], ownSid?: string): PeerRow[];
65
+ export type Target = {
66
+ kind: "peer";
67
+ to: string;
68
+ peer: PeerRow;
69
+ } | {
70
+ kind: "cli";
71
+ to: string;
72
+ } | {
73
+ kind: "ambiguous";
74
+ candidates: PeerRow[];
75
+ } | {
76
+ kind: "refused";
77
+ reason: string;
78
+ code?: "no-label";
79
+ };
80
+ /**
81
+ * What `--to` the CLI gets for a model's `to`. Only a `p2p:` address or a
82
+ * `name@fingerprint` address goes out: a bare name is refused, since anyone
83
+ * can choose their own name. A listed session is named by its owner's full
84
+ * userId and ref, so the CLI decides by userId, never by a name.
85
+ */
86
+ export declare function resolveTarget(to: string, peers: readonly PeerRow[], ownSid?: string): Target;
87
+ /**
88
+ * The `from` address of a received message: the sender's own session (with
89
+ * label and ref) when it came from one, else the user's address alone.
90
+ */
91
+ export declare function eventAddress(event: {
92
+ from: {
93
+ userId: string;
94
+ address: string;
95
+ self?: boolean;
96
+ };
97
+ own: string;
98
+ sid: string;
99
+ ref: string;
100
+ fromRef?: unknown;
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;
116
+ /**
117
+ * What the bridge knows of this Codex session's own mode, from Codex itself
118
+ * (never from a peer). Every field may be unknown (undefined or null):
119
+ * - `permissionMode`: the hooks' `permission_mode` (Codex maps approval
120
+ * `never` to `bypassPermissions` and every other policy to `default`);
121
+ * - `approval`: `approval_policy` (untrusted, on-request, granular, never),
122
+ * from the session's latest turn context;
123
+ * - `sandbox`: read-only, workspace-write or danger-full-access, from a
124
+ * tool call's `_meta` or the turn context;
125
+ * - `autoReview`: approvals routed to automatic review (`--approve-for-me`).
126
+ */
127
+ export type CodexMode = {
128
+ permissionMode?: string | null;
129
+ approval?: string | null;
130
+ sandbox?: string | null;
131
+ autoReview?: boolean | null;
132
+ };
133
+ /**
134
+ * Whether this Codex session acts without asking the person. Codex asks
135
+ * before acting only when approvals go to the person (not `never`, not
136
+ * automatic review) AND the sandbox is `read-only`: under `workspace-write`
137
+ * Codex edits files and runs sandboxed commands without asking, which is
138
+ * what a peer's message could then steer. Anything unknown counts as
139
+ * auto-approving, so messages from other people are held.
140
+ */
141
+ export declare function isAutoApproving(mode: CodexMode | null | undefined): boolean;
142
+ /** The words a mode is shown with, for the person (never published to peers). */
143
+ export declare function modeWords(mode: CodexMode | null | undefined): string;
144
+ /** The grouped 16-character fingerprint of a userId (core displayFingerprint). */
145
+ export declare function groupedFingerprint(userId: string): string;
146
+ /** Who P2P_AUTO_DELIVER lets drive an auto-approving session, and what it ignored. */
147
+ export type AutoDeliver = {
148
+ userIds: ReadonlySet<string>;
149
+ fingerprints: ReadonlySet<string>;
150
+ ignored: string[];
151
+ };
152
+ /**
153
+ * P2P_AUTO_DELIVER: only full userIds (`p2p:…`) and `name@fingerprint`
154
+ * entries count, and a `name@fingerprint` entry counts by its fingerprint
155
+ * alone, matched against the sender's full userId. A bare name or petname is
156
+ * ignored: names are self-chosen, so `morgan` could be anyone.
157
+ */
158
+ export declare function parseAutoDeliver(raw: string | undefined): AutoDeliver;
159
+ /** Whether P2P_AUTO_DELIVER names this sender (by full userId, or its fingerprint). */
160
+ export declare function isAutoDeliver(list: AutoDeliver, userId: string): boolean;
161
+ export type HoldVerdict = {
162
+ isHeld: false;
163
+ } | {
164
+ isHeld: true;
165
+ why: string;
166
+ };
167
+ /**
168
+ * Whether a message waits for the person. The sender's own claims (its mode
169
+ * included) play no part:
170
+ * - from this user's own devices: delivered;
171
+ * - into a session that asks before acting: delivered, since the person
172
+ * still approves every action;
173
+ * - into a session that approves by itself (or whose mode is unknown):
174
+ * held, unless the person listed the sender in P2P_AUTO_DELIVER.
175
+ */
176
+ export declare function holdVerdict(o: {
177
+ fromSelf: boolean;
178
+ fromUserId: string;
179
+ mode: CodexMode | null;
180
+ autoDeliver: AutoDeliver;
181
+ }): HoldVerdict;
182
+ /** At most this many held messages per sender, and in all; the oldest go first. */
183
+ export declare const HELD_PER_SENDER = 5;
184
+ export declare const HELD_TOTAL = 50;
185
+ /** The held list capped per sender and in total, oldest dropped (the list is oldest first). */
186
+ export declare function capHeld<T extends {
187
+ from: {
188
+ userId: string;
189
+ };
190
+ bucket?: string;
191
+ }>(list: readonly T[]): T[];
192
+ /** Turns peers may start: per sender and in all, in a sliding window. */
193
+ export declare const TURN_WINDOW_MS: number;
194
+ export declare const TURNS_PER_SENDER = 3;
195
+ export declare const TURNS_TOTAL = 10;
196
+ /** Whether `senders` may start one more turn at `now`, given the turns peers started before. */
197
+ export declare function mayStartTurn(history: readonly {
198
+ at: number;
199
+ sender: string;
200
+ }[], senders: readonly string[], now: number): boolean;
201
+ export declare const MAX_SUMMARY_CHARS = 200;
202
+ export declare const MAX_SHARED_FILES = 25;
203
+ /** The last segment of a path, whichever separator it uses. */
204
+ export declare function pathBasename(path: string): string | undefined;
205
+ /** A relative path as the relay takes it (core isSafeRelativePath, plus the mod's own rules). */
206
+ export declare function isShareablePath(rel: string): boolean;
207
+ /** `path` relative to the repo `root` with `/` separators; undefined outside the repo. */
208
+ export declare function repoRelative(root: string, path: string): string | undefined;
209
+ /**
210
+ * A file the model names, as a shareable repo-relative path: an absolute
211
+ * path inside the repo is made relative; anything outside it, or unsafe, is
212
+ * dropped. Never an absolute path.
213
+ */
214
+ export declare function shareableFile(root: string | undefined, file: string): string | undefined;
215
+ /** Most recent first, deduplicated, at most `MAX_SHARED_FILES`. */
216
+ export declare function touchFile(files: readonly string[], rel: string): string[];
217
+ /** Absolute path tokens (`/home/x/…`, `~/…`, `C:\…`, `C:/…`, `\\server\…`) taken out of a line. */
218
+ export declare function stripPaths(line: string): string;
219
+ /** A summary as one shareable line (no absolute paths, at most 200 characters), or undefined. */
220
+ export declare function cleanSummary(text: string): string | undefined;
221
+ export type Conflict = {
222
+ peer: PeerRow;
223
+ files: string[];
224
+ };
225
+ /** One key per (peer session, file): a conflict is new only when it names a file not raised with that session yet. */
226
+ export declare function conflictKeys(c: Conflict): string[];
227
+ /** Live sessions (not this one) in the same repo changing files this session changed. */
228
+ export declare function conflicts(peers: readonly PeerRow[], repo: string | undefined, mine: readonly string[], ownSid?: string): Conflict[];
229
+ /**
230
+ * The peer-activity digest: peers' sessions that share a status, same repo
231
+ * first, with any overlap flagged. Everything a peer wrote is inert and the
232
+ * block says it is their claim.
233
+ */
234
+ export declare function peerActivity(peers: readonly PeerRow[], repo: string | undefined, mine: readonly string[], ownSid?: string): {
235
+ text: string;
236
+ conflicts: Conflict[];
237
+ };
238
+ /** The short message a conflict sends to the peer's session, once per (session, file). */
239
+ export declare function conflictMessage(files: readonly string[], repo: string): string;
240
+ /**
241
+ * Tool names the server never exposes, and refuses by name: they change who
242
+ * reaches this user (join, approve, relays, invite, …) or touch its keys.
243
+ * Only the person runs them, in a terminal, with `p2p`.
244
+ */
245
+ export declare const MUTATING_TOOLS: Set<string>;
246
+ /**
247
+ * The mutating `p2p` verb a shell command runs, or null (the mod's
248
+ * `mutatingP2PVerb`, for Codex's PreToolUse hook). Defence in depth only:
249
+ * parsed conservatively, it may refuse a harmless command, never the reverse
250
+ * on purpose, but a determined command can spell things another way.
251
+ */
252
+ export declare function mutatingP2PVerb(command: string, binNames?: readonly string[], depth?: number): string | null;
253
+ /**
254
+ * Whether a shell command reaches the backup phrase file or the CLI's key
255
+ * store (`.p2p` together with `backup`, or the `.p2p` folder listed, globbed
256
+ * or its key store). Best effort, like every guard here.
257
+ */
258
+ export declare function touchesSecrets(command: string): boolean;
259
+ /**
260
+ * The approval policy, sandbox and reviewer of a Codex session from its
261
+ * rollout transcript (`transcript_path` in a hook's payload): the last
262
+ * `turn_context` line wins. Best effort: the transcript is Codex's internal
263
+ * format, so anything unreadable is left unknown (and unknown holds).
264
+ */
265
+ export declare function modeFromTranscript(tail: string): CodexMode;
266
+ /** Marks the Codex process's TMPDIR among writable roots (resolved by the bridge, which inherits it). */
267
+ export declare const TMPDIR_ROOT = "@tmpdir";
268
+ /**
269
+ * Where the session's sandboxed commands may write, from a turn context:
270
+ * a list of roots (TMPDIR as `@tmpdir`), "all" (no sandbox, or root
271
+ * writable), or undefined when it can't be told (an unknown policy shape:
272
+ * treated as "could be anywhere").
273
+ */
274
+ export declare function writableRootsOf(p: Record<string, unknown>): string[] | "all" | undefined;
275
+ /** One rollout line, when it is a `turn_context`: the mode it records, its turn, cwd and writable roots. */
276
+ export declare function turnContextOf(line: string): {
277
+ mode: CodexMode;
278
+ turnId?: string;
279
+ cwd?: string;
280
+ writable?: string[] | "all";
281
+ at?: number;
282
+ } | null;
283
+ /** Whether `path` is `root` or inside it (both already resolved; case-insensitive on macOS/Windows). */
284
+ export declare function isInside(path: string, root: string, caseless?: boolean): boolean;
285
+ /** A mode that, by itself, says the session acts without asking (one source is enough to hold). */
286
+ export declare function isExplicitlyAuto(m: CodexMode | null | undefined): boolean;
287
+ export type ModeClass = "asking" | "auto" | "unknown";
288
+ /**
289
+ * What this session's mode is, from the sources the bridge trusts:
290
+ * - `transcript`: the latest turn context in this thread's own rollout file
291
+ * under CODEX_HOME/sessions, which the bridge reads itself (a sandboxed
292
+ * command can't write it);
293
+ * - `meta`: the sandbox and auto-review Codex puts on each tool call;
294
+ * - `reportedAuto`: a hook reported an auto-approving mode. Hooks reach
295
+ * the bridge over a local socket anyone running as the user can talk
296
+ * to, so a report can only make the mode stricter, never looser.
297
+ * `confirmed` false (at UserPromptSubmit, before this turn's context is
298
+ * certainly written) makes anything short of "auto" unknown.
299
+ * "asking" needs the transcript's approval and sandbox, both asking, and no
300
+ * source saying otherwise. Unknown is never treated as asking.
301
+ */
302
+ export declare function classifyMode(o: {
303
+ transcript: CodexMode;
304
+ meta: CodexMode;
305
+ reportedAuto: boolean;
306
+ confirmed: boolean;
307
+ }): ModeClass;
308
+ export type Screen = {
309
+ deliver: true;
310
+ } | {
311
+ deliver: false;
312
+ reason: "auto" | "unknown";
313
+ why: string;
314
+ };
315
+ /**
316
+ * The hold rule on a classified mode (a location refusal holds everything): own devices and P2P_AUTO_DELIVER
317
+ * senders are delivered; otherwise only an asking session delivers. An
318
+ * auto-approving one holds for the person; an unknown one holds until the
319
+ * mode is known (and then delivers only if it asks).
320
+ */
321
+ export declare function screenMessage(o: {
322
+ fromSelf: boolean;
323
+ fromUserId: string;
324
+ mode: ModeClass;
325
+ autoDeliver: AutoDeliver;
326
+ refused?: string | undefined;
327
+ ownAgent?: boolean;
328
+ elsewhere?: boolean;
329
+ }): Screen;
330
+ /** What a tool call's `_meta["x-codex-turn-metadata"]` says: the thread and the sandbox. */
331
+ export declare function fromToolMeta(meta: unknown): {
332
+ threadId?: string;
333
+ mode: CodexMode;
334
+ };
335
+ /** Merges what one source knows over what another knew: known values win, unknown ones keep the old. */
336
+ export declare function mergeMode(base: CodexMode, next: CodexMode): CodexMode;
337
+ /**
338
+ * The files a tool call changed, as the model named them: apply_patch
339
+ * envelopes (`*** Update File: path`, in any string of the input), and an
340
+ * edit tool's `file_path`/`path`. Made repo-relative (or dropped) by the
341
+ * caller; never shared as given.
342
+ */
343
+ export declare function editedFiles(toolName: string, input: unknown): string[];
344
+ /** Stands for a `$` or backtick that was quoted text (shellTokens' markLiteral): never an expansion. */
345
+ export declare const LITERAL = "\uE000";
346
+ /**
347
+ * A shell command line as words, the way a POSIX shell reads them: adjacent quoted and unquoted
348
+ * parts join into one word (`''x1` and `"x"1` are `x1`), backslashes escape, `$'…'` is
349
+ * ANSI-C quoted, and `;`, `|`, `&`, `(`, `)`, `<`, `>` and newlines separate words. Expansions
350
+ * (`$X`, `$(…)`, backticks) stay as text. Linear in the length, with no cap on the number of words
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).
354
+ */
355
+ export declare function shellTokens(command: string, markLiteral?: boolean, substs?: string[], starts?: Set<number>): string[];
356
+ /** `p` made absolute against `cwd` (POSIX or Windows separators), `.` and `..` resolved. Linear: no regex over the input. */
357
+ export declare function resolveLike(cwd: string, p: string): string;
358
+ /** At most this many folders one command may name; past it the session is private (`over`). */
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';
362
+ /**
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).
375
+ */
376
+ export interface ShellPaths {
377
+ paths: string[];
378
+ over: boolean;
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;
413
+ /** Whether a command runs interpreter code given inline, or anything under a pseudo-terminal wrapper (by its words: linear). */
414
+ export declare function hidesCommand(command: string): 'interpreter' | 'pty' | null;
415
+ /** Commands naming p2p longer than this are refused unread. */
416
+ export declare const MAX_GUARDED_COMMAND: number;
417
+ /** Whether a command line names the p2p CLI (as a word, a path ending in it, the bundle or its variables). */
418
+ export declare function namesP2PCli(command: string): boolean;
419
+ /**
420
+ * Why a shell command naming p2p is refused beyond its verb, or null (projects.ts): it speaks for a
421
+ * session other than this bridge's own (`--from-session`/`--session`, read as the shell reads them),
422
+ * hides p2p inside interpreter code or a pseudo-terminal, or shares a project.
423
+ */
424
+ export declare function boundaryRefusal(command: string, ownSid: string | undefined): string | null;
425
+ /** A `p2p` session id as the CLI takes it: `[A-Za-z0-9._-]`, at most 128. */
426
+ export declare function isSid(sid: string): boolean;
427
+ /** The one-shot notice `notify_when_idle` asked for. */
428
+ export declare function idleNotice(address: string, reason: string): string;
429
+ /**
430
+ * Which local Codex session holds a message no session was named for: the
431
+ * live one the person used most recently (ties: the lowest sid). Each
432
+ * session computes the same answer from the same registry, so at most one
433
+ * holds it.
434
+ */
435
+ export declare function pickHolder(board: readonly {
436
+ sid: string;
437
+ activeAt: number;
438
+ }[]): string | undefined;