gjcm-bridge 0.1.1 → 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/README.md +26 -2
- package/package.json +1 -1
- package/src/cli.ts +7 -2
- package/src/client.ts +3 -1
- package/src/host-asks.ts +107 -3
- package/src/hub.ts +954 -67
- package/src/sdk-cli.ts +72 -0
- package/src/server.ts +34 -6
- package/src/tmux.ts +229 -0
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 {
|
|
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
|
|
|
@@ -76,6 +86,12 @@ export const PERMISSION_MODE_UPDATE = "x_gjcm_permission_mode";
|
|
|
76
86
|
export const PERMISSION_MODES = ["prompt", "allow", "deny"] as const;
|
|
77
87
|
export type PermissionMode = (typeof PERMISSION_MODES)[number];
|
|
78
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";
|
|
79
95
|
|
|
80
96
|
export interface BufferedUpdate {
|
|
81
97
|
seq: number;
|
|
@@ -89,7 +105,11 @@ export interface PendingPermission {
|
|
|
89
105
|
sessionId: string;
|
|
90
106
|
toolCall: unknown;
|
|
91
107
|
options: Array<{ optionId: string; name: string; kind: string }>;
|
|
92
|
-
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;
|
|
93
113
|
}
|
|
94
114
|
|
|
95
115
|
interface SessionState {
|
|
@@ -103,6 +123,31 @@ interface SessionState {
|
|
|
103
123
|
running: boolean;
|
|
104
124
|
/** Settles when the bridge-started `session/prompt` in flight resolves or rejects. */
|
|
105
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;
|
|
106
151
|
/** gjc's own phase flag (session_info_update _meta.running): also true for turns started elsewhere. */
|
|
107
152
|
hostRunning: boolean;
|
|
108
153
|
throughput: Throughput;
|
|
@@ -122,6 +167,37 @@ interface SessionState {
|
|
|
122
167
|
hostAsks: Set<string>;
|
|
123
168
|
/** Transcript path and the size/mtime last scanned for [hostAsks]. */
|
|
124
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>;
|
|
125
201
|
}
|
|
126
202
|
|
|
127
203
|
export interface SessionStatus {
|
|
@@ -133,6 +209,81 @@ export interface SessionStatus {
|
|
|
133
209
|
queued: QueuedMessage[];
|
|
134
210
|
}
|
|
135
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
|
+
|
|
136
287
|
export interface QueuedMessage {
|
|
137
288
|
id: string;
|
|
138
289
|
text: string;
|
|
@@ -143,6 +294,8 @@ const STREAMED_TEXT_UPDATES = new Set(["agent_message_chunk", "agent_thought_chu
|
|
|
143
294
|
|
|
144
295
|
export interface HubClient {
|
|
145
296
|
readonly id: string;
|
|
297
|
+
/** The paired device behind this connection, which a reconnecting phone keeps (`id` is per connection). */
|
|
298
|
+
readonly device?: string;
|
|
146
299
|
deliver(event: string, payload: unknown): void;
|
|
147
300
|
}
|
|
148
301
|
|
|
@@ -154,6 +307,11 @@ export interface HubOptions {
|
|
|
154
307
|
maxBufferedUpdates?: number;
|
|
155
308
|
maxBufferedBytes?: number;
|
|
156
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;
|
|
157
315
|
}
|
|
158
316
|
|
|
159
317
|
export interface OpenSnapshot {
|
|
@@ -170,8 +328,10 @@ export interface OpenSnapshot {
|
|
|
170
328
|
}
|
|
171
329
|
|
|
172
330
|
export class SessionHub {
|
|
173
|
-
#options: Required<Omit<HubOptions, "acp">> &
|
|
331
|
+
#options: Required<Omit<HubOptions, "acp" | "tmux" | "log">> & Pick<HubOptions, "acp" | "log">;
|
|
174
332
|
readonly #saved: SavedSessionIndex;
|
|
333
|
+
readonly #tmux?: TmuxLauncher;
|
|
334
|
+
readonly #sdkCli?: SdkCli;
|
|
175
335
|
#acp?: AcpProcess;
|
|
176
336
|
#starting?: Promise<AcpProcess>;
|
|
177
337
|
#agentInfo: unknown;
|
|
@@ -182,10 +342,16 @@ export class SessionHub {
|
|
|
182
342
|
#restartDelayMs = 0;
|
|
183
343
|
#recyclePending = false;
|
|
184
344
|
#statusTimer?: ReturnType<typeof setInterval>;
|
|
345
|
+
#stopped = false;
|
|
185
346
|
|
|
186
347
|
constructor(options: HubOptions) {
|
|
187
|
-
this.#options = { maxBufferedUpdates: 5000, maxBufferedBytes:
|
|
348
|
+
this.#options = { maxBufferedUpdates: 5000, maxBufferedBytes: MAX_BUFFERED_BYTES, stuckTurnCheckMs: STUCK_TURN_CHECK_MS, ...options };
|
|
188
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
|
+
}
|
|
189
355
|
}
|
|
190
356
|
|
|
191
357
|
// ── clients ──────────────────────────────────────────────────────────────
|
|
@@ -229,6 +395,7 @@ export class SessionHub {
|
|
|
229
395
|
this.#acp = acp;
|
|
230
396
|
this.#restartDelayMs = 0;
|
|
231
397
|
queueMicrotask(() => this.#maybeRecycle());
|
|
398
|
+
queueMicrotask(() => void this.#reattach());
|
|
232
399
|
return acp;
|
|
233
400
|
} catch (error) {
|
|
234
401
|
acp.kill();
|
|
@@ -243,22 +410,53 @@ export class SessionHub {
|
|
|
243
410
|
// Whatever spawns next resolves the launcher again, so a pending recycle is satisfied.
|
|
244
411
|
this.#recyclePending = false;
|
|
245
412
|
this.#restartDelayMs = Math.min(Math.max(this.#restartDelayMs * 2, 1000), 30_000);
|
|
246
|
-
|
|
247
|
-
|
|
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
|
+
}
|
|
248
420
|
for (const state of this.#sessions.values()) {
|
|
249
421
|
state.loaded = false;
|
|
422
|
+
state.channel = undefined;
|
|
250
423
|
if (state.running) {
|
|
251
424
|
state.running = false;
|
|
252
425
|
this.#append(state, { sessionUpdate: AGENT_EXIT, code, stderrTail: acp.stderrTail.slice(-2000) });
|
|
253
426
|
}
|
|
254
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
|
+
}
|
|
255
432
|
}
|
|
256
433
|
|
|
257
434
|
stop(): void {
|
|
435
|
+
this.#stopped = true;
|
|
258
436
|
if (this.#statusTimer) clearInterval(this.#statusTimer);
|
|
259
437
|
this.#acp?.kill();
|
|
260
438
|
}
|
|
261
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
|
+
|
|
262
460
|
/**
|
|
263
461
|
* Observed on gjc 0.18.7: after hours of uptime the ACP process's broker socket can go bad, and
|
|
264
462
|
* every resume then fails ~10s in with "SDK request outcome is uncertain after the frame was sent"
|
|
@@ -297,7 +495,7 @@ export class SessionHub {
|
|
|
297
495
|
if (!this.#starting) this.#recyclePending = false;
|
|
298
496
|
return;
|
|
299
497
|
}
|
|
300
|
-
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;
|
|
301
499
|
this.#onExit(acp, null);
|
|
302
500
|
this.#restartDelayMs = 0;
|
|
303
501
|
acp.kill();
|
|
@@ -308,7 +506,215 @@ export class SessionHub {
|
|
|
308
506
|
#onNotification(method: string, params: any): void {
|
|
309
507
|
if (method !== "session/update" || typeof params?.sessionId !== "string") return;
|
|
310
508
|
const state = this.#stateFor(params.sessionId);
|
|
311
|
-
this.#
|
|
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
|
+
}
|
|
312
718
|
}
|
|
313
719
|
|
|
314
720
|
async #onRequest(method: string, params: any): Promise<unknown> {
|
|
@@ -338,6 +744,8 @@ export class SessionHub {
|
|
|
338
744
|
sessionId,
|
|
339
745
|
cwd: cwd ?? this.#options.defaultCwd,
|
|
340
746
|
seq: 0,
|
|
747
|
+
historySeq: 0,
|
|
748
|
+
resync: new Set(),
|
|
341
749
|
buffer: [],
|
|
342
750
|
bufferBytes: 0,
|
|
343
751
|
loaded: false,
|
|
@@ -345,6 +753,10 @@ export class SessionHub {
|
|
|
345
753
|
hostRunning: false,
|
|
346
754
|
throughput: new Throughput(),
|
|
347
755
|
queued: [],
|
|
756
|
+
remoteAsks: new Map(),
|
|
757
|
+
remoteAsksDone: new Set(),
|
|
758
|
+
remoteAsksDismissed: new Set(),
|
|
759
|
+
remoteAskAnswers: 0,
|
|
348
760
|
configOptions: [],
|
|
349
761
|
permissionMode: "prompt",
|
|
350
762
|
hostAsks: new Set(),
|
|
@@ -364,14 +776,16 @@ export class SessionHub {
|
|
|
364
776
|
this.#track(state, update);
|
|
365
777
|
const entry = { seq: ++state.seq, update };
|
|
366
778
|
state.buffer.push(entry);
|
|
367
|
-
state.bufferBytes +=
|
|
779
|
+
state.bufferBytes += jsonBytes(update);
|
|
368
780
|
while (
|
|
369
781
|
state.buffer.length > this.#options.maxBufferedUpdates ||
|
|
370
782
|
(state.bufferBytes > this.#options.maxBufferedBytes && state.buffer.length > 1)
|
|
371
783
|
) {
|
|
372
784
|
const dropped = state.buffer.shift()!;
|
|
373
|
-
state.bufferBytes -=
|
|
785
|
+
state.bufferBytes -= jsonBytes(dropped.update);
|
|
374
786
|
}
|
|
787
|
+
// A phone showing the chat already has the history a reload of the bridge's own replays.
|
|
788
|
+
if (state.quietReplay) return;
|
|
375
789
|
for (const { client, sessions } of this.#clients.values()) {
|
|
376
790
|
if (sessions.has(state.sessionId)) client.deliver("session.update", { sessionId: state.sessionId, ...entry });
|
|
377
791
|
}
|
|
@@ -394,8 +808,9 @@ export class SessionHub {
|
|
|
394
808
|
return;
|
|
395
809
|
}
|
|
396
810
|
if (kind === "session_info_update") {
|
|
397
|
-
const
|
|
398
|
-
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;
|
|
399
814
|
}
|
|
400
815
|
if (kind === TURN_END || kind === AGENT_EXIT) state.hostRunning = false;
|
|
401
816
|
const active = isActive(state);
|
|
@@ -444,9 +859,12 @@ export class SessionHub {
|
|
|
444
859
|
*/
|
|
445
860
|
#sampleQueue(state: SessionState): Promise<void> {
|
|
446
861
|
if (!state.loaded) return Promise.resolve();
|
|
862
|
+
const sampledAt = Date.now();
|
|
447
863
|
state.queueSample ??= this.sdk({ sessionId: state.sessionId, kind: "query", op: "queue.messages.list", internal: true })
|
|
448
864
|
.then(result => {
|
|
449
|
-
|
|
865
|
+
const queue = queuedMessages(result);
|
|
866
|
+
if (isActive(state)) state.queued = queue;
|
|
867
|
+
this.#settleEchoHold(state, queue, sampledAt);
|
|
450
868
|
})
|
|
451
869
|
.catch(() => {})
|
|
452
870
|
.finally(() => {
|
|
@@ -492,6 +910,116 @@ export class SessionHub {
|
|
|
492
910
|
state.hostAsks.delete(id);
|
|
493
911
|
this.#append(state, hostAskSettled(id, result));
|
|
494
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);
|
|
495
1023
|
}
|
|
496
1024
|
|
|
497
1025
|
/** One tick per second while any session is working, so list rows show a live rate and chats gjc's queue. */
|
|
@@ -501,6 +1029,8 @@ export class SessionHub {
|
|
|
501
1029
|
const active = [...this.#sessions.values()].filter(isActive);
|
|
502
1030
|
for (const state of active) {
|
|
503
1031
|
this.#sampleHostAsks(state);
|
|
1032
|
+
this.#syncRemoteAsks(state);
|
|
1033
|
+
this.#watchStuckTurn(state);
|
|
504
1034
|
void Promise.all([this.#sampleUsage(state), this.#sampleQueue(state)]).finally(() => this.#publishStatus(state));
|
|
505
1035
|
}
|
|
506
1036
|
if (active.length === 0) {
|
|
@@ -556,7 +1086,24 @@ export class SessionHub {
|
|
|
556
1086
|
const cwd = params.cwd || this.#options.defaultCwd;
|
|
557
1087
|
// gjc answers a missing cwd with "Lifecycle worktree does not exist" after spawning a session host.
|
|
558
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)}`);
|
|
559
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
|
+
}
|
|
560
1107
|
const state = this.#stateFor(result.sessionId, cwd);
|
|
561
1108
|
state.loaded = true;
|
|
562
1109
|
state.configOptions = supportedConfigOptions(result.configOptions ?? state.configOptions);
|
|
@@ -564,38 +1111,66 @@ export class SessionHub {
|
|
|
564
1111
|
}
|
|
565
1112
|
|
|
566
1113
|
async openSession(clientId: string, params: { sessionId: string; cwd?: string; afterSeq?: number }): Promise<OpenSnapshot> {
|
|
567
|
-
const acp = await this.agent();
|
|
568
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(() => {});
|
|
569
1117
|
if (!state.loaded) {
|
|
570
|
-
|
|
571
|
-
// A reload replays the full history again; start the replay buffer from scratch.
|
|
572
|
-
state.buffer = [];
|
|
573
|
-
state.bufferBytes = 0;
|
|
574
|
-
// The replay carries a waiting ask as failed ("ends without a result"); show it again as pending.
|
|
575
|
-
state.hostAsks.clear();
|
|
576
|
-
state.hostAskScan = undefined;
|
|
577
|
-
const result = await acp.request("session/load", {
|
|
578
|
-
sessionId: state.sessionId,
|
|
579
|
-
cwd: state.cwd,
|
|
580
|
-
mcpServers: [],
|
|
581
|
-
});
|
|
582
|
-
state.configOptions = supportedConfigOptions(result?.configOptions ?? state.configOptions);
|
|
583
|
-
if (state.permissionMode !== "prompt") await this.#applyPermissionMode(acp, state.sessionId, state.permissionMode);
|
|
584
|
-
state.loaded = true;
|
|
585
|
-
})()
|
|
586
|
-
.catch(error => {
|
|
587
|
-
this.#recycleOnBrokerLoss(acp, error);
|
|
588
|
-
throw error;
|
|
589
|
-
})
|
|
590
|
-
.finally(() => {
|
|
591
|
-
state.loading = undefined;
|
|
592
|
-
});
|
|
593
|
-
await state.loading;
|
|
1118
|
+
await this.#load(state);
|
|
594
1119
|
return this.#subscribe(clientId, state, 0, true);
|
|
595
1120
|
}
|
|
596
1121
|
return this.#subscribe(clientId, state, params.afterSeq ?? 0);
|
|
597
1122
|
}
|
|
598
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
|
+
|
|
599
1174
|
/** Copies a saved session into a new one and opens it (gjc replays the copied history on load). */
|
|
600
1175
|
async forkSession(clientId: string, params: { sessionId: string; cwd?: string }): Promise<OpenSnapshot> {
|
|
601
1176
|
const acp = await this.agent();
|
|
@@ -627,19 +1202,23 @@ export class SessionHub {
|
|
|
627
1202
|
}
|
|
628
1203
|
|
|
629
1204
|
#subscribe(clientId: string, state: SessionState, afterSeq: number, forceReset = false): OpenSnapshot {
|
|
630
|
-
this.#clients.get(clientId)
|
|
1205
|
+
const entry = this.#clients.get(clientId);
|
|
1206
|
+
entry?.sessions.add(state.sessionId);
|
|
1207
|
+
const resync = state.resync.delete(entry?.client.device ?? clientId);
|
|
631
1208
|
const firstSeq = state.buffer[0]?.seq ?? state.seq + 1;
|
|
632
|
-
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;
|
|
633
1210
|
return {
|
|
634
1211
|
sessionId: state.sessionId,
|
|
635
1212
|
cwd: state.cwd,
|
|
636
1213
|
configOptions: state.configOptions,
|
|
637
|
-
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),
|
|
638
1217
|
seq: state.seq,
|
|
639
1218
|
reset,
|
|
640
1219
|
updates: reset ? state.buffer.slice() : state.buffer.filter(u => u.seq > afterSeq),
|
|
641
1220
|
permissions: [...this.#permissions.values()].filter(p => p.sessionId === state.sessionId).map(publicPermission),
|
|
642
|
-
permissionMode: state
|
|
1221
|
+
permissionMode: shownPermissionMode(state),
|
|
643
1222
|
};
|
|
644
1223
|
}
|
|
645
1224
|
|
|
@@ -653,17 +1232,29 @@ export class SessionHub {
|
|
|
653
1232
|
if (!mode) throw new AcpError(-32602, `permission mode must be one of ${PERMISSION_MODES.join(", ")}`);
|
|
654
1233
|
const state = this.#sessions.get(params.sessionId);
|
|
655
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));
|
|
656
1253
|
await this.#applyPermissionMode(await this.agent(), state.sessionId, mode, state);
|
|
657
1254
|
state.permissionMode = mode;
|
|
1255
|
+
state.shownMode = mode;
|
|
658
1256
|
this.#append(state, { sessionUpdate: PERMISSION_MODE_UPDATE, mode });
|
|
659
|
-
|
|
660
|
-
const kind = mode === "allow" ? "allow_once" : "reject_once";
|
|
661
|
-
for (const pending of this.#permissions.values()) {
|
|
662
|
-
if (pending.sessionId !== state.sessionId) continue;
|
|
663
|
-
const option = pending.options.find(o => o.kind === kind);
|
|
664
|
-
if (option) pending.resolve({ outcome: "selected", optionId: option.optionId });
|
|
665
|
-
}
|
|
666
|
-
}
|
|
1257
|
+
settle(false);
|
|
667
1258
|
return { mode };
|
|
668
1259
|
}
|
|
669
1260
|
|
|
@@ -678,38 +1269,198 @@ export class SessionHub {
|
|
|
678
1269
|
throw new AcpError(-32020, message, { code: response.error?.code ?? "internal" });
|
|
679
1270
|
}
|
|
680
1271
|
|
|
681
|
-
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 }> {
|
|
682
1273
|
const acp = await this.agent();
|
|
683
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(() => {});
|
|
684
1277
|
if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
|
|
685
|
-
if (state.running
|
|
1278
|
+
if (state.running || (state.interrupting && !interrupting))
|
|
1279
|
+
throw new AcpError(-32003, "A turn is already running in this session");
|
|
686
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);
|
|
687
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() };
|
|
688
1296
|
this.#track(state, { sessionUpdate: "x_gjcm_turn_start" });
|
|
689
|
-
|
|
1297
|
+
const turn: Promise<void> = acp.request("session/prompt", { sessionId: params.sessionId, prompt: params.prompt }).then(
|
|
690
1298
|
result => {
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
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" });
|
|
694
1304
|
},
|
|
695
1305
|
error => {
|
|
696
|
-
state.
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
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 });
|
|
700
1315
|
},
|
|
701
1316
|
);
|
|
702
|
-
|
|
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();
|
|
703
1332
|
}
|
|
704
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
|
+
*/
|
|
705
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 }> {
|
|
706
1368
|
for (const permission of this.#permissions.values()) {
|
|
707
|
-
if (permission.sessionId ===
|
|
1369
|
+
if (permission.sessionId === sessionId) permission.resolve({ outcome: "cancelled" });
|
|
708
1370
|
}
|
|
709
|
-
(await this.agent()).notify("session/cancel", { sessionId
|
|
1371
|
+
(await this.agent()).notify("session/cancel", { sessionId });
|
|
710
1372
|
return { ok: true };
|
|
711
1373
|
}
|
|
712
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
|
+
|
|
713
1464
|
/**
|
|
714
1465
|
* The phone's "끼어들기" for steers still waiting on a busy turn (the TUI's Esc with a queued steer): stop
|
|
715
1466
|
* the turn now and start a new one with the waiting steers. gjc's own queue (`queue.messages.list`) is the
|
|
@@ -730,19 +1481,51 @@ export class SessionHub {
|
|
|
730
1481
|
* the run it owns. Measured 2026-10-26 on a TUI turn: `session/cancel` had no effect (10s, then -32004),
|
|
731
1482
|
* `turn.abort` answered `no_active_turn`, `turn.abort{mode:"terminal"}` `terminal_no_effect`, and the operator
|
|
732
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]).
|
|
733
1491
|
*/
|
|
734
1492
|
async interrupt(params: { sessionId: string }): Promise<{ accepted: true; text: string }> {
|
|
735
1493
|
const state = this.#sessions.get(params.sessionId);
|
|
736
1494
|
if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
|
|
737
1495
|
const steers = await this.#queuedSteers(params.sessionId);
|
|
738
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)));
|
|
739
1501
|
if (!state.running && state.hostRunning)
|
|
740
1502
|
throw new AcpError(-32004, "터미널에서 시작한 턴은 앱에서 멈출 수 없습니다. 지시는 대기열에 있고 턴의 다음 단계에서 전달됩니다.", {
|
|
741
1503
|
code: "host_turn",
|
|
742
1504
|
});
|
|
1505
|
+
if (ownPromptQueued)
|
|
1506
|
+
throw new AcpError(
|
|
1507
|
+
-32004,
|
|
1508
|
+
"보낸 메시지가 터미널에서 시작한 턴 뒤에서 기다리고 있어 끼어들 수 없습니다. 메시지는 첨부와 함께 그 턴에 전달됩니다.",
|
|
1509
|
+
{ code: "host_turn" },
|
|
1510
|
+
);
|
|
1511
|
+
if (state.interrupting) throw new AcpError(-32003, "끼어들기가 이미 진행 중입니다.");
|
|
743
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 };
|
|
744
1527
|
if (isActive(state)) {
|
|
745
|
-
await this
|
|
1528
|
+
await this.#cancelTurn(params.sessionId);
|
|
746
1529
|
if (!(await this.#settled(state, INTERRUPT_SETTLE_TIMEOUT_MS)))
|
|
747
1530
|
throw new AcpError(-32004, "진행 중인 턴이 중단되지 않았습니다. 잠시 후 다시 시도하세요.");
|
|
748
1531
|
}
|
|
@@ -759,7 +1542,7 @@ export class SessionHub {
|
|
|
759
1542
|
const waiting = steers.filter(s => !delivered.includes(s.text));
|
|
760
1543
|
if (waiting.length === 0) throw noPendingSteer();
|
|
761
1544
|
const text = waiting.map(s => s.text).join("\n\n");
|
|
762
|
-
await this.prompt({ sessionId: params.sessionId, prompt: [{ type: "text", text }] });
|
|
1545
|
+
await this.prompt({ sessionId: params.sessionId, prompt: [{ type: "text", text }] }, true);
|
|
763
1546
|
return { accepted: true, text };
|
|
764
1547
|
}
|
|
765
1548
|
|
|
@@ -1029,6 +1812,39 @@ export const MODEL_ROLE_TARGETS = [
|
|
|
1029
1812
|
] as const;
|
|
1030
1813
|
const CONFIG_FLUSH_TIMEOUT_MS = 5000;
|
|
1031
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
|
+
}
|
|
1032
1848
|
const MODEL_SELECTOR = /^[\w.@-]+(\/[\w.@:+-]+)+$/;
|
|
1033
1849
|
|
|
1034
1850
|
interface AgentConfig {
|
|
@@ -1117,6 +1933,76 @@ export function supportedConfigOptions(options: unknown[]): unknown[] {
|
|
|
1117
1933
|
});
|
|
1118
1934
|
}
|
|
1119
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
|
+
|
|
1120
2006
|
function noPendingSteer(): AcpError {
|
|
1121
2007
|
return new AcpError(-32005, "대기 중인 끼어들기 메시지가 없습니다. 이미 전달됐습니다.", { code: "no_pending_steer" });
|
|
1122
2008
|
}
|
|
@@ -1167,8 +2053,9 @@ function isDirectory(dir: string): boolean {
|
|
|
1167
2053
|
}
|
|
1168
2054
|
}
|
|
1169
2055
|
|
|
1170
|
-
|
|
1171
|
-
|
|
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));
|
|
1172
2059
|
}
|
|
1173
2060
|
|
|
1174
2061
|
function stripUndefined<T extends object>(value: T): T {
|