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/hub.ts CHANGED
@@ -13,9 +13,19 @@ import fs from "node:fs";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
15
15
  import { AcpError, AcpProcess, type AcpSpawnOptions } from "./acp";
16
- import { hostAskSettled, hostAskToolCall, scanTranscriptAsks } from "./host-asks";
16
+ import {
17
+ hostAskSettled,
18
+ hostAskToolCall,
19
+ type RemoteAskCard,
20
+ remoteAskCard,
21
+ remoteAskRequests,
22
+ scanTranscriptAsks,
23
+ terminalAsk,
24
+ } from "./host-asks";
17
25
  import { SavedSessionIndex } from "./saved-sessions";
18
26
  import { Throughput } from "./throughput";
27
+ import { SdkCli } from "./sdk-cli";
28
+ import { TmuxError, TmuxLauncher, type TmuxOptions, tuiCommand } from "./tmux";
19
29
 
20
30
  export const TURN_END = "x_gjcm_turn_end";
21
31
 
@@ -46,7 +56,8 @@ export const SDK_QUERIES = new Set([
46
56
  ]);
47
57
  export const SDK_CONTROLS = new Set([
48
58
  "turn.steer",
49
- // Ephemeral /btw side question (gjc local patch 0004): { question, exchanges? } -> { replyText }.
59
+ // Ephemeral /btw side question: { question, exchanges? } -> { replyText }. The hub routes it to official btw.ask or to
60
+ // turn.btw (local patch 0004) by the session host's runtime.capabilities; see #sideQuestion.
50
61
  "turn.btw",
51
62
  "turn.follow_up",
52
63
  "compaction.run",
@@ -75,6 +86,12 @@ export const PERMISSION_MODE_UPDATE = "x_gjcm_permission_mode";
75
86
  export const PERMISSION_MODES = ["prompt", "allow", "deny"] as const;
76
87
  export type PermissionMode = (typeof PERMISSION_MODES)[number];
77
88
  const STALE_ATTACHMENT = "SDK session attachment is stale";
89
+ /**
90
+ * How gjc fails a prompt stopped before it ran (0.19.3 and 0.20.0, a session a terminal hosts): `session/prompt` fails with
91
+ * this instead of settling as cancelled, and the prompt never reaches the transcript (measured 2026-11-08, stop 0ms
92
+ * after a photo prompt; 800ms later it settled as cancelled and was kept).
93
+ */
94
+ const PREFLIGHT_CANCELLED = "Prompt preflight was cancelled before execution";
78
95
 
79
96
  export interface BufferedUpdate {
80
97
  seq: number;
@@ -88,7 +105,11 @@ export interface PendingPermission {
88
105
  sessionId: string;
89
106
  toolCall: unknown;
90
107
  options: Array<{ optionId: string; name: string; kind: string }>;
91
- resolve(outcome: PermissionOutcome): void;
108
+ resolve(outcome: PermissionOutcome): void | Promise<void>;
109
+ /** A TUI ask answered through `ask.answer` (see `SessionHub.#syncRemoteAsks`), not a guarded tool: no mode answers it. */
110
+ hostAsk?: boolean;
111
+ /** Shown from a tmux session's approval channel rather than asked over ACP (see `SessionHub.#enableChannel`). */
112
+ fromChannel?: boolean;
92
113
  }
93
114
 
94
115
  interface SessionState {
@@ -102,6 +123,31 @@ interface SessionState {
102
123
  running: boolean;
103
124
  /** Settles when the bridge-started `session/prompt` in flight resolves or rejects. */
104
125
  turn?: Promise<void>;
126
+ /** That turn's id, given to the phone that sent it (`session.prompt` reply) and repeated on its turn end. */
127
+ turnId?: string;
128
+ /**
129
+ * Whether that prompt went in while a turn started elsewhere (the TUI) was running. gjc then queues it as a
130
+ * steer of that turn instead of starting a turn the bridge owns. Held until the prompt settles: gjc 0.19.3
131
+ * reports no `running: false` while an ACP prompt waits (acp-agent phase owner), so the bridge cannot see
132
+ * when a TUI turn that ended without taking it promotes it to a run of its own; 끼어들기 is refused there too.
133
+ */
134
+ turnBehindHost?: boolean;
135
+ /** The text of that prompt when it carries attachments: still listed by gjc's queue means it waits there. */
136
+ turnAttachmentText?: string;
137
+ /** That prompt's own message while it waits in gjc's queue (see `#holdEcho`). */
138
+ echoHold?: EchoHold;
139
+ /** The last `gjcPhase` gjc reported for the session (`session_info_update`). */
140
+ hostPhase?: string;
141
+ /** Watch for a turn gjc ACP never ends (`#watchStuckTurn`): when the host was last asked, the `seq` it answered idle at. */
142
+ stuckCheck?: { at: number; idleSeq?: number; asking?: boolean };
143
+ /** In-flight `#releaseTurn`. */
144
+ releasing?: Promise<void>;
145
+ /**
146
+ * Set by `interrupt()` from its cancel until its replacement prompt has started. Another prompt in that window
147
+ * (a phone sending a held photo message as the cancelled turn ends) would take the turn the waiting steers are
148
+ * meant for, and the replacement would fail -32003 after gjc's queue had already been emptied of them.
149
+ */
150
+ interrupting?: boolean;
105
151
  /** gjc's own phase flag (session_info_update _meta.running): also true for turns started elsewhere. */
106
152
  hostRunning: boolean;
107
153
  throughput: Throughput;
@@ -121,6 +167,37 @@ interface SessionState {
121
167
  hostAsks: Set<string>;
122
168
  /** Transcript path and the size/mtime last scanned for [hostAsks]. */
123
169
  hostAskScan?: { file: string; size: number; mtimeMs: number };
170
+ /** Cards for those asks by gjc's `ask.requests.list` id (see `#syncRemoteAsks`). */
171
+ remoteAsks: Map<string, PendingPermission>;
172
+ /** Ids answered or dismissed on a phone: never shown again, though a listing taken before may still carry them. */
173
+ remoteAsksDone: Set<string>;
174
+ /** Questions (`questionId`) dismissed on a phone: left to the terminal, also once a terminal toggle gives them a new id. */
175
+ remoteAsksDismissed: Set<string>;
176
+ /** `ask.answer` calls in flight; a pending recycle waits for them. */
177
+ remoteAskAnswers: number;
178
+ /** The last `ask.requests.list` failure logged, so a lasting one is logged once. */
179
+ remoteAskError?: string;
180
+ /** In-flight `ask.requests.list` read; `again` when another was asked for meanwhile. */
181
+ remoteAskSync?: { again: boolean };
182
+ /** The session host has no `ask.requests.list` (gjc 0.19.3 and older): asks stay answerable in the terminal only. */
183
+ remoteAsksUnsupported?: boolean;
184
+ /** Opened by this bridge in a tmux window, so gjc in the terminal hosts it (asks show only there). */
185
+ inTmux?: boolean;
186
+ /** That window's permission approval channel, which brings its tool approvals to the phones (see `#readChannel`). */
187
+ channel?: ApprovalChannel;
188
+ /** While `session/load` replays the history: no channel reads for replayed tool calls. */
189
+ replaying?: boolean;
190
+ /** `seq` once the last load's replay ended: a phone that last saw less gets a full snapshot, never the replay as news. */
191
+ historySeq: number;
192
+ /** The permission mode last announced to the phones (`shownPermissionMode`). */
193
+ shownMode?: PermissionMode;
194
+ /** A reload the bridge started on its own (`#reattach`): its replay is kept from phones already showing the chat. */
195
+ quietReplay?: boolean;
196
+ /**
197
+ * Phones (`HubClient.device`) that showed the chat during a quiet replay: they lack what the terminal did while gjc ACP
198
+ * was gone, and their later live updates hide that from `afterSeq`, so their next open gets a full snapshot.
199
+ */
200
+ resync: Set<string>;
124
201
  }
125
202
 
126
203
  export interface SessionStatus {
@@ -132,6 +209,81 @@ export interface SessionStatus {
132
209
  queued: QueuedMessage[];
133
210
  }
134
211
 
212
+ /** A tmux session's permission approval channel as the bridge follows it (see `SessionHub.#enableChannel`). */
213
+ interface ApprovalChannel {
214
+ /** Requests shown to the phones, by gjc's request id. */
215
+ requests: Map<string, { requestId: string; toolCallId: string }>;
216
+ /** Tool calls that arrived pending and are not listed in the channel yet. */
217
+ waitingTools: Set<string>;
218
+ /** Requests answered or taken down, never shown again. */
219
+ settled: Set<string>;
220
+ reading?: Promise<void>;
221
+ /** Another read was asked for while one ran. */
222
+ again?: boolean;
223
+ }
224
+
225
+ /** `permission.requests.list` item (gjc external-permissions.ts). */
226
+ interface ChannelRequest {
227
+ id: string;
228
+ toolCallId: string;
229
+ toolCall: unknown;
230
+ options: PendingPermission["options"];
231
+ }
232
+
233
+ /**
234
+ * The permission mode a phone is shown. A session gjc hosts in a tmux window runs guarded tools unasked unless its
235
+ * approval channel is on (measured on gjc 0.19.3), so `prompt` without the channel is shown as what happens: `allow`.
236
+ */
237
+ function shownPermissionMode(state: SessionState): PermissionMode {
238
+ return state.inTmux && !state.channel && state.permissionMode === "prompt" ? "allow" : state.permissionMode;
239
+ }
240
+
241
+ /** Reads per trigger at most, and the wait between them while a pending tool call is not listed yet. */
242
+ const CHANNEL_READS = 4;
243
+ const CHANNEL_RETRY_MS = 1000;
244
+
245
+ /** `permission.requests.list` result (`{sessionId, enabled, requests:[{id, sessionId, expiresAt, options, toolCall}]}`). */
246
+ function channelRequests(result: unknown): { enabled: boolean; requests: ChannelRequest[] } {
247
+ const { enabled, requests } = (result ?? {}) as { enabled?: unknown; requests?: unknown };
248
+ return { enabled: enabled !== false, requests: Array.isArray(requests) ? channelRequestItems(requests) : [] };
249
+ }
250
+
251
+ function channelRequestItems(requests: unknown[]): ChannelRequest[] {
252
+ return requests.flatMap(item => {
253
+ const r = item as { id?: unknown; options?: unknown; toolCall?: { toolCallId?: unknown } };
254
+ if (typeof r.id !== "string" || !Array.isArray(r.options) || typeof r.toolCall?.toolCallId !== "string") return [];
255
+ const options = r.options.filter(
256
+ (o): o is PendingPermission["options"][number] =>
257
+ typeof o?.optionId === "string" && typeof o?.name === "string" && typeof o?.kind === "string",
258
+ );
259
+ return [{ id: r.id, toolCallId: r.toolCall.toolCallId, toolCall: r.toolCall, options }];
260
+ });
261
+ }
262
+
263
+ /** The echo of a phone prompt queued behind a TUI turn, held until gjc hands the prompt to the model. */
264
+ interface EchoHold {
265
+ /** Echo blocks still to arrive (see `echoedBlocks`); only chunks matching them are held. */
266
+ blocks: EchoBlock[];
267
+ updates: Record<string, unknown>[];
268
+ /** The prompt's text as gjc's queue lists it (see `queueText`). */
269
+ text: string;
270
+ /** Queue ids already listed when the prompt went in, so an older message with the same text is not taken for it. */
271
+ before: Set<string>;
272
+ /** The prompt's id in gjc's queue once a read listed it. */
273
+ queueId?: string;
274
+ echoedAt?: number;
275
+ /** When `#lookForHandOver` last started a queue read. */
276
+ lookedAt?: number;
277
+ }
278
+
279
+ type EchoBlock = { type: "text"; text: string } | { type: "image"; data: string };
280
+
281
+ /** How often a streaming turn may trigger a queue read while a held echo waits to be handed over. */
282
+ const ECHO_LOOK_MS = 300;
283
+
284
+ /** How long after the echo a queue read must start for the prompt's absence to mean gjc already took it. */
285
+ const ECHO_QUEUE_GRACE_MS = 1500;
286
+
135
287
  export interface QueuedMessage {
136
288
  id: string;
137
289
  text: string;
@@ -142,6 +294,8 @@ const STREAMED_TEXT_UPDATES = new Set(["agent_message_chunk", "agent_thought_chu
142
294
 
143
295
  export interface HubClient {
144
296
  readonly id: string;
297
+ /** The paired device behind this connection, which a reconnecting phone keeps (`id` is per connection). */
298
+ readonly device?: string;
145
299
  deliver(event: string, payload: unknown): void;
146
300
  }
147
301
 
@@ -153,6 +307,11 @@ export interface HubOptions {
153
307
  maxBufferedUpdates?: number;
154
308
  maxBufferedBytes?: number;
155
309
  version: string;
310
+ /** Opt-in: open new sessions as windows of this tmux session (see tmux.ts). */
311
+ tmux?: TmuxOptions;
312
+ /** How often a phone turn gjc ACP may never end is checked against the host (see `#watchStuckTurn`). */
313
+ stuckTurnCheckMs?: number;
314
+ log?: (line: string) => void;
156
315
  }
157
316
 
158
317
  export interface OpenSnapshot {
@@ -169,8 +328,10 @@ export interface OpenSnapshot {
169
328
  }
170
329
 
171
330
  export class SessionHub {
172
- #options: Required<Omit<HubOptions, "acp">> & { acp: AcpSpawnOptions };
331
+ #options: Required<Omit<HubOptions, "acp" | "tmux" | "log">> & Pick<HubOptions, "acp" | "log">;
173
332
  readonly #saved: SavedSessionIndex;
333
+ readonly #tmux?: TmuxLauncher;
334
+ readonly #sdkCli?: SdkCli;
174
335
  #acp?: AcpProcess;
175
336
  #starting?: Promise<AcpProcess>;
176
337
  #agentInfo: unknown;
@@ -181,10 +342,16 @@ export class SessionHub {
181
342
  #restartDelayMs = 0;
182
343
  #recyclePending = false;
183
344
  #statusTimer?: ReturnType<typeof setInterval>;
345
+ #stopped = false;
184
346
 
185
347
  constructor(options: HubOptions) {
186
- this.#options = { maxBufferedUpdates: 5000, maxBufferedBytes: 48 * 1024 * 1024, ...options };
348
+ this.#options = { maxBufferedUpdates: 5000, maxBufferedBytes: MAX_BUFFERED_BYTES, stuckTurnCheckMs: STUCK_TURN_CHECK_MS, ...options };
187
349
  this.#saved = new SavedSessionIndex(options.agentDir);
350
+ // The window gets the tmux server's environment; point gjc there at the agent dir the ACP side uses.
351
+ if (options.tmux) {
352
+ this.#tmux = new TmuxLauncher(options.tmux, tuiCommand(options.acp.command), { GJC_CODING_AGENT_DIR: options.agentDir });
353
+ this.#sdkCli = new SdkCli({ command: tuiCommand(options.acp.command), agentDir: options.agentDir });
354
+ }
188
355
  }
189
356
 
190
357
  // ── clients ──────────────────────────────────────────────────────────────
@@ -228,6 +395,7 @@ export class SessionHub {
228
395
  this.#acp = acp;
229
396
  this.#restartDelayMs = 0;
230
397
  queueMicrotask(() => this.#maybeRecycle());
398
+ queueMicrotask(() => void this.#reattach());
231
399
  return acp;
232
400
  } catch (error) {
233
401
  acp.kill();
@@ -242,22 +410,53 @@ export class SessionHub {
242
410
  // Whatever spawns next resolves the launcher again, so a pending recycle is satisfied.
243
411
  this.#recyclePending = false;
244
412
  this.#restartDelayMs = Math.min(Math.max(this.#restartDelayMs * 2, 1000), 30_000);
245
- for (const permission of this.#permissions.values()) permission.resolve({ outcome: "cancelled" });
246
- this.#permissions.clear();
413
+ // An approval asked over ACP dies with the process. One from a tmux session's channel lives on in the TUI host:
414
+ // its card is only taken down, and the reload below lists it again.
415
+ for (const permission of this.#permissions.values()) if (!permission.fromChannel) permission.resolve({ outcome: "cancelled" });
416
+ for (const permission of [...this.#permissions.values()]) {
417
+ this.#permissions.delete(permission.requestId);
418
+ if (permission.fromChannel) this.#broadcastAll("permission.resolved", { requestId: permission.requestId, sessionId: permission.sessionId });
419
+ }
247
420
  for (const state of this.#sessions.values()) {
248
421
  state.loaded = false;
422
+ state.channel = undefined;
249
423
  if (state.running) {
250
424
  state.running = false;
251
425
  this.#append(state, { sessionUpdate: AGENT_EXIT, code, stderrTail: acp.stderrTail.slice(-2000) });
252
426
  }
253
427
  }
428
+ // The TUI in a tmux window waits on the bridge for its tool approvals: attach again without waiting for a phone.
429
+ if (!this.#stopped && [...this.#sessions.values()].some(s => s.inTmux)) {
430
+ setTimeout(() => void this.agent().catch(error => this.#options.log?.(`gjc ACP restart failed: ${error?.message ?? error}`)), 0);
431
+ }
254
432
  }
255
433
 
256
434
  stop(): void {
435
+ this.#stopped = true;
257
436
  if (this.#statusTimer) clearInterval(this.#statusTimer);
258
437
  this.#acp?.kill();
259
438
  }
260
439
 
440
+ /**
441
+ * Loads every session a tmux window of the bridge hosts, after the ACP process (re)started: on bridge start, after a
442
+ * recycle or a crash. Until then nothing would watch its approval channel, and a tool typed in the terminal would wait
443
+ * 60s for an answer only the phone can give, then be rejected.
444
+ */
445
+ async #reattach(): Promise<void> {
446
+ if (!this.#tmux || this.#stopped) return;
447
+ const windows = new Map((await this.#tmux.hostedSessions()).map(w => [w.sessionId, w.cwd]));
448
+ for (const state of this.#sessions.values()) if (state.inTmux && !windows.has(state.sessionId)) windows.set(state.sessionId, state.cwd);
449
+ for (const [sessionId, windowCwd] of windows) {
450
+ const known = this.#sessions.get(sessionId);
451
+ if (known?.loaded || this.#stopped) continue;
452
+ const cwd = known?.cwd ?? (windowCwd || this.#saved.find(sessionId)?.cwd);
453
+ if (!cwd) continue;
454
+ await this.#load(this.#stateFor(sessionId, cwd), true).catch(error =>
455
+ this.#options.log?.(`reattach ${sessionId} failed: ${error instanceof Error ? error.message : String(error)}`),
456
+ );
457
+ }
458
+ }
459
+
261
460
  /**
262
461
  * Observed on gjc 0.18.7: after hours of uptime the ACP process's broker socket can go bad, and
263
462
  * every resume then fails ~10s in with "SDK request outcome is uncertain after the frame was sent"
@@ -296,7 +495,7 @@ export class SessionHub {
296
495
  if (!this.#starting) this.#recyclePending = false;
297
496
  return;
298
497
  }
299
- if ([...this.#sessions.values()].some(s => s.running) || this.#permissions.size > 0) return;
498
+ if ([...this.#sessions.values()].some(s => s.running || s.remoteAskAnswers > 0) || this.#permissions.size > 0) return;
300
499
  this.#onExit(acp, null);
301
500
  this.#restartDelayMs = 0;
302
501
  acp.kill();
@@ -307,7 +506,215 @@ export class SessionHub {
307
506
  #onNotification(method: string, params: any): void {
308
507
  if (method !== "session/update" || typeof params?.sessionId !== "string") return;
309
508
  const state = this.#stateFor(params.sessionId);
310
- this.#append(state, params.update);
509
+ if (this.#holdEcho(state, params.update)) return;
510
+ this.#append(state, state.inTmux ? terminalAsk(params.update) : params.update);
511
+ this.#lookForHandOver(state, params.update);
512
+ if (state.channel && !state.replaying) this.#watchChannel(state, params.update);
513
+ }
514
+
515
+ /**
516
+ * Keeps back the echo of a phone prompt queued behind a TUI turn until gjc hands it to the model. gjc echoes a
517
+ * prompt's text and image blocks as `user_message_chunk` the moment it receives it, before the prompt waits in
518
+ * its queue (measured 2026-11-07 on pve3, gjc 0.19.3: echoed at once, listed as `steer:1` for 25s until the TUI
519
+ * turn's tool ended, then answered; nothing announced the hand-over). Shown at once, the message sat in the
520
+ * middle of the TUI turn's output while the phone also listed it as waiting; the TUI shows it only once
521
+ * delivered. The echo is released when the queue no longer lists it (`#settleEchoHold`) or the prompt ends.
522
+ */
523
+ #holdEcho(state: SessionState, update: any): boolean {
524
+ const hold = state.echoHold;
525
+ if (!hold || update?.sessionUpdate !== "user_message_chunk" || !sameBlock(hold.blocks[0], update.content)) return false;
526
+ hold.blocks.shift();
527
+ hold.updates.push(update);
528
+ if (hold.blocks.length === 0) hold.echoedAt = Date.now();
529
+ return true;
530
+ }
531
+
532
+ /**
533
+ * gjc hands a queued message over at a step boundary: when a tool ends, or when the model's answer goes on.
534
+ * Looks at once on a tool end and at most every [ECHO_LOOK_MS] while the turn streams, instead of waiting for
535
+ * the once-a-second read. A read already in flight may predate the hand-over, so the look starts after it.
536
+ */
537
+ #lookForHandOver(state: SessionState, update: any): void {
538
+ const hold = state.echoHold;
539
+ if (hold?.queueId === undefined) return;
540
+ const now = Date.now();
541
+ const toolEnded = update?.status === "completed" || update?.status === "failed";
542
+ if (!toolEnded && now - (hold.lookedAt ?? 0) < ECHO_LOOK_MS) return;
543
+ hold.lookedAt = now;
544
+ void (state.queueSample ?? Promise.resolve()).then(() => this.#sampleQueue(state));
545
+ }
546
+
547
+ /** Releases the held echo once gjc's queue (read at [sampledAt]) shows the prompt left it. */
548
+ #settleEchoHold(state: SessionState, queue: QueuedMessage[], sampledAt: number): void {
549
+ const hold = state.echoHold;
550
+ if (!hold || hold.echoedAt === undefined) return;
551
+ if (hold.queueId === undefined) {
552
+ // gjc lists it as a steer, or as a follow-up when one already waits ahead of it. Matched by text only: a
553
+ // steer typed in the TUI meanwhile is new to [before] too, and taking it for this prompt would hold the
554
+ // message until that one goes.
555
+ const listed = queue.find(m => !hold.before.has(m.id) && m.text.trim() === hold.text);
556
+ if (listed) {
557
+ hold.queueId = listed.id;
558
+ return;
559
+ }
560
+ // Never listed: taken straight away (the TUI turn was at a step boundary or had just ended). A read started
561
+ // right after the echo may predate the queueing, so only a later one counts.
562
+ if (sampledAt - hold.echoedAt < ECHO_QUEUE_GRACE_MS) return;
563
+ } else if (queue.some(m => m.id === hold.queueId)) {
564
+ return;
565
+ }
566
+ this.#releaseEcho(state);
567
+ }
568
+
569
+ #releaseEcho(state: SessionState): void {
570
+ const hold = state.echoHold;
571
+ state.echoHold = undefined;
572
+ for (const update of hold?.updates ?? []) this.#append(state, update);
573
+ }
574
+
575
+ /**
576
+ * Turns on the permission approval channel of a session gjc hosts in a tmux window. gjc sends a TUI host's tool
577
+ * approvals to no ACP client, and gjc 0.19.3 prohibits the channel over ACP, so the bridge goes through the
578
+ * session CLI (see sdk-cli.ts). Measured 2026-11-07 on pve3: with the channel on, the bash approvals of both a
579
+ * phone turn and a turn typed in the terminal are listed by `permission.requests.list` (the TUI shows only a
580
+ * spinner meanwhile) and `permission.respond` allows or rejects them. Without it the TUI ran bash unasked while
581
+ * the phone showed `prompt`. Enabling sets the session to prompt; re-enabling is a no-op. A failure leaves the
582
+ * session without the channel, logged.
583
+ */
584
+ async #enableChannel(state: SessionState): Promise<void> {
585
+ const cli = this.#sdkCli;
586
+ if (!cli || state.channel) return;
587
+ try {
588
+ await cli.control(state.sessionId, state.cwd, "permission.channel.set", { enabled: true });
589
+ state.channel = { requests: new Map(), waitingTools: new Set(), settled: new Set() };
590
+ } catch (error) {
591
+ this.#options.log?.(`permission channel not enabled for ${state.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
592
+ }
593
+ }
594
+
595
+ /**
596
+ * gjc announces a channel request on no stream, but the tool it gates arrives over ACP as a pending tool call
597
+ * first (measured ~1.4s before it is listed): read the channel then, again while such a call stays pending
598
+ * unlisted, and drop the card of a call that ended (expired, cancelled, answered in another way).
599
+ */
600
+ #watchChannel(state: SessionState, update: any): void {
601
+ const channel = state.channel!;
602
+ const kind = update?.sessionUpdate;
603
+ if (kind !== "tool_call" && kind !== "tool_call_update") return;
604
+ const toolCallId = update.toolCallId;
605
+ if (typeof toolCallId !== "string") return;
606
+ const pending = update.status === "pending" || (kind === "tool_call" && update.status === undefined);
607
+ // gjc starts every tool call pending; only a guarded one in prompt mode waits on the channel, never an ask.
608
+ if (pending && (state.permissionMode !== "prompt" || update.rawInput?.questions !== undefined)) return;
609
+ if (pending) {
610
+ channel.waitingTools.add(toolCallId);
611
+ this.#readChannel(state);
612
+ return;
613
+ }
614
+ if (update.status === undefined) return;
615
+ channel.waitingTools.delete(toolCallId);
616
+ if (update.status !== "completed" && update.status !== "failed") return;
617
+ for (const [id, request] of channel.requests) {
618
+ if (request.toolCallId === toolCallId) this.#dropChannelRequest(state, id);
619
+ }
620
+ }
621
+
622
+ /** Lists the channel's requests into phone permission cards; one read at a time, another queued behind it. */
623
+ #readChannel(state: SessionState): void {
624
+ const channel = state.channel;
625
+ const cli = this.#sdkCli;
626
+ if (!channel || !cli) return;
627
+ if (channel.reading) {
628
+ channel.again = true;
629
+ return;
630
+ }
631
+ channel.reading = (async () => {
632
+ for (let attempt = 0; attempt < CHANNEL_READS; attempt++) {
633
+ channel.again = false;
634
+ let read: { enabled: boolean; requests: ChannelRequest[] };
635
+ try {
636
+ read = channelRequests(await cli.query(state.sessionId, state.cwd, "permission.requests.list"));
637
+ } catch (error) {
638
+ this.#options.log?.(`permission.requests.list failed for ${state.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
639
+ return;
640
+ }
641
+ if (state.channel !== channel) return;
642
+ if (!read.enabled) {
643
+ // The host lost it (a TUI restarted under the same id): turn it on again.
644
+ for (const id of [...channel.requests.keys()]) this.#dropChannelRequest(state, id);
645
+ state.channel = undefined;
646
+ await this.#enableChannel(state);
647
+ this.#announceShownMode(state);
648
+ return;
649
+ }
650
+ const listed = read.requests.filter(r => !channel.settled.has(r.id));
651
+ const ids = new Set(listed.map(r => r.id));
652
+ for (const id of channel.requests.keys()) if (!ids.has(id)) this.#dropChannelRequest(state, id);
653
+ for (const request of listed) {
654
+ channel.waitingTools.delete(request.toolCallId);
655
+ if (!channel.requests.has(request.id)) this.#showChannelRequest(state, request);
656
+ }
657
+ // A gated call shows up in the channel a moment after it arrives here; one that never does was not gated.
658
+ if (!channel.again && channel.waitingTools.size === 0) return;
659
+ if (!channel.again) await Bun.sleep(CHANNEL_RETRY_MS);
660
+ }
661
+ })().finally(() => {
662
+ channel.reading = undefined;
663
+ if (channel.again) this.#readChannel(state);
664
+ });
665
+ }
666
+
667
+ #showChannelRequest(state: SessionState, request: ChannelRequest): void {
668
+ const channel = state.channel!;
669
+ const requestId = `perm-${this.#nextPermission++}`;
670
+ channel.requests.set(request.id, { requestId, toolCallId: request.toolCallId });
671
+ const pending: PendingPermission = {
672
+ requestId,
673
+ sessionId: state.sessionId,
674
+ toolCall: request.toolCall,
675
+ options: request.options,
676
+ resolve: outcome => this.#answerChannel(state, request, outcome),
677
+ fromChannel: true,
678
+ };
679
+ this.#permissions.set(requestId, pending);
680
+ this.#broadcastAll("permission.request", publicPermission(pending));
681
+ }
682
+
683
+ /** Tells the phones the permission mode to show when it changed, e.g. `allow` for a TUI host that lost its channel. */
684
+ #announceShownMode(state: SessionState): void {
685
+ const shown = shownPermissionMode(state);
686
+ if (shown === (state.shownMode ?? state.permissionMode)) return;
687
+ state.shownMode = shown;
688
+ this.#append(state, { sessionUpdate: PERMISSION_MODE_UPDATE, mode: shown });
689
+ }
690
+
691
+ /** Removes a request's card from the phones without answering it (gjc settled it some other way). */
692
+ #dropChannelRequest(state: SessionState, id: string): void {
693
+ const shown = state.channel?.requests.get(id);
694
+ if (!shown) return;
695
+ state.channel!.requests.delete(id);
696
+ // A read that started before gjc settled it may still list it: never shown again.
697
+ state.channel!.settled.add(id);
698
+ this.#permissions.delete(shown.requestId);
699
+ this.#broadcastAll("permission.resolved", { requestId: shown.requestId, sessionId: state.sessionId });
700
+ if (this.#recyclePending) setTimeout(() => this.#maybeRecycle(), 0);
701
+ }
702
+
703
+ /** The phone's answer: `permission.respond` with the picked option, a dismissal as the offered rejection. */
704
+ async #answerChannel(state: SessionState, request: ChannelRequest, outcome: PermissionOutcome): Promise<void> {
705
+ if (!state.channel?.requests.has(request.id)) return;
706
+ this.#dropChannelRequest(state, request.id);
707
+ const optionId =
708
+ outcome.outcome === "selected" ? outcome.optionId : request.options.find(o => o.kind === "reject_once" || o.kind === "reject_always")?.optionId;
709
+ if (!optionId) return; // nothing to reject with: gjc fails it closed when it expires
710
+ try {
711
+ await this.#sdkCli!.control(state.sessionId, state.cwd, "permission.respond", { sessionId: state.sessionId, id: request.id, optionId });
712
+ } catch (error) {
713
+ this.#options.log?.(`permission.respond failed for ${state.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
714
+ // Still waiting (the CLI failed, not gjc): show it again.
715
+ state.channel?.settled.delete(request.id);
716
+ this.#readChannel(state);
717
+ }
311
718
  }
312
719
 
313
720
  async #onRequest(method: string, params: any): Promise<unknown> {
@@ -337,6 +744,8 @@ export class SessionHub {
337
744
  sessionId,
338
745
  cwd: cwd ?? this.#options.defaultCwd,
339
746
  seq: 0,
747
+ historySeq: 0,
748
+ resync: new Set(),
340
749
  buffer: [],
341
750
  bufferBytes: 0,
342
751
  loaded: false,
@@ -344,6 +753,10 @@ export class SessionHub {
344
753
  hostRunning: false,
345
754
  throughput: new Throughput(),
346
755
  queued: [],
756
+ remoteAsks: new Map(),
757
+ remoteAsksDone: new Set(),
758
+ remoteAsksDismissed: new Set(),
759
+ remoteAskAnswers: 0,
347
760
  configOptions: [],
348
761
  permissionMode: "prompt",
349
762
  hostAsks: new Set(),
@@ -363,14 +776,16 @@ export class SessionHub {
363
776
  this.#track(state, update);
364
777
  const entry = { seq: ++state.seq, update };
365
778
  state.buffer.push(entry);
366
- state.bufferBytes += approxBytes(update);
779
+ state.bufferBytes += jsonBytes(update);
367
780
  while (
368
781
  state.buffer.length > this.#options.maxBufferedUpdates ||
369
782
  (state.bufferBytes > this.#options.maxBufferedBytes && state.buffer.length > 1)
370
783
  ) {
371
784
  const dropped = state.buffer.shift()!;
372
- state.bufferBytes -= approxBytes(dropped.update);
785
+ state.bufferBytes -= jsonBytes(dropped.update);
373
786
  }
787
+ // A phone showing the chat already has the history a reload of the bridge's own replays.
788
+ if (state.quietReplay) return;
374
789
  for (const { client, sessions } of this.#clients.values()) {
375
790
  if (sessions.has(state.sessionId)) client.deliver("session.update", { sessionId: state.sessionId, ...entry });
376
791
  }
@@ -393,8 +808,9 @@ export class SessionHub {
393
808
  return;
394
809
  }
395
810
  if (kind === "session_info_update") {
396
- const running = (update._meta as { running?: unknown } | undefined)?.running;
397
- if (typeof running === "boolean") state.hostRunning = running;
811
+ const meta = update._meta as { running?: unknown; gjcPhase?: unknown } | undefined;
812
+ if (typeof meta?.running === "boolean") state.hostRunning = meta.running;
813
+ if (typeof meta?.gjcPhase === "string") state.hostPhase = meta.gjcPhase;
398
814
  }
399
815
  if (kind === TURN_END || kind === AGENT_EXIT) state.hostRunning = false;
400
816
  const active = isActive(state);
@@ -443,9 +859,12 @@ export class SessionHub {
443
859
  */
444
860
  #sampleQueue(state: SessionState): Promise<void> {
445
861
  if (!state.loaded) return Promise.resolve();
862
+ const sampledAt = Date.now();
446
863
  state.queueSample ??= this.sdk({ sessionId: state.sessionId, kind: "query", op: "queue.messages.list", internal: true })
447
864
  .then(result => {
448
- if (isActive(state)) state.queued = queuedMessages(result);
865
+ const queue = queuedMessages(result);
866
+ if (isActive(state)) state.queued = queue;
867
+ this.#settleEchoHold(state, queue, sampledAt);
449
868
  })
450
869
  .catch(() => {})
451
870
  .finally(() => {
@@ -491,6 +910,116 @@ export class SessionHub {
491
910
  state.hostAsks.delete(id);
492
911
  this.#append(state, hostAskSettled(id, result));
493
912
  }
913
+ if (state.hostAsks.size === 0) this.#dropRemoteAsks(state);
914
+ }
915
+
916
+ /**
917
+ * Makes the TUI's pending asks answerable on the phone where the session host lists them (`ask.requests.list`, newer
918
+ * than gjc 0.19.3): each selector question becomes a permission card whose pick goes back as `ask.answer`. Runs on
919
+ * the status tick while the transcript shows an unanswered ask, since every pick (a multi-select toggle, the next
920
+ * question) gives the request a new id. A host without it leaves the read-only card from the transcript.
921
+ */
922
+ #syncRemoteAsks(state: SessionState): void {
923
+ if (state.remoteAsksUnsupported || !state.loaded || state.hostAsks.size === 0) return;
924
+ if (state.remoteAskSync) {
925
+ state.remoteAskSync.again = true;
926
+ return;
927
+ }
928
+ const sync = { again: false };
929
+ state.remoteAskSync = sync;
930
+ void (async () => {
931
+ try {
932
+ do {
933
+ sync.again = false;
934
+ const acp = await this.agent();
935
+ let listed: ReturnType<typeof remoteAskRequests>;
936
+ try {
937
+ listed = remoteAskRequests(await this.#sdkRequest(acp, state, "query", "ask.requests.list", {}));
938
+ } catch (error) {
939
+ const message = error instanceof Error ? error.message : String(error);
940
+ if (error instanceof AcpError && (error.data as { code?: unknown } | undefined)?.code === "host_outdated") state.remoteAsksUnsupported = true;
941
+ else if (state.remoteAskError !== message) console.error(`ask.requests.list failed for ${state.sessionId}: ${message}`);
942
+ state.remoteAskError = message;
943
+ return;
944
+ }
945
+ state.remoteAskError = undefined;
946
+ if (state.hostAsks.size === 0) return;
947
+ const live = new Set<string>();
948
+ for (const request of listed) {
949
+ if (request.sessionId !== undefined && request.sessionId !== state.sessionId) continue;
950
+ if (state.remoteAsksDone.has(request.id)) continue;
951
+ if (request.questionId !== undefined && state.remoteAsksDismissed.has(request.questionId)) continue;
952
+ const card = remoteAskCard(request);
953
+ if (!card) continue;
954
+ live.add(request.id);
955
+ if (!state.remoteAsks.has(request.id)) this.#showRemoteAsk(state, request.id, request.questionId, request.question, card);
956
+ }
957
+ for (const id of [...state.remoteAsks.keys()]) if (!live.has(id)) this.#dropRemoteAsk(state, id);
958
+ // Dismissed questions the host no longer lists are done with.
959
+ const listedQuestions = new Set(listed.map(r => r.questionId));
960
+ for (const questionId of state.remoteAsksDismissed) if (!listedQuestions.has(questionId)) state.remoteAsksDismissed.delete(questionId);
961
+ } while (sync.again);
962
+ } finally {
963
+ state.remoteAskSync = undefined;
964
+ }
965
+ })();
966
+ }
967
+
968
+ #showRemoteAsk(state: SessionState, id: string, questionId: string | undefined, question: string, card: RemoteAskCard): void {
969
+ const requestId = `perm-${this.#nextPermission++}`;
970
+ // The ask row on the phone carries the transcript's tool call id; with several pending, the card stands alone.
971
+ const toolCallId = state.hostAsks.size === 1 ? [...state.hostAsks][0]! : `ask-${id}`;
972
+ const pending: PendingPermission = {
973
+ requestId,
974
+ sessionId: state.sessionId,
975
+ // No rawInput: the question is the title, and the ask row above already lists it with its options.
976
+ toolCall: { toolCallId, toolName: "ask", title: question, kind: "other", status: "pending" },
977
+ options: card.options,
978
+ hostAsk: true,
979
+ resolve: outcome => {
980
+ // Dismissing the card leaves the question to the terminal.
981
+ const answer = outcome.outcome === "selected" ? card.answers.get(outcome.optionId) : undefined;
982
+ if (!answer && questionId !== undefined) state.remoteAsksDismissed.add(questionId);
983
+ if (answer) state.remoteAskAnswers++;
984
+ this.#dropRemoteAsk(state, id);
985
+ if (answer) void this.#answerRemoteAsk(state, id, answer);
986
+ },
987
+ };
988
+ state.remoteAsks.set(id, pending);
989
+ this.#permissions.set(requestId, pending);
990
+ this.#broadcastAll("permission.request", publicPermission(pending));
991
+ }
992
+
993
+ #dropRemoteAsk(state: SessionState, id: string): void {
994
+ const shown = state.remoteAsks.get(id);
995
+ if (!shown) return;
996
+ state.remoteAsks.delete(id);
997
+ state.remoteAsksDone.add(id);
998
+ this.#permissions.delete(shown.requestId);
999
+ this.#broadcastAll("permission.resolved", { requestId: shown.requestId, sessionId: state.sessionId });
1000
+ if (this.#recyclePending) setTimeout(() => this.#maybeRecycle(), 0);
1001
+ }
1002
+
1003
+ #dropRemoteAsks(state: SessionState): void {
1004
+ for (const id of [...state.remoteAsks.keys()]) this.#dropRemoteAsk(state, id);
1005
+ }
1006
+
1007
+ async #answerRemoteAsk(state: SessionState, id: string, answer: { kind: "value"; value: string } | { kind: "control"; controlId: string }): Promise<void> {
1008
+ try {
1009
+ const acp = await this.agent();
1010
+ await this.#sdkRequest(acp, state, "control", "ask.answer", { id, answer });
1011
+ } catch (error) {
1012
+ // A terminal answer that won the race, or a transition, makes the id stale: the next listing shows what is left.
1013
+ // Anything else did not reach the question: show the card again if it is still listed.
1014
+ if (!(error instanceof AcpError && (error.data as { code?: unknown } | undefined)?.code === "stale_request")) {
1015
+ state.remoteAsksDone.delete(id);
1016
+ console.error(`ask.answer failed for ${state.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1017
+ }
1018
+ } finally {
1019
+ state.remoteAskAnswers--;
1020
+ }
1021
+ this.#syncRemoteAsks(state);
1022
+ if (this.#recyclePending) setTimeout(() => this.#maybeRecycle(), 0);
494
1023
  }
495
1024
 
496
1025
  /** One tick per second while any session is working, so list rows show a live rate and chats gjc's queue. */
@@ -500,6 +1029,8 @@ export class SessionHub {
500
1029
  const active = [...this.#sessions.values()].filter(isActive);
501
1030
  for (const state of active) {
502
1031
  this.#sampleHostAsks(state);
1032
+ this.#syncRemoteAsks(state);
1033
+ this.#watchStuckTurn(state);
503
1034
  void Promise.all([this.#sampleUsage(state), this.#sampleQueue(state)]).finally(() => this.#publishStatus(state));
504
1035
  }
505
1036
  if (active.length === 0) {
@@ -555,7 +1086,24 @@ export class SessionHub {
555
1086
  const cwd = params.cwd || this.#options.defaultCwd;
556
1087
  // gjc answers a missing cwd with "Lifecycle worktree does not exist" after spawning a session host.
557
1088
  if (!isDirectory(cwd)) throw new AcpError(-32602, `호스트에 작업 디렉터리가 없습니다: ${cwd}`);
1089
+ const tmuxSkipped = this.#tmux && (await this.#tmux.unavailable());
1090
+ if (tmuxSkipped) this.#options.log?.(`tmux skipped (opening over ACP): ${tmuxSkipped.slice(0, 200)}`);
558
1091
  const result = await acp.request("session/new", { cwd, mcpServers: [] });
1092
+ if (this.#tmux && !tmuxSkipped) {
1093
+ // ACP lets go of the session it just wrote, and gjc in the window resumes it; the phone then attaches
1094
+ // to that TUI host like to any terminal session. A failure leaves the (empty) session saved.
1095
+ try {
1096
+ await acp.request("session/close", { sessionId: result.sessionId });
1097
+ await this.#tmux.open(result.sessionId, cwd);
1098
+ } catch (error) {
1099
+ const message = error instanceof Error ? error.message : String(error);
1100
+ throw new AcpError(-32021, `새 세션을 tmux 창으로 열지 못했습니다(${result.sessionId}): ${message}`, {
1101
+ code: error instanceof TmuxError ? error.code : "tmux_handoff_failed",
1102
+ });
1103
+ }
1104
+ this.#stateFor(result.sessionId, cwd).inTmux = true;
1105
+ return this.openSession(clientId, { sessionId: result.sessionId, cwd });
1106
+ }
559
1107
  const state = this.#stateFor(result.sessionId, cwd);
560
1108
  state.loaded = true;
561
1109
  state.configOptions = supportedConfigOptions(result.configOptions ?? state.configOptions);
@@ -563,38 +1111,66 @@ export class SessionHub {
563
1111
  }
564
1112
 
565
1113
  async openSession(clientId: string, params: { sessionId: string; cwd?: string; afterSeq?: number }): Promise<OpenSnapshot> {
566
- const acp = await this.agent();
567
1114
  const state = this.#stateFor(params.sessionId, params.cwd ?? this.#saved.find(params.sessionId)?.cwd);
1115
+ // A turn being released (`#releaseTurn`) reloads the session itself.
1116
+ await state.releasing?.catch(() => {});
568
1117
  if (!state.loaded) {
569
- state.loading ??= (async () => {
570
- // A reload replays the full history again; start the replay buffer from scratch.
571
- state.buffer = [];
572
- state.bufferBytes = 0;
573
- // The replay carries a waiting ask as failed ("ends without a result"); show it again as pending.
574
- state.hostAsks.clear();
575
- state.hostAskScan = undefined;
576
- const result = await acp.request("session/load", {
577
- sessionId: state.sessionId,
578
- cwd: state.cwd,
579
- mcpServers: [],
580
- });
581
- state.configOptions = supportedConfigOptions(result?.configOptions ?? state.configOptions);
582
- if (state.permissionMode !== "prompt") await this.#applyPermissionMode(acp, state.sessionId, state.permissionMode);
583
- state.loaded = true;
584
- })()
585
- .catch(error => {
586
- this.#recycleOnBrokerLoss(acp, error);
587
- throw error;
588
- })
589
- .finally(() => {
590
- state.loading = undefined;
591
- });
592
- await state.loading;
1118
+ await this.#load(state);
593
1119
  return this.#subscribe(clientId, state, 0, true);
594
1120
  }
595
1121
  return this.#subscribe(clientId, state, params.afterSeq ?? 0);
596
1122
  }
597
1123
 
1124
+ /** Loads the session into the ACP process (`session/load`); one load at a time per session. */
1125
+ #load(state: SessionState, quiet = false): Promise<void> {
1126
+ if (state.loaded) return Promise.resolve();
1127
+ state.loading ??= (async () => {
1128
+ const acp = await this.agent();
1129
+ // A reload replays the full history again; start the replay buffer from scratch.
1130
+ state.buffer = [];
1131
+ state.bufferBytes = 0;
1132
+ state.hostPhase = undefined;
1133
+ // The replay carries a waiting ask as failed ("ends without a result"); show it again as pending.
1134
+ state.hostAsks.clear();
1135
+ state.hostAskScan = undefined;
1136
+ // The cards went with the ACP process that listed them (or are listed again below); the host may be another build.
1137
+ this.#dropRemoteAsks(state);
1138
+ state.remoteAsksDone.clear();
1139
+ state.remoteAsksDismissed.clear();
1140
+ state.remoteAsksUnsupported = undefined;
1141
+ // The channel is judged again below; its cards come back from the first read.
1142
+ for (const id of [...(state.channel?.requests.keys() ?? [])]) this.#dropChannelRequest(state, id);
1143
+ state.channel = undefined;
1144
+ state.replaying = true;
1145
+ state.quietReplay = quiet;
1146
+ let result: any;
1147
+ try {
1148
+ result = await acp.request("session/load", { sessionId: state.sessionId, cwd: state.cwd, mcpServers: [] });
1149
+ } catch (error) {
1150
+ this.#recycleOnBrokerLoss(acp, error);
1151
+ throw error;
1152
+ } finally {
1153
+ state.replaying = false;
1154
+ state.quietReplay = false;
1155
+ state.historySeq = state.seq;
1156
+ if (quiet) for (const { client, sessions } of this.#clients.values()) if (sessions.has(state.sessionId)) state.resync.add(client.device ?? client.id);
1157
+ }
1158
+ state.configOptions = supportedConfigOptions(result?.configOptions ?? state.configOptions);
1159
+ // Judged on every load: a window the bridge opened (also before a restart) hosts it, or no longer does.
1160
+ if (this.#tmux) state.inTmux = await this.#tmux.hosts(state.sessionId, state.cwd);
1161
+ // Before the mode: enabling the channel sets the session to prompt.
1162
+ if (state.inTmux) await this.#enableChannel(state);
1163
+ if (state.permissionMode !== "prompt") await this.#applyPermissionMode(acp, state.sessionId, state.permissionMode);
1164
+ state.loaded = true;
1165
+ this.#announceShownMode(state);
1166
+ // Requests already waiting (from before a restart) are not announced by any later tool call.
1167
+ this.#readChannel(state);
1168
+ })().finally(() => {
1169
+ state.loading = undefined;
1170
+ });
1171
+ return state.loading;
1172
+ }
1173
+
598
1174
  /** Copies a saved session into a new one and opens it (gjc replays the copied history on load). */
599
1175
  async forkSession(clientId: string, params: { sessionId: string; cwd?: string }): Promise<OpenSnapshot> {
600
1176
  const acp = await this.agent();
@@ -626,19 +1202,23 @@ export class SessionHub {
626
1202
  }
627
1203
 
628
1204
  #subscribe(clientId: string, state: SessionState, afterSeq: number, forceReset = false): OpenSnapshot {
629
- this.#clients.get(clientId)?.sessions.add(state.sessionId);
1205
+ const entry = this.#clients.get(clientId);
1206
+ entry?.sessions.add(state.sessionId);
1207
+ const resync = state.resync.delete(entry?.client.device ?? clientId);
630
1208
  const firstSeq = state.buffer[0]?.seq ?? state.seq + 1;
631
- const reset = forceReset || afterSeq === 0 || afterSeq < firstSeq - 1 || afterSeq > state.seq;
1209
+ const reset = forceReset || resync || afterSeq === 0 || afterSeq < firstSeq - 1 || afterSeq > state.seq || afterSeq < state.historySeq;
632
1210
  return {
633
1211
  sessionId: state.sessionId,
634
1212
  cwd: state.cwd,
635
1213
  configOptions: state.configOptions,
636
- running: state.running,
1214
+ // A turn started in the terminal counts too, as it does in the live `_meta.running` and session.status:
1215
+ // a phone opening the chat then steers it, and a photo message it holds waits for that turn's end.
1216
+ running: isActive(state),
637
1217
  seq: state.seq,
638
1218
  reset,
639
1219
  updates: reset ? state.buffer.slice() : state.buffer.filter(u => u.seq > afterSeq),
640
1220
  permissions: [...this.#permissions.values()].filter(p => p.sessionId === state.sessionId).map(publicPermission),
641
- permissionMode: state.permissionMode,
1221
+ permissionMode: shownPermissionMode(state),
642
1222
  };
643
1223
  }
644
1224
 
@@ -652,17 +1232,29 @@ export class SessionHub {
652
1232
  if (!mode) throw new AcpError(-32602, `permission mode must be one of ${PERMISSION_MODES.join(", ")}`);
653
1233
  const state = this.#sessions.get(params.sessionId);
654
1234
  if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
1235
+ if (mode === "prompt" && state.inTmux && !state.channel) {
1236
+ await this.#enableChannel(state);
1237
+ if (!state.channel)
1238
+ throw new AcpError(-32020, "터미널(tmux) 세션의 승인 채널을 켜지 못해 폰에서 승인할 수 없습니다. 브리지 로그를 확인하세요.", {
1239
+ code: "approval_channel_unavailable",
1240
+ });
1241
+ }
1242
+ const kind = mode === "allow" ? "allow_once" : "reject_once";
1243
+ const settle = (fromChannel: boolean) => {
1244
+ if (mode === "prompt") return [];
1245
+ return [...this.#permissions.values()].flatMap(pending => {
1246
+ if (pending.sessionId !== state.sessionId || pending.hostAsk || Boolean(pending.fromChannel) !== fromChannel) return [];
1247
+ const option = pending.options.find(o => o.kind === kind);
1248
+ return option ? [pending.resolve({ outcome: "selected", optionId: option.optionId })] : [];
1249
+ });
1250
+ };
1251
+ // gjc cancels the channel's waiting requests when the mode changes: answer them first.
1252
+ await Promise.all(settle(true));
655
1253
  await this.#applyPermissionMode(await this.agent(), state.sessionId, mode, state);
656
1254
  state.permissionMode = mode;
1255
+ state.shownMode = mode;
657
1256
  this.#append(state, { sessionUpdate: PERMISSION_MODE_UPDATE, mode });
658
- if (mode !== "prompt") {
659
- const kind = mode === "allow" ? "allow_once" : "reject_once";
660
- for (const pending of this.#permissions.values()) {
661
- if (pending.sessionId !== state.sessionId) continue;
662
- const option = pending.options.find(o => o.kind === kind);
663
- if (option) pending.resolve({ outcome: "selected", optionId: option.optionId });
664
- }
665
- }
1257
+ settle(false);
666
1258
  return { mode };
667
1259
  }
668
1260
 
@@ -677,38 +1269,198 @@ export class SessionHub {
677
1269
  throw new AcpError(-32020, message, { code: response.error?.code ?? "internal" });
678
1270
  }
679
1271
 
680
- async prompt(params: { sessionId: string; prompt: unknown[] }): Promise<{ accepted: true }> {
1272
+ async prompt(params: { sessionId: string; prompt: unknown[] }, interrupting = false): Promise<{ accepted: true; turnId: string }> {
681
1273
  const acp = await this.agent();
682
1274
  const state = this.#sessions.get(params.sessionId);
1275
+ // A released turn ends before its session is loaded again; the phone may already send the next message.
1276
+ await state?.releasing?.catch(() => {});
683
1277
  if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
684
- if (state.running) throw new AcpError(-32003, "A turn is already running in this session");
1278
+ if (state.running || (state.interrupting && !interrupting))
1279
+ throw new AcpError(-32003, "A turn is already running in this session");
685
1280
  if (!Array.isArray(params.prompt) || params.prompt.length === 0) throw new AcpError(-32602, "prompt must be a non-empty block array");
1281
+ const promptBytes = Buffer.byteLength(JSON.stringify(params.prompt));
1282
+ if (promptBytes > PROMPT_BYTES_LIMIT) throw promptTooLarge(params.prompt, promptBytes);
686
1283
  state.running = true;
1284
+ const turnId = crypto.randomUUID();
1285
+ state.turnId = turnId;
1286
+ state.turnBehindHost = state.hostRunning;
1287
+ state.turnAttachmentText = params.prompt.some(block => (block as { type?: unknown } | null)?.type !== "text")
1288
+ ? promptText(params.prompt) || undefined
1289
+ : undefined;
1290
+ const echoed = echoedBlocks(params.prompt);
1291
+ state.echoHold =
1292
+ state.hostRunning && echoed.length > 0
1293
+ ? { blocks: echoed, updates: [], text: queueText(params.prompt), before: new Set(state.queued.map(m => m.id)) }
1294
+ : undefined;
1295
+ state.stuckCheck = { at: Date.now() };
687
1296
  this.#track(state, { sessionUpdate: "x_gjcm_turn_start" });
688
- state.turn = acp.request("session/prompt", { sessionId: params.sessionId, prompt: params.prompt }).then(
1297
+ const turn: Promise<void> = acp.request("session/prompt", { sessionId: params.sessionId, prompt: params.prompt }).then(
689
1298
  result => {
690
- state.running = false;
691
- this.#append(state, { sessionUpdate: TURN_END, stopReason: result?.stopReason ?? "end_turn" });
692
- this.#maybeRecycle();
1299
+ // Already ended by `#releaseTurn`; a late answer must not end the next turn.
1300
+ if (state.turn !== turn) return;
1301
+ // Answered, so gjc took it: a hand-over the queue reads missed still shows the message, before the turn end.
1302
+ this.#releaseEcho(state);
1303
+ this.#endTurn(state, { sessionUpdate: TURN_END, stopReason: result?.stopReason ?? "end_turn" });
693
1304
  },
694
1305
  error => {
695
- state.running = false;
696
- if (String(error?.message ?? error).includes(STALE_ATTACHMENT)) state.loaded = false;
697
- this.#append(state, { sessionUpdate: TURN_END, stopReason: "error", error: String(error?.message ?? error) });
698
- this.#maybeRecycle();
1306
+ if (state.turn !== turn) return;
1307
+ // Still held: it never reached the model (gjc 0.19.3 fails a queued prompt purged from its queue as
1308
+ // "Prompt submission failed."), so it is not shown as said.
1309
+ state.echoHold = undefined;
1310
+ const message = String(error?.message ?? error);
1311
+ if (message.includes(STALE_ATTACHMENT)) state.loaded = false;
1312
+ // A stop, not a failure; `undelivered` tells the phone that sent it to put the message back in its composer.
1313
+ if (message.includes(PREFLIGHT_CANCELLED)) this.#endTurn(state, { sessionUpdate: TURN_END, stopReason: "cancelled", undelivered: true });
1314
+ else this.#endTurn(state, { sessionUpdate: TURN_END, stopReason: "error", error: message });
699
1315
  },
700
1316
  );
701
- return { accepted: true };
1317
+ state.turn = turn;
1318
+ return { accepted: true, turnId };
1319
+ }
1320
+
1321
+ #endTurn(state: SessionState, turnEnd: Record<string, unknown>): void {
1322
+ // Only the phone that sent the prompt knows this id, so only it takes an `undelivered` message back.
1323
+ const turnId = state.turnId;
1324
+ state.turn = undefined;
1325
+ state.turnId = undefined;
1326
+ state.running = false;
1327
+ state.turnBehindHost = false;
1328
+ state.turnAttachmentText = undefined;
1329
+ state.stuckCheck = undefined;
1330
+ this.#append(state, turnId ? { ...turnEnd, turnId } : turnEnd);
1331
+ this.#maybeRecycle();
702
1332
  }
703
1333
 
1334
+ /**
1335
+ * The phone's stop. gjc lets a client stop only a run it owns (see `interrupt`), so a turn typed in the TUI and a
1336
+ * phone prompt that went in behind one are refused at once, pointing at the terminal's Esc. Measured 2026-11-08 on
1337
+ * gjc 0.19.3: `session/cancel` left both running, and while the phone's prompt still waited in gjc's queue it
1338
+ * purged it, photos included ("Prompt submission failed."); a held photo message went back to the composer while
1339
+ * the turn went on. Such a phone turn whose host has nothing left to do is one gjc ACP no longer ends: it is
1340
+ * released (`#releaseTurn`). All this is for a session a terminal hosts (`primaryControlSurface` `cli`); in one gjc
1341
+ * ACP hosts itself (`sdk`, measured: a session the bridge created) the stop is the plain `session/cancel` as before.
1342
+ * When the host cannot say, a phone prompt that went in behind another turn is still refused (`session/cancel`
1343
+ * could purge it), and anything else gets the plain stop.
1344
+ */
704
1345
  async cancel(params: { sessionId: string }): Promise<{ ok: true }> {
1346
+ const state = this.#sessions.get(params.sessionId);
1347
+ if (state?.releasing) {
1348
+ await state.releasing;
1349
+ return { ok: true };
1350
+ }
1351
+ // The bridge's own turn stops as before; its stop also stays when a steer repeats an attachment prompt's text
1352
+ // (the backstop `interrupt` has would make it refuse a turn a phone-only session can stop nowhere else).
1353
+ if (state?.loaded && (state.running ? state.turnBehindHost : state.hostRunning)) {
1354
+ const host = await this.#hostState(state);
1355
+ if (host?.terminal) {
1356
+ if (state.running && host.idle) {
1357
+ await this.#releaseTurn(state);
1358
+ return { ok: true };
1359
+ }
1360
+ if (state.running || !host.idle) throw hostTurnStop(state.running);
1361
+ } else if (!host && state.running) throw hostTurnStop(true);
1362
+ }
1363
+ return this.#cancelTurn(params.sessionId);
1364
+ }
1365
+
1366
+ /** Stops a turn this bridge owns: gjc settles its `session/prompt` as cancelled. */
1367
+ async #cancelTurn(sessionId: string): Promise<{ ok: true }> {
705
1368
  for (const permission of this.#permissions.values()) {
706
- if (permission.sessionId === params.sessionId) permission.resolve({ outcome: "cancelled" });
1369
+ if (permission.sessionId === sessionId) permission.resolve({ outcome: "cancelled" });
707
1370
  }
708
- (await this.agent()).notify("session/cancel", { sessionId: params.sessionId });
1371
+ (await this.agent()).notify("session/cancel", { sessionId });
709
1372
  return { ok: true };
710
1373
  }
711
1374
 
1375
+ /**
1376
+ * What the session host says of itself (gjc 0.19.3), apart from the ACP phase, which a pending prompt keeps at
1377
+ * working: whether a terminal hosts it (`runtime.capabilities` `primaryControlSurface` `cli`), and whether it has
1378
+ * nothing left to do (`context.get` `isStreaming` false with empty queues, and no compaction or retry under way:
1379
+ * `isStreaming` does not cover those). `undefined` when it cannot say.
1380
+ */
1381
+ async #hostState(state: SessionState): Promise<{ terminal: boolean; idle: boolean } | undefined> {
1382
+ try {
1383
+ const acp = await this.agent();
1384
+ const [capabilities, context] = await Promise.all([
1385
+ this.#sdkRequest(acp, state, "query", "runtime.capabilities", {}),
1386
+ this.#sdkRequest(acp, state, "query", "context.get", {}),
1387
+ ]);
1388
+ const surface = capabilities?.page?.items?.[0]?.primaryControlSurface;
1389
+ const item = context?.page?.items?.[0];
1390
+ if ((surface !== "cli" && surface !== "sdk") || typeof item?.isStreaming !== "boolean") return undefined;
1391
+ const idle = !item.isStreaming && !item.steeringQueueDepth && !item.followupQueueDepth && !HOST_BUSY_PHASES.has(state.hostPhase ?? "");
1392
+ return { terminal: surface === "cli", idle };
1393
+ } catch {
1394
+ return undefined;
1395
+ }
1396
+ }
1397
+
1398
+ /**
1399
+ * Ends a phone turn gjc ACP no longer ends. Seen 2026-11-08 on pve3 (gjc 0.19.3): a phone prompt went in behind a
1400
+ * TUI turn and ran on after it until the terminal's Esc; the TUI went idle, but `session/prompt` stayed unanswered
1401
+ * for over an hour, so the phone showed the turn working and refused every new message (-32003). Closing the ACP
1402
+ * attachment settles the waiting prompt (as cancelled) and leaves a TUI host alone; the session is loaded again
1403
+ * at once. Measured on gjc 0.19.3 with a TUI host: settled in 16ms, the host's turn ran on, reattached in 1.2s,
1404
+ * and the next prompt was answered normally. gjc's close settles only the prompt it tracks as active, so a prompt
1405
+ * still unanswered after [RELEASE_SETTLE_TIMEOUT_MS] (or a failed close) is ended here as cancelled.
1406
+ */
1407
+ #releaseTurn(state: SessionState): Promise<void> {
1408
+ state.releasing ??= (async () => {
1409
+ const acp = await this.agent();
1410
+ const turn = state.turn;
1411
+ this.#options.log?.(`releasing a turn of ${state.sessionId}: its host is idle, but gjc ACP never ended it`);
1412
+ // Nothing else goes to the attachment being closed.
1413
+ state.loaded = false;
1414
+ try {
1415
+ await acp.request("session/close", { sessionId: state.sessionId });
1416
+ } catch (error) {
1417
+ this.#options.log?.(`closing ${state.sessionId} to release its turn failed: ${error instanceof Error ? error.message : String(error)}`);
1418
+ }
1419
+ const settled = !turn || (await Promise.race([turn.then(() => true), Bun.sleep(RELEASE_SETTLE_TIMEOUT_MS).then(() => false)]));
1420
+ if (!settled && state.turn === turn) {
1421
+ state.echoHold = undefined;
1422
+ this.#endTurn(state, { sessionUpdate: TURN_END, stopReason: "cancelled" });
1423
+ }
1424
+ // The turn is over either way; a failed load leaves the session closed, and the phone's next call (-32002)
1425
+ // opens it again.
1426
+ await this.#load(state, true).catch(error =>
1427
+ this.#options.log?.(`loading ${state.sessionId} again after releasing its turn failed: ${error instanceof Error ? error.message : String(error)}`),
1428
+ );
1429
+ })().finally(() => {
1430
+ state.releasing = undefined;
1431
+ });
1432
+ return state.releasing;
1433
+ }
1434
+
1435
+ /**
1436
+ * Notices a turn `#releaseTurn` is for without waiting for a stop. While a phone prompt that went in behind a TUI
1437
+ * turn is pending, the host is asked every [HubOptions.stuckTurnCheckMs]; idle twice in a row with no update in
1438
+ * between releases it. A phone turn of its own is left to the stop: it settles with its run (measured).
1439
+ */
1440
+ #watchStuckTurn(state: SessionState): void {
1441
+ const check = state.stuckCheck;
1442
+ if (!check || check.asking || !state.running || !state.turnBehindHost || !state.loaded || state.releasing) return;
1443
+ if (Date.now() - check.at < this.#options.stuckTurnCheckMs) return;
1444
+ const seq = state.seq;
1445
+ check.asking = true;
1446
+ void this.#hostState(state).then(host => {
1447
+ check.asking = false;
1448
+ check.at = Date.now();
1449
+ if (state.stuckCheck !== check) return;
1450
+ if (!host?.terminal || !host.idle || state.seq !== seq) {
1451
+ check.idleSeq = undefined;
1452
+ return;
1453
+ }
1454
+ if (check.idleSeq !== seq) {
1455
+ check.idleSeq = seq;
1456
+ return;
1457
+ }
1458
+ void this.#releaseTurn(state).catch(error =>
1459
+ this.#options.log?.(`releasing a turn of ${state.sessionId} failed: ${error instanceof Error ? error.message : String(error)}`),
1460
+ );
1461
+ });
1462
+ }
1463
+
712
1464
  /**
713
1465
  * The phone's "끼어들기" for steers still waiting on a busy turn (the TUI's Esc with a queued steer): stop
714
1466
  * the turn now and start a new one with the waiting steers. gjc's own queue (`queue.messages.list`) is the
@@ -729,19 +1481,51 @@ export class SessionHub {
729
1481
  * the run it owns. Measured 2026-10-26 on a TUI turn: `session/cancel` had no effect (10s, then -32004),
730
1482
  * `turn.abort` answered `no_active_turn`, `turn.abort{mode:"terminal"}` `terminal_no_effect`, and the operator
731
1483
  * variant is reserved to gjc's Broker route. Such a turn is refused at once instead.
1484
+ *
1485
+ * The same holds when the bridge's own prompt went in during such a turn: gjc queues it as a steer of that turn
1486
+ * (it is listed by `queue.messages.list`), and `session/cancel` leaves the TUI turn running but purges the queued
1487
+ * prompt, failing it as "Prompt submission failed.". Measured 2026-11-06 on pve3 with gjc 0.19.3: a phone's
1488
+ * photo+text was lost that way and only its text came back from the queue. It is refused too; gjc delivers it,
1489
+ * attachments included, at the turn's next step, or runs it as a turn of its own once the TUI turn ends without
1490
+ * taking it. In that last case 끼어들기 stays refused for the rest of that turn (see [SessionState.turnBehindHost]).
732
1491
  */
733
1492
  async interrupt(params: { sessionId: string }): Promise<{ accepted: true; text: string }> {
734
1493
  const state = this.#sessions.get(params.sessionId);
735
1494
  if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
736
1495
  const steers = await this.#queuedSteers(params.sessionId);
737
1496
  if (steers.length === 0) throw noPendingSteer();
1497
+ const ownPromptQueued =
1498
+ state.running &&
1499
+ (state.turnBehindHost === true ||
1500
+ (state.turnAttachmentText !== undefined && steers.some(s => s.text.trim() === state.turnAttachmentText)));
738
1501
  if (!state.running && state.hostRunning)
739
1502
  throw new AcpError(-32004, "터미널에서 시작한 턴은 앱에서 멈출 수 없습니다. 지시는 대기열에 있고 턴의 다음 단계에서 전달됩니다.", {
740
1503
  code: "host_turn",
741
1504
  });
1505
+ if (ownPromptQueued)
1506
+ throw new AcpError(
1507
+ -32004,
1508
+ "보낸 메시지가 터미널에서 시작한 턴 뒤에서 기다리고 있어 끼어들 수 없습니다. 메시지는 첨부와 함께 그 턴에 전달됩니다.",
1509
+ { code: "host_turn" },
1510
+ );
1511
+ if (state.interrupting) throw new AcpError(-32003, "끼어들기가 이미 진행 중입니다.");
742
1512
  const mark = state.seq;
1513
+ state.interrupting = true;
1514
+ try {
1515
+ return await this.#interruptAndResend(state, steers, mark);
1516
+ } finally {
1517
+ state.interrupting = false;
1518
+ }
1519
+ }
1520
+
1521
+ async #interruptAndResend(
1522
+ state: SessionState,
1523
+ steers: { id: string; text: string }[],
1524
+ mark: number,
1525
+ ): Promise<{ accepted: true; text: string }> {
1526
+ const params = { sessionId: state.sessionId };
743
1527
  if (isActive(state)) {
744
- await this.cancel({ sessionId: params.sessionId });
1528
+ await this.#cancelTurn(params.sessionId);
745
1529
  if (!(await this.#settled(state, INTERRUPT_SETTLE_TIMEOUT_MS)))
746
1530
  throw new AcpError(-32004, "진행 중인 턴이 중단되지 않았습니다. 잠시 후 다시 시도하세요.");
747
1531
  }
@@ -758,7 +1542,7 @@ export class SessionHub {
758
1542
  const waiting = steers.filter(s => !delivered.includes(s.text));
759
1543
  if (waiting.length === 0) throw noPendingSteer();
760
1544
  const text = waiting.map(s => s.text).join("\n\n");
761
- await this.prompt({ sessionId: params.sessionId, prompt: [{ type: "text", text }] });
1545
+ await this.prompt({ sessionId: params.sessionId, prompt: [{ type: "text", text }] }, true);
762
1546
  return { accepted: true, text };
763
1547
  }
764
1548
 
@@ -908,15 +1692,70 @@ export class SessionHub {
908
1692
  const state = this.#sessions.get(params.sessionId);
909
1693
  if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
910
1694
  const acp = await this.agent();
911
- const input = params.input ?? {};
1695
+ if (params.kind === "control" && params.op === "turn.btw") return { result: await this.#sideQuestion(acp, state, params.input ?? {}) };
1696
+ const response = await this.#sdkRequest(acp, state, params.kind, params.op, params.input ?? {}, params.confirm);
1697
+ if (params.kind === "query") {
1698
+ const items: unknown[] = response?.page?.items ?? [];
1699
+ return { items: params.op === "context.get" ? items.map(withoutSystemPrompt) : items, complete: response?.page?.complete !== false };
1700
+ }
1701
+ // Measured shapes: most operations answer with the bare result ({renamed:true}, {path}, …);
1702
+ // some (mode.goal.operate) answer with the control envelope instead.
1703
+ if (response?.type === "control_response") return { result: response.result ?? null };
1704
+ return { result: response ?? null };
1705
+ }
1706
+
1707
+ /**
1708
+ * The phone's `/btw` (`turn.btw` {question, exchanges?: [{question, answer}]} -> {replyText}) on whichever side-question
1709
+ * operation the gjc hosting this session has, read from its `runtime.capabilities` on every call (a session host can
1710
+ * restart on another build):
1711
+ * - `turn.btw` (local patch 0004): unchanged. First, because only it answers mid-turn with the main turn's pending
1712
+ * request kept out of the side conversation; a patched build rebased past gajae-code#7583 advertises both;
1713
+ * - official `btw.ask` that takes `exchanges` (`btwAskExchangesVersion` 1, gajae-code#7583): history passed as is;
1714
+ * - official `btw.ask` without it (0.19.3 accepts and silently drops `exchanges`, measured): the answered history is
1715
+ * folded into the question, oldest exchanges dropped first to stay within gjc's 16 KiB question limit.
1716
+ */
1717
+ async #sideQuestion(acp: AcpProcess, state: SessionState, input: Record<string, unknown>): Promise<{ replyText: string }> {
1718
+ const response = await this.#sdkRequest(acp, state, "query", "runtime.capabilities", {});
1719
+ const capabilities = response?.page?.items?.[0];
1720
+ if (!Array.isArray(capabilities?.operations)) {
1721
+ throw new AcpError(-32020, "gjc의 runtime.capabilities 응답에 연산 목록(page.items[0].operations)이 없습니다.", { code: "internal" });
1722
+ }
1723
+ const operations: unknown[] = capabilities.operations;
1724
+ const question = typeof input.question === "string" ? input.question : "";
1725
+ const exchanges = btwExchanges(input.exchanges);
1726
+ if (operations.includes("turn.btw")) {
1727
+ return { replyText: String((await this.#sdkRequest(acp, state, "control", "turn.btw", input))?.replyText ?? "") };
1728
+ }
1729
+ if (operations.includes("btw.ask") && capabilities.btwAskExchangesVersion >= 1) {
1730
+ const asked = { question, ...(exchanges.length ? { exchanges: exchanges.map(e => ({ question: e.question, reply: e.answer })) } : {}) };
1731
+ return { replyText: String((await this.#sdkRequest(acp, state, "control", "btw.ask", asked))?.reply ?? "") };
1732
+ }
1733
+ if (operations.includes("btw.ask")) {
1734
+ const asked = { question: foldBtwExchanges(question, exchanges) };
1735
+ return { replyText: String((await this.#sdkRequest(acp, state, "control", "btw.ask", asked))?.reply ?? "") };
1736
+ }
1737
+ throw new AcpError(-32020, "이 세션의 gjc에는 BTW 기능(btw.ask)이 없습니다. gjc 0.19.3 이상이 필요하고, 업데이트 전에 시작된 세션이면 gjc를 다시 시작해야 합니다.", {
1738
+ code: "host_outdated",
1739
+ });
1740
+ }
1741
+
1742
+ /** One `_gjc/sdk/query|control` round trip; gjc's `{ok:false}` answers become typed AcpErrors. */
1743
+ async #sdkRequest(
1744
+ acp: AcpProcess,
1745
+ state: SessionState,
1746
+ kind: "query" | "control",
1747
+ op: string,
1748
+ input: Record<string, unknown>,
1749
+ confirm?: boolean,
1750
+ ): Promise<any> {
912
1751
  const response =
913
- params.kind === "query"
914
- ? await acp.request("_gjc/sdk/query", { sessionId: params.sessionId, query: params.op, input })
1752
+ kind === "query"
1753
+ ? await acp.request("_gjc/sdk/query", { sessionId: state.sessionId, query: op, input })
915
1754
  : await acp.request("_gjc/sdk/control", {
916
- sessionId: params.sessionId,
917
- operation: params.op,
1755
+ sessionId: state.sessionId,
1756
+ operation: op,
918
1757
  input,
919
- ...(params.confirm ? { confirm: true } : {}),
1758
+ ...(confirm ? { confirm: true } : {}),
920
1759
  });
921
1760
  if (response?.ok === false) {
922
1761
  const error = response.error ?? {};
@@ -929,24 +1768,17 @@ export class SessionHub {
929
1768
  }
930
1769
  if (error.code === "unknown_operation") {
931
1770
  // The operation is in the bridge allowlist but the gjc hosting this session lacks it: either the gjc build
932
- // never had it (turn.btw is not in any official gjc release) or the session host started before it was added.
1771
+ // never had it or the session host started before it was added.
933
1772
  // A restart only helps in the second case, so the message does not promise it.
934
1773
  throw new AcpError(
935
1774
  -32020,
936
- `이 세션의 gjc가 ${params.op}을(를) 지원하지 않습니다. 공식 gjc 릴리스에 없는 기능이거나, 그 기능이 들어가기 전에 시작된 세션입니다.`,
1775
+ `이 세션의 gjc가 ${op}을(를) 지원하지 않습니다. 공식 gjc 릴리스에 없는 기능이거나, 그 기능이 들어가기 전에 시작된 세션입니다.`,
937
1776
  { code: "host_outdated" },
938
1777
  );
939
1778
  }
940
1779
  throw new AcpError(-32020, message, { code: error.code ?? "internal" });
941
1780
  }
942
- if (params.kind === "query") {
943
- const items: unknown[] = response?.page?.items ?? [];
944
- return { items: params.op === "context.get" ? items.map(withoutSystemPrompt) : items, complete: response?.page?.complete !== false };
945
- }
946
- // Measured shapes: most operations answer with the bare result ({renamed:true}, {path}, …);
947
- // some (mode.goal.operate) answer with the control envelope instead.
948
- if (response?.type === "control_response") return { result: response.result ?? null };
949
- return { result: response ?? null };
1781
+ return response;
950
1782
  }
951
1783
 
952
1784
  respondPermission(params: { requestId: string; optionId?: string | null }): { ok: boolean } {
@@ -980,6 +1812,39 @@ export const MODEL_ROLE_TARGETS = [
980
1812
  ] as const;
981
1813
  const CONFIG_FLUSH_TIMEOUT_MS = 5000;
982
1814
  const INTERRUPT_SETTLE_TIMEOUT_MS = 10_000;
1815
+ /** `session/close` settled the waiting prompt in 16ms (gjc 0.19.3, TUI host). */
1816
+ const RELEASE_SETTLE_TIMEOUT_MS = 5000;
1817
+ /** Spacing of the host checks `#watchStuckTurn` needs twice in a row (a host step rarely goes 15s without an update). */
1818
+ const STUCK_TURN_CHECK_MS = 15_000;
1819
+ /**
1820
+ * A session.open from scratch sends the whole buffer as one frame, and a phone drops the connection on a frame over
1821
+ * 32 MiB (server MAX_FRAME_BYTES, iOS maximumMessageSize). The buffer stays well under it, room left for the rest of
1822
+ * the snapshot (2026-11-08, pve1: a buffer then counted in UTF-16 units under a 48MB cap answered 28.2MB of UTF-8).
1823
+ */
1824
+ const MAX_BUFFERED_BYTES = 24 * 1024 * 1024;
1825
+ /** `gjcPhase` values gjc 0.19.3 reports while the host works with `isStreaming` false (acp-event-mapper). */
1826
+ const HOST_BUSY_PHASES = new Set(["compacting", "retrying"]);
1827
+ /**
1828
+ * gjc's ACP refuses a prompt whose SDK frame passes 256 KiB (`MAX_PROMPT_FRAME_BYTES`, gjc 0.19.3) with an English
1829
+ * message the phone shows as is ("ACP prompt is 326 KiB, over the 256 KiB transport limit..."). The frame carries the
1830
+ * same text and base64 images as the prompt blocks plus a ~200-byte envelope, so the blocks are held to that limit
1831
+ * minus a margin and refused here, before a turn is started, in Korean.
1832
+ */
1833
+ const PROMPT_BYTES_LIMIT = 256 * 1024 - 1024;
1834
+
1835
+ /** Says which part to cut: since app 1.0.3 photos are re-encoded to fit, so what is left over is mostly text. */
1836
+ function promptTooLarge(prompt: unknown[], bytes: number): AcpError {
1837
+ const textBytes = prompt.reduce<number>((sum, block) => {
1838
+ const text = (block as { type?: unknown; text?: unknown } | null)?.text;
1839
+ return typeof text === "string" ? sum + Buffer.byteLength(text) : sum;
1840
+ }, 0);
1841
+ const kib = (n: number) => Math.ceil(n / 1024);
1842
+ return new AcpError(
1843
+ -32602,
1844
+ `메시지가 ${kib(bytes)}KiB(글 ${kib(textBytes)}KiB, 사진 등 ${kib(Math.max(0, bytes - textBytes))}KiB)라 gjc가 한 번에 받는 256KiB를 넘습니다. 글이나 사진을 줄이세요.`,
1845
+ { code: "prompt_too_large", bytes, limit: PROMPT_BYTES_LIMIT },
1846
+ );
1847
+ }
983
1848
  const MODEL_SELECTOR = /^[\w.@-]+(\/[\w.@:+-]+)+$/;
984
1849
 
985
1850
  interface AgentConfig {
@@ -1008,6 +1873,44 @@ function publicPermission(p: PendingPermission): Omit<PendingPermission, "resolv
1008
1873
  return { requestId: p.requestId, sessionId: p.sessionId, toolCall: p.toolCall, options: p.options };
1009
1874
  }
1010
1875
 
1876
+ /** gjc's `btw.ask` question limit (BTW_MAX_QUESTION_UTF8_BYTES). */
1877
+ const BTW_ASK_QUESTION_BYTES = 16 * 1024;
1878
+
1879
+ interface BtwExchange {
1880
+ question: string;
1881
+ answer: string;
1882
+ }
1883
+
1884
+ /**
1885
+ * The phone's answered `/btw` history (`[{question, answer}]`) for the `btw.ask` paths. The apps only send answered
1886
+ * exchanges; a malformed entry is left out rather than failing the whole side question.
1887
+ */
1888
+ function btwExchanges(value: unknown): BtwExchange[] {
1889
+ if (!Array.isArray(value)) return [];
1890
+ return value.flatMap(entry =>
1891
+ typeof entry?.question === "string" && typeof entry?.answer === "string" ? [{ question: entry.question, answer: entry.answer }] : [],
1892
+ );
1893
+ }
1894
+
1895
+ /**
1896
+ * The question for a `btw.ask` that drops `exchanges`: the answered history quoted ahead of it, oldest exchanges left
1897
+ * out first so the whole stays within gjc's question limit. A question that alone exceeds it goes out unchanged and
1898
+ * gjc refuses it as `invalid_input`; so does an empty question, which is not dressed up with history.
1899
+ */
1900
+ export function foldBtwExchanges(question: string, exchanges: BtwExchange[]): string {
1901
+ if (!question.trim()) return question;
1902
+ const bytes = (text: string) => Buffer.byteLength(text, "utf8");
1903
+ for (let start = 0; start < exchanges.length; start++) {
1904
+ const history = exchanges
1905
+ .slice(start)
1906
+ .map(e => `Q: ${e.question}\nA: ${e.answer}`)
1907
+ .join("\n\n");
1908
+ const folded = `Earlier questions and answers in this side chat, oldest first:\n\n${history}\n\nCurrent question: ${question}`;
1909
+ if (bytes(folded) <= BTW_ASK_QUESTION_BYTES) return folded;
1910
+ }
1911
+ return question;
1912
+ }
1913
+
1011
1914
  /** context.get carries the whole system prompt (~40KB measured); the phone only needs its size. */
1012
1915
  function withoutSystemPrompt(item: unknown): unknown {
1013
1916
  if (!item || typeof item !== "object" || !("systemPrompt" in item)) return item;
@@ -1030,6 +1933,76 @@ export function supportedConfigOptions(options: unknown[]): unknown[] {
1030
1933
  });
1031
1934
  }
1032
1935
 
1936
+ /** The prompt blocks gjc echoes back as `user_message_chunk`, in order (acp-agent: text with content and images). */
1937
+ function echoedBlocks(prompt: unknown[]): EchoBlock[] {
1938
+ return prompt.flatMap((block): EchoBlock[] => {
1939
+ const b = block as { type?: unknown; text?: unknown; data?: unknown } | null;
1940
+ if (b?.type === "image" && typeof b.data === "string") return [{ type: "image", data: b.data }];
1941
+ if (b?.type === "text" && typeof b.text === "string" && b.text.length > 0) return [{ type: "text", text: b.text }];
1942
+ return [];
1943
+ });
1944
+ }
1945
+
1946
+ function sameBlock(expected: EchoBlock | undefined, content: unknown): boolean {
1947
+ const c = content as { type?: unknown; text?: unknown; data?: unknown } | null | undefined;
1948
+ if (!expected || c?.type !== expected.type) return false;
1949
+ return expected.type === "text" ? c.text === expected.text : c.data === expected.data;
1950
+ }
1951
+
1952
+ /**
1953
+ * The text gjc 0.19.3 lists a prompt under in its queue: `acpPromptPayload` joins its text blocks and renders file
1954
+ * links and text resources into the text, and an empty text with images is shown as "[Image]" (agent-session).
1955
+ */
1956
+ function queueText(prompt: unknown[]): string {
1957
+ const text: string[] = [];
1958
+ let images = 0;
1959
+ for (const block of prompt) {
1960
+ const b = block as Record<string, any> | null;
1961
+ switch (b?.type) {
1962
+ case "text":
1963
+ if (typeof b.text === "string") text.push(b.text);
1964
+ break;
1965
+ case "image":
1966
+ images++;
1967
+ break;
1968
+ case "resource_link":
1969
+ text.push(
1970
+ [
1971
+ `[Resource: ${b.name}]`,
1972
+ `URI: ${b.uri}`,
1973
+ ...(b.title ? [`Title: ${b.title}`] : []),
1974
+ ...(b.description ? [b.description] : []),
1975
+ ...(b.mimeType ? [`MIME: ${b.mimeType}`] : []),
1976
+ ...(typeof b.size === "number" ? [`Size: ${b.size}`] : []),
1977
+ ].join("\n"),
1978
+ );
1979
+ break;
1980
+ case "resource":
1981
+ if (typeof b.resource?.text === "string")
1982
+ text.push([`[Resource: ${b.resource.uri}]`, ...(b.resource.mimeType ? [`MIME: ${b.resource.mimeType}`] : []), b.resource.text].join("\n"));
1983
+ else images++;
1984
+ break;
1985
+ }
1986
+ }
1987
+ const joined = text.join("\n");
1988
+ return (joined || (images > 0 ? "[Image]" : "")).trim();
1989
+ }
1990
+
1991
+ /** The text blocks of a prompt as gjc's queue lists it (attachments carry no text). */
1992
+ function promptText(prompt: unknown[]): string {
1993
+ return prompt
1994
+ .map(block => (block as { type?: unknown; text?: unknown } | null))
1995
+ .filter(block => block?.type === "text" && typeof block.text === "string")
1996
+ .map(block => block!.text as string)
1997
+ .join("\n")
1998
+ .trim();
1999
+ }
2000
+
2001
+ function hostTurnStop(phoneTurn: boolean): AcpError {
2002
+ const what = phoneTurn ? "보낸 메시지는 터미널에서 시작한 턴에 이어져 있어" : "터미널에서 시작한 턴은";
2003
+ return new AcpError(-32004, `${what} 앱에서 멈출 수 없습니다. 터미널에서 Esc로 멈추세요.`, { code: "host_turn" });
2004
+ }
2005
+
1033
2006
  function noPendingSteer(): AcpError {
1034
2007
  return new AcpError(-32005, "대기 중인 끼어들기 메시지가 없습니다. 이미 전달됐습니다.", { code: "no_pending_steer" });
1035
2008
  }
@@ -1080,8 +2053,9 @@ function isDirectory(dir: string): boolean {
1080
2053
  }
1081
2054
  }
1082
2055
 
1083
- function approxBytes(value: unknown): number {
1084
- return JSON.stringify(value).length;
2056
+ /** UTF-8 bytes of `value` as JSON, as it goes out: `length` counts UTF-16 units, a third of that for Korean text. */
2057
+ function jsonBytes(value: unknown): number {
2058
+ return Buffer.byteLength(JSON.stringify(value));
1085
2059
  }
1086
2060
 
1087
2061
  function stripUndefined<T extends object>(value: T): T {