gjcm-bridge 0.1.4 → 0.1.5

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 CHANGED
@@ -48,7 +48,7 @@ npm 패키지 `gjcm-bridge`이며 [Bun](https://bun.sh)으로만 실행됩니다
48
48
 
49
49
  `sdk.query`/`sdk.control`은 gjc `_gjc/sdk/query|control` 패스스루이며(단, `turn.btw`는 브리지가 세션 호스트에 맞는 연산으로 바꿔 보냅니다. 아래 [gjc 요구 사항](#gjc-요구-사항) 참고) `src/hub.ts`의 `SDK_QUERIES`/`SDK_CONTROLS` 허용 목록 밖의 op는 -32601로 거부합니다. `context.get` 응답의 `systemPrompt` 본문(~40KB)은 잘라내고 `systemPromptChars`만 보냅니다.
50
50
 
51
- 오류 코드: -32002 모르는 세션, -32003 실행 중(끼어들기가 턴을 다시 시작하는 동안 들어온 프롬프트 포함), -32004 멈출 수 없음(`host_turn`: 터미널에서 시작한 턴이나 그 뒤에 이어진 폰 턴의 끼어들기·중단. 끼어들기가 10초 안에 턴을 멈추지 못한 경우도 -32004), -32020 SDK op 실패(gjc 메시지 또는 브리지 진단: `host_outdated`, `approval_channel_unavailable` 등), -32021 tmux 창에서 gjc가 준비되지 않음(아래 [새 세션을 tmux 창으로 열기](#새-세션을-tmux-창으로-열기-옵트인)), -32601 허용 안 됨, -32602 잘못된 요청(`prompt_too_large`: 메시지가 gjc 0.19.3의 프롬프트 한도 256KiB를 넘음. 앱은 1.0.3부터 사진을 합쳐 180KB 안으로, 글이 길면 그만큼 더 작게 다시 인코딩합니다), -32010..-32014 업로드, -32030 응답이 프레임 한도 32MiB를 넘음(`response_too_large`, `bytes`·`limit`). 앱이 그런 프레임을 받으면 연결을 끊고 다시 붙으면서 같은 응답을 또 받으므로, 브리지는 보내지 않고 오류로 답합니다. 한도를 넘는 이벤트는 건너뜁니다.
51
+ 오류 코드: -32002 모르는 세션, -32003 실행 중(끼어들기가 턴을 다시 시작하는 동안 들어온 프롬프트 포함), -32004 터미널 것이라 앱에서 할 수 없음(`terminal_session`: TUI가 호스트하는 세션의 삭제. `host_turn`: 터미널에서 시작한 턴이나 그 뒤에 이어진 폰 턴의 끼어들기·중단. 끼어들기가 10초 안에 턴을 멈추지 못한 경우도 -32004), -32020 SDK op 실패(gjc 메시지 또는 브리지 진단: `host_outdated`, `approval_channel_unavailable` 등), -32021 tmux 창에서 gjc가 준비되지 않음(아래 [새 세션을 tmux 창으로 열기](#새-세션을-tmux-창으로-열기-옵트인)), -32601 허용 안 됨, -32602 잘못된 요청(`prompt_too_large`: 메시지가 gjc 0.19.3의 프롬프트 한도 256KiB를 넘음. 앱은 1.0.3부터 사진을 합쳐 180KB 안으로, 글이 길면 그만큼 더 작게 다시 인코딩합니다), -32010..-32014 업로드, -32030 응답이 프레임 한도 32MiB를 넘음(`response_too_large`, `bytes`·`limit`). 앱이 그런 프레임을 받으면 연결을 끊고 다시 붙으면서 같은 응답을 또 받으므로, 브리지는 보내지 않고 오류로 답합니다. 한도를 넘는 이벤트는 건너뜁니다.
52
52
 
53
53
  ## 세션 목록과 재개
54
54
 
@@ -62,16 +62,26 @@ npm 패키지 `gjcm-bridge`이며 [Bun](https://bun.sh)으로만 실행됩니다
62
62
  `serve --tmux-session gjcm`을 주면 앱의 "새 세션"이 tmux 세션 `gjcm`의 창 하나로 열립니다. 창에는 평소처럼 gjc TUI가 뜨고, 폰은 그 세션에 붙습니다. PC에서는 `tmux attach -t gjcm`(또는 접속 중인 tmux에서 prefix+`s`)으로 폰에서 시작한 작업을 그대로 이어 봅니다. 세션 이름을 `main`처럼 쓰고 있는 세션으로 주면 그 세션에 창이 생깁니다.
63
63
 
64
64
  - **tmux 서버가 이미 떠 있을 때만** 이렇게 엽니다. 서버가 없으면 지금처럼 ACP로 열고 이유를 로그에 남깁니다(`tmux skipped (opening over ACP): …`). 브리지가 서버를 띄우면 그 서버가 브리지 systemd 유닛의 cgroup에 들어가 브리지를 재시작할 때 창이 전부 같이 죽기 때문입니다. 대상 세션(`gjcm`)이 없으면 첫 창과 함께 만듭니다. 브리지는 tmux의 기본 소켓(같은 사용자의 `/tmp/tmux-<uid>/default`)을 씁니다. 그래서 브리지와 사용자 셸의 `TMUX_TMPDIR`이 같아야 하고, systemd 유닛에 `PrivateTmp=yes`를 주면 브리지가 사용자의 tmux 서버를 보지 못해 ACP로 엽니다.
65
- - 동작: ACP `session/new`로 세션을 만들고(gjc가 이때 기록 파일을 바로 씁니다) `session/close`로 놓아 준 뒤, `tmux new-window -d`로 `<--gjc에서 --mode=acp를 뺀 명령> --resume <id>`를 띄웁니다. 그 창의 프로세스가 `<cwd>/.gjc/state/sdk/<id>.json` endpoint를 쓰면 `session/load`로 붙습니다. TUI에서 새로 시작한 세션은 첫 답변 전까지 기록 파일이 없어 ACP `session/load`가 `Saved ACP session does not exist`로 실패하므로 이 순서를 씁니다(0.19.3 실측). gjc `--tmux`는 TTY가 있어야 하고 새 tmux 세션을 만들기 때문에 쓰지 않습니다.
66
- - 30초 안에 endpoint가 없거나 창의 gjc가 바로 끝나면 만든 창을 지우고 앱에 -32021과 이유를 돌려줍니다.
67
- - 실측(pve3, 공식 gjc 0.19.3, 2026-11-07, ACP가 떠 있는 상태): `session.new` 14.8~15.0초(ACP 경로 5.7~5.9초), 승인 채널까지 켠 실측에서는 22.9초. 늘어난 시간은 창의 gjc 기동(endpoint까지 약 6.3초), 다시 붙기, 채널 켜기(CLI 한 번 2~4초)입니다. 이 기능의 가치는 속도가 아니라 PC에서 이어 보기입니다.
65
+ - 동작: `tmux new-window -d`로 `<--gjc에서 --mode=acp를 뺀 명령>`을 띄웁니다. 창의 gjc가 새 세션을 직접 시작하고, 그 프로세스(또는 그 자식)의 pid가 적힌 `<cwd>/.gjc/state/sdk/<id>.json` endpoint가 생기면 그 id로 ACP `session/load`를 보내 붙습니다. 같은 폴더에 다른 프로세스가 남긴 endpoint는 pid가 창 밖이거나 창을 만들기 전부터 있던 파일이라 고르지 않습니다(gjc는 endpoint를 임시 파일에 쓴 뒤 rename하므로 창의 gjc가 쓴 파일은 늘 새 파일입니다). gjc는 endpoint를 먼저 쓰고 그 뒤에 세션을 broker에 등록하며, 그 등록을 기다리지 않습니다(gjc 0.19.3·0.20.0 `session-runtime.ts`). 등록 전의 load는 `not_found`로 실패하므로 브리지는 창이 살아 있는 동안 15초까지 0.25초 간격으로 다시 보냅니다. 등록된 뒤에는 첫 답변 전이라 기록 파일이 없어도 load가 살아 있는 TUI에 붙습니다(2026-11-09 공식 0.19.3·0.20.0 실측). 첫 답변 전에 창을 닫으면 기록이 남지 않습니다. gjc `--tmux`는 TTY가 있어야 하고 새 tmux 세션을 만들기 때문에 쓰지 않습니다.
66
+ - 30초 안에 endpoint가 없거나, 창의 gjc가 바로 끝나거나, 15초 안에 load로 붙지 못하면 만든 창을 지우고 앱에 -32021과 이유(`data.code`: `tmux_ready_timeout`, `tmux_window_exited`, `tmux_attach_failed`, `tmux_failed`)를 돌려줍니다. endpoint를 기다리는 동안 브리지가 재시작되면 그 창에는 아직 세션 표시(`@gjcm_session`)가 없어 브리지가 다시 찾지 못합니다. 그 창은 터미널에서 닫습니다.
67
+ - 실측(2026-11-09, ACP가 떠 있는 상태, cwd `/root/tmp`, 요청부터 승인 채널 켜기까지 전체): lab 5.3~7.4초, pve3 14.0~15.3초, pve1 13.8~17.7초. 이전 방식(ACP `session/new`→`session/close`→창에서 `--resume`)은 gjc를 두 번 띄워 lab 8.3초, pve3 22~27초, pve1 43.7초였습니다. 남은 시간은 대부분 세 구간입니다.
68
+ - 창의 gjc 기동(창 생성부터 endpoint까지): lab 3.6~3.8초, pve3 10~11초, pve1 7.7~8.3초.
69
+ - load: pve3 약 2초, pve1 4.9~5.1초. endpoint가 생기고 15초 뒤에 보내면 pve3 1.5초, pve1 2.3초입니다.
70
+ - 채널 켜기(세션 CLI 한 번): lab 1.6~2.6초, pve3 약 2초, pve1 1.8초.
71
+
72
+ 창의 gjc와 세션 CLI는 둘 다 `--gjc` 명령을 그대로 씁니다. 그래서 실행할 때마다 다른 일을 하는 래퍼(pve3·lab의 OCI 모델 동기화, 한 번에 최대 2초)가 두 번 더해집니다. 래퍼를 빼면 전체가 lab 3.3~3.6초, pve3 11.6~12.3초(endpoint까지 8.6~9.0초)입니다. 큰 작업 폴더도 gjc 기동을 늦춥니다. pve3에서 래퍼 없이 작은 저장소로 열면 전체 7.3~8.0초, endpoint까지 4.4초입니다.
68
73
  - 이 세션은 TUI가 소유합니다. 같은 실측에서 확인한 차이:
69
74
  - 앱에서 보낸 턴은 TUI 화면에도 그대로 보입니다.
70
75
  - **ask는 터미널에서만 답할 수 있습니다.** gjc는 앱이 시작한 턴의 ask도 TUI에 띄우고 폰에는 답할 수 없는 `tool_call`만 보냅니다(`session/request_permission` 없음, `workflow.gates.list` 비어 있음). 브리지는 이 카드에 질문·선택지와 "터미널에서 답" 안내를 붙이고, 터미널에서 고른 답과 턴 끝은 폰에 옵니다. 이 안내는 브리지가 tmux 창으로 연 세션(본인이 연 창을 다시 열 때 알아봄)에만 붙습니다.
71
- - **도구 승인(bash 등)은 폰으로 옵니다.** TUI가 소유한 세션은 승인을 ACP로 묻지 않고, gjc 0.19.3은 외부 승인 채널(`permission.channel.set`)도 ACP에서 막습니다(`operation_prohibited`). 그래서 브리지는 세션을 열 때 공식 세션 CLI(`gjc sdk session raw control|query`, `src/sdk-cli.ts`)로 채널을 켭니다. 대기 중인 `tool_call`이 오면 `permission.requests.list`를 읽어 폰에 승인 카드(`permission.request`)를 띄우고, 폰의 답을 `permission.respond`로 돌려줍니다(카드를 닫으면 거부). 앱에서 시작한 턴과 터미널에서 친 턴 모두 적용되며, 그동안 TUI에는 스피너만 보입니다. 답하지 않은 요청은 gjc가 60초 뒤 거부하고 카드도 사라집니다. 앱의 권한모드 `allow`/`deny`는 그대로 우선합니다. CLI 호출 하나가 2~4초라 카드는 도구 호출 뒤 약 2초에 뜹니다. 채널이 없으면 TUI는 묻지 않고 실행하므로(0.19.3 실측), 채널을 켜지 못한 세션은 로그(`permission channel not enabled for ...`)를 남기고 폰에 권한모드를 `allow`로 보이며, 폰에서 `prompt`로 바꾸려 하면 -32020 `approval_channel_unavailable`로 거절합니다. 세션을 다시 열 때마다 다시 켜 봅니다. 실측(pve3, 0.19.3, 2026-11-07): 앱 턴 bash는 폰 허용으로 실행, 터미널 턴 bash는 폰 거부로 "Tool call rejected by user".
72
- - **브리지가 지켜보지 않으면 터미널의 도구 호출은 60초 뒤 거부됩니다.** 채널은 TUI 호스트 메모리에 남고 그 승인은 폰만 할 수 있기 때문입니다. 그래서 브리지는 gjc ACP를 (다시) 띄울 때마다(브리지 시작, gjc 업데이트 뒤 재시작, 크래시) tmux 창들을 찾아(브리지가 연 창에 붙인 tmux 창 옵션 `@gjcm_session <id>`와, 그 창의 gjc가 가진 endpoint로 확인. 사용자가 같은 tmux 세션에 직접 띄운 `gjc --resume`은 건드리지 않음) 폰이 채팅을 열지 않아도 다시 붙고, 채널을 켜고, 이미 기다리던 요청을 카드로 다시 띄웁니다. 이 다시 붙기의 기록 재생은 열려 있는 폰에 새 메시지로 보내지 않습니다. 그래서 그 폰은 ACP가 없던 동안 터미널에서 일어난 일을 놓치므로, 브리지는 그 기기(다시 연결해도 같은 기기)의 다음 채팅 열기(앱 복귀·재연결·채팅 재진입)에 전체 기록을 줍니다. 다시 열기 전까지는 그 사이 내용이 화면에 비어 보입니다(앱에 밀어 넣는 재동기화 신호는 아직 없음). ACP가 죽어도 채널 카드는 거부하지 않고 내렸다가 다시 띄웁니다. 대기 중에 폰이 `allow`/`deny`로 바꾸면 먼저 그 요청에 답한 뒤 모드를 바꿉니다(gjc는 모드가 바뀌면 대기 요청을 취소함). 호스트가 채널을 잃었으면(같은 id로 TUI를 다시 띄움) 다음 읽기에서 다시 켭니다. 브리지가 꺼져 있는 동안에는 지켜볼 수 없으니, 터미널에서 도구를 쓰는 동안에는 브리지를 켜 둡니다.
76
+ - **도구 승인(bash 등)은 폰으로 옵니다.** TUI가 소유한 세션은 승인을 ACP로 묻지 않고, gjc 0.19.3은 외부 승인 채널(`permission.channel.set`)도 ACP에서 막습니다(`operation_prohibited`). 그래서 브리지는 세션을 열 때 공식 세션 CLI(`gjc sdk session raw control|query`, `src/sdk-cli.ts`)로 채널을 켭니다. 대기 중인 `tool_call`이 오면 `permission.requests.list`를 읽어 폰에 승인 카드(`permission.request`)를 띄우고, 폰의 답을 `permission.respond`로 돌려줍니다(카드를 닫으면 거부). 승인을 기다리는 동안 TUI에는 스피너만 보이고 터미널에서는 답할 수 없습니다. 그래서 **폰이 보낸 턴만 폰에 묻고, 터미널에서 친 턴의 도구는 브리지가 바로 허용합니다**(채널 없는 터미널의 gjc와 같은 동작). 폰 승인을 기다리게 두면 폰이 채팅을 보고 있지 않을 때 터미널 턴이 스피너만 돌다 60초 뒤 `Permission request cancelled`로 끝났습니다([#114](https://github.com/yazzang-homelab/gajae-mobile/issues/114), 2026-11-11 pve3, gjc 0.20.0 실측). gjc는 실행을 누가 시작했는지 알려 주지 않으므로 기준은 폰의 `session.prompt`가 진행 중인지입니다. 터미널 턴 뒤에 줄 선 폰 메시지가 있으면 그 턴의 도구도 폰에 묻습니다. 브리지가 폰 턴인지 알 수 없게 된 경우(폰 턴 도중 gjc ACP가 죽음, 폰 메시지 전송이 오류로 끝남, 브리지가 그 세션에 처음 붙을 때 호스트가 일하는 중)에는 TUI가 이어 가는 그 턴을 계속 폰에 묻고, 3초마다 호스트를 확인해 쉬고 있거나 폰이 새 메시지를 보내면 풉니다. 폰의 「끼어들기」·「다음에 보내기」(`turn.steer`·`turn.follow_up`)는 어느 턴에서 보냈든 기준을 바꾸지 않으므로, 터미널 턴에 얹힌 그 메시지 뒤의 도구는 묻지 않고 실행됩니다. 바로 허용도 세션 CLI 두 번(목록·응답)을 거치므로 터미널 턴의 도구마다 그만큼 늦게 시작합니다(같은 실측에서 호출당 4~5초). 답하지 않은 요청은 gjc가 60초 뒤 거부하고 카드도 사라집니다. 앱의 권한모드 `allow`/`deny`는 그대로 우선합니다. CLI 호출 하나가 2~4초라 카드는 도구 호출 뒤 약 2초에 뜹니다. 채널이 없으면 TUI는 묻지 않고 실행하므로(0.19.3 실측), 채널을 켜지 못한 세션은 로그(`permission channel not enabled for ...`)를 남기고 폰에 권한모드를 `allow`로 보이며, 폰에서 `prompt`로 바꾸려 하면 -32020 `approval_channel_unavailable`로 거절합니다. 세션을 다시 열 때마다 다시 켜 봅니다. 실측(pve3, 0.19.3, 2026-11-07): 앱 턴 bash는 폰 허용으로 실행, 터미널 턴 bash는 폰 거부로 "Tool call rejected by user".
77
+ - **브리지가 지켜보지 않으면 터미널의 도구 호출은 60초 뒤 거부됩니다.** 채널은 TUI 호스트 메모리에 남고 그 승인은 폰만 할 수 있기 때문입니다. 그래서 브리지는 gjc ACP를 (다시) 띄울 때마다(브리지 시작, gjc 업데이트 뒤 재시작, 크래시) tmux 창들을 찾아(브리지가 연 창에 붙인 tmux 창 옵션 `@gjcm_session <id>`와, 그 창의 gjc가 가진 endpoint로 확인. 사용자가 같은 tmux 세션에 직접 띄운 `gjc --resume`은 건드리지 않음) 폰이 채팅을 열지 않아도 다시 붙고, 채널을 켜고, 이미 기다리던 요청을 다시 읽습니다(폰 턴이거나 폰 턴일 수 있으면 카드로 다시 띄우고, 터미널 턴이면 바로 허용). 이 다시 붙기의 기록 재생은(폰이 ACP 재시작 뒤 채팅을 다시 열어 일어나는 재적재도 같습니다) 열려 있는 다른 폰에 새 메시지로 보내지 않고, 그 사이 브리지가 직접 붙이는 턴 끝 같은 행은 그대로 보냅니다. 그래서 그 폰은 ACP가 없던 동안 터미널에서 일어난 일을 놓치므로, 브리지는 그 기기(다시 연결해도 같은 기기)의 다음 채팅 열기(앱 복귀·재연결·채팅 재진입)에 전체 기록을 줍니다. 다시 열기 전까지는 그 사이 내용이 화면에 비어 보입니다(앱에 밀어 넣는 재동기화 신호는 아직 없음). ACP가 죽어도 채널 카드는 거부하지 않고 내렸다가 다시 띄웁니다. 대기 중에 폰이 `allow`/`deny`로 바꾸면 먼저 그 요청에 답한 뒤 모드를 바꿉니다(gjc는 모드가 바뀌면 대기 요청을 취소함). 호스트가 채널을 잃었으면(같은 id로 TUI를 다시 띄움) 다음 읽기에서 다시 켭니다. 브리지가 꺼져 있는 동안에는 지켜볼 수 없으니, 터미널에서 도구를 쓰는 동안에는 브리지를 켜 둡니다.
73
78
  - 앱이 시작한 턴은 앱에서 멈출 수 있습니다(`session.cancel` 후 약 0.4초에 `cancelled`). 터미널에서 친 턴은 앱의 멈춤을 바로 거절하므로 터미널에서 Esc로 멈춥니다(gjc가 턴을 시작한 연결에만 중단을 허용, 상류 [gajae-code#7566](https://github.com/Yeachan-Heo/gajae-code/issues/7566)).
74
- - 앱에서 채팅을 닫거나 브리지를 멈춰도 tmux 창과 TUI는 남습니다. 창은 터미널에서 닫습니다. TUI가 소유한 동안에는 gjc가 앱의 세션 삭제를 거부합니다(`operation_prohibited`, gjc 코드 기준, 실측 안 함). 창을 닫은 뒤 삭제합니다.
79
+ - 앱에서 채팅을 닫거나 브리지를 멈춰도 tmux 창과 TUI는 남습니다. 창은 터미널에서 닫습니다.
80
+ - 세션 삭제(gjc 0.20.0 실측, [#95](https://github.com/yazzang-homelab/gajae-mobile/issues/95)):
81
+ - 창이 열려 있으면 gjc가 앱의 삭제를 거부합니다(`operation_prohibited`). 앱에는 "PC 터미널(gjc TUI)에서 열려 있는 세션입니다"로 보입니다(`-32004`, `terminal_session`). 창에서 `/session delete`로 지우거나 창을 닫습니다.
82
+ - gjc ACP는 TUI가 끝난 뒤에도 그 세션을 터미널 것으로 붙들고 있어 같은 거부를 냅니다. 그래서 브리지가 붙어 있던 세션이 거부되면(브리지 창이 아직 호스트하는 경우는 빼고) 붙은 것을 놓고(`session/close`) 다시 불러(`session/load`) 한 번 더 지웁니다. 삭제하려고 방금 불러온 세션이 거부되면 다시 시도하지 않고 그 붙은 것만 놓습니다.
83
+ - 창을 닫은 세션 가운데 답을 한 번도 받지 않은 것은 저장된 것이 없어 바로 지워집니다. 답을 받은 세션은 gjc가 아티팩트 폴더 정리를 끝내지 못해 `cleanup_pending`으로 실패하고 세션이 남습니다(Linux, 상류 문제). 이때는 PC에서 `gjc --resume <id>` 뒤 `/session delete`로 지웁니다.
84
+ - 창에서 `/session delete`로 지운 세션과, 답을 받기 전에 창이 닫힌 세션은 앱 목록에 나오지 않습니다.
75
85
  - Windows 호스트와 tmux를 쓰지 않는 호스트에서는 이 옵션을 주지 않습니다.
76
86
 
77
87
  ## gjc 요구 사항
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gjcm-bridge",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "Host bridge that exposes gjc --mode=acp to the Gajae Code mobile apps over an end-to-end encrypted WebSocket",
6
6
  "bin": {
package/src/acp.ts CHANGED
@@ -107,7 +107,7 @@ export class AcpProcess {
107
107
  while (newline >= 0) {
108
108
  const line = buffer.slice(0, newline).trim();
109
109
  buffer = buffer.slice(newline + 1);
110
- if (line) this.#dispatch(line);
110
+ if (line) this.#dispatchSafely(line);
111
111
  newline = buffer.indexOf("\n");
112
112
  }
113
113
  }
@@ -120,6 +120,16 @@ export class AcpProcess {
120
120
  }
121
121
  }
122
122
 
123
+ // One malformed or unhandled line must not end the read loop (and with it the bridge): drop it and go on.
124
+ #dispatchSafely(line: string): void {
125
+ try {
126
+ this.#dispatch(line);
127
+ } catch (error) {
128
+ // The stack says whether gjc's line or the bridge's own handler was at fault; the line itself is never logged.
129
+ console.error("gjc ACP line dropped:", error);
130
+ }
131
+ }
132
+
123
133
  #dispatch(line: string): void {
124
134
  let message: any;
125
135
  try {
package/src/hub.ts CHANGED
@@ -150,6 +150,15 @@ interface SessionState {
150
150
  interrupting?: boolean;
151
151
  /** gjc's own phase flag (session_info_update _meta.running): also true for turns started elsewhere. */
152
152
  hostRunning: boolean;
153
+ /**
154
+ * The TUI in the tmux window may be going on with a phone turn this process holds no prompt for: the gjc ACP
155
+ * process died under it, its prompt failed, or this process first attached while the host was busy. Its tool approvals
156
+ * still go to the phone (see `#allowTerminalRequest`) until the host is found idle (`#watchCutTurn`) or the phone
157
+ * sends a prompt.
158
+ */
159
+ phoneTurnCut?: boolean;
160
+ /** The next look of `#watchCutTurn`. */
161
+ cutTurnCheck?: ReturnType<typeof setTimeout>;
153
162
  throughput: Throughput;
154
163
  /** In-flight `session.stats` read feeding [throughput]. */
155
164
  usageSample?: Promise<void>;
@@ -191,7 +200,7 @@ interface SessionState {
191
200
  historySeq: number;
192
201
  /** The permission mode last announced to the phones (`shownPermissionMode`). */
193
202
  shownMode?: PermissionMode;
194
- /** A reload the bridge started on its own (`#reattach`): its replay is kept from phones already showing the chat. */
203
+ /** While a reload replays: gjc's updates are kept from phones already showing the chat (every reload is quiet). */
195
204
  quietReplay?: boolean;
196
205
  /**
197
206
  * Phones (`HubClient.device`) that showed the chat during a quiet replay: they lack what the terminal did while gjc ACP
@@ -238,9 +247,14 @@ function shownPermissionMode(state: SessionState): PermissionMode {
238
247
  return state.inTmux && !state.channel && state.permissionMode === "prompt" ? "allow" : state.permissionMode;
239
248
  }
240
249
 
250
+ /** Wait between `session/load` attempts while gjc in a new tmux window registers its session (see `#attachWindow`). */
251
+ const ATTACH_RETRY_MS = 250;
252
+
241
253
  /** Reads per trigger at most, and the wait between them while a pending tool call is not listed yet. */
242
254
  const CHANNEL_READS = 4;
243
255
  const CHANNEL_RETRY_MS = 1000;
256
+ /** Wait between looks at whether the host a phone turn was cut from has gone idle (see `#watchCutTurn`). */
257
+ const CUT_TURN_CHECK_MS = 3000;
244
258
 
245
259
  /** `permission.requests.list` result (`{sessionId, enabled, requests:[{id, sessionId, expiresAt, options, toolCall}]}`). */
246
260
  function channelRequests(result: unknown): { enabled: boolean; requests: ChannelRequest[] } {
@@ -422,6 +436,7 @@ export class SessionHub {
422
436
  state.channel = undefined;
423
437
  if (state.running) {
424
438
  state.running = false;
439
+ state.phoneTurnCut = state.inTmux;
425
440
  this.#append(state, { sessionUpdate: AGENT_EXIT, code, stderrTail: acp.stderrTail.slice(-2000) });
426
441
  }
427
442
  }
@@ -434,6 +449,7 @@ export class SessionHub {
434
449
  stop(): void {
435
450
  this.#stopped = true;
436
451
  if (this.#statusTimer) clearInterval(this.#statusTimer);
452
+ for (const state of this.#sessions.values()) clearTimeout(state.cutTurnCheck);
437
453
  this.#acp?.kill();
438
454
  }
439
455
 
@@ -451,9 +467,12 @@ export class SessionHub {
451
467
  if (known?.loaded || this.#stopped) continue;
452
468
  const cwd = known?.cwd ?? (windowCwd || this.#saved.find(sessionId)?.cwd);
453
469
  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
- );
470
+ const state = this.#stateFor(sessionId, cwd);
471
+ await this.#load(state).catch(async error => {
472
+ this.#options.log?.(`reattach ${sessionId} failed: ${error instanceof Error ? error.message : String(error)}`);
473
+ // A window closed before its gjc's first answer leaves nothing to load: no longer the bridge's window session.
474
+ if (this.#tmux && !(await this.#tmux.hosts(sessionId, cwd))) state.inTmux = false;
475
+ });
457
476
  }
458
477
  }
459
478
 
@@ -507,7 +526,7 @@ export class SessionHub {
507
526
  if (method !== "session/update" || typeof params?.sessionId !== "string") return;
508
527
  const state = this.#stateFor(params.sessionId);
509
528
  if (this.#holdEcho(state, params.update)) return;
510
- this.#append(state, state.inTmux ? terminalAsk(params.update) : params.update);
529
+ this.#append(state, state.inTmux ? terminalAsk(params.update) : params.update, state.quietReplay);
511
530
  this.#lookForHandOver(state, params.update);
512
531
  if (state.channel && !state.replaying) this.#watchChannel(state, params.update);
513
532
  }
@@ -619,6 +638,44 @@ export class SessionHub {
619
638
  }
620
639
  }
621
640
 
641
+ /**
642
+ * Allows a guarded tool of a turn the phone did not send, as gjc does in a terminal without the channel. The TUI
643
+ * shows a waiting approval as a spinner only and cannot answer it, so a turn typed there stood still until a phone
644
+ * answered, or until gjc rejected the tool after 60s (gm#114, measured 2026-11-11 on pve3, gjc 0.20.0). gjc tells
645
+ * neither who started a run nor reliably when one starts, so the phone's own prompt is the line: its turn asks the
646
+ * phone, as does a turn its queued prompt waits behind. False when the request is to be shown as a card.
647
+ */
648
+ async #allowTerminalRequest(state: SessionState, channel: ApprovalChannel, request: ChannelRequest): Promise<boolean> {
649
+ // A mode other than prompt answers by itself, also what waited when the phone switched to it.
650
+ if (state.running || state.phoneTurnCut || state.permissionMode !== "prompt") return false;
651
+ const optionId = request.options.find(o => o.kind === "allow_once")?.optionId;
652
+ if (!optionId) return false;
653
+ try {
654
+ await this.#sdkCli!.control(state.sessionId, state.cwd, "permission.respond", { sessionId: state.sessionId, id: request.id, optionId });
655
+ } catch (error) {
656
+ this.#options.log?.(`permission.respond (terminal turn) failed for ${state.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
657
+ return false;
658
+ }
659
+ channel.settled.add(request.id);
660
+ return true;
661
+ }
662
+
663
+ /**
664
+ * Looks every `CUT_TURN_CHECK_MS` whether the host a phone turn was cut from has nothing left to do: gjc reports
665
+ * the end of a run it started for no ACP prompt unreliably (measured 2026-11-11 on pve3, gjc 0.20.0: no idle
666
+ * report after such a turn), and until then a turn typed at the terminal would wait for the phone again.
667
+ */
668
+ #watchCutTurn(state: SessionState): void {
669
+ if (!state.phoneTurnCut || state.cutTurnCheck || this.#stopped) return;
670
+ state.cutTurnCheck = setTimeout(async () => {
671
+ state.cutTurnCheck = undefined;
672
+ // Not loaded: the next load looks, and watches on.
673
+ if (this.#stopped || !state.phoneTurnCut || !state.loaded) return;
674
+ if (!state.running && (await this.#hostState(state))?.idle) state.phoneTurnCut = false;
675
+ else this.#watchCutTurn(state);
676
+ }, CUT_TURN_CHECK_MS);
677
+ }
678
+
622
679
  /** Lists the channel's requests into phone permission cards; one read at a time, another queued behind it. */
623
680
  #readChannel(state: SessionState): void {
624
681
  const channel = state.channel;
@@ -652,7 +709,10 @@ export class SessionHub {
652
709
  for (const id of channel.requests.keys()) if (!ids.has(id)) this.#dropChannelRequest(state, id);
653
710
  for (const request of listed) {
654
711
  channel.waitingTools.delete(request.toolCallId);
655
- if (!channel.requests.has(request.id)) this.#showChannelRequest(state, request);
712
+ if (channel.requests.has(request.id)) continue;
713
+ const allowed = await this.#allowTerminalRequest(state, channel, request);
714
+ if (state.channel !== channel) return;
715
+ if (!allowed) this.#showChannelRequest(state, request);
656
716
  }
657
717
  // A gated call shows up in the channel a moment after it arrives here; one that never does was not gated.
658
718
  if (!channel.again && channel.waitingTools.size === 0) return;
@@ -751,6 +811,8 @@ export class SessionHub {
751
811
  loaded: false,
752
812
  running: false,
753
813
  hostRunning: false,
814
+ // Until its first load finds the host idle: it may be a window from before this bridge started.
815
+ phoneTurnCut: true,
754
816
  throughput: new Throughput(),
755
817
  queued: [],
756
818
  remoteAsks: new Map(),
@@ -768,7 +830,8 @@ export class SessionHub {
768
830
  return state;
769
831
  }
770
832
 
771
- #append(state: SessionState, update: Record<string, unknown>): void {
833
+ /** `quiet`: gjc's replay while the session reloads; it stays in the buffer but is not sent live (see `quietReplay`). */
834
+ #append(state: SessionState, update: Record<string, unknown>, quiet = false): void {
772
835
  if (update.sessionUpdate === "config_option_update" && Array.isArray(update.configOptions)) {
773
836
  update = { ...update, configOptions: supportedConfigOptions(update.configOptions) };
774
837
  state.configOptions = update.configOptions as unknown[];
@@ -784,8 +847,9 @@ export class SessionHub {
784
847
  const dropped = state.buffer.shift()!;
785
848
  state.bufferBytes -= jsonBytes(dropped.update);
786
849
  }
787
- // A phone showing the chat already has the history a reload of the bridge's own replays.
788
- if (state.quietReplay) return;
850
+ // A phone showing the chat already has the history a quiet reload replays. What the bridge appends itself during
851
+ // the reload (a turn end, a held message, a host ask row) is news and goes out.
852
+ if (quiet) return;
789
853
  for (const { client, sessions } of this.#clients.values()) {
790
854
  if (sessions.has(state.sessionId)) client.deliver("session.update", { sessionId: state.sessionId, ...entry });
791
855
  }
@@ -1056,7 +1120,7 @@ export class SessionHub {
1056
1120
  };
1057
1121
  }
1058
1122
 
1059
- listSessions(params: { cwd?: string; cursor?: string; query?: string }) {
1123
+ async listSessions(params: { cwd?: string; cursor?: string; query?: string }) {
1060
1124
  const page = this.#saved.list(params);
1061
1125
  const listed = new Set(page.sessions.map(s => s.sessionId));
1062
1126
  // Sessions this bridge created but that have not written a transcript yet (no prompt sent).
@@ -1071,8 +1135,13 @@ export class SessionHub {
1071
1135
  (!needle || `${s.cwd}\n${s.sessionId}`.toLowerCase().includes(needle)),
1072
1136
  );
1073
1137
  const saved = candidates.length > 0 ? this.#saved.ids() : new Set<string>();
1074
- const fresh = candidates
1075
- .filter(s => !saved.has(s.sessionId))
1138
+ const unsaved = candidates.filter(s => !saved.has(s.sessionId));
1139
+ // A tmux window's session stays loaded here after the window deleted it (`/session delete`) or ended before its
1140
+ // first answer, and is saved nowhere then: it is a new session only while its window hosts it (gm#95).
1141
+ const tmux = this.#tmux;
1142
+ const open = await Promise.all(unsaved.map(async s => !s.inTmux || !tmux || (await tmux.hosts(s.sessionId, s.cwd))));
1143
+ const fresh = unsaved
1144
+ .filter((_, i) => open[i])
1076
1145
  .map(s => ({ sessionId: s.sessionId, cwd: s.cwd, updatedAt: new Date().toISOString() }));
1077
1146
  const sessions = [...fresh, ...page.sessions].map(s => {
1078
1147
  const state = this.#sessions.get(s.sessionId);
@@ -1088,33 +1157,61 @@ export class SessionHub {
1088
1157
  if (!isDirectory(cwd)) throw new AcpError(-32602, `호스트에 작업 디렉터리가 없습니다: ${cwd}`);
1089
1158
  const tmuxSkipped = this.#tmux && (await this.#tmux.unavailable());
1090
1159
  if (tmuxSkipped) this.#options.log?.(`tmux skipped (opening over ACP): ${tmuxSkipped.slice(0, 200)}`);
1091
- const result = await acp.request("session/new", { cwd, mcpServers: [] });
1092
1160
  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.
1161
+ // gjc in the window starts the session; the phone then attaches to that TUI host like to any terminal
1162
+ // session. Nothing is saved until its first answer, so a window closed unused leaves no transcript behind.
1163
+ let window: { sessionId: string; pane: string };
1095
1164
  try {
1096
- await acp.request("session/close", { sessionId: result.sessionId });
1097
- await this.#tmux.open(result.sessionId, cwd);
1165
+ window = await this.#tmux.open(cwd);
1098
1166
  } 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
- });
1167
+ if (!(error instanceof TmuxError)) throw error;
1168
+ throw new AcpError(-32021, `새 세션을 tmux 창으로 열지 못했습니다: ${error.message}`, { code: error.code });
1103
1169
  }
1104
- this.#stateFor(result.sessionId, cwd).inTmux = true;
1105
- return this.openSession(clientId, { sessionId: result.sessionId, cwd });
1170
+ return this.#attachWindow(clientId, this.#tmux, window, cwd);
1106
1171
  }
1172
+ const result = await acp.request("session/new", { cwd, mcpServers: [] });
1107
1173
  const state = this.#stateFor(result.sessionId, cwd);
1108
1174
  state.loaded = true;
1109
1175
  state.configOptions = supportedConfigOptions(result.configOptions ?? state.configOptions);
1110
1176
  return this.#subscribe(clientId, state, 0);
1111
1177
  }
1112
1178
 
1179
+ /**
1180
+ * Attaches the phone to the session gjc in a new tmux window started. gjc writes its SDK endpoint before it registers
1181
+ * the session with the broker, and `session/load` answers `not_found` until it has (gjc 0.19.3/0.20.0
1182
+ * `session-runtime.ts`), so the load is tried again while the window lives, up to `attachTimeoutMs`. A window the
1183
+ * phone could not attach to is removed: nobody would find it again before its first answer saved the session.
1184
+ */
1185
+ async #attachWindow(clientId: string, tmux: TmuxLauncher, window: { sessionId: string; pane: string }, cwd: string): Promise<OpenSnapshot> {
1186
+ const { sessionId, pane } = window;
1187
+ const state = this.#stateFor(sessionId, cwd);
1188
+ state.inTmux = true;
1189
+ const deadline = Date.now() + tmux.attachTimeoutMs;
1190
+ for (;;) {
1191
+ try {
1192
+ return await this.openSession(clientId, { sessionId, cwd });
1193
+ } catch (error) {
1194
+ const unregistered = errorCode(error) === "not_found";
1195
+ const retry = unregistered && Date.now() < deadline && (await tmux.hosts(sessionId, cwd));
1196
+ if (retry) {
1197
+ await Bun.sleep(ATTACH_RETRY_MS);
1198
+ continue;
1199
+ }
1200
+ await tmux.close(pane);
1201
+ if (this.#sessions.get(sessionId) === state) this.#sessions.delete(sessionId);
1202
+ if (!unregistered) throw error;
1203
+ const message = error instanceof Error ? error.message : String(error);
1204
+ throw new AcpError(-32021, `새 세션 창의 gjc에 붙지 못했습니다: ${message}`, { code: "tmux_attach_failed" });
1205
+ }
1206
+ }
1207
+ }
1208
+
1113
1209
  async openSession(clientId: string, params: { sessionId: string; cwd?: string; afterSeq?: number }): Promise<OpenSnapshot> {
1114
1210
  const state = this.#stateFor(params.sessionId, params.cwd ?? this.#saved.find(params.sessionId)?.cwd);
1115
1211
  // A turn being released (`#releaseTurn`) reloads the session itself.
1116
1212
  await state.releasing?.catch(() => {});
1117
1213
  if (!state.loaded) {
1214
+ // The opener gets the replay as its snapshot; other phones showing the chat must not get it appended again.
1118
1215
  await this.#load(state);
1119
1216
  return this.#subscribe(clientId, state, 0, true);
1120
1217
  }
@@ -1122,7 +1219,7 @@ export class SessionHub {
1122
1219
  }
1123
1220
 
1124
1221
  /** Loads the session into the ACP process (`session/load`); one load at a time per session. */
1125
- #load(state: SessionState, quiet = false): Promise<void> {
1222
+ #load(state: SessionState): Promise<void> {
1126
1223
  if (state.loaded) return Promise.resolve();
1127
1224
  state.loading ??= (async () => {
1128
1225
  const acp = await this.agent();
@@ -1142,7 +1239,7 @@ export class SessionHub {
1142
1239
  for (const id of [...(state.channel?.requests.keys() ?? [])]) this.#dropChannelRequest(state, id);
1143
1240
  state.channel = undefined;
1144
1241
  state.replaying = true;
1145
- state.quietReplay = quiet;
1242
+ state.quietReplay = true;
1146
1243
  let result: any;
1147
1244
  try {
1148
1245
  result = await acp.request("session/load", { sessionId: state.sessionId, cwd: state.cwd, mcpServers: [] });
@@ -1153,7 +1250,7 @@ export class SessionHub {
1153
1250
  state.replaying = false;
1154
1251
  state.quietReplay = false;
1155
1252
  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);
1253
+ for (const { client, sessions } of this.#clients.values()) if (sessions.has(state.sessionId)) state.resync.add(client.device ?? client.id);
1157
1254
  }
1158
1255
  state.configOptions = supportedConfigOptions(result?.configOptions ?? state.configOptions);
1159
1256
  // Judged on every load: a window the bridge opened (also before a restart) hosts it, or no longer does.
@@ -1161,7 +1258,10 @@ export class SessionHub {
1161
1258
  // Before the mode: enabling the channel sets the session to prompt.
1162
1259
  if (state.inTmux) await this.#enableChannel(state);
1163
1260
  if (state.permissionMode !== "prompt") await this.#applyPermissionMode(acp, state.sessionId, state.permissionMode);
1261
+ // The cut phone turn is over once the host has nothing left to do; only a tmux session's channel asks.
1262
+ if (state.phoneTurnCut && (!state.inTmux || (await this.#hostState(state, acp))?.idle)) state.phoneTurnCut = false;
1164
1263
  state.loaded = true;
1264
+ this.#watchCutTurn(state);
1165
1265
  this.#announceShownMode(state);
1166
1266
  // Requests already waiting (from before a restart) are not announced by any later tool call.
1167
1267
  this.#readChannel(state);
@@ -1180,18 +1280,74 @@ export class SessionHub {
1180
1280
  return this.openSession(clientId, { sessionId: forked.sessionId, cwd });
1181
1281
  }
1182
1282
 
1183
- /** Deletes a session's transcript and artifacts through gjc. */
1283
+ /**
1284
+ * Deletes a session's transcript and artifacts through gjc. gjc refuses a session this ACP process is attached to
1285
+ * as a terminal's (`operation_prohibited`), and keeps that attachment until `session/close`, also after the TUI
1286
+ * ended (gjc 0.20.0 `acp-agent.ts` `deleteSession`; gm#95: a tmux window's session could not be deleted after its
1287
+ * window closed). So a refused delete of a session loaded here is tried once more on a fresh attachment: gjc ACP
1288
+ * then hosts a session whose TUI is gone and deletes it, and refuses again while a TUI still hosts it.
1289
+ */
1184
1290
  async deleteSession(params: { sessionId: string }): Promise<{ ok: true }> {
1185
1291
  const state = this.#sessions.get(params.sessionId);
1186
1292
  if (state?.running) throw new AcpError(-32003, "Stop the running turn before deleting the session");
1187
1293
  const acp = await this.agent();
1294
+ const attachedBefore = state?.loaded === true;
1188
1295
  if (!state?.loaded) {
1189
1296
  // gjc resolves delete authority from sessions it knows; a saved-only session is loaded first.
1190
1297
  const cwd = state?.cwd ?? this.#saved.find(params.sessionId)?.cwd;
1191
1298
  if (!cwd) throw new AcpError(-32002, `Unknown session ${params.sessionId}`);
1192
1299
  await acp.request("session/load", { sessionId: params.sessionId, cwd, mcpServers: [] });
1193
1300
  }
1194
- await acp.request("session/delete", { sessionId: params.sessionId });
1301
+ try {
1302
+ await acp.request("session/delete", { sessionId: params.sessionId });
1303
+ } catch (error) {
1304
+ if (errorCode(error) !== "operation_prohibited") {
1305
+ // gjc ends its attachment before it deletes (0.20.0 `deleteSession`: `#teardownSession`, then the durable
1306
+ // delete), so a delete that failed after that (`cleanup_pending`) leaves nothing loaded here: the phone's
1307
+ // next call (-32002) opens the session again.
1308
+ if (state && attachedBefore) state.loaded = false;
1309
+ throw error;
1310
+ }
1311
+ if (!state || !attachedBefore) {
1312
+ // Loaded just now: a TUI hosts it. The attachment made for the delete is let go, or gjc would refuse the
1313
+ // session as the terminal's also after that TUI ended. Not one a phone opened meanwhile (the load above
1314
+ // takes as long as the history is), nor while such a load is under way.
1315
+ const opened = this.#sessions.get(params.sessionId);
1316
+ if (!opened?.loading && !opened?.loaded)
1317
+ await acp.request("session/close", { sessionId: params.sessionId }).catch(closing => {
1318
+ this.#options.log?.(`closing ${params.sessionId} after its refused delete failed: ${closing instanceof Error ? closing.message : String(closing)}`);
1319
+ });
1320
+ throw terminalSession();
1321
+ }
1322
+ // The bridge's window still hosts it: refused again for certain, so its attachment is left as it is.
1323
+ if (state.inTmux && (await this.#tmux?.hosts(state.sessionId, state.cwd))) throw terminalSession();
1324
+ await state.releasing?.catch(() => {});
1325
+ // A prompt that came in meanwhile would be ended by the close below.
1326
+ if (state.running) throw new AcpError(-32003, "Stop the running turn before deleting the session");
1327
+ // Nothing else goes to the attachment being closed; a failure below leaves the session closed, and the
1328
+ // phone's next call (-32002) opens it again.
1329
+ state.loaded = false;
1330
+ await acp.request("session/close", { sessionId: params.sessionId });
1331
+ // A TUI that ended before its first answer saved nothing: there is no session left to load or delete.
1332
+ const saved = await this.#load(state).then(
1333
+ () => true,
1334
+ reload => {
1335
+ if (errorCode(reload) !== "not_found") throw reload;
1336
+ return false;
1337
+ },
1338
+ );
1339
+ if (saved) {
1340
+ try {
1341
+ // The load may have started another gjc ACP process.
1342
+ await (await this.agent()).request("session/delete", { sessionId: params.sessionId });
1343
+ } catch (again) {
1344
+ if (errorCode(again) === "operation_prohibited") throw terminalSession();
1345
+ // As above: gjc ended the attachment the load made.
1346
+ state.loaded = false;
1347
+ throw again;
1348
+ }
1349
+ }
1350
+ }
1195
1351
  this.#sessions.delete(params.sessionId);
1196
1352
  for (const { sessions } of this.#clients.values()) sessions.delete(params.sessionId);
1197
1353
  return { ok: true };
@@ -1281,6 +1437,8 @@ export class SessionHub {
1281
1437
  const promptBytes = Buffer.byteLength(JSON.stringify(params.prompt));
1282
1438
  if (promptBytes > PROMPT_BYTES_LIMIT) throw promptTooLarge(params.prompt, promptBytes);
1283
1439
  state.running = true;
1440
+ // From here this prompt is what asks the phone; it ends behind whatever the cut turn left running.
1441
+ state.phoneTurnCut = false;
1284
1442
  const turnId = crypto.randomUUID();
1285
1443
  state.turnId = turnId;
1286
1444
  state.turnBehindHost = state.hostRunning;
@@ -1311,7 +1469,14 @@ export class SessionHub {
1311
1469
  if (message.includes(STALE_ATTACHMENT)) state.loaded = false;
1312
1470
  // A stop, not a failure; `undelivered` tells the phone that sent it to put the message back in its composer.
1313
1471
  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 });
1472
+ else {
1473
+ // The failure does not tell whether the TUI host took the prompt and runs it.
1474
+ if (state.inTmux) {
1475
+ state.phoneTurnCut = true;
1476
+ this.#watchCutTurn(state);
1477
+ }
1478
+ this.#endTurn(state, { sessionUpdate: TURN_END, stopReason: "error", error: message });
1479
+ }
1315
1480
  },
1316
1481
  );
1317
1482
  state.turn = turn;
@@ -1378,9 +1543,9 @@ export class SessionHub {
1378
1543
  * nothing left to do (`context.get` `isStreaming` false with empty queues, and no compaction or retry under way:
1379
1544
  * `isStreaming` does not cover those). `undefined` when it cannot say.
1380
1545
  */
1381
- async #hostState(state: SessionState): Promise<{ terminal: boolean; idle: boolean } | undefined> {
1546
+ async #hostState(state: SessionState, attached?: AcpProcess): Promise<{ terminal: boolean; idle: boolean } | undefined> {
1382
1547
  try {
1383
- const acp = await this.agent();
1548
+ const acp = attached ?? (await this.agent());
1384
1549
  const [capabilities, context] = await Promise.all([
1385
1550
  this.#sdkRequest(acp, state, "query", "runtime.capabilities", {}),
1386
1551
  this.#sdkRequest(acp, state, "query", "context.get", {}),
@@ -1423,7 +1588,7 @@ export class SessionHub {
1423
1588
  }
1424
1589
  // The turn is over either way; a failed load leaves the session closed, and the phone's next call (-32002)
1425
1590
  // opens it again.
1426
- await this.#load(state, true).catch(error =>
1591
+ await this.#load(state).catch(error =>
1427
1592
  this.#options.log?.(`loading ${state.sessionId} again after releasing its turn failed: ${error instanceof Error ? error.message : String(error)}`),
1428
1593
  );
1429
1594
  })().finally(() => {
@@ -2007,6 +2172,16 @@ function noPendingSteer(): AcpError {
2007
2172
  return new AcpError(-32005, "대기 중인 끼어들기 메시지가 없습니다. 이미 전달됐습니다.", { code: "no_pending_steer" });
2008
2173
  }
2009
2174
 
2175
+ /** The adapter's code gjc ACP puts in a failure's data (`not_found`, `operation_prohibited`, …). */
2176
+ function errorCode(error: unknown): unknown {
2177
+ return error instanceof AcpError ? (error.data as { code?: unknown } | undefined)?.code : undefined;
2178
+ }
2179
+
2180
+ /** A session a TUI hosts is deleted there (gjc refuses it over ACP). */
2181
+ function terminalSession(): AcpError {
2182
+ return new AcpError(-32004, "PC 터미널(gjc TUI)에서 열려 있는 세션입니다. 그 창에서 /session delete로 지우거나, 창을 닫은 뒤 다시 지우세요.", { code: "terminal_session" });
2183
+ }
2184
+
2010
2185
  function isActive(state: SessionState): boolean {
2011
2186
  return state.running || state.hostRunning;
2012
2187
  }
package/src/server.ts CHANGED
@@ -83,6 +83,22 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
83
83
  const sendBody = (ws: ServerWebSocket<Conn>, body: Buffer) => {
84
84
  const conn = ws.data;
85
85
  if (conn.phase !== "open" || !conn.cipher) return;
86
+ // `gjcm-bridge revoke` runs in another process and rewrites devices.json; check it before anything goes out.
87
+ let paired: boolean;
88
+ try {
89
+ paired = state.findDevice(conn.deviceKey!) !== undefined;
90
+ } catch (error) {
91
+ // An unreadable devices.json must not travel up into the hub's delivery loop: only this connection ends.
92
+ log(`device check failed, closing the connection: ${error instanceof Error ? error.message : String(error)}`);
93
+ conn.phase = "closed";
94
+ ws.close(1011, "internal_error");
95
+ return;
96
+ }
97
+ if (!paired) {
98
+ conn.phase = "closed";
99
+ ws.close(4403, "device_revoked");
100
+ return;
101
+ }
86
102
  ws.sendBinary(conn.cipher.seal(body));
87
103
  };
88
104
  const send = (ws: ServerWebSocket<Conn>, message: { id?: number; e?: unknown; ev?: string; p?: unknown }) => {
@@ -203,7 +219,14 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
203
219
  clientNonce,
204
220
  serverNonce,
205
221
  };
206
- const keys = serverKeys(host.keyPair, serverEph, transcript);
222
+ let keys: ReturnType<typeof serverKeys>;
223
+ try {
224
+ keys = serverKeys(host.keyPair, serverEph, transcript);
225
+ } catch {
226
+ // A device key is public, so anyone can send an ephemeral key that the key agreement rejects (all zero bytes).
227
+ log(`rejected hello device=${deviceKeyText.slice(0, 8)}: key agreement failed`);
228
+ return fail(ws, "bad_hello", "malformed keys");
229
+ }
207
230
  ws.data.cipher = new FrameCipher(keys.s2c, keys.c2s);
208
231
  ws.data.deviceKey = deviceKeyText;
209
232
  ws.data.deviceName = state.findDevice(deviceKeyText)?.name;
@@ -219,6 +242,26 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
219
242
  );
220
243
  };
221
244
 
245
+ const handleMessage = (ws: ServerWebSocket<Conn>, raw: string | Buffer) => {
246
+ const conn = ws.data;
247
+ if (conn.phase === "hello") {
248
+ if (typeof raw !== "string") return fail(ws, "bad_hello", "hello must be a text frame");
249
+ return onHello(ws, raw);
250
+ }
251
+ if (conn.phase === "closed") return;
252
+ if (typeof raw === "string") {
253
+ conn.phase = "closed";
254
+ ws.close(4400, "binary_frames_required");
255
+ return;
256
+ }
257
+ // `onFrame` is async, so the `message` handler's catch does not see what it throws.
258
+ onFrame(ws, Buffer.from(raw)).catch(error => {
259
+ log(`frame handler failed: ${error instanceof Error ? error.message : String(error)}`);
260
+ ws.data.phase = "closed";
261
+ ws.close(1011, "internal_error");
262
+ });
263
+ };
264
+
222
265
  const onFrame = async (ws: ServerWebSocket<Conn>, frame: Buffer) => {
223
266
  const conn = ws.data;
224
267
  let message: any;
@@ -229,7 +272,7 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
229
272
  ws.close(4400, "decrypt_failed");
230
273
  return;
231
274
  }
232
- // Revocation (`gjcm-bridge revoke`) takes effect on the device's next frame.
275
+ // Revocation (`gjcm-bridge revoke`) also takes effect on the device's next frame.
233
276
  if (!state.findDevice(conn.deviceKey!)) {
234
277
  conn.phase = "closed";
235
278
  ws.close(4403, "device_revoked");
@@ -290,18 +333,14 @@ export function startBridgeServer(options: BridgeServerOptions): Server<Conn> {
290
333
  }, HANDSHAKE_TIMEOUT_MS);
291
334
  },
292
335
  message(ws, raw) {
293
- const conn = ws.data;
294
- if (conn.phase === "hello") {
295
- if (typeof raw !== "string") return fail(ws, "bad_hello", "hello must be a text frame");
296
- return onHello(ws, raw);
297
- }
298
- if (conn.phase === "closed") return;
299
- if (typeof raw === "string") {
300
- conn.phase = "closed";
301
- ws.close(4400, "binary_frames_required");
302
- return;
336
+ try {
337
+ handleMessage(ws, raw);
338
+ } catch (error) {
339
+ // One bad frame must not take the whole bridge down with every other phone's connection.
340
+ log(`message handler failed: ${error instanceof Error ? error.message : String(error)}`);
341
+ ws.data.phase = "closed";
342
+ ws.close(1011, "internal_error");
303
343
  }
304
- void onFrame(ws, Buffer.from(raw));
305
344
  },
306
345
  close(ws, code, reason) {
307
346
  // Who closed tells a drop the app chose (it closes with 1000, e.g. on a frame over its limit) from a lost network
package/src/tmux.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  /**
2
2
  * Opens a phone-started session as a window of one dedicated tmux session (gm#58), so the terminal shows the
3
- * same TUI the phone drives. The window runs `gjc --resume <id>`: gjc writes the transcript only after the first
4
- * answer for a TUI-started session, and ACP `session/load` resolves a session through that transcript, so the
5
- * bridge creates the session over ACP (which writes it at once), lets go of it, and hands it to the TUI.
3
+ * same TUI the phone drives. The window runs plain `gjc`, which starts a new session itself; the bridge learns its
4
+ * id from the SDK endpoint that process publishes and attaches with ACP `session/load`, which reaches a live host
5
+ * through the broker before any transcript exists (measured on 0.19.3 and 0.20.0). gjc writes the endpoint first and
6
+ * registers the session with the broker after it, without waiting (`session-runtime.ts`: `runtime.start()`, then
7
+ * `registerBroker()`); until then the load answers `not_found`, so the hub tries it again while the window lives. One
8
+ * gjc start instead of creating the session over ACP first and resuming it in the window: bridge `session.new`
9
+ * measured 2026-11-09 in /root/tmp, pve3 22–27s → 14–15s, lab 8.3s → 5.3–7.4s.
6
10
  *
7
11
  * The bridge never starts a tmux server: a server started from the bridge's systemd unit would live in the
8
12
  * bridge's cgroup and die with every bridge restart, taking the phone's sessions with it. Every tmux call carries
@@ -16,12 +20,20 @@ export interface TmuxOptions {
16
20
  session: string;
17
21
  /** `tmux -L` socket name; the user's default server when absent. */
18
22
  socket?: string;
19
- /** How long gjc in the window may take to publish its SDK endpoint (measured 5.6–6.6s on pve3). */
23
+ /** How long gjc in the window may take to publish its SDK endpoint (measured 2026-11-09 in /root/tmp: lab 3.6–3.8s, pve3 10–11s, pve1 7.7–8.3s). */
20
24
  readyTimeoutMs?: number;
25
+ /**
26
+ * How long the hub tries `session/load` while gjc in the window registers its session with the broker, which waits on
27
+ * the broker and its session index lock: a busy host may take seconds.
28
+ */
29
+ attachTimeoutMs?: number;
21
30
  }
22
31
 
23
- /** Why a window did not become the session's host; the bridge passes it to the phone as -32021 `data.code`. */
24
- export type TmuxFailure = "tmux_failed" | "tmux_window_exited" | "tmux_ready_timeout";
32
+ /**
33
+ * Why a window did not become the session's host; the bridge passes it to the phone as -32021 `data.code`.
34
+ * `tmux_attach_failed` is the hub's: the window's gjc published its endpoint, but `session/load` never attached.
35
+ */
36
+ export type TmuxFailure = "tmux_failed" | "tmux_window_exited" | "tmux_ready_timeout" | "tmux_attach_failed";
25
37
 
26
38
  export class TmuxError extends Error {
27
39
  constructor(
@@ -33,6 +45,7 @@ export class TmuxError extends Error {
33
45
  }
34
46
 
35
47
  const DEFAULT_READY_TIMEOUT_MS = 30_000;
48
+ const DEFAULT_ATTACH_TIMEOUT_MS = 15_000;
36
49
  const POLL_MS = 200;
37
50
  /** tmux turns `.` and `:` in session names into `_`, so such a name would never be found again. */
38
51
  const SESSION_NAME = /^[A-Za-z0-9_-]+$/;
@@ -61,16 +74,21 @@ export function tuiCommand(acpCommand: string[]): string[] {
61
74
  return argv;
62
75
  }
63
76
 
77
+ const PROCFS = fs.existsSync("/proc/self/stat");
78
+
64
79
  function parentPid(pid: number): number | undefined {
65
80
  try {
66
- // /proc/<pid>/stat: "pid (comm) state ppid …"; comm may hold spaces and parentheses.
67
- const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
68
- return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
69
- } catch {
81
+ if (PROCFS) {
82
+ // /proc/<pid>/stat: "pid (comm) state ppid …"; comm may hold spaces and parentheses.
83
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
84
+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
85
+ }
70
86
  // No procfs (macOS): ask ps.
71
- const ps = Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)]);
72
- const parent = Number(ps.stdout.toString().trim());
87
+ const parent = Number(Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)]).stdout.toString().trim());
73
88
  return Number.isInteger(parent) && parent > 0 ? parent : undefined;
89
+ } catch {
90
+ // The process is gone (or ps is missing).
91
+ return undefined;
74
92
  }
75
93
  }
76
94
 
@@ -118,6 +136,10 @@ export class TmuxLauncher {
118
136
  }
119
137
  }
120
138
 
139
+ get attachTimeoutMs(): number {
140
+ return this.#options.attachTimeoutMs ?? DEFAULT_ATTACH_TIMEOUT_MS;
141
+ }
142
+
121
143
  /** Why a new session cannot go to tmux now (no tmux, no server running), or undefined when it can. */
122
144
  async unavailable(): Promise<string | undefined> {
123
145
  const listed = await this.#run(["list-sessions", "-F", "#{session_name}"]);
@@ -126,24 +148,37 @@ export class TmuxLauncher {
126
148
  }
127
149
 
128
150
  /**
129
- * Starts `gjc --resume <sessionId>` in a new window of the dedicated session and waits until that process
130
- * publishes the session's SDK endpoint. Removes the window and throws a TmuxError when it does not.
151
+ * Starts gjc in a new window of the dedicated session, waits until that process publishes the SDK endpoint of the
152
+ * session it started, and returns that session's id with the window's pane. Removes the window and throws a
153
+ * TmuxError when it does not.
131
154
  */
132
- async open(sessionId: string, cwd: string): Promise<void> {
133
- if (!SESSION_ID.test(sessionId)) throw new TmuxError("tmux_failed", `tmux 창에 열 수 없는 세션 id입니다: ${sessionId}`);
155
+ async open(cwd: string): Promise<{ sessionId: string; pane: string }> {
156
+ const dir = path.join(cwd, ".gjc", "state", "sdk");
157
+ // Endpoints already there are other processes'. One may name a pid that comes around again as the window's gjc;
158
+ // gjc writes each endpoint to a new file (temp file, then rename), so the window's has an inode not seen here.
159
+ const existing = this.#endpoints(dir);
134
160
  // Window creation runs one at a time, so two phones starting sessions together do not both create the
135
161
  // tmux session; waiting for gjc does not hold the next phone up.
136
- const created = this.#creating.then(() => this.#create(sessionId, cwd));
162
+ const created = this.#creating.then(() => this.#create(cwd));
137
163
  this.#creating = created.catch(() => {});
138
164
  const { panePid, pane } = await created;
139
165
  try {
140
- await this.#waitReady(sessionId, cwd, panePid);
166
+ const sessionId = await this.#waitReady(dir, panePid, existing);
167
+ // Untagged, the window would not be found again: its tool approvals would reach no phone.
168
+ const tagged = await this.#run(["set-option", "-w", "-t", pane, SESSION_TAG, sessionId]);
169
+ if (tagged.code !== 0) throw new TmuxError("tmux_failed", `tmux 창에 세션 표시를 못 달았습니다: ${tagged.stderr || `exit ${tagged.code}`}`);
170
+ return { sessionId, pane };
141
171
  } catch (error) {
142
- await this.#run(["kill-pane", "-t", pane]);
172
+ await this.close(pane);
143
173
  throw error;
144
174
  }
145
175
  }
146
176
 
177
+ /** Removes a window `open` made (tmux sends its gjc SIGHUP). */
178
+ async close(pane: string): Promise<void> {
179
+ await this.#run(["kill-pane", "-t", pane]);
180
+ }
181
+
147
182
  /**
148
183
  * Whether a window of the dedicated session hosts `sessionId` now: the bridge opened it for `sessionId` and the
149
184
  * session's SDK endpoint names a process in it. Recognizes the bridge's windows again after a bridge restart; a
@@ -173,51 +208,69 @@ export class TmuxLauncher {
173
208
  });
174
209
  }
175
210
 
176
- async #create(sessionId: string, cwd: string): Promise<{ panePid: number; pane: string }> {
211
+ async #create(cwd: string): Promise<{ panePid: number; pane: string }> {
177
212
  const { session } = this.#options;
178
213
  const env = Object.entries(this.#env).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
179
214
  // tmux expands formats in -c; a literal `#` in the path is written `##`.
180
215
  const start = ["-c", cwd.replaceAll("#", "##"), ...env, "-P", "-F", "#{pane_pid} #{pane_id}"];
181
- const command = [...this.#tui, "--resume", sessionId];
182
216
  const exists = (await this.#run(["has-session", "-t", `=${session}`])).code === 0;
183
217
  const created = exists
184
- ? await this.#run(["new-window", "-d", "-t", `=${session}:`, ...start, ...command])
185
- : await this.#run(["new-session", "-d", "-s", session, ...start, ...command]);
218
+ ? await this.#run(["new-window", "-d", "-t", `=${session}:`, ...start, ...this.#tui])
219
+ : await this.#run(["new-session", "-d", "-s", session, ...start, ...this.#tui]);
186
220
  const verb = exists ? "new-window" : "new-session";
187
221
  if (created.code !== 0) throw new TmuxError("tmux_failed", `tmux ${verb} 실패: ${created.stderr || `exit ${created.code}`}`);
188
222
  const [pidText, pane] = created.stdout.split(" ");
189
223
  const panePid = Number(pidText);
190
224
  if (!Number.isInteger(panePid) || !pane) throw new TmuxError("tmux_failed", `tmux ${verb}가 창 정보를 주지 않았습니다: ${created.stdout}`);
191
- // Untagged, the window would not be found again: its tool approvals would reach no phone.
192
- const tagged = await this.#run(["set-option", "-w", "-t", pane, SESSION_TAG, sessionId]);
193
- if (tagged.code !== 0) {
194
- // A command that cannot start (a wrong --gjc) takes its window with it before the tag lands.
195
- if (!alive(panePid)) throw new TmuxError("tmux_window_exited", `tmux 세션 ${session}의 새 창에서 gjc가 바로 끝났습니다`);
196
- await this.#run(["kill-pane", "-t", pane]);
197
- throw new TmuxError("tmux_failed", `tmux 창에 세션 표시를 못 달았습니다: ${tagged.stderr || `exit ${tagged.code}`}`);
198
- }
199
225
  return { panePid, pane };
200
226
  }
201
227
 
202
- async #waitReady(sessionId: string, cwd: string, panePid: number): Promise<void> {
228
+ /**
229
+ * The id of the session gjc in the window started: the one whose SDK endpoint names that process. Endpoints in
230
+ * `existing` are skipped; others name a pid outside the window (or a gone one), and each is read once.
231
+ */
232
+ async #waitReady(dir: string, panePid: number, existing: Map<string, bigint>): Promise<string> {
203
233
  const { session } = this.#options;
204
- const endpoint = path.join(cwd, ".gjc", "state", "sdk", `${sessionId}.json`);
205
234
  const timeoutMs = this.#options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
206
235
  const deadline = Date.now() + timeoutMs;
207
- // The endpoint the ACP host left behind names a process outside the window; check each pid once.
208
- const foreign = new Set<number>();
236
+ const foreign = new Set<string>();
209
237
  while (Date.now() < deadline) {
210
238
  if (!alive(panePid)) throw new TmuxError("tmux_window_exited", `tmux 세션 ${session}의 새 창에서 gjc가 바로 끝났습니다`);
211
- const pid = this.#endpointPid(endpoint);
212
- if (pid !== undefined && !foreign.has(pid)) {
213
- if (descendsFrom(pid, panePid)) return;
214
- foreign.add(pid);
239
+ for (const [sessionId, inode] of this.#endpoints(dir)) {
240
+ if (existing.get(sessionId) === inode) continue;
241
+ const pid = this.#endpointPid(path.join(dir, `${sessionId}.json`));
242
+ if (pid === undefined) continue;
243
+ const key = `${sessionId}\t${pid}`;
244
+ if (foreign.has(key)) continue;
245
+ if (alive(pid) && descendsFrom(pid, panePid)) return sessionId;
246
+ foreign.add(key);
215
247
  }
216
248
  await Bun.sleep(POLL_MS);
217
249
  }
218
250
  throw new TmuxError("tmux_ready_timeout", `tmux 세션 ${session}의 새 창에서 gjc가 ${Math.round(timeoutMs / 1000)}초 안에 준비되지 않았습니다`);
219
251
  }
220
252
 
253
+ /** The SDK endpoint files (`<id>.json`) in `dir`: session id → inode. */
254
+ #endpoints(dir: string): Map<string, bigint> {
255
+ const endpoints = new Map<string, bigint>();
256
+ let names: string[];
257
+ try {
258
+ names = fs.readdirSync(dir);
259
+ } catch {
260
+ return endpoints;
261
+ }
262
+ for (const name of names) {
263
+ const id = name.endsWith(".json") ? name.slice(0, -".json".length) : "";
264
+ if (!SESSION_ID.test(id)) continue;
265
+ try {
266
+ endpoints.set(id, fs.statSync(path.join(dir, name), { bigint: true }).ino);
267
+ } catch {
268
+ // Gone since the listing, or unreadable: nothing to take.
269
+ }
270
+ }
271
+ return endpoints;
272
+ }
273
+
221
274
  #endpointPid(file: string): number | undefined {
222
275
  try {
223
276
  const pid = JSON.parse(fs.readFileSync(file, "utf8"))?.pid;