@kkcode-app/agent 1.0.10

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 ADDED
@@ -0,0 +1,139 @@
1
+ # @kkcode-app/opencode
2
+
3
+ KKCode 的桌面配套工具:它可将电脑上的 OpenCode HTTP server 或 Codex app-server 通过中继连接到手机,并作为 OpenCode 插件向 iPhone 发送提醒。
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ cd cli
9
+ npm install
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ### Default: spawn opencode serve for you
15
+
16
+ ```bash
17
+ npx -y @kkcode-app/opencode@latest
18
+ ```
19
+
20
+ This will:
21
+
22
+ 1. Spawn `opencode serve` on `127.0.0.1:<random-port>`.
23
+ 2. Open a WebSocket tunnel to the relay.
24
+ 3. Print a QR code. In KKCode, open **Servers** →
25
+ **Scan tunnel QR code**, then scan the terminal QR code.
26
+
27
+ Keep the terminal open while using the connection. The CLI reconnects after a
28
+ temporary network loss. Use KKCode's manual server-address entry only for a
29
+ normal LAN/Tailscale/OpenCode URL: a tunnel QR code contains a temporary access
30
+ token and must be scanned.
31
+
32
+ ### Codex app-server Bridge
33
+
34
+ ```bash
35
+ npx -y @kkcode-app/opencode@latest --backend codex
36
+ ```
37
+
38
+ Codex mode spawns `codex app-server` over stdio, completes the
39
+ `initialize`/`initialized` handshake, and exposes a token-protected HTTP/SSE
40
+ Bridge on a random `127.0.0.1` port. The tunnel injects the local bridge token;
41
+ it is never included in the QR code. Codex QR payloads use version 5 with
42
+ `backend: "codex"` and `bridgeProtocol: 1`; OpenCode QR payloads remain version 4.
43
+
44
+ Codex mode does not support `--attach` or background service lifecycle commands,
45
+ including `--install`. Keep the foreground process open.
46
+
47
+ Bridge protocol v1 endpoints:
48
+
49
+ | Endpoint | Behavior |
50
+ | --------------------------------------------------- | ---------------------------------------------------------- |
51
+ | `GET /codex/v1/meta` | Bridge version, sequence range, timeout and RPC allowlist |
52
+ | `POST /codex/v1/rpc` | Allowlisted synchronous app-server RPC, 15 second timeout |
53
+ | `GET /codex/v1/events?after=<sequence>` | SSE ready event, bounded replay, live events and heartbeat |
54
+ | `GET /codex/v1/server-requests` | Pending app-server requests with type-safe `resolveId` |
55
+ | `POST /codex/v1/server-requests/:resolveId/resolve` | Return a `result` or JSON-RPC `error` to Codex |
56
+
57
+ Every endpoint requires `x-kkcode-bridge-token`. The Bridge only listens on
58
+ `127.0.0.1`; direct LAN access is intentionally unavailable.
59
+
60
+ ### Background service (macOS & Linux)
61
+
62
+ First run the tunnel in the foreground and scan its QR code in KKCode. Then
63
+ install the tunnel as a **background service** so it auto-starts on login and
64
+ auto-restarts on crash. On macOS it uses launchd (LaunchAgent), on Linux it
65
+ uses a systemd user service. The CLI refuses a first-time `--install`, because
66
+ the QR code would only be written to the service log instead of your terminal.
67
+
68
+ ```bash
69
+ npx -y @kkcode-app/opencode@latest --install
70
+ ```
71
+
72
+ The first time you run `--install` it captures the current `PATH` and the
73
+ absolute paths of `node` and `opencode`, so the background service can find
74
+ them even though the service manager does not source your shell profile.
75
+
76
+ Other commands:
77
+
78
+ ```bash
79
+ npx -y @kkcode-app/opencode@latest --status # check if installed/loaded/running
80
+ npx -y @kkcode-app/opencode@latest --restart # restart the background service
81
+ npx -y @kkcode-app/opencode@latest --uninstall # stop and remove the service
82
+ ```
83
+
84
+ Logs are written to `~/.config/kkcode/tunnel/tunnel.log`. The tunnel `code` and
85
+ shared `secret` are persisted across restarts, so your phone stays connected without re-scanning
86
+ as long as the relay session hasn't expired. If a legacy
87
+ `~/.config/opencode-tunnel/config.json` exists, it is migrated automatically
88
+ on first run.
89
+
90
+ ### Attach to an already running opencode serve
91
+
92
+ ```bash
93
+ opencode serve --port 4096 &
94
+ npx -y @kkcode-app/opencode@latest --attach --port 4096
95
+ ```
96
+
97
+ ### Flags
98
+
99
+ | Flag | Description | Default |
100
+ | ------------------ | --------------------------------------------------------------------- | --------------------------------------------------- |
101
+ | `--backend <name>` | Local backend: `opencode` or `codex` | `opencode` |
102
+ | `--relay <url>` | Relay base URL (`ws://` or `wss://`) | `$OPENCODE_RELAY_URL` or `wss://relay.kkcode.app` |
103
+ | `--port <n>` | Port for `opencode serve` (random free port if omitted) | random |
104
+ | `--hostname <h>` | Local hostname for `opencode serve` | `127.0.0.1` |
105
+ | `--attach` | Don't spawn — reuse an existing `opencode serve` | off |
106
+ | `--command <bin>` | Binary to spawn | `$OPENCODE_CMD`/`opencode`, or `$CODEX_CMD`/`codex` |
107
+ | `--reset-tunnel` | Forget the saved secret and create a new tunnel | off |
108
+ | `--install` | Install as macOS LaunchAgent (background, auto-start on login) | off |
109
+ | `--uninstall` | Remove the LaunchAgent and stop the background service | off |
110
+ | `--restart` | Restart the background service (`kickstart -k` / `systemctl restart`) | off |
111
+
112
+ ## iPhone notifications
113
+
114
+ In KKCode, enable notifications and copy the generated command. It includes a
115
+ phone-owned notification token, saves it to `~/.config/kkcode/notify.json`, and
116
+ registers `@kkcode-app/opencode` in `~/.config/opencode/opencode.json` in one
117
+ step. Restart OpenCode afterwards. Resetting the token in the app immediately
118
+ invalidates every earlier command.
119
+ | `--status` | Show whether the LaunchAgent is installed/loaded/running | off |
120
+
121
+ ## How it works
122
+
123
+ - The CLI registers as a "host" on the relay over a single WebSocket.
124
+ - The CLI generates a random shared secret and derives an opaque tunnel ID with SHA-256.
125
+ - The phone hits `https://relay.example.com/t/<tunnel-id>/...` with the secret in a
126
+ header. The relay forwards each request frame-by-frame over the WebSocket to
127
+ the CLI, which then `fetch()`es the local `opencode serve` and streams the
128
+ response back.
129
+ - Streaming endpoints (SSE) pass through unchanged — chunks are forwarded as
130
+ they arrive.
131
+
132
+ The secret is persisted in `~/.config/kkcode/tunnel/config.json` so that
133
+ restarting or reconnecting the CLI gets you the **same tunnel** without a
134
+ second scan. OpenCode retains the legacy relay-only secret key; Codex uses a
135
+ separate `codex:<relay-url>` key so backend identities cannot collide.
136
+
137
+ ## License
138
+
139
+ MIT.
@@ -0,0 +1,102 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { hostname, homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { getAgentIdentity } from "./config.js";
5
+ const DEFAULT_API_URL = "https://api.kkcode.app";
6
+ const apiUrl = (process.env.KKCODE_NOTIFY_API_URL ?? DEFAULT_API_URL).replace(/\/$/u, "");
7
+ const configRoot = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
8
+ const agentConfigPath = process.env.KKCODE_AGENT_CONFIG ?? join(configRoot, "kkcode", "agent.json");
9
+ const opencodeConfigPath = process.env.OPENCODE_CONFIG ?? join(configRoot, "opencode", "opencode.json");
10
+ const PLUGIN_PACKAGE = "@kkcode-app/agent/plugin";
11
+ function flagValue(args, flag) {
12
+ const index = args.indexOf(flag);
13
+ return index >= 0 ? args[index + 1]?.trim() : undefined;
14
+ }
15
+ async function writeJSON(path, value) {
16
+ await mkdir(dirname(path), { recursive: true });
17
+ const temp = `${path}.${process.pid}.tmp`;
18
+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
19
+ await rename(temp, path);
20
+ }
21
+ async function ensureOpenCodePlugin() {
22
+ let config = {};
23
+ try {
24
+ const parsed = JSON.parse(await readFile(opencodeConfigPath, "utf8"));
25
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
26
+ throw new Error("OpenCode config must be a JSON object.");
27
+ }
28
+ config = parsed;
29
+ }
30
+ catch (error) {
31
+ if (error.code !== "ENOENT")
32
+ throw error;
33
+ }
34
+ const plugins = config.plugin;
35
+ if (plugins !== undefined &&
36
+ (!Array.isArray(plugins) || plugins.some((item) => typeof item !== "string"))) {
37
+ throw new Error('OpenCode config field "plugin" must be an array of package names.');
38
+ }
39
+ if (Array.isArray(plugins) && plugins.includes(PLUGIN_PACKAGE))
40
+ return;
41
+ await writeJSON(opencodeConfigPath, { ...config, plugin: [...(plugins ?? []), PLUGIN_PACKAGE] });
42
+ }
43
+ export async function configureAgentRuntime(identity, backend) {
44
+ await writeJSON(agentConfigPath, {
45
+ node_id: identity.nodeId,
46
+ node_secret: identity.nodeSecret,
47
+ service_id: identity.serviceId,
48
+ api_url: apiUrl,
49
+ });
50
+ if (backend === "opencode")
51
+ await ensureOpenCodePlugin();
52
+ }
53
+ export async function createAgentLinkTicket(identity, backend) {
54
+ const response = await fetch(`${apiUrl}/v1/agent-link-tickets`, {
55
+ method: "POST",
56
+ headers: { "Content-Type": "application/json" },
57
+ body: JSON.stringify({
58
+ node_id: identity.nodeId,
59
+ node_secret: identity.nodeSecret,
60
+ service_id: identity.serviceId,
61
+ backend,
62
+ machine_label: (process.env.KKCODE_AGENT_MACHINE_LABEL ?? hostname()).slice(0, 80),
63
+ }),
64
+ });
65
+ const body = (await response.json().catch(() => ({})));
66
+ if (!response.ok || !body.ticket) {
67
+ throw new Error(body.message ?? `Could not prepare notification linking (${response.status}).`);
68
+ }
69
+ return body.ticket;
70
+ }
71
+ export async function runAgentLink(args) {
72
+ const ticket = flagValue(args, "--ticket");
73
+ const backend = (flagValue(args, "--backend") ?? "opencode");
74
+ if (!ticket || !/^[A-Za-z0-9_-]{32,256}$/u.test(ticket)) {
75
+ throw new Error("A valid one-time --ticket is required.");
76
+ }
77
+ if (backend !== "opencode" && backend !== "codex") {
78
+ throw new Error("--backend must be opencode or codex.");
79
+ }
80
+ const identity = await getAgentIdentity(backend);
81
+ const response = await fetch(`${apiUrl}/v1/agent-links/claim`, {
82
+ method: "POST",
83
+ headers: { "Content-Type": "application/json" },
84
+ body: JSON.stringify({
85
+ ticket,
86
+ node_id: identity.nodeId,
87
+ node_secret: identity.nodeSecret,
88
+ service_id: identity.serviceId,
89
+ backend,
90
+ machine_label: (process.env.KKCODE_AGENT_MACHINE_LABEL ?? hostname()).slice(0, 80),
91
+ }),
92
+ });
93
+ const body = (await response.json().catch(() => ({})));
94
+ if (!response.ok)
95
+ throw new Error(body.message ?? `Link request failed (${response.status}).`);
96
+ await configureAgentRuntime(identity, backend);
97
+ if (backend === "opencode") {
98
+ console.log(`OpenCode plugin registered in ${opencodeConfigPath}. Restart OpenCode to load it.`);
99
+ }
100
+ console.log(`Linked Agent service ${identity.serviceId} to this phone.`);
101
+ }
102
+ //# sourceMappingURL=agent-link.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-link.js","sourceRoot":"","sources":["../src/agent-link.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,gBAAgB,EAAsB,MAAM,aAAa,CAAC;AAEnE,MAAM,eAAe,GAAG,wBAAwB,CAAC;AACjD,MAAM,MAAM,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,eAAe,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAC1F,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAC;AAC7E,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;AACpG,MAAM,kBAAkB,GACtB,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,IAAI,CAAC,UAAU,EAAE,UAAU,EAAE,eAAe,CAAC,CAAC;AAC/E,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAElD,SAAS,SAAS,CAAC,IAAc,EAAE,IAAY;IAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,I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AQ,CAAC,SAAS;YAC9B,OAAO;YACP,aAAa,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,0BAA0B,IAAI,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;SACnF,CAAC;KACH,CAAC,CAAC;IACH,MAAM,IAAI,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAyB,CAAC;IAC/E,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,wBAAwB,QAAQ,CAAC,MAAM,IAAI,CAAC,CAAC;IAE/F,MAAM,qBAAqB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;QAC3B,OAAO,CAAC,GAAG,CACT,iCAAiC,kBAAkB,gCAAgC,CACpF,CAAC;IACJ,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,wBAAwB,QAAQ,CAAC,SAAS,iBAAiB,CAAC,CAAC;AAC3E,CAAC"}
@@ -0,0 +1,334 @@
1
+ /**
2
+ * [INPUT]: 依赖 node:http、node:crypto,依赖 codex-process.ts 的 RPC 与 server request 能力及 codex-journal.ts 的 replay
3
+ * [OUTPUT]: 对外提供 CODEX_RPC_ALLOWLIST、CodexBridge、CodexBridgeOptions 与 startCodexBridge
4
+ * [POS]: cli Codex 后端的本地 HTTP/SSE 边界,仅监听 127.0.0.1 并以 bridge token 保护全部端点
5
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
6
+ */
7
+ import { randomBytes, timingSafeEqual } from "node:crypto";
8
+ import { createServer } from "node:http";
9
+ import { EventJournal } from "./codex-journal.js";
10
+ import { isJsonRpcId, isRecord } from "./codex-jsonrpc.js";
11
+ import { CodexProcess } from "./codex-process.js";
12
+ const HOST = process.env.CODEX_BRIDGE_HOST ?? "127.0.0.1";
13
+ const MAX_BODY_BYTES = 1024 * 1024;
14
+ const HEARTBEAT_MS = 15_000;
15
+ const RPC_TIMEOUT_MS = 15_000;
16
+ class RequestError extends Error {
17
+ status;
18
+ code;
19
+ constructor(status, code, message) {
20
+ super(message);
21
+ this.status = status;
22
+ this.code = code;
23
+ }
24
+ }
25
+ export const CODEX_RPC_ALLOWLIST = new Set([
26
+ "thread/start",
27
+ "thread/resume",
28
+ "thread/fork",
29
+ "thread/archive",
30
+ "thread/unarchive",
31
+ "thread/delete",
32
+ "thread/list",
33
+ "thread/read",
34
+ "thread/compact/start",
35
+ "thread/name/set",
36
+ "turn/start",
37
+ "turn/steer",
38
+ "turn/interrupt",
39
+ "review/start",
40
+ "model/list",
41
+ "modelProvider/capabilities/read",
42
+ "skills/list",
43
+ "hooks/list",
44
+ "mcpServerStatus/list",
45
+ "mcpServer/resource/read",
46
+ "account/read",
47
+ "account/rateLimits/read",
48
+ "account/usage/read",
49
+ "config/read",
50
+ "configRequirements/read",
51
+ ]);
52
+ export async function startCodexBridge(options = {}) {
53
+ const token = randomBytes(32).toString("base64url");
54
+ const instanceId = randomBytes(16).toString("base64url");
55
+ const journal = new EventJournal(options.journalCapacity ?? 512);
56
+ let ready = true;
57
+ const codex = await CodexProcess.start({
58
+ command: options.command,
59
+ args: options.processArgs,
60
+ rpcTimeoutMs: RPC_TIMEOUT_MS,
61
+ });
62
+ codex.on("notification", (message) => journal.append("notification", message));
63
+ codex.on("serverRequest", (request) => journal.append("server-request", {
64
+ ...request,
65
+ resolveId: encodeBridgeRequestId(instanceId, request.id),
66
+ }));
67
+ codex.on("protocolError", (error) => journal.append("bridge-error", { message: error.message }));
68
+ codex.on("exit", (error) => {
69
+ ready = false;
70
+ journal.append("process-exit", { message: error.message });
71
+ });
72
+ codex.on("stderr", (message) => console.error(`[codex] ${message}`));
73
+ const server = createServer((request, response) => {
74
+ handleRequest(request, response, token, instanceId, () => ready, codex, journal).catch((error) => {
75
+ if (!response.headersSent && error instanceof RequestError) {
76
+ sendJson(response, error.status, { error: error.code, message: error.message });
77
+ }
78
+ else if (!response.headersSent) {
79
+ sendJson(response, 500, { error: "internal_error" });
80
+ }
81
+ else
82
+ response.destroy(error);
83
+ });
84
+ });
85
+ server.requestTimeout = 20_000;
86
+ server.headersTimeout = 10_000;
87
+ server.keepAliveTimeout = 5_000;
88
+ try {
89
+ await new Promise((resolve, reject) => {
90
+ server.once("error", reject);
91
+ server.listen(options.port ?? 0, HOST, resolve);
92
+ });
93
+ }
94
+ catch (error) {
95
+ await codex.stop();
96
+ throw error;
97
+ }
98
+ const address = server.address();
99
+ if (!address || typeof address === "string") {
100
+ server.close();
101
+ await codex.stop();
102
+ throw new Error("could not determine Codex Bridge port");
103
+ }
104
+ return {
105
+ host: HOST,
106
+ port: address.port,
107
+ token,
108
+ process: codex,
109
+ stop: async () => {
110
+ await new Promise((resolve) => server.close(() => resolve()));
111
+ await codex.stop();
112
+ },
113
+ };
114
+ }
115
+ async function handleRequest(request, response, token, instanceId, isReady, codex, journal) {
116
+ if (!authorized(request, token)) {
117
+ sendJson(response, 401, { error: "unauthorized" });
118
+ return;
119
+ }
120
+ const url = new URL(request.url ?? "/", `http://${HOST}`);
121
+ if (request.method === "GET" && url.pathname === "/codex/v1/meta") {
122
+ sendJson(response, 200, {
123
+ backend: "codex",
124
+ bridgeProtocol: 1,
125
+ bridgeVersion: "1.0.0",
126
+ instanceId,
127
+ codexVersion: "unknown",
128
+ ready: isReady(),
129
+ rpcTimeoutMs: RPC_TIMEOUT_MS,
130
+ latestSequence: journal.latestSequence,
131
+ oldestSequence: journal.oldestSequence,
132
+ rpcMethods: [...CODEX_RPC_ALLOWLIST],
133
+ });
134
+ return;
135
+ }
136
+ if (request.method === "POST" && url.pathname === "/codex/v1/rpc") {
137
+ const body = await readJsonBody(request);
138
+ if (!isRecord(body) || typeof body.method !== "string") {
139
+ sendJson(response, 400, { error: "invalid_request", message: "method must be a string" });
140
+ return;
141
+ }
142
+ if (!CODEX_RPC_ALLOWLIST.has(body.method)) {
143
+ sendJson(response, 403, { error: "method_not_allowed", method: body.method });
144
+ return;
145
+ }
146
+ try {
147
+ const rpcResponse = await codex.call(body.method, body.params, RPC_TIMEOUT_MS);
148
+ sendJson(response, 200, {
149
+ ...(typeof body.requestId === "string" ? { requestId: body.requestId } : {}),
150
+ ...(rpcResponse.error ? { error: rpcResponse.error } : { result: rpcResponse.result }),
151
+ });
152
+ }
153
+ catch (error) {
154
+ const message = error.message;
155
+ const timedOut = message.includes("timed out");
156
+ sendJson(response, timedOut ? 504 : 502, {
157
+ error: timedOut ? "rpc_timeout" : "codex_unavailable",
158
+ message,
159
+ });
160
+ }
161
+ return;
162
+ }
163
+ if (request.method === "GET" && url.pathname === "/codex/v1/events") {
164
+ const after = parseSequence(url.searchParams.get("after"));
165
+ if (after === null) {
166
+ sendJson(response, 400, { error: "invalid_after" });
167
+ return;
168
+ }
169
+ serveEvents(request, response, journal, after);
170
+ return;
171
+ }
172
+ if (request.method === "GET" && url.pathname === "/codex/v1/server-requests") {
173
+ sendJson(response, 200, {
174
+ requests: codex.listServerRequests().map((pending) => ({
175
+ ...pending,
176
+ resolveId: encodeBridgeRequestId(instanceId, pending.id),
177
+ })),
178
+ });
179
+ return;
180
+ }
181
+ const resolveMatch = url.pathname.match(/^\/codex\/v1\/server-requests\/([^/]+)\/resolve$/);
182
+ if (request.method === "POST" && resolveMatch) {
183
+ const decoded = decodeBridgeRequestId(resolveMatch[1]);
184
+ const body = await readJsonBody(request);
185
+ if (decoded === null || !isRecord(body)) {
186
+ sendJson(response, 400, { error: "invalid_resolution" });
187
+ return;
188
+ }
189
+ if (decoded.instanceId !== instanceId) {
190
+ sendJson(response, 410, { error: "stale_bridge_generation" });
191
+ return;
192
+ }
193
+ const id = decoded.id;
194
+ const error = body.error;
195
+ const hasResult = Object.hasOwn(body, "result");
196
+ const hasError = Object.hasOwn(body, "error");
197
+ if (hasResult === hasError) {
198
+ sendJson(response, 400, {
199
+ error: "invalid_resolution",
200
+ message: "provide exactly one of result or error",
201
+ });
202
+ return;
203
+ }
204
+ if (error !== undefined && !isValidError(error)) {
205
+ sendJson(response, 400, { error: "invalid_resolution_error" });
206
+ return;
207
+ }
208
+ const resolution = hasError ? { error: error } : { result: body.result };
209
+ if (!codex.resolveServerRequest(id, resolution)) {
210
+ sendJson(response, 404, { error: "server_request_not_found" });
211
+ return;
212
+ }
213
+ journal.append("server-request-resolved", { id, resolution: hasError ? "error" : "result" });
214
+ sendJson(response, 200, { resolved: true });
215
+ return;
216
+ }
217
+ sendJson(response, 404, { error: "not_found" });
218
+ }
219
+ function serveEvents(request, response, journal, after) {
220
+ response.writeHead(200, {
221
+ "content-type": "text/event-stream",
222
+ "cache-control": "no-cache, no-transform",
223
+ connection: "keep-alive",
224
+ "x-accel-buffering": "no",
225
+ });
226
+ response.flushHeaders();
227
+ response.write(`event: ready\ndata: ${JSON.stringify({ sequence: journal.latestSequence })}\n\n`);
228
+ const replayMiss = after > 0 && journal.latestSequence > 0 && after < journal.oldestSequence - 1;
229
+ if (replayMiss) {
230
+ response.write(`event: replay-miss\ndata: ${JSON.stringify({
231
+ sequence: journal.latestSequence,
232
+ data: { oldestSequence: journal.oldestSequence, requestedAfter: after },
233
+ })}\n\n`);
234
+ }
235
+ else {
236
+ for (const event of journal.after(after))
237
+ writeEvent(response, event);
238
+ }
239
+ const unsubscribe = journal.subscribe((event) => writeEvent(response, event));
240
+ const heartbeat = setInterval(() => response.write(`: heartbeat ${Date.now()}\n\n`), HEARTBEAT_MS);
241
+ request.once("close", () => {
242
+ clearInterval(heartbeat);
243
+ unsubscribe();
244
+ });
245
+ }
246
+ function writeEvent(response, event) {
247
+ response.write(`id: ${event.sequence}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
248
+ }
249
+ function authorized(request, token) {
250
+ const candidate = request.headers["x-kkcode-bridge-token"];
251
+ if (typeof candidate !== "string")
252
+ return false;
253
+ const actual = Buffer.from(candidate);
254
+ const expected = Buffer.from(token);
255
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
256
+ }
257
+ async function readJsonBody(request) {
258
+ const chunks = [];
259
+ let size = 0;
260
+ for await (const chunk of request) {
261
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
262
+ size += buffer.length;
263
+ if (size > MAX_BODY_BYTES) {
264
+ throw new RequestError(413, "body_too_large", `request body exceeds ${MAX_BODY_BYTES} bytes`);
265
+ }
266
+ chunks.push(buffer);
267
+ }
268
+ if (chunks.length === 0)
269
+ return {};
270
+ try {
271
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
272
+ }
273
+ catch {
274
+ throw new RequestError(400, "invalid_json", "request body must be valid JSON");
275
+ }
276
+ }
277
+ function sendJson(response, status, body) {
278
+ const encoded = JSON.stringify(body);
279
+ response.writeHead(status, {
280
+ "content-type": "application/json; charset=utf-8",
281
+ "content-length": Buffer.byteLength(encoded),
282
+ "cache-control": "no-store",
283
+ });
284
+ response.end(encoded);
285
+ }
286
+ function parseSequence(value) {
287
+ if (value === null || value === "")
288
+ return 0;
289
+ const sequence = Number(value);
290
+ return Number.isSafeInteger(sequence) && sequence >= 0 ? sequence : null;
291
+ }
292
+ function decodeRequestId(encoded) {
293
+ let value;
294
+ try {
295
+ value = decodeURIComponent(encoded);
296
+ }
297
+ catch {
298
+ return null;
299
+ }
300
+ if (value.startsWith("n:")) {
301
+ const numeric = Number(value.slice(2));
302
+ return Number.isSafeInteger(numeric) ? numeric : null;
303
+ }
304
+ const id = value.startsWith("s:") ? value.slice(2) : value;
305
+ return isJsonRpcId(id) ? id : null;
306
+ }
307
+ function encodeRequestId(id) {
308
+ return `${typeof id === "number" ? "n" : "s"}:${id}`;
309
+ }
310
+ function encodeBridgeRequestId(instanceId, id) {
311
+ return `${instanceId}.${encodeRequestId(id)}`;
312
+ }
313
+ function decodeBridgeRequestId(encoded) {
314
+ let value;
315
+ try {
316
+ value = decodeURIComponent(encoded);
317
+ }
318
+ catch {
319
+ return null;
320
+ }
321
+ const separator = value.indexOf(".");
322
+ if (separator <= 0)
323
+ return null;
324
+ const instanceId = value.slice(0, separator);
325
+ const id = decodeRequestId(value.slice(separator + 1));
326
+ return id === null ? null : { instanceId, id };
327
+ }
328
+ function isValidError(value) {
329
+ return (isRecord(value) &&
330
+ typeof value.code === "number" &&
331
+ Number.isSafeInteger(value.code) &&
332
+ typeof value.message === "string");
333
+ }
334
+ //# sourceMappingURL=codex-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-bridge.js","sourceRoot":"","sources":["../src/codex-bridge.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAC;AACpF,OAAO,EAAE,YAAY,EAAmB,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAqB,MAAM,oBAAoB,CAAC;AAC9E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,WAAW,CAAC;AAC1D,MAAM,cAAc,GAAG,IAAI,GAAG,IAAI,CAAC;AACnC,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,cAAc,GAAG,MAAM,CAAC;AAE9B,MAAM,YAAa,SAAQ,KAAK;IAEnB;IACA;IAFX,YACW,MAAc,EACd,IAAY,EACrB,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAJN,WAAM,GAAN,MAAM,CAAQ;QACd,SAAI,GAAJ,IAAI,CAAQ;IAIvB,CAAC;CACF;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IACzC,cAAc;IACd,eAAe;IACf,aAAa;IACb,gBAAgB;IAChB,kBAAkB;IAClB,eAAe;IACf,aAAa;IACb,aA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CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC;IACvD,OAAO,EAAE,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;AACjD,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,CACL,QAAQ,CAAC,KAAK,CAAC;QACf,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC;QAChC,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAClC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * [INPUT]: 依赖内存数组与订阅回调,不依赖外部存储
3
+ * [OUTPUT]: 对外提供 CodexEvent、EventJournal 与有界 sequence replay 能力
4
+ * [POS]: cli Codex Bridge 的事件缓冲层,为 SSE 提供单调序号、有限回放和实时订阅
5
+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
6
+ */
7
+ export class EventJournal {
8
+ capacity;
9
+ events = [];
10
+ listeners = new Set();
11
+ sequence = 0;
12
+ constructor(capacity = 512) {
13
+ this.capacity = capacity;
14
+ if (!Number.isSafeInteger(capacity) || capacity < 1) {
15
+ throw new Error("event journal capacity must be a positive integer");
16
+ }
17
+ }
18
+ append(type, data) {
19
+ const event = {
20
+ sequence: ++this.sequence,
21
+ type,
22
+ timestamp: new Date().toISOString(),
23
+ data,
24
+ };
25
+ this.events.push(event);
26
+ if (this.events.length > this.capacity)
27
+ this.events.shift();
28
+ for (const listener of this.listeners)
29
+ listener(event);
30
+ return event;
31
+ }
32
+ after(sequence) {
33
+ return this.events.filter((event) => event.sequence > sequence);
34
+ }
35
+ subscribe(listener) {
36
+ this.listeners.add(listener);
37
+ return () => this.listeners.delete(listener);
38
+ }
39
+ get latestSequence() {
40
+ return this.sequence;
41
+ }
42
+ get oldestSequence() {
43
+ return this.events[0]?.sequence ?? this.sequence + 1;
44
+ }
45
+ }
46
+ //# sourceMappingURL=codex-journal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-journal.js","sourceRoot":"","sources":["../src/codex-journal.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AASH,MAAM,OAAO,YAAY;IAKM;IAJrB,MAAM,GAAiB,EAAE,CAAC;IAC1B,SAAS,GAAG,IAAI,GAAG,EAA+B,CAAC;IACnD,QAAQ,GAAG,CAAC,CAAC;IAErB,YAA6B,WAAW,GAAG;QAAd,aAAQ,GAAR,QAAQ,CAAM;QACzC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,QAAQ,GAAG,CAAC,EAAE,CAAC;YACpD,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;IAED,MAAM,CAAC,IAAY,EAAE,IAAa;QAChC,MAAM,KAAK,GAAe;YACxB,QAAQ,EAAE,EAAE,IAAI,CAAC,QAAQ;YACzB,IAAI;YACJ,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,IAAI;SACL,CAAC;QACF,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACxB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ;YAAE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QAC5D,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS;YAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;QACvD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,QAAgB;QACpB,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC,CAAC;IAClE,CAAC;IAED,SAAS,CAAC,QAAqC;QAC7C,IAAI,CAAC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