gjcm-bridge 0.1.0 → 0.1.4

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/src/sdk-cli.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * gjc's session CLI raw hatch (`gjc sdk session raw control|query <sessionId> … --json`), the official path for a
3
+ * local machine controller to reach a session's SDK operations that ACP refuses. The bridge uses it for the
4
+ * external permission approval channel (`permission.channel.set`, `permission.requests.list`,
5
+ * `permission.respond`), which gjc 0.19.3 prohibits over ACP ("permission.channel.set is prohibited for ACP.").
6
+ * Each call starts a gjc process: measured 2.2–3.8s on pve3.
7
+ */
8
+
9
+ export interface SdkCliOptions {
10
+ /** The gjc launcher without `--mode=acp` (see `tuiCommand`). */
11
+ command: string[];
12
+ /** gjc agent dir, so the CLI resolves the session through the same broker as the bridge's ACP process. */
13
+ agentDir: string;
14
+ timeoutMs?: number;
15
+ }
16
+
17
+ export class SdkCliError extends Error {
18
+ constructor(
19
+ readonly code: string,
20
+ message: string,
21
+ ) {
22
+ super(message);
23
+ }
24
+ }
25
+
26
+ const DEFAULT_TIMEOUT_MS = 20_000;
27
+
28
+ export class SdkCli {
29
+ readonly #options: SdkCliOptions;
30
+
31
+ constructor(options: SdkCliOptions) {
32
+ this.#options = options;
33
+ }
34
+
35
+ control(sessionId: string, cwd: string, operation: string, input: unknown): Promise<unknown> {
36
+ return this.#run(cwd, ["control", sessionId, "--op", operation, "--json-input", JSON.stringify(input)]);
37
+ }
38
+
39
+ query(sessionId: string, cwd: string, query: string): Promise<unknown> {
40
+ return this.#run(cwd, ["query", sessionId, "--query", query]);
41
+ }
42
+
43
+ async #run(cwd: string, args: string[]): Promise<unknown> {
44
+ const proc = Bun.spawn([...this.#options.command, "sdk", "session", "raw", ...args, "--json"], {
45
+ cwd,
46
+ env: { ...process.env, GJC_CODING_AGENT_DIR: this.#options.agentDir },
47
+ stdin: "ignore",
48
+ stdout: "pipe",
49
+ stderr: "pipe",
50
+ });
51
+ const timer = setTimeout(() => proc.kill(), this.#options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
52
+ try {
53
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
54
+ let response: { ok?: unknown; result?: unknown; error?: { code?: unknown; message?: unknown } } | undefined;
55
+ try {
56
+ response = JSON.parse(stdout.trim());
57
+ } catch {
58
+ // stdout can carry a request's command or file content (`permission.requests.list`): log only its size.
59
+ throw new SdkCliError("cli_failed", `gjc sdk session raw exited ${code} (${stdout.length} bytes of stdout): ${stderr.trim().slice(0, 300)}`);
60
+ }
61
+ if (response?.ok === true) return response.result;
62
+ // A failed operation answers `{ok:false,error}`; a CLI failure is a `gjc.command-error` envelope.
63
+ const error = response?.error ?? (response as { code?: unknown; message?: unknown } | undefined);
64
+ throw new SdkCliError(
65
+ typeof error?.code === "string" ? error.code : "cli_failed",
66
+ typeof error?.message === "string" ? error.message : `gjc sdk session raw exited ${code}`,
67
+ );
68
+ } finally {
69
+ clearTimeout(timer);
70
+ }
71
+ }
72
+ }
package/src/server.ts CHANGED
@@ -25,7 +25,11 @@ import type { HubClient, SessionHub } from "./hub";
25
25
  import type { BridgeState } from "./state";
26
26
  import type { UploadStore } from "./uploads";
27
27
 
28
+ /** The largest frame either side takes (the apps' iOS `maximumMessageSize` is the same 32 MiB). */
28
29
  export const MAX_FRAME_BYTES = 32 * 1024 * 1024;
30
+ /** Room for a sealed frame's counter and tag around its JSON. */
31
+ const SEAL_OVERHEAD_BYTES = 64;
32
+ const mib = (bytes: number) => `${(bytes / (1024 * 1024)).toFixed(1)}MiB`;
29
33
  /** RPCs slower than this are logged; a resume waits on gjc spawning a session host. */
30
34
  const SLOW_RPC_MS = 5_000;
31
35
 
@@ -70,10 +74,23 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
70
74
  const log = options.log ?? (() => {});
71
75
  const host = state.host();
72
76
 
73
- const send = (ws: ServerWebSocket<Conn>, message: unknown) => {
77
+ /**
78
+ * A phone drops the connection on a frame over its limit and dials again into the same frame (2026-11-08, pve1: 32
79
+ * reconnects 0.55s apart). So nothing over it goes out: an event that big is skipped, and an answer that big becomes
80
+ * a `response_too_large` error (see `onFrame`).
81
+ */
82
+ const fitsFrame = (body: Buffer) => body.length <= MAX_FRAME_BYTES - SEAL_OVERHEAD_BYTES;
83
+ const sendBody = (ws: ServerWebSocket<Conn>, body: Buffer) => {
74
84
  const conn = ws.data;
75
85
  if (conn.phase !== "open" || !conn.cipher) return;
76
- ws.sendBinary(conn.cipher.seal(Buffer.from(JSON.stringify(message))));
86
+ ws.sendBinary(conn.cipher.seal(body));
87
+ };
88
+ const send = (ws: ServerWebSocket<Conn>, message: { id?: number; e?: unknown; ev?: string; p?: unknown }) => {
89
+ const body = Buffer.from(JSON.stringify(message));
90
+ if (fitsFrame(body)) return sendBody(ws, body);
91
+ const sessionId = (message.p as { sessionId?: unknown } | undefined)?.sessionId;
92
+ const what = message.ev ? `event ${message.ev} session=${String(sessionId ?? "-")}` : `reply id=${message.id}`;
93
+ log(`skipped ${what}: ${body.length} bytes over the ${MAX_FRAME_BYTES}-byte frame limit`);
77
94
  };
78
95
 
79
96
  const fail = (ws: ServerWebSocket<Conn>, code: string, message: string) => {
@@ -229,7 +246,14 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
229
246
  if (typeof id !== "number" || typeof m !== "string") return;
230
247
  const started = performance.now();
231
248
  try {
232
- send(ws, { id, r: (await dispatch(ws, m, p)) ?? null });
249
+ const body = Buffer.from(JSON.stringify({ id, r: (await dispatch(ws, m, p)) ?? null }));
250
+ if (!fitsFrame(body))
251
+ throw new AcpError(-32030, `응답이 너무 커서(${mib(body.length)}) 폰으로 보낼 수 없습니다. 한도는 ${mib(MAX_FRAME_BYTES)}입니다.`, {
252
+ code: "response_too_large",
253
+ bytes: body.length,
254
+ limit: MAX_FRAME_BYTES,
255
+ });
256
+ sendBody(ws, body);
233
257
  const ms = Math.round(performance.now() - started);
234
258
  if (ms >= SLOW_RPC_MS) log(`slow rpc ${m} ${ms}ms`);
235
259
  } catch (error: any) {
@@ -279,7 +303,11 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
279
303
  }
280
304
  void onFrame(ws, Buffer.from(raw));
281
305
  },
282
- close(ws) {
306
+ close(ws, code, reason) {
307
+ // Who closed tells a drop the app chose (it closes with 1000, e.g. on a frame over its limit) from a lost network
308
+ // (1006) or the bridge's own 44xx (#88).
309
+ // The reason comes from the peer, maybe before it proved its key: quoted so it cannot add a log line.
310
+ if (ws.data.deviceKey) log(`disconnected device=${ws.data.deviceKey.slice(0, 8)} code=${code}${reason ? ` reason=${JSON.stringify(reason)}` : ""}`);
283
311
  clearTimeout(ws.data.timer);
284
312
  ws.data.phase = "closed";
285
313
  hub.detach(ws.data.id);
@@ -289,6 +317,6 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
289
317
  });
290
318
  }
291
319
 
292
- function clientFor(ws: ServerWebSocket<Conn>, send: (ws: ServerWebSocket<Conn>, m: unknown) => void): HubClient {
293
- return { id: ws.data.id, deliver: (ev, p) => send(ws, { ev, p }) };
320
+ function clientFor(ws: ServerWebSocket<Conn>, send: (ws: ServerWebSocket<Conn>, m: { ev: string; p: unknown }) => void): HubClient {
321
+ return { id: ws.data.id, device: ws.data.deviceKey, deliver: (ev, p) => send(ws, { ev, p }) };
294
322
  }
package/src/tmux.ts ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Opens a phone-started session as a window of one dedicated tmux session (gm#58), so the terminal shows the
3
+ * same TUI the phone drives. The window runs `gjc --resume <id>`: gjc writes the transcript only after the first
4
+ * answer for a TUI-started session, and ACP `session/load` resolves a session through that transcript, so the
5
+ * bridge creates the session over ACP (which writes it at once), lets go of it, and hands it to the TUI.
6
+ *
7
+ * The bridge never starts a tmux server: a server started from the bridge's systemd unit would live in the
8
+ * bridge's cgroup and die with every bridge restart, taking the phone's sessions with it. Every tmux call carries
9
+ * `-N` (tmux 3.2+), so a server that goes away between the check and the window is not started again.
10
+ */
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+
14
+ export interface TmuxOptions {
15
+ /** tmux session that collects the windows; created on the first window. */
16
+ session: string;
17
+ /** `tmux -L` socket name; the user's default server when absent. */
18
+ socket?: string;
19
+ /** How long gjc in the window may take to publish its SDK endpoint (measured 5.6–6.6s on pve3). */
20
+ readyTimeoutMs?: number;
21
+ }
22
+
23
+ /** Why a window did not become the session's host; the bridge passes it to the phone as -32021 `data.code`. */
24
+ export type TmuxFailure = "tmux_failed" | "tmux_window_exited" | "tmux_ready_timeout";
25
+
26
+ export class TmuxError extends Error {
27
+ constructor(
28
+ readonly code: TmuxFailure,
29
+ message: string,
30
+ ) {
31
+ super(message);
32
+ }
33
+ }
34
+
35
+ const DEFAULT_READY_TIMEOUT_MS = 30_000;
36
+ const POLL_MS = 200;
37
+ /** tmux turns `.` and `:` in session names into `_`, so such a name would never be found again. */
38
+ const SESSION_NAME = /^[A-Za-z0-9_-]+$/;
39
+ /** The window option naming the session a window was opened for: only windows the bridge opened carry it. */
40
+ const SESSION_TAG = "@gjcm_session";
41
+ const SESSION_ID = /^[A-Za-z0-9_-]+$/;
42
+
43
+ interface Run {
44
+ code: number;
45
+ stdout: string;
46
+ stderr: string;
47
+ }
48
+
49
+ /** The TUI launcher from the bridge's ACP command: the same gjc without `--mode=acp`. */
50
+ export function tuiCommand(acpCommand: string[]): string[] {
51
+ const argv: string[] = [];
52
+ for (let i = 0; i < acpCommand.length; i++) {
53
+ const arg = acpCommand[i]!;
54
+ if (arg === "--mode=acp") continue;
55
+ if (arg === "--mode" && acpCommand[i + 1] === "acp") {
56
+ i++;
57
+ continue;
58
+ }
59
+ argv.push(arg);
60
+ }
61
+ return argv;
62
+ }
63
+
64
+ function parentPid(pid: number): number | undefined {
65
+ try {
66
+ // /proc/<pid>/stat: "pid (comm) state ppid …"; comm may hold spaces and parentheses.
67
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
68
+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
69
+ } catch {
70
+ // No procfs (macOS): ask ps.
71
+ const ps = Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)]);
72
+ const parent = Number(ps.stdout.toString().trim());
73
+ return Number.isInteger(parent) && parent > 0 ? parent : undefined;
74
+ }
75
+ }
76
+
77
+ /** Whether `pid` is `ancestor` or runs below it (the launcher may be a wrapper that starts gjc as a child). */
78
+ function descendsFrom(pid: number, ancestor: number): boolean {
79
+ let current: number | undefined = pid;
80
+ for (let depth = 0; depth < 16 && current !== undefined && current > 1; depth++) {
81
+ if (current === ancestor) return true;
82
+ current = parentPid(current);
83
+ }
84
+ return false;
85
+ }
86
+
87
+ function alive(pid: number): boolean {
88
+ try {
89
+ process.kill(pid, 0);
90
+ return true;
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ export class TmuxLauncher {
97
+ readonly #options: TmuxOptions;
98
+ readonly #tui: string[];
99
+ readonly #env: Record<string, string>;
100
+ #creating: Promise<unknown> = Promise.resolve();
101
+
102
+ /** `env` goes into the window: tmux gives it the server's environment, not the bridge's. */
103
+ constructor(options: TmuxOptions, tui: string[], env: Record<string, string> = {}) {
104
+ if (!SESSION_NAME.test(options.session)) throw new Error(`tmux session name must match ${SESSION_NAME}: ${options.session}`);
105
+ this.#options = options;
106
+ this.#tui = tui;
107
+ this.#env = env;
108
+ }
109
+
110
+ async #run(args: string[]): Promise<Run> {
111
+ const argv = ["tmux", "-N", ...(this.#options.socket ? ["-L", this.#options.socket] : []), ...args];
112
+ try {
113
+ const proc = Bun.spawn(argv, { stdin: "ignore", stdout: "pipe", stderr: "pipe" });
114
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
115
+ return { code, stdout: stdout.trim(), stderr: stderr.trim() };
116
+ } catch (error) {
117
+ return { code: -1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
118
+ }
119
+ }
120
+
121
+ /** Why a new session cannot go to tmux now (no tmux, no server running), or undefined when it can. */
122
+ async unavailable(): Promise<string | undefined> {
123
+ const listed = await this.#run(["list-sessions", "-F", "#{session_name}"]);
124
+ if (listed.code === 0) return undefined;
125
+ return listed.stderr || `tmux list-sessions exited ${listed.code}`;
126
+ }
127
+
128
+ /**
129
+ * Starts `gjc --resume <sessionId>` in a new window of the dedicated session and waits until that process
130
+ * publishes the session's SDK endpoint. Removes the window and throws a TmuxError when it does not.
131
+ */
132
+ async open(sessionId: string, cwd: string): Promise<void> {
133
+ if (!SESSION_ID.test(sessionId)) throw new TmuxError("tmux_failed", `tmux 창에 열 수 없는 세션 id입니다: ${sessionId}`);
134
+ // Window creation runs one at a time, so two phones starting sessions together do not both create the
135
+ // tmux session; waiting for gjc does not hold the next phone up.
136
+ const created = this.#creating.then(() => this.#create(sessionId, cwd));
137
+ this.#creating = created.catch(() => {});
138
+ const { panePid, pane } = await created;
139
+ try {
140
+ await this.#waitReady(sessionId, cwd, panePid);
141
+ } catch (error) {
142
+ await this.#run(["kill-pane", "-t", pane]);
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Whether a window of the dedicated session hosts `sessionId` now: the bridge opened it for `sessionId` and the
149
+ * session's SDK endpoint names a process in it. Recognizes the bridge's windows again after a bridge restart; a
150
+ * `gjc --resume` the user started in that tmux session is theirs and keeps its own approvals.
151
+ */
152
+ async hosts(sessionId: string, cwd: string): Promise<boolean> {
153
+ const pid = this.#endpointPid(path.join(cwd, ".gjc", "state", "sdk", `${sessionId}.json`));
154
+ if (pid === undefined) return false;
155
+ return (await this.#panes()).some(pane => pane.sessionId === sessionId && descendsFrom(pid, pane.panePid));
156
+ }
157
+
158
+ /**
159
+ * The sessions the bridge opened the dedicated session's windows for, with each window's working directory: what
160
+ * to load again after a bridge or ACP restart. `hosts` confirms each one.
161
+ */
162
+ async hostedSessions(): Promise<Array<{ sessionId: string; cwd: string }>> {
163
+ return (await this.#panes()).map(({ sessionId, cwd }) => ({ sessionId, cwd }));
164
+ }
165
+
166
+ async #panes(): Promise<Array<{ panePid: number; sessionId: string; cwd: string }>> {
167
+ const listed = await this.#run(["list-panes", "-s", "-t", `=${this.#options.session}`, "-F", `#{pane_pid}\t#{pane_current_path}\t#{${SESSION_TAG}}`]);
168
+ if (listed.code !== 0) return [];
169
+ return listed.stdout.split("\n").flatMap(line => {
170
+ const [pidText = "", cwd = "", sessionId = ""] = line.split("\t");
171
+ const panePid = Number(pidText);
172
+ return SESSION_ID.test(sessionId) && Number.isInteger(panePid) ? [{ panePid, sessionId, cwd }] : [];
173
+ });
174
+ }
175
+
176
+ async #create(sessionId: string, cwd: string): Promise<{ panePid: number; pane: string }> {
177
+ const { session } = this.#options;
178
+ const env = Object.entries(this.#env).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
179
+ // tmux expands formats in -c; a literal `#` in the path is written `##`.
180
+ const start = ["-c", cwd.replaceAll("#", "##"), ...env, "-P", "-F", "#{pane_pid} #{pane_id}"];
181
+ const command = [...this.#tui, "--resume", sessionId];
182
+ const exists = (await this.#run(["has-session", "-t", `=${session}`])).code === 0;
183
+ const created = exists
184
+ ? await this.#run(["new-window", "-d", "-t", `=${session}:`, ...start, ...command])
185
+ : await this.#run(["new-session", "-d", "-s", session, ...start, ...command]);
186
+ const verb = exists ? "new-window" : "new-session";
187
+ if (created.code !== 0) throw new TmuxError("tmux_failed", `tmux ${verb} 실패: ${created.stderr || `exit ${created.code}`}`);
188
+ const [pidText, pane] = created.stdout.split(" ");
189
+ const panePid = Number(pidText);
190
+ if (!Number.isInteger(panePid) || !pane) throw new TmuxError("tmux_failed", `tmux ${verb}가 창 정보를 주지 않았습니다: ${created.stdout}`);
191
+ // Untagged, the window would not be found again: its tool approvals would reach no phone.
192
+ const tagged = await this.#run(["set-option", "-w", "-t", pane, SESSION_TAG, sessionId]);
193
+ if (tagged.code !== 0) {
194
+ // A command that cannot start (a wrong --gjc) takes its window with it before the tag lands.
195
+ if (!alive(panePid)) throw new TmuxError("tmux_window_exited", `tmux 세션 ${session}의 새 창에서 gjc가 바로 끝났습니다`);
196
+ await this.#run(["kill-pane", "-t", pane]);
197
+ throw new TmuxError("tmux_failed", `tmux 창에 세션 표시를 못 달았습니다: ${tagged.stderr || `exit ${tagged.code}`}`);
198
+ }
199
+ return { panePid, pane };
200
+ }
201
+
202
+ async #waitReady(sessionId: string, cwd: string, panePid: number): Promise<void> {
203
+ const { session } = this.#options;
204
+ const endpoint = path.join(cwd, ".gjc", "state", "sdk", `${sessionId}.json`);
205
+ const timeoutMs = this.#options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
206
+ const deadline = Date.now() + timeoutMs;
207
+ // The endpoint the ACP host left behind names a process outside the window; check each pid once.
208
+ const foreign = new Set<number>();
209
+ while (Date.now() < deadline) {
210
+ if (!alive(panePid)) throw new TmuxError("tmux_window_exited", `tmux 세션 ${session}의 새 창에서 gjc가 바로 끝났습니다`);
211
+ const pid = this.#endpointPid(endpoint);
212
+ if (pid !== undefined && !foreign.has(pid)) {
213
+ if (descendsFrom(pid, panePid)) return;
214
+ foreign.add(pid);
215
+ }
216
+ await Bun.sleep(POLL_MS);
217
+ }
218
+ throw new TmuxError("tmux_ready_timeout", `tmux 세션 ${session}의 새 창에서 gjc가 ${Math.round(timeoutMs / 1000)}초 안에 준비되지 않았습니다`);
219
+ }
220
+
221
+ #endpointPid(file: string): number | undefined {
222
+ try {
223
+ const pid = JSON.parse(fs.readFileSync(file, "utf8"))?.pid;
224
+ return Number.isInteger(pid) ? pid : undefined;
225
+ } catch {
226
+ return undefined;
227
+ }
228
+ }
229
+ }