@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/LICENSE +201 -0
- package/README.md +214 -2
- package/dist/bridge.d.ts +380 -0
- package/dist/bridge.js +1116 -0
- package/dist/commands.d.ts +47 -0
- package/dist/commands.js +141 -0
- package/dist/confirm.d.ts +68 -0
- package/dist/confirm.js +248 -0
- package/dist/hook.d.ts +22 -0
- package/dist/hook.js +144 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +18 -0
- package/dist/install.d.ts +76 -0
- package/dist/install.js +264 -0
- package/dist/ipc.d.ts +69 -0
- package/dist/ipc.js +302 -0
- package/dist/knobs.d.ts +266 -0
- package/dist/knobs.js +1020 -0
- package/dist/lib.d.ts +374 -0
- package/dist/lib.js +987 -0
- package/dist/mcp.d.ts +66 -0
- package/dist/mcp.js +181 -0
- package/dist/p2p.d.ts +135 -0
- package/dist/p2p.js +121 -0
- package/dist/server.d.ts +41 -0
- package/dist/server.js +274 -0
- package/dist/tools.d.ts +7 -0
- package/dist/tools.js +207 -0
- package/dist/trusted.d.ts +46 -0
- package/dist/trusted.js +177 -0
- package/package.json +48 -4
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export declare const PROTOCOL_VERSION = "2025-06-18";
|
|
2
|
+
export type JsonObject = Record<string, unknown>;
|
|
3
|
+
export interface ToolResult {
|
|
4
|
+
content: {
|
|
5
|
+
type: "text";
|
|
6
|
+
text: string;
|
|
7
|
+
}[];
|
|
8
|
+
isError?: boolean;
|
|
9
|
+
structuredContent?: JsonObject;
|
|
10
|
+
}
|
|
11
|
+
export interface Tool {
|
|
12
|
+
name: string;
|
|
13
|
+
title?: string;
|
|
14
|
+
description: string;
|
|
15
|
+
inputSchema: JsonObject;
|
|
16
|
+
annotations?: JsonObject;
|
|
17
|
+
call(args: JsonObject, ctx: CallContext): Promise<ToolResult>;
|
|
18
|
+
}
|
|
19
|
+
export interface CallContext {
|
|
20
|
+
/** Sends a request to the client (Codex) and waits for its answer. */
|
|
21
|
+
request(method: string, params: JsonObject, timeoutMs?: number): Promise<unknown>;
|
|
22
|
+
/** What the client said it can do at initialize. */
|
|
23
|
+
clientCapabilities: JsonObject;
|
|
24
|
+
/** The request's `_meta` (Codex puts its turn metadata there). */
|
|
25
|
+
meta?: unknown;
|
|
26
|
+
}
|
|
27
|
+
export interface ServerInfo {
|
|
28
|
+
name: string;
|
|
29
|
+
version: string;
|
|
30
|
+
instructions?: string;
|
|
31
|
+
}
|
|
32
|
+
export declare const text: (body: string, isError?: boolean) => ToolResult;
|
|
33
|
+
/**
|
|
34
|
+
* Serves `tools` on a line-oriented transport. `write` gets one JSON line per
|
|
35
|
+
* message; feed incoming lines to the returned `onLine`.
|
|
36
|
+
*/
|
|
37
|
+
export declare class McpServer {
|
|
38
|
+
private readonly info;
|
|
39
|
+
private readonly tools;
|
|
40
|
+
private readonly write;
|
|
41
|
+
private readonly refuse;
|
|
42
|
+
private readonly pending;
|
|
43
|
+
private nextId;
|
|
44
|
+
clientCapabilities: JsonObject;
|
|
45
|
+
clientInfo: JsonObject;
|
|
46
|
+
/** Called once the client sent `notifications/initialized`. */
|
|
47
|
+
onInitialized?: () => void;
|
|
48
|
+
/** Called for a tool name the server does not list (after the refusal). */
|
|
49
|
+
onUnknownTool?: (name: string) => void;
|
|
50
|
+
constructor(info: ServerInfo, tools: readonly Tool[], write: (line: string) => void, refuse?: (name: string) => ToolResult | null);
|
|
51
|
+
private send;
|
|
52
|
+
request(method: string, params: JsonObject, timeoutMs?: number): Promise<unknown>;
|
|
53
|
+
/** Rejects every request still waiting on the client (the transport closed). */
|
|
54
|
+
close(): void;
|
|
55
|
+
onLine(line: string): Promise<void>;
|
|
56
|
+
private dispatch;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Splits a stream into lines and hands each to the server as it arrives.
|
|
60
|
+
* Not serialised: a tool call that waits on the client (elicitation) must not
|
|
61
|
+
* block the line that carries the client's answer.
|
|
62
|
+
*/
|
|
63
|
+
export declare function lineFeeder(onLine: (line: string) => Promise<void>): {
|
|
64
|
+
push(chunk: string): void;
|
|
65
|
+
end(): Promise<void>;
|
|
66
|
+
};
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// A minimal MCP server over stdio: newline-delimited JSON-RPC 2.0, as the
|
|
4
|
+
// MCP stdio transport specifies (one message per line, nothing else on
|
|
5
|
+
// stdout). Just what the bridge needs: initialize, ping, tools/list,
|
|
6
|
+
// tools/call, and server-to-client requests (elicitation/create, roots/list).
|
|
7
|
+
// No SDK dependency, so the bundled `p2p.mjs` stays one self-contained file.
|
|
8
|
+
export const PROTOCOL_VERSION = "2025-06-18";
|
|
9
|
+
const SUPPORTED_VERSIONS = new Set(["2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"]);
|
|
10
|
+
export const text = (body, isError = false) => ({ content: [{ type: "text", text: body }], ...(isError ? { isError: true } : {}) });
|
|
11
|
+
/**
|
|
12
|
+
* Serves `tools` on a line-oriented transport. `write` gets one JSON line per
|
|
13
|
+
* message; feed incoming lines to the returned `onLine`.
|
|
14
|
+
*/
|
|
15
|
+
export class McpServer {
|
|
16
|
+
info;
|
|
17
|
+
tools;
|
|
18
|
+
write;
|
|
19
|
+
refuse;
|
|
20
|
+
pending = new Map();
|
|
21
|
+
nextId = 1;
|
|
22
|
+
clientCapabilities = {};
|
|
23
|
+
clientInfo = {};
|
|
24
|
+
/** Called once the client sent `notifications/initialized`. */
|
|
25
|
+
onInitialized;
|
|
26
|
+
/** Called for a tool name the server does not list (after the refusal). */
|
|
27
|
+
onUnknownTool;
|
|
28
|
+
constructor(info, tools, write, refuse = () => null) {
|
|
29
|
+
this.info = info;
|
|
30
|
+
this.tools = tools;
|
|
31
|
+
this.write = write;
|
|
32
|
+
this.refuse = refuse;
|
|
33
|
+
}
|
|
34
|
+
send(msg) {
|
|
35
|
+
this.write(JSON.stringify({ jsonrpc: "2.0", ...msg }));
|
|
36
|
+
}
|
|
37
|
+
request(method, params, timeoutMs = 60_000) {
|
|
38
|
+
const id = this.nextId++;
|
|
39
|
+
return new Promise((resolve, reject) => {
|
|
40
|
+
const timer = setTimeout(() => {
|
|
41
|
+
this.pending.delete(id);
|
|
42
|
+
reject(new Error(`${method} timed out`));
|
|
43
|
+
}, timeoutMs);
|
|
44
|
+
timer.unref?.();
|
|
45
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
46
|
+
this.send({ id, method, params });
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/** Rejects every request still waiting on the client (the transport closed). */
|
|
50
|
+
close() {
|
|
51
|
+
for (const [id, p] of this.pending) {
|
|
52
|
+
clearTimeout(p.timer);
|
|
53
|
+
p.reject(new Error("closed"));
|
|
54
|
+
this.pending.delete(id);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async onLine(line) {
|
|
58
|
+
if (line.trim() === "")
|
|
59
|
+
return;
|
|
60
|
+
let msg;
|
|
61
|
+
try {
|
|
62
|
+
const v = JSON.parse(line);
|
|
63
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
64
|
+
throw new Error("not an object");
|
|
65
|
+
msg = v;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
this.send({ id: null, error: { code: -32700, message: "Parse error" } });
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const id = msg.id;
|
|
72
|
+
const method = typeof msg.method === "string" ? msg.method : undefined;
|
|
73
|
+
// A response to one of our requests.
|
|
74
|
+
if (method === undefined) {
|
|
75
|
+
if (typeof id === "number" && this.pending.has(id)) {
|
|
76
|
+
const p = this.pending.get(id);
|
|
77
|
+
this.pending.delete(id);
|
|
78
|
+
clearTimeout(p.timer);
|
|
79
|
+
if (msg.error)
|
|
80
|
+
p.reject(new Error(String(msg.error.message ?? "error")));
|
|
81
|
+
else
|
|
82
|
+
p.resolve(msg.result);
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const isNotification = id === undefined || id === null;
|
|
87
|
+
try {
|
|
88
|
+
const result = await this.dispatch(method, (msg.params ?? {}));
|
|
89
|
+
if (!isNotification)
|
|
90
|
+
this.send({ id, result });
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
if (!isNotification) {
|
|
94
|
+
const err = e;
|
|
95
|
+
this.send({ id, error: { code: typeof err.code === "number" ? err.code : -32603, message: String(err.message ?? e) } });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
async dispatch(method, params) {
|
|
100
|
+
switch (method) {
|
|
101
|
+
case "initialize": {
|
|
102
|
+
this.clientCapabilities = (params.capabilities ?? {});
|
|
103
|
+
this.clientInfo = (params.clientInfo ?? {});
|
|
104
|
+
const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION;
|
|
105
|
+
return {
|
|
106
|
+
protocolVersion: SUPPORTED_VERSIONS.has(asked) ? asked : PROTOCOL_VERSION,
|
|
107
|
+
capabilities: { tools: { listChanged: false } },
|
|
108
|
+
serverInfo: { name: this.info.name, version: this.info.version },
|
|
109
|
+
...(this.info.instructions ? { instructions: this.info.instructions } : {}),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
case "notifications/initialized":
|
|
113
|
+
this.onInitialized?.();
|
|
114
|
+
return {};
|
|
115
|
+
case "ping":
|
|
116
|
+
return {};
|
|
117
|
+
case "tools/list":
|
|
118
|
+
return {
|
|
119
|
+
tools: this.tools.map((t) => ({
|
|
120
|
+
name: t.name,
|
|
121
|
+
...(t.title ? { title: t.title } : {}),
|
|
122
|
+
description: t.description,
|
|
123
|
+
inputSchema: t.inputSchema,
|
|
124
|
+
...(t.annotations ? { annotations: t.annotations } : {}),
|
|
125
|
+
})),
|
|
126
|
+
};
|
|
127
|
+
case "tools/call": {
|
|
128
|
+
const name = String(params.name ?? "");
|
|
129
|
+
const args = (typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {});
|
|
130
|
+
const tool = this.tools.find((t) => t.name === name);
|
|
131
|
+
if (!tool) {
|
|
132
|
+
this.onUnknownTool?.(name);
|
|
133
|
+
return this.refuse(name) ?? text(`Unknown tool: ${name.replace(/[^\w.-]/g, "").slice(0, 64)}`, true);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
return await tool.call(args, { request: (m, p, t) => this.request(m, p, t), clientCapabilities: this.clientCapabilities, meta: params._meta });
|
|
137
|
+
}
|
|
138
|
+
catch (e) {
|
|
139
|
+
return text(`${name} failed: ${String(e?.message ?? e).replace(/[<>\p{Cc}\p{Cf}]/gu, " ")}`, true);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
case "resources/list":
|
|
143
|
+
return { resources: [] };
|
|
144
|
+
case "prompts/list":
|
|
145
|
+
return { prompts: [] };
|
|
146
|
+
default:
|
|
147
|
+
if (method.startsWith("notifications/"))
|
|
148
|
+
return {};
|
|
149
|
+
throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Splits a stream into lines and hands each to the server as it arrives.
|
|
155
|
+
* Not serialised: a tool call that waits on the client (elicitation) must not
|
|
156
|
+
* block the line that carries the client's answer.
|
|
157
|
+
*/
|
|
158
|
+
export function lineFeeder(onLine) {
|
|
159
|
+
let buffer = "";
|
|
160
|
+
const inflight = new Set();
|
|
161
|
+
const run = (line) => {
|
|
162
|
+
const p = onLine(line.replace(/\r$/, "")).catch(() => undefined);
|
|
163
|
+
inflight.add(p);
|
|
164
|
+
void p.finally(() => inflight.delete(p));
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
push(chunk) {
|
|
168
|
+
buffer += chunk;
|
|
169
|
+
const parts = buffer.split("\n");
|
|
170
|
+
buffer = parts.pop() ?? "";
|
|
171
|
+
for (const line of parts)
|
|
172
|
+
run(line);
|
|
173
|
+
},
|
|
174
|
+
async end() {
|
|
175
|
+
if (buffer.trim() !== "")
|
|
176
|
+
run(buffer);
|
|
177
|
+
buffer = "";
|
|
178
|
+
await Promise.all([...inflight]);
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
package/dist/p2p.d.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { PeerRow } from "./lib.js";
|
|
2
|
+
export type RunResult = {
|
|
3
|
+
exitCode: number;
|
|
4
|
+
stdout: string;
|
|
5
|
+
stderr: string;
|
|
6
|
+
};
|
|
7
|
+
/** Runs a command by argv. */
|
|
8
|
+
export interface Exec {
|
|
9
|
+
run(argv: readonly string[], init?: {
|
|
10
|
+
stdin?: string;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}): Promise<RunResult>;
|
|
13
|
+
}
|
|
14
|
+
export type Outcome<T> = {
|
|
15
|
+
ok: true;
|
|
16
|
+
value: T;
|
|
17
|
+
} | {
|
|
18
|
+
ok: false;
|
|
19
|
+
error: string;
|
|
20
|
+
reason: string;
|
|
21
|
+
};
|
|
22
|
+
/** Exec over node's child_process with the given environment. */
|
|
23
|
+
export declare function nodeExec(env?: NodeJS.ProcessEnv): Exec;
|
|
24
|
+
/** The JSON object a `--json` command printed (its last line), or null. */
|
|
25
|
+
export declare function parseJson<T>(stdout: string): T | null;
|
|
26
|
+
export type Whoami = {
|
|
27
|
+
userId: string;
|
|
28
|
+
name: string;
|
|
29
|
+
address: string;
|
|
30
|
+
did: string;
|
|
31
|
+
relays: string[];
|
|
32
|
+
};
|
|
33
|
+
export type HeldItem = {
|
|
34
|
+
id: string;
|
|
35
|
+
type: string;
|
|
36
|
+
from: string;
|
|
37
|
+
at: number;
|
|
38
|
+
address: string;
|
|
39
|
+
summary: string;
|
|
40
|
+
cid?: string;
|
|
41
|
+
};
|
|
42
|
+
export type RosterView = {
|
|
43
|
+
sid: string;
|
|
44
|
+
ref: string;
|
|
45
|
+
vis: "circle" | "private";
|
|
46
|
+
circle?: string;
|
|
47
|
+
parts: {
|
|
48
|
+
userId: string;
|
|
49
|
+
address: string;
|
|
50
|
+
}[];
|
|
51
|
+
};
|
|
52
|
+
export type SendResult = {
|
|
53
|
+
delivered: boolean;
|
|
54
|
+
to: {
|
|
55
|
+
userId: string;
|
|
56
|
+
address: string;
|
|
57
|
+
own: string;
|
|
58
|
+
sid: string;
|
|
59
|
+
ref: string;
|
|
60
|
+
};
|
|
61
|
+
relays: number;
|
|
62
|
+
};
|
|
63
|
+
/** What `p2p status` says about the session's projects (projects.ts). */
|
|
64
|
+
export type ProjectInfo = {
|
|
65
|
+
projects: {
|
|
66
|
+
id: string;
|
|
67
|
+
name: string;
|
|
68
|
+
}[];
|
|
69
|
+
policy: "private" | "shared" | "none";
|
|
70
|
+
why?: string;
|
|
71
|
+
circles?: string[];
|
|
72
|
+
people?: string[];
|
|
73
|
+
};
|
|
74
|
+
export type RelaysInfo = {
|
|
75
|
+
listed: string[];
|
|
76
|
+
connected: string[];
|
|
77
|
+
failed: {
|
|
78
|
+
url: string;
|
|
79
|
+
reason: string;
|
|
80
|
+
}[];
|
|
81
|
+
};
|
|
82
|
+
export declare class P2P {
|
|
83
|
+
private readonly exec;
|
|
84
|
+
/** The `p2p` command, argv[0] first. */
|
|
85
|
+
readonly bin: readonly string[];
|
|
86
|
+
constructor(exec: Exec,
|
|
87
|
+
/** The `p2p` command, argv[0] first. */
|
|
88
|
+
bin: readonly string[]);
|
|
89
|
+
/** Runs `p2p <args> --json` and parses its one JSON object. Never rejects. */
|
|
90
|
+
call<T>(args: readonly string[], init?: {
|
|
91
|
+
stdin?: string;
|
|
92
|
+
timeoutMs?: number;
|
|
93
|
+
}): Promise<Outcome<T>>;
|
|
94
|
+
whoami(): Promise<Outcome<Whoami>>;
|
|
95
|
+
ls(): Promise<Outcome<{
|
|
96
|
+
peers: PeerRow[];
|
|
97
|
+
relays?: RelaysInfo;
|
|
98
|
+
}>>;
|
|
99
|
+
/**
|
|
100
|
+
* This session's status. Never a mode: what this session auto-approves is nobody else's business.
|
|
101
|
+
* `projectDirs`: every folder the session has worked in (projects.ts binds each one's project).
|
|
102
|
+
*/
|
|
103
|
+
status(o: {
|
|
104
|
+
session: string;
|
|
105
|
+
state: "busy" | "idle";
|
|
106
|
+
label: string;
|
|
107
|
+
repo?: string;
|
|
108
|
+
branch?: string;
|
|
109
|
+
summary?: string;
|
|
110
|
+
files?: readonly string[];
|
|
111
|
+
projectDirs?: readonly string[];
|
|
112
|
+
projectDirsOver?: boolean;
|
|
113
|
+
}, timeoutMs?: number): Promise<Outcome<{
|
|
114
|
+
delivered: unknown[];
|
|
115
|
+
failed: {
|
|
116
|
+
address: string;
|
|
117
|
+
error: string;
|
|
118
|
+
}[];
|
|
119
|
+
roster?: RosterView;
|
|
120
|
+
warnings?: string[];
|
|
121
|
+
project?: ProjectInfo;
|
|
122
|
+
}>>;
|
|
123
|
+
/** A message from this session; refused (`not_shared`) to anyone its projects don't share (projects.ts). */
|
|
124
|
+
send(o: {
|
|
125
|
+
fromSession: string;
|
|
126
|
+
to: string;
|
|
127
|
+
text: string;
|
|
128
|
+
notifyWhenIdle?: boolean;
|
|
129
|
+
projectDirs?: readonly string[];
|
|
130
|
+
projectDirsOver?: boolean;
|
|
131
|
+
}): Promise<Outcome<SendResult>>;
|
|
132
|
+
/** This session's roster, read only (the default circle, else private). Changing it is the person's, in a terminal. */
|
|
133
|
+
roster(sid: string): Promise<Outcome<RosterView>>;
|
|
134
|
+
held(): Promise<Outcome<HeldItem[]>>;
|
|
135
|
+
}
|
package/dist/p2p.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// The bridge's calls to the `p2p` CLI, as child processes (argv, no shell),
|
|
4
|
+
// mirroring the Claude mod's backend (mods/claude/peer2peer/hooks/backend.ts).
|
|
5
|
+
// The bridge never touches keys: `p2p` holds the identity and device keys,
|
|
6
|
+
// seals and verifies every envelope, and keeps its state in P2P_HOME.
|
|
7
|
+
// Peer-derived positionals follow `--` and peer-derived option values use
|
|
8
|
+
// `--opt=value`, so neither can be read as a flag. Message text goes over
|
|
9
|
+
// stdin (`--stdin`), never argv, so it never shows in a process listing.
|
|
10
|
+
//
|
|
11
|
+
// Only read-only and session-scoped verbs are here: whoami, ls, status, send,
|
|
12
|
+
// held (list), friends, session roster (read, no change) and watch. Nothing
|
|
13
|
+
// that changes who reaches this user (join, approve, relays, invite, …).
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { inert } from "./lib.js";
|
|
16
|
+
const TIMEOUT_MS = 30_000;
|
|
17
|
+
/** Exec over node's child_process with the given environment. */
|
|
18
|
+
export function nodeExec(env = process.env) {
|
|
19
|
+
return {
|
|
20
|
+
run: (argv, init) => new Promise((resolve, reject) => {
|
|
21
|
+
const child = spawn(argv[0], argv.slice(1), { env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
22
|
+
let stdout = "";
|
|
23
|
+
let stderr = "";
|
|
24
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), init?.timeoutMs ?? TIMEOUT_MS);
|
|
25
|
+
child.stdout.on("data", (d) => (stdout += String(d)));
|
|
26
|
+
child.stderr.on("data", (d) => (stderr = `${stderr}${String(d)}`.slice(-8_000)));
|
|
27
|
+
child.on("error", (e) => {
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
reject(e);
|
|
30
|
+
});
|
|
31
|
+
child.on("close", (code) => {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
resolve({ exitCode: code ?? 1, stdout, stderr });
|
|
34
|
+
});
|
|
35
|
+
child.stdin.on("error", () => { });
|
|
36
|
+
child.stdin.end(init?.stdin ?? "");
|
|
37
|
+
}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** The JSON object a `--json` command printed (its last line), or null. */
|
|
41
|
+
export function parseJson(stdout) {
|
|
42
|
+
const lines = stdout.trim().split("\n");
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(lines.at(-1) ?? "");
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export class P2P {
|
|
51
|
+
exec;
|
|
52
|
+
bin;
|
|
53
|
+
constructor(exec,
|
|
54
|
+
/** The `p2p` command, argv[0] first. */
|
|
55
|
+
bin) {
|
|
56
|
+
this.exec = exec;
|
|
57
|
+
this.bin = bin;
|
|
58
|
+
}
|
|
59
|
+
/** Runs `p2p <args> --json` and parses its one JSON object. Never rejects. */
|
|
60
|
+
async call(args, init = {}) {
|
|
61
|
+
const dash = args.indexOf("--");
|
|
62
|
+
const argv = dash < 0 ? [...args, "--json"] : [...args.slice(0, dash), "--json", ...args.slice(dash)];
|
|
63
|
+
let ran;
|
|
64
|
+
try {
|
|
65
|
+
ran = await this.exec.run([...this.bin, ...argv], { timeoutMs: init.timeoutMs ?? TIMEOUT_MS, ...(init.stdin !== undefined ? { stdin: init.stdin } : {}) });
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
return { ok: false, error: "cli_missing", reason: `could not run ${this.bin.join(" ")}: ${inert(String(e?.message ?? e))}` };
|
|
69
|
+
}
|
|
70
|
+
const parsed = parseJson(ran.stdout);
|
|
71
|
+
if (ran.exitCode === 0 && parsed !== null)
|
|
72
|
+
return { ok: true, value: parsed };
|
|
73
|
+
const error = typeof parsed?.error === "string" ? parsed.error : ran.exitCode === 0 ? "unreadable" : "failed";
|
|
74
|
+
const last = ran.stderr.trim().split("\n").pop() ?? "";
|
|
75
|
+
const reason = typeof parsed?.reason === "string" ? parsed.reason : last || `p2p ${args[0] ?? ""} exited ${ran.exitCode}`;
|
|
76
|
+
return { ok: false, error, reason: inert(reason) };
|
|
77
|
+
}
|
|
78
|
+
whoami() {
|
|
79
|
+
return this.call(["whoami"]);
|
|
80
|
+
}
|
|
81
|
+
async ls() {
|
|
82
|
+
const r = await this.call(["ls"]);
|
|
83
|
+
if (!r.ok)
|
|
84
|
+
return r;
|
|
85
|
+
return { ok: true, value: { peers: Array.isArray(r.value.peers) ? r.value.peers : [], ...(r.value.relays ? { relays: r.value.relays } : {}) } };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* This session's status. Never a mode: what this session auto-approves is nobody else's business.
|
|
89
|
+
* `projectDirs`: every folder the session has worked in (projects.ts binds each one's project).
|
|
90
|
+
*/
|
|
91
|
+
status(o, timeoutMs) {
|
|
92
|
+
const args = ["status", `--session=${o.session}`, `--state=${o.state}`, `--label=${o.label}`];
|
|
93
|
+
if (o.repo)
|
|
94
|
+
args.push(`--repo=${o.repo}`);
|
|
95
|
+
if (o.branch)
|
|
96
|
+
args.push(`--branch=${o.branch}`);
|
|
97
|
+
if (o.summary)
|
|
98
|
+
args.push(`--summary=${o.summary}`);
|
|
99
|
+
for (const file of o.files ?? [])
|
|
100
|
+
args.push(`--file=${file}`);
|
|
101
|
+
for (const dir of o.projectDirs ?? [])
|
|
102
|
+
args.push(`--project-dir=${dir}`);
|
|
103
|
+
if (o.projectDirsOver)
|
|
104
|
+
args.push("--project-dirs-over");
|
|
105
|
+
return this.call(args, timeoutMs !== undefined ? { timeoutMs } : {});
|
|
106
|
+
}
|
|
107
|
+
/** A message from this session; refused (`not_shared`) to anyone its projects don't share (projects.ts). */
|
|
108
|
+
send(o) {
|
|
109
|
+
const dirs = [...(o.projectDirs ?? []).map((d) => `--project-dir=${d}`), ...(o.projectDirsOver ? ["--project-dirs-over"] : [])];
|
|
110
|
+
return this.call(["send", `--from-session=${o.fromSession}`, `--to=${o.to}`, ...(o.notifyWhenIdle ? ["--notify-when-idle"] : []), ...dirs, "--stdin"], { stdin: o.text });
|
|
111
|
+
}
|
|
112
|
+
/** This session's roster, read only (the default circle, else private). Changing it is the person's, in a terminal. */
|
|
113
|
+
async roster(sid) {
|
|
114
|
+
const r = await this.call(["session", "roster", "--", sid]);
|
|
115
|
+
return r.ok ? { ok: true, value: r.value.roster } : r;
|
|
116
|
+
}
|
|
117
|
+
async held() {
|
|
118
|
+
const r = await this.call(["held"]);
|
|
119
|
+
return r.ok ? { ok: true, value: Array.isArray(r.value.held) ? r.value.held : [] } : r;
|
|
120
|
+
}
|
|
121
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Readable, Writable } from "node:stream";
|
|
2
|
+
import { type HookReport, type WatchRunner } from "./bridge.js";
|
|
3
|
+
export declare const BRIDGE_VERSION = "0.1.0";
|
|
4
|
+
export type Env = Record<string, string | undefined>;
|
|
5
|
+
export declare function resolveHome(env: Env): string;
|
|
6
|
+
/** `p2p watch` as a child: stdout lines as they come; killed when `signal` aborts. */
|
|
7
|
+
export declare function childWatch(env: Env, extra?: Env): WatchRunner;
|
|
8
|
+
/**
|
|
9
|
+
* `git <args>` in `cwd`: git by absolute path, with a scrubbed environment
|
|
10
|
+
* (no GIT_*, a fixed system PATH) and no fsmonitor, so neither the
|
|
11
|
+
* server's env (which a project config can set) nor the repo picks what
|
|
12
|
+
* runs. Its trimmed stdout, or undefined.
|
|
13
|
+
*/
|
|
14
|
+
export declare function gitIn(git?: string | undefined): (cwd: string, args: readonly string[]) => Promise<string | undefined>;
|
|
15
|
+
/**
|
|
16
|
+
* `codex queue --thread <id> --message <text>` (opt-in, P2P_CODEX_QUEUE=1):
|
|
17
|
+
* P2P_CODEX_BIN when it is an absolute path, else `codex` from the usual
|
|
18
|
+
* install folders, never through the env's PATH. Its PATH is the node
|
|
19
|
+
* running this server plus the system folders (an npm-installed `codex` is
|
|
20
|
+
* a node script). Undefined (no queueing) when there is no such binary.
|
|
21
|
+
*/
|
|
22
|
+
export declare function codexQueue(env: Env, log?: (line: string) => void): ((threadId: string, text: string) => Promise<boolean>) | undefined;
|
|
23
|
+
/** A hook report off the socket, reduced to the fields and types the bridge reads. */
|
|
24
|
+
/**
|
|
25
|
+
* The person token in `<P2P_HOME>/cli/person.key` (made here if the CLI hasn't yet): what lets the
|
|
26
|
+
* CLI tell this bridge's runs from the model's own shell (packages/p2p/src/projects.ts). Codex's
|
|
27
|
+
* sandbox may let a model's command read P2P_HOME: the token is then defence in depth only.
|
|
28
|
+
*/
|
|
29
|
+
export declare function personTokenOf(home: string | undefined): string | undefined;
|
|
30
|
+
export declare function sanitizeReport(raw: unknown): HookReport;
|
|
31
|
+
export interface McpOptions {
|
|
32
|
+
/** The argv that runs this very `p2p` script (P2P_BIN from the user-level config replaces it). */
|
|
33
|
+
bin: readonly string[];
|
|
34
|
+
env: Env;
|
|
35
|
+
stdin: Readable;
|
|
36
|
+
stdout: Writable;
|
|
37
|
+
stderr?: Writable;
|
|
38
|
+
cwd?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Serves MCP on stdin/stdout until stdin closes; then the final idle status and cleanup. */
|
|
41
|
+
export declare function runMcpServer(o: McpOptions): Promise<void>;
|