@peer2peer/codex-bridge 0.0.0-stage → 0.1.0

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,374 @@
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
+ };
79
+ /**
80
+ * What `--to` the CLI gets for a model's `to`. Only a `p2p:` address or a
81
+ * `name@fingerprint` address goes out: a bare name is refused, since anyone
82
+ * can choose their own name. A listed session is named by its owner's full
83
+ * userId and ref, so the CLI decides by userId, never by a name.
84
+ */
85
+ export declare function resolveTarget(to: string, peers: readonly PeerRow[], ownSid?: string): Target;
86
+ /**
87
+ * The `from` address of a received message: the sender's own session (with
88
+ * label and ref) when it came from one, else the user's address alone.
89
+ */
90
+ export declare function eventAddress(event: {
91
+ from: {
92
+ userId: string;
93
+ address: string;
94
+ };
95
+ own: string;
96
+ sid: string;
97
+ ref: string;
98
+ }, peers: readonly PeerRow[]): string;
99
+ /**
100
+ * What the bridge knows of this Codex session's own mode, from Codex itself
101
+ * (never from a peer). Every field may be unknown (undefined or null):
102
+ * - `permissionMode`: the hooks' `permission_mode` (Codex maps approval
103
+ * `never` to `bypassPermissions` and every other policy to `default`);
104
+ * - `approval`: `approval_policy` (untrusted, on-request, granular, never),
105
+ * from the session's latest turn context;
106
+ * - `sandbox`: read-only, workspace-write or danger-full-access, from a
107
+ * tool call's `_meta` or the turn context;
108
+ * - `autoReview`: approvals routed to automatic review (`--approve-for-me`).
109
+ */
110
+ export type CodexMode = {
111
+ permissionMode?: string | null;
112
+ approval?: string | null;
113
+ sandbox?: string | null;
114
+ autoReview?: boolean | null;
115
+ };
116
+ /**
117
+ * Whether this Codex session acts without asking the person. Codex asks
118
+ * before acting only when approvals go to the person (not `never`, not
119
+ * automatic review) AND the sandbox is `read-only`: under `workspace-write`
120
+ * Codex edits files and runs sandboxed commands without asking, which is
121
+ * what a peer's message could then steer. Anything unknown counts as
122
+ * auto-approving, so messages from other people are held.
123
+ */
124
+ export declare function isAutoApproving(mode: CodexMode | null | undefined): boolean;
125
+ /** The words a mode is shown with, for the person (never published to peers). */
126
+ export declare function modeWords(mode: CodexMode | null | undefined): string;
127
+ /** The grouped 16-character fingerprint of a userId (core displayFingerprint). */
128
+ export declare function groupedFingerprint(userId: string): string;
129
+ /** Who P2P_AUTO_DELIVER lets drive an auto-approving session, and what it ignored. */
130
+ export type AutoDeliver = {
131
+ userIds: ReadonlySet<string>;
132
+ fingerprints: ReadonlySet<string>;
133
+ ignored: string[];
134
+ };
135
+ /**
136
+ * P2P_AUTO_DELIVER: only full userIds (`p2p:…`) and `name@fingerprint`
137
+ * entries count, and a `name@fingerprint` entry counts by its fingerprint
138
+ * alone, matched against the sender's full userId. A bare name or petname is
139
+ * ignored: names are self-chosen, so `morgan` could be anyone.
140
+ */
141
+ export declare function parseAutoDeliver(raw: string | undefined): AutoDeliver;
142
+ /** Whether P2P_AUTO_DELIVER names this sender (by full userId, or its fingerprint). */
143
+ export declare function isAutoDeliver(list: AutoDeliver, userId: string): boolean;
144
+ export type HoldVerdict = {
145
+ isHeld: false;
146
+ } | {
147
+ isHeld: true;
148
+ why: string;
149
+ };
150
+ /**
151
+ * Whether a message waits for the person. The sender's own claims (its mode
152
+ * included) play no part:
153
+ * - from this user's own devices: delivered;
154
+ * - into a session that asks before acting: delivered, since the person
155
+ * still approves every action;
156
+ * - into a session that approves by itself (or whose mode is unknown):
157
+ * held, unless the person listed the sender in P2P_AUTO_DELIVER.
158
+ */
159
+ export declare function holdVerdict(o: {
160
+ fromSelf: boolean;
161
+ fromUserId: string;
162
+ mode: CodexMode | null;
163
+ autoDeliver: AutoDeliver;
164
+ }): HoldVerdict;
165
+ /** At most this many held messages per sender, and in all; the oldest go first. */
166
+ export declare const HELD_PER_SENDER = 5;
167
+ export declare const HELD_TOTAL = 50;
168
+ /** The held list capped per sender and in total, oldest dropped (the list is oldest first). */
169
+ export declare function capHeld<T extends {
170
+ from: {
171
+ userId: string;
172
+ };
173
+ }>(list: readonly T[]): T[];
174
+ /** Turns peers may start: per sender and in all, in a sliding window. */
175
+ export declare const TURN_WINDOW_MS: number;
176
+ export declare const TURNS_PER_SENDER = 3;
177
+ export declare const TURNS_TOTAL = 10;
178
+ /** Whether `senders` may start one more turn at `now`, given the turns peers started before. */
179
+ export declare function mayStartTurn(history: readonly {
180
+ at: number;
181
+ sender: string;
182
+ }[], senders: readonly string[], now: number): boolean;
183
+ export declare const MAX_SUMMARY_CHARS = 200;
184
+ export declare const MAX_SHARED_FILES = 25;
185
+ /** The last segment of a path, whichever separator it uses. */
186
+ export declare function pathBasename(path: string): string | undefined;
187
+ /** A relative path as the relay takes it (core isSafeRelativePath, plus the mod's own rules). */
188
+ export declare function isShareablePath(rel: string): boolean;
189
+ /** `path` relative to the repo `root` with `/` separators; undefined outside the repo. */
190
+ export declare function repoRelative(root: string, path: string): string | undefined;
191
+ /**
192
+ * A file the model names, as a shareable repo-relative path: an absolute
193
+ * path inside the repo is made relative; anything outside it, or unsafe, is
194
+ * dropped. Never an absolute path.
195
+ */
196
+ export declare function shareableFile(root: string | undefined, file: string): string | undefined;
197
+ /** Most recent first, deduplicated, at most `MAX_SHARED_FILES`. */
198
+ export declare function touchFile(files: readonly string[], rel: string): string[];
199
+ /** Absolute path tokens (`/home/x/…`, `~/…`, `C:\…`, `C:/…`, `\\server\…`) taken out of a line. */
200
+ export declare function stripPaths(line: string): string;
201
+ /** A summary as one shareable line (no absolute paths, at most 200 characters), or undefined. */
202
+ export declare function cleanSummary(text: string): string | undefined;
203
+ export type Conflict = {
204
+ peer: PeerRow;
205
+ files: string[];
206
+ };
207
+ /** One key per (peer session, file): a conflict is new only when it names a file not raised with that session yet. */
208
+ export declare function conflictKeys(c: Conflict): string[];
209
+ /** Live sessions (not this one) in the same repo changing files this session changed. */
210
+ export declare function conflicts(peers: readonly PeerRow[], repo: string | undefined, mine: readonly string[], ownSid?: string): Conflict[];
211
+ /**
212
+ * The peer-activity digest: peers' sessions that share a status, same repo
213
+ * first, with any overlap flagged. Everything a peer wrote is inert and the
214
+ * block says it is their claim.
215
+ */
216
+ export declare function peerActivity(peers: readonly PeerRow[], repo: string | undefined, mine: readonly string[], ownSid?: string): {
217
+ text: string;
218
+ conflicts: Conflict[];
219
+ };
220
+ /** The short message a conflict sends to the peer's session, once per (session, file). */
221
+ export declare function conflictMessage(files: readonly string[], repo: string): string;
222
+ /**
223
+ * Tool names the server never exposes, and refuses by name: they change who
224
+ * reaches this user (join, approve, relays, invite, …) or touch its keys.
225
+ * Only the person runs them, in a terminal, with `p2p`.
226
+ */
227
+ export declare const MUTATING_TOOLS: Set<string>;
228
+ /**
229
+ * The mutating `p2p` verb a shell command runs, or null (the mod's
230
+ * `mutatingP2PVerb`, for Codex's PreToolUse hook). Defence in depth only:
231
+ * parsed conservatively, it may refuse a harmless command, never the reverse
232
+ * on purpose, but a determined command can spell things another way.
233
+ */
234
+ export declare function mutatingP2PVerb(command: string, binNames?: readonly string[], depth?: number): string | null;
235
+ /**
236
+ * Whether a shell command reaches the backup phrase file or the CLI's key
237
+ * store (`.p2p` together with `backup`, or the `.p2p` folder listed, globbed
238
+ * or its key store). Best effort, like every guard here.
239
+ */
240
+ export declare function touchesSecrets(command: string): boolean;
241
+ /**
242
+ * The approval policy, sandbox and reviewer of a Codex session from its
243
+ * rollout transcript (`transcript_path` in a hook's payload): the last
244
+ * `turn_context` line wins. Best effort: the transcript is Codex's internal
245
+ * format, so anything unreadable is left unknown (and unknown holds).
246
+ */
247
+ export declare function modeFromTranscript(tail: string): CodexMode;
248
+ /** Marks the Codex process's TMPDIR among writable roots (resolved by the bridge, which inherits it). */
249
+ export declare const TMPDIR_ROOT = "@tmpdir";
250
+ /**
251
+ * Where the session's sandboxed commands may write, from a turn context:
252
+ * a list of roots (TMPDIR as `@tmpdir`), "all" (no sandbox, or root
253
+ * writable), or undefined when it can't be told (an unknown policy shape:
254
+ * treated as "could be anywhere").
255
+ */
256
+ export declare function writableRootsOf(p: Record<string, unknown>): string[] | "all" | undefined;
257
+ /** One rollout line, when it is a `turn_context`: the mode it records, its turn, cwd and writable roots. */
258
+ export declare function turnContextOf(line: string): {
259
+ mode: CodexMode;
260
+ turnId?: string;
261
+ cwd?: string;
262
+ writable?: string[] | "all";
263
+ at?: number;
264
+ } | null;
265
+ /** Whether `path` is `root` or inside it (both already resolved; case-insensitive on macOS/Windows). */
266
+ export declare function isInside(path: string, root: string, caseless?: boolean): boolean;
267
+ /** A mode that, by itself, says the session acts without asking (one source is enough to hold). */
268
+ export declare function isExplicitlyAuto(m: CodexMode | null | undefined): boolean;
269
+ export type ModeClass = "asking" | "auto" | "unknown";
270
+ /**
271
+ * What this session's mode is, from the sources the bridge trusts:
272
+ * - `transcript`: the latest turn context in this thread's own rollout file
273
+ * under CODEX_HOME/sessions, which the bridge reads itself (a sandboxed
274
+ * command can't write it);
275
+ * - `meta`: the sandbox and auto-review Codex puts on each tool call;
276
+ * - `reportedAuto`: a hook reported an auto-approving mode. Hooks reach
277
+ * the bridge over a local socket anyone running as the user can talk
278
+ * to, so a report can only make the mode stricter, never looser.
279
+ * `confirmed` false (at UserPromptSubmit, before this turn's context is
280
+ * certainly written) makes anything short of "auto" unknown.
281
+ * "asking" needs the transcript's approval and sandbox, both asking, and no
282
+ * source saying otherwise. Unknown is never treated as asking.
283
+ */
284
+ export declare function classifyMode(o: {
285
+ transcript: CodexMode;
286
+ meta: CodexMode;
287
+ reportedAuto: boolean;
288
+ confirmed: boolean;
289
+ }): ModeClass;
290
+ export type Screen = {
291
+ deliver: true;
292
+ } | {
293
+ deliver: false;
294
+ reason: "auto" | "unknown";
295
+ why: string;
296
+ };
297
+ /**
298
+ * The hold rule on a classified mode (a location refusal holds everything): own devices and P2P_AUTO_DELIVER
299
+ * senders are delivered; otherwise only an asking session delivers. An
300
+ * auto-approving one holds for the person; an unknown one holds until the
301
+ * mode is known (and then delivers only if it asks).
302
+ */
303
+ export declare function screenMessage(o: {
304
+ fromSelf: boolean;
305
+ fromUserId: string;
306
+ mode: ModeClass;
307
+ autoDeliver: AutoDeliver;
308
+ refused?: string | undefined;
309
+ }): Screen;
310
+ /** What a tool call's `_meta["x-codex-turn-metadata"]` says: the thread and the sandbox. */
311
+ export declare function fromToolMeta(meta: unknown): {
312
+ threadId?: string;
313
+ mode: CodexMode;
314
+ };
315
+ /** Merges what one source knows over what another knew: known values win, unknown ones keep the old. */
316
+ export declare function mergeMode(base: CodexMode, next: CodexMode): CodexMode;
317
+ /**
318
+ * The files a tool call changed, as the model named them: apply_patch
319
+ * envelopes (`*** Update File: path`, in any string of the input), and an
320
+ * edit tool's `file_path`/`path`. Made repo-relative (or dropped) by the
321
+ * caller; never shared as given.
322
+ */
323
+ export declare function editedFiles(toolName: string, input: unknown): string[];
324
+ /** Stands for a `$` or backtick that was quoted text (shellTokens' markLiteral): never an expansion. */
325
+ export declare const LITERAL = "\uE000";
326
+ /**
327
+ * A shell command line as words, the way a POSIX shell reads them: adjacent quoted and unquoted
328
+ * parts join into one word (`''x1` and `"x"1` are `x1`), backslashes escape, `$'…'` is
329
+ * ANSI-C quoted, and `;`, `|`, `&`, `(`, `)`, `<`, `>` and newlines separate words. Expansions
330
+ * (`$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.
332
+ */
333
+ export declare function shellTokens(command: string, markLiteral?: boolean): string[];
334
+ /** `p` made absolute against `cwd` (POSIX or Windows separators), `.` and `..` resolved. Linear: no regex over the input. */
335
+ export declare function resolveLike(cwd: string, p: string): string;
336
+ /** At most this many folders one command may name; past it the session is private (`over`). */
337
+ export declare const MAX_COMMAND_PATHS = 256;
338
+ /**
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.
344
+ */
345
+ export declare function shellPaths(command: string, cwd: string, home?: string): {
346
+ paths: string[];
347
+ over: boolean;
348
+ };
349
+ /** Whether a command runs interpreter code given inline, or anything under a pseudo-terminal wrapper (by its words: linear). */
350
+ export declare function hidesCommand(command: string): 'interpreter' | 'pty' | null;
351
+ /** Commands naming p2p longer than this are refused unread. */
352
+ export declare const MAX_GUARDED_COMMAND: number;
353
+ /** Whether a command line names the p2p CLI (as a word, a path ending in it, the bundle or its variables). */
354
+ export declare function namesP2PCli(command: string): boolean;
355
+ /**
356
+ * Why a shell command naming p2p is refused beyond its verb, or null (projects.ts): it speaks for a
357
+ * session other than this bridge's own (`--from-session`/`--session`, read as the shell reads them),
358
+ * hides p2p inside interpreter code or a pseudo-terminal, or shares a project.
359
+ */
360
+ export declare function boundaryRefusal(command: string, ownSid: string | undefined): string | null;
361
+ /** A `p2p` session id as the CLI takes it: `[A-Za-z0-9._-]`, at most 128. */
362
+ export declare function isSid(sid: string): boolean;
363
+ /** The one-shot notice `notify_when_idle` asked for. */
364
+ export declare function idleNotice(address: string, reason: string): string;
365
+ /**
366
+ * Which local Codex session holds a message no session was named for: the
367
+ * live one the person used most recently (ties: the lowest sid). Each
368
+ * session computes the same answer from the same registry, so at most one
369
+ * holds it.
370
+ */
371
+ export declare function pickHolder(board: readonly {
372
+ sid: string;
373
+ activeAt: number;
374
+ }[]): string | undefined;