gjcm-bridge 0.1.0 → 0.1.1

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
@@ -40,20 +40,21 @@ npm 패키지 `gjcm-bridge`이며 [Bun](https://bun.sh)으로만 실행됩니다
40
40
 
41
41
  `session.setPermissionMode`는 앱 세션 메뉴의 「권한모드」 항목입니다(누를 때마다 `prompt` → `allow` → `deny` 순환). gjc SDK `permission_mode.set`으로 세션의 가드 도구(`bash`·`eval`·`delete`·`move`) 정책을 바꾸고, 모든 폰에 `x_gjcm_permission_mode{mode}` 업데이트를 보냅니다. 스냅샷에는 `permissionMode`가 들어갑니다. gjc는 ACP 연결(`session/new`·`session/load`)마다 `prompt`로 되돌리므로 브리지가 세션별 모드를 기억했다가 다시 불러올 때 재적용합니다(브리지 재시작 시에는 `prompt`). 모드를 바꿀 때 이미 대기 중인 승인 요청은 새 모드대로(`allow` → 한 번 허용, `deny` → 한 번 거부) 처리합니다. 추적을 위해 `permission_mode.set`은 범용 `sdk.control`에서 열지 않습니다.
42
42
 
43
- `sdk.query`/`sdk.control`은 gjc `_gjc/sdk/query|control` 패스스루이며 `src/hub.ts`의 `SDK_QUERIES`/`SDK_CONTROLS` 허용 목록 밖의 op는 -32601로 거부합니다. `context.get` 응답의 `systemPrompt` 본문(~40KB)은 잘라내고 `systemPromptChars`만 보냅니다.
43
+ `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`만 보냅니다.
44
44
 
45
- 오류 코드: -32002 모르는 세션, -32003 실행 중, -32020 SDK op 실패(gjc 메시지 그대로), -32601 허용 안 됨, -32010..-32014 업로드.
45
+ 오류 코드: -32002 모르는 세션, -32003 실행 중, -32020 SDK op 실패(gjc 메시지 또는 브리지 진단: `host_outdated` 등), -32601 허용 안 됨, -32010..-32014 업로드.
46
46
 
47
47
  ## 세션 목록과 재개
48
48
 
49
- - 목록은 ACP `session/list`가 아니라 gjc가 저장한 트랜스크립트(`sessions/<bucket>/<stamp>_<id>.jsonl` 헤더)에서 최신순으로 만듭니다. TUI `/resume`이 보여주는 목록과 같습니다. ACP `session/list`는 브로커 엔드포인트 색인을 오래된 순으로 주고, 실측 시 100행 중 78행에 저장 기록이 없었으며 저장된 859개 중 837개가 빠져 있었습니다.
50
- - 재개(세션 호스트 기동)는 바쁜 호스트에서 약 36초 걸립니다. gjc 기본 준비 타임아웃 22초로는 실패하므로 서비스 파일에서 `GJC_ACP_SESSION_READINESS_TIMEOUT_MS=60000`을 줍니다.
49
+ - 목록은 ACP `session/list`가 아니라 gjc가 저장한 트랜스크립트(`sessions/<bucket>/<stamp>_<id>.jsonl` 헤더)에서 최신순으로 만듭니다. TUI `/resume`이 보여주는 목록과 같습니다. ACP `session/list`는 브로커 엔드포인트 색인(30일 보존)을 오래된 순으로 줍니다. 실측 시 100행 중 78행에 저장 기록이 없었고, 저장된 859개 중 837개(0.19.3에서는 214개 중 181개)가 빠져 있었습니다. ACP 프로세스가 재시작될 때마다 열 수 없는 빈 행이 하나씩 생기는 문제는 상류 [gajae-code#7558](https://github.com/Yeachan-Heo/gajae-code/pull/7558)로 0.19.3 다음 릴리스에서 고쳐집니다.
50
+ - 재개(세션 호스트 기동, `session/load`)는 0.19.3 격리 환경 콜드 실측 2.7초입니다. 이전에 바쁜 호스트에서 약 36초가 걸린 기록이 있고, 공식 gjc의 준비 타임아웃은 22초로 고정입니다.
51
+ - 최근 답변이 긴 세션(최근 이벤트 합계가 1 MiB 초과)은 0.19.3에서 `cursor_expired`로 재개가 실패합니다. 상류 [gajae-code#7564](https://github.com/Yeachan-Heo/gajae-code/pull/7564)가 dev에 들어가 0.19.3 다음 릴리스에서 고쳐집니다.
51
52
  - ACP 프로세스의 브로커 소켓이 장시간 운영 뒤 망가지면 `SDK request outcome is uncertain after the frame was sent`가 납니다. 실행 중인 턴과 대기 중인 권한 요청이 없을 때 브리지가 ACP 프로세스를 자동으로 재시작합니다.
52
53
 
53
54
  ## gjc 요구 사항
54
55
 
55
- - BTW 사이드 질문([BTW.ko.md](../docs/BTW.ko.md))은 `turn.btw` ACP 제어를 넣은 gjc 빌드가 필요합니다. 공식 gjc 릴리스에는 아직 없습니다. 지원하지 않는 gjc는 `unknown_operation`으로 답하고, 브리지는 이를 `host_outdated`로 앱에 전달합니다.
56
- - `GJC_ACP_SESSION_READINESS_TIMEOUT_MS`(허용 범위 4000–60000ms, 그 밖은 22000으로 되돌아감)는 이를 지원하는 gjc 빌드에서만 적용됩니다. 지원하지 않는 빌드에서는 콜드 재개가 22초에서 실패할 수 있습니다.
56
+ - BTW 사이드 질문([BTW.ko.md](../docs/BTW.ko.md))은 gjc 0.19.3 이상이 필요합니다. 브리지가 세션 호스트의 `runtime.capabilities`를 보고 로컬 패치 0004의 `turn.btw`가 있으면 그것을, 없으면 공식 `btw.ask`로 보냅니다. 0.19.3의 `btw.ask`는 이전 문답(`exchanges`)을 받아도 무시하므로 브리지가 질문 본문에 붙이고, `btwAskExchangesVersion` 1을 광고하는 호스트(상류 gajae-code#7583 포함 릴리스)에는 `exchanges`로 그대로 넘깁니다. 둘 다 없는 gjc에서는 `host_outdated`로 앱에 전달합니다.
57
+ - `GJC_ACP_SESSION_READINESS_TIMEOUT_MS`(허용 범위 4000–60000ms, 그 밖은 22000으로 되돌아감)는 **공식 gjc(0.19.3과 dev 포함)가 읽지 않습니다.** 로컬 패치 `0002-acp-session-readiness-timeout-env.patch`를 넣은 빌드에서만 적용됩니다. 서비스 예시와 e2e 명령에 남아 있는 값은 그런 빌드를 위한 것이고, 공식 빌드에서는 아무 효과가 없습니다. 공식 빌드에서는 바쁜 호스트의 콜드 재개가 22초에서 실패할 수 있습니다.
57
58
 
58
59
  ## 외부망에서 접속하기
59
60
 
@@ -384,6 +384,9 @@ async function handle(msg: any) {
384
384
  switch (params.query) {
385
385
  case "queue.messages.list":
386
386
  return ok(queued);
387
+ // The bridge reads this before every /btw to pick the side-question operation; the demo answers turn.btw.
388
+ case "runtime.capabilities":
389
+ return ok([{ operations: ["turn.steer", "turn.follow_up", "turn.btw"], hostTools: false }]);
387
390
  case "context.get": {
388
391
  const used = tokens(session).context;
389
392
  return ok([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gjcm-bridge",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
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/hub.ts CHANGED
@@ -46,7 +46,8 @@ export const SDK_QUERIES = new Set([
46
46
  ]);
47
47
  export const SDK_CONTROLS = new Set([
48
48
  "turn.steer",
49
- // Ephemeral /btw side question (gjc local patch 0004): { question, exchanges? } -> { replyText }.
49
+ // Ephemeral /btw side question: { question, exchanges? } -> { replyText }. The hub routes it to official btw.ask or to
50
+ // turn.btw (local patch 0004) by the session host's runtime.capabilities; see #sideQuestion.
50
51
  "turn.btw",
51
52
  "turn.follow_up",
52
53
  "compaction.run",
@@ -908,15 +909,70 @@ export class SessionHub {
908
909
  const state = this.#sessions.get(params.sessionId);
909
910
  if (!state?.loaded) throw new AcpError(-32002, "Session is not open; call session.open first");
910
911
  const acp = await this.agent();
911
- const input = params.input ?? {};
912
+ if (params.kind === "control" && params.op === "turn.btw") return { result: await this.#sideQuestion(acp, state, params.input ?? {}) };
913
+ const response = await this.#sdkRequest(acp, state, params.kind, params.op, params.input ?? {}, params.confirm);
914
+ if (params.kind === "query") {
915
+ const items: unknown[] = response?.page?.items ?? [];
916
+ return { items: params.op === "context.get" ? items.map(withoutSystemPrompt) : items, complete: response?.page?.complete !== false };
917
+ }
918
+ // Measured shapes: most operations answer with the bare result ({renamed:true}, {path}, …);
919
+ // some (mode.goal.operate) answer with the control envelope instead.
920
+ if (response?.type === "control_response") return { result: response.result ?? null };
921
+ return { result: response ?? null };
922
+ }
923
+
924
+ /**
925
+ * The phone's `/btw` (`turn.btw` {question, exchanges?: [{question, answer}]} -> {replyText}) on whichever side-question
926
+ * operation the gjc hosting this session has, read from its `runtime.capabilities` on every call (a session host can
927
+ * restart on another build):
928
+ * - `turn.btw` (local patch 0004): unchanged. First, because only it answers mid-turn with the main turn's pending
929
+ * request kept out of the side conversation; a patched build rebased past gajae-code#7583 advertises both;
930
+ * - official `btw.ask` that takes `exchanges` (`btwAskExchangesVersion` 1, gajae-code#7583): history passed as is;
931
+ * - official `btw.ask` without it (0.19.3 accepts and silently drops `exchanges`, measured): the answered history is
932
+ * folded into the question, oldest exchanges dropped first to stay within gjc's 16 KiB question limit.
933
+ */
934
+ async #sideQuestion(acp: AcpProcess, state: SessionState, input: Record<string, unknown>): Promise<{ replyText: string }> {
935
+ const response = await this.#sdkRequest(acp, state, "query", "runtime.capabilities", {});
936
+ const capabilities = response?.page?.items?.[0];
937
+ if (!Array.isArray(capabilities?.operations)) {
938
+ throw new AcpError(-32020, "gjc의 runtime.capabilities 응답에 연산 목록(page.items[0].operations)이 없습니다.", { code: "internal" });
939
+ }
940
+ const operations: unknown[] = capabilities.operations;
941
+ const question = typeof input.question === "string" ? input.question : "";
942
+ const exchanges = btwExchanges(input.exchanges);
943
+ if (operations.includes("turn.btw")) {
944
+ return { replyText: String((await this.#sdkRequest(acp, state, "control", "turn.btw", input))?.replyText ?? "") };
945
+ }
946
+ if (operations.includes("btw.ask") && capabilities.btwAskExchangesVersion >= 1) {
947
+ const asked = { question, ...(exchanges.length ? { exchanges: exchanges.map(e => ({ question: e.question, reply: e.answer })) } : {}) };
948
+ return { replyText: String((await this.#sdkRequest(acp, state, "control", "btw.ask", asked))?.reply ?? "") };
949
+ }
950
+ if (operations.includes("btw.ask")) {
951
+ const asked = { question: foldBtwExchanges(question, exchanges) };
952
+ return { replyText: String((await this.#sdkRequest(acp, state, "control", "btw.ask", asked))?.reply ?? "") };
953
+ }
954
+ throw new AcpError(-32020, "이 세션의 gjc에는 BTW 기능(btw.ask)이 없습니다. gjc 0.19.3 이상이 필요하고, 업데이트 전에 시작된 세션이면 gjc를 다시 시작해야 합니다.", {
955
+ code: "host_outdated",
956
+ });
957
+ }
958
+
959
+ /** One `_gjc/sdk/query|control` round trip; gjc's `{ok:false}` answers become typed AcpErrors. */
960
+ async #sdkRequest(
961
+ acp: AcpProcess,
962
+ state: SessionState,
963
+ kind: "query" | "control",
964
+ op: string,
965
+ input: Record<string, unknown>,
966
+ confirm?: boolean,
967
+ ): Promise<any> {
912
968
  const response =
913
- params.kind === "query"
914
- ? await acp.request("_gjc/sdk/query", { sessionId: params.sessionId, query: params.op, input })
969
+ kind === "query"
970
+ ? await acp.request("_gjc/sdk/query", { sessionId: state.sessionId, query: op, input })
915
971
  : await acp.request("_gjc/sdk/control", {
916
- sessionId: params.sessionId,
917
- operation: params.op,
972
+ sessionId: state.sessionId,
973
+ operation: op,
918
974
  input,
919
- ...(params.confirm ? { confirm: true } : {}),
975
+ ...(confirm ? { confirm: true } : {}),
920
976
  });
921
977
  if (response?.ok === false) {
922
978
  const error = response.error ?? {};
@@ -929,24 +985,17 @@ export class SessionHub {
929
985
  }
930
986
  if (error.code === "unknown_operation") {
931
987
  // The operation is in the bridge allowlist but the gjc hosting this session lacks it: either the gjc build
932
- // never had it (turn.btw is not in any official gjc release) or the session host started before it was added.
988
+ // never had it or the session host started before it was added.
933
989
  // A restart only helps in the second case, so the message does not promise it.
934
990
  throw new AcpError(
935
991
  -32020,
936
- `이 세션의 gjc가 ${params.op}을(를) 지원하지 않습니다. 공식 gjc 릴리스에 없는 기능이거나, 그 기능이 들어가기 전에 시작된 세션입니다.`,
992
+ `이 세션의 gjc가 ${op}을(를) 지원하지 않습니다. 공식 gjc 릴리스에 없는 기능이거나, 그 기능이 들어가기 전에 시작된 세션입니다.`,
937
993
  { code: "host_outdated" },
938
994
  );
939
995
  }
940
996
  throw new AcpError(-32020, message, { code: error.code ?? "internal" });
941
997
  }
942
- if (params.kind === "query") {
943
- const items: unknown[] = response?.page?.items ?? [];
944
- return { items: params.op === "context.get" ? items.map(withoutSystemPrompt) : items, complete: response?.page?.complete !== false };
945
- }
946
- // Measured shapes: most operations answer with the bare result ({renamed:true}, {path}, …);
947
- // some (mode.goal.operate) answer with the control envelope instead.
948
- if (response?.type === "control_response") return { result: response.result ?? null };
949
- return { result: response ?? null };
998
+ return response;
950
999
  }
951
1000
 
952
1001
  respondPermission(params: { requestId: string; optionId?: string | null }): { ok: boolean } {
@@ -1008,6 +1057,44 @@ function publicPermission(p: PendingPermission): Omit<PendingPermission, "resolv
1008
1057
  return { requestId: p.requestId, sessionId: p.sessionId, toolCall: p.toolCall, options: p.options };
1009
1058
  }
1010
1059
 
1060
+ /** gjc's `btw.ask` question limit (BTW_MAX_QUESTION_UTF8_BYTES). */
1061
+ const BTW_ASK_QUESTION_BYTES = 16 * 1024;
1062
+
1063
+ interface BtwExchange {
1064
+ question: string;
1065
+ answer: string;
1066
+ }
1067
+
1068
+ /**
1069
+ * The phone's answered `/btw` history (`[{question, answer}]`) for the `btw.ask` paths. The apps only send answered
1070
+ * exchanges; a malformed entry is left out rather than failing the whole side question.
1071
+ */
1072
+ function btwExchanges(value: unknown): BtwExchange[] {
1073
+ if (!Array.isArray(value)) return [];
1074
+ return value.flatMap(entry =>
1075
+ typeof entry?.question === "string" && typeof entry?.answer === "string" ? [{ question: entry.question, answer: entry.answer }] : [],
1076
+ );
1077
+ }
1078
+
1079
+ /**
1080
+ * The question for a `btw.ask` that drops `exchanges`: the answered history quoted ahead of it, oldest exchanges left
1081
+ * out first so the whole stays within gjc's question limit. A question that alone exceeds it goes out unchanged and
1082
+ * gjc refuses it as `invalid_input`; so does an empty question, which is not dressed up with history.
1083
+ */
1084
+ export function foldBtwExchanges(question: string, exchanges: BtwExchange[]): string {
1085
+ if (!question.trim()) return question;
1086
+ const bytes = (text: string) => Buffer.byteLength(text, "utf8");
1087
+ for (let start = 0; start < exchanges.length; start++) {
1088
+ const history = exchanges
1089
+ .slice(start)
1090
+ .map(e => `Q: ${e.question}\nA: ${e.answer}`)
1091
+ .join("\n\n");
1092
+ const folded = `Earlier questions and answers in this side chat, oldest first:\n\n${history}\n\nCurrent question: ${question}`;
1093
+ if (bytes(folded) <= BTW_ASK_QUESTION_BYTES) return folded;
1094
+ }
1095
+ return question;
1096
+ }
1097
+
1011
1098
  /** context.get carries the whole system prompt (~40KB measured); the phone only needs its size. */
1012
1099
  function withoutSystemPrompt(item: unknown): unknown {
1013
1100
  if (!item || typeof item !== "object" || !("systemPrompt" in item)) return item;