handmux 0.30.0 → 0.31.0

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.
Files changed (108) hide show
  1. package/dist/connectors/claude/index.js +33 -562
  2. package/dist/connectors/codebuddy/index.js +49 -0
  3. package/dist/connectors/hookBridge.js +560 -0
  4. package/dist/hooks/handmux-codebuddy-notify.sh +116 -0
  5. package/dist/hooks/handmux-notify.sh +2 -0
  6. package/dist/hooks/handmux-write.cjs +72 -5
  7. package/dist/package.json +7 -7
  8. package/dist/public/assets/{abnfDiagram-O67JEVCF-CmVVGJqt.js → abnfDiagram-O67JEVCF-BsRDIQEB.js} +1 -1
  9. package/dist/public/assets/{arc-aYtCI03A.js → arc-DLtLfMnX.js} +1 -1
  10. package/dist/public/assets/{architectureDiagram-NJMV4G6O-CyZZDTaL.js → architectureDiagram-NJMV4G6O-DoIXhWqZ.js} +1 -1
  11. package/dist/public/assets/{blockDiagram-BEXU5L5S-D_ODtFS0.js → blockDiagram-BEXU5L5S-W0HiOcVA.js} +1 -1
  12. package/dist/public/assets/{c4Diagram-YGBWAQC7-C8qZFFmC.js → c4Diagram-YGBWAQC7-72uAUMvX.js} +1 -1
  13. package/dist/public/assets/channel-CzALSnb0.js +1 -0
  14. package/dist/public/assets/{chunk-2Q5K7J3B-Bo85fSxI.js → chunk-2Q5K7J3B-B9wSRFQ0.js} +1 -1
  15. package/dist/public/assets/{chunk-3FUC2YCW-BnET3fKr.js → chunk-3FUC2YCW-ryphp4s0.js} +2 -2
  16. package/dist/public/assets/{chunk-5VM5RSS4-DDw_KNv1.js → chunk-5VM5RSS4-Cm4KeKby.js} +1 -1
  17. package/dist/public/assets/{chunk-GTNCS2PH-B_K2164R.js → chunk-GTNCS2PH-Du4_i7r3.js} +1 -1
  18. package/dist/public/assets/{chunk-GWA4HPMP-1GA2Su8A.js → chunk-GWA4HPMP-CL1biVIA.js} +1 -1
  19. package/dist/public/assets/{chunk-JWPE2WC7-Cfc-8kSE.js → chunk-JWPE2WC7-B8eAVfuB.js} +1 -1
  20. package/dist/public/assets/{chunk-NETBCI7D-C7zyDFCq.js → chunk-NETBCI7D-D273GzYg.js} +1 -1
  21. package/dist/public/assets/{chunk-WEXAMYUT-BI2Zijn_.js → chunk-WEXAMYUT-DipTfRbc.js} +1 -1
  22. package/dist/public/assets/{chunk-XXDRQBXY-Bl50fDL9.js → chunk-XXDRQBXY-D4SqXrQ8.js} +1 -1
  23. package/dist/public/assets/{classDiagram-v2-NBCMYWYE-BMWMChZ4.js → classDiagram-v2-NBCMYWYE-PrpnIXcA.js} +1 -1
  24. package/dist/public/assets/{cose-bilkent-JH36ORCC-B_HUrBN4.js → cose-bilkent-JH36ORCC-BfcYMYTa.js} +1 -1
  25. package/dist/public/assets/{cynefin-OW5HDTMX-2jTRe-JA.js → cynefin-OW5HDTMX-Du659bmz.js} +1 -1
  26. package/dist/public/assets/{cynefinDiagram-VND7K2PF-ClDtZNOK.js → cynefinDiagram-VND7K2PF-DR_2Copy.js} +1 -1
  27. package/dist/public/assets/{dagre-6A5THRUB-CJS3bbcm.js → dagre-6A5THRUB-COsChaV5.js} +1 -1
  28. package/dist/public/assets/{diagram-22UHCM2B-BpRgaKhU.js → diagram-22UHCM2B-Cx2T1HvL.js} +1 -1
  29. package/dist/public/assets/{diagram-3UASUU5V-BNwvXb9K.js → diagram-3UASUU5V-Cp04LOka.js} +1 -1
  30. package/dist/public/assets/{diagram-ATOU4E4O-DyphKhOl.js → diagram-ATOU4E4O-DlqFSshY.js} +1 -1
  31. package/dist/public/assets/{diagram-CDSNMT55-BRazAxS2.js → diagram-CDSNMT55-goq40ctA.js} +1 -1
  32. package/dist/public/assets/{diagram-MLGK6HIB-NN_P6wZp.js → diagram-MLGK6HIB-Bdzjsy4r.js} +1 -1
  33. package/dist/public/assets/{diagram-MPIPVDR6-DHBe5DA4.js → diagram-MPIPVDR6-DtU7cM6P.js} +1 -1
  34. package/dist/public/assets/{ebnfDiagram-ZINNZB2B-BCTHXp7J.js → ebnfDiagram-ZINNZB2B-XyVCfmED.js} +1 -1
  35. package/dist/public/assets/{elk-276RUBZZ-yXNwrgXQ.js → elk-276RUBZZ-aHVIw-2x.js} +1 -1
  36. package/dist/public/assets/{erDiagram-OPXOYQCR-YsAJcCqg.js → erDiagram-OPXOYQCR-Bq_PhTIL.js} +1 -1
  37. package/dist/public/assets/{flowDiagram-KWPJA3E3-CyX8qF-3.js → flowDiagram-KWPJA3E3-WuqnDSiF.js} +1 -1
  38. package/dist/public/assets/{ganttDiagram-FUAMR5RP-BMFOvdDK.js → ganttDiagram-FUAMR5RP-DZ4lXzkC.js} +1 -1
  39. package/dist/public/assets/{gitGraphDiagram-X574FWY7-D1sZiiWD.js → gitGraphDiagram-X574FWY7-t6l07b9g.js} +1 -1
  40. package/dist/public/assets/index-DiYff8oR.css +32 -0
  41. package/dist/public/assets/index-YZNK723o.js +203 -0
  42. package/dist/public/assets/{infoDiagram-VRGFBTTK-CiayIr0f.js → infoDiagram-VRGFBTTK-iUGqoOFp.js} +1 -1
  43. package/dist/public/assets/{ishikawaDiagram-OU5B5YK6-Bf4mzvKk.js → ishikawaDiagram-OU5B5YK6-B0TmoUOK.js} +1 -1
  44. package/dist/public/assets/{journeyDiagram-ZHPQQLJL-mvwzOMZ7.js → journeyDiagram-ZHPQQLJL-CQE61MCu.js} +1 -1
  45. package/dist/public/assets/{kanban-definition-PNTS6WVX-CMFYAtvx.js → kanban-definition-PNTS6WVX-D2MWCUyS.js} +1 -1
  46. package/dist/public/assets/{linear-BcK1QK3e.js → linear-WKGxVNP1.js} +1 -1
  47. package/dist/public/assets/{mermaid.core-BmCR7le1.js → mermaid.core-DPEwUsaj.js} +4 -4
  48. package/dist/public/assets/{mindmap-definition-NLK3R4M7-hvUFWkg7.js → mindmap-definition-NLK3R4M7-DsYEsBsI.js} +1 -1
  49. package/dist/public/assets/{pegDiagram-GJSIUBJH-B8FGnth6.js → pegDiagram-GJSIUBJH-BS52Fbxt.js} +1 -1
  50. package/dist/public/assets/{pieDiagram-5QR66LMP-BdhppGvz.js → pieDiagram-5QR66LMP-D4o8g7nW.js} +1 -1
  51. package/dist/public/assets/{quadrantDiagram-O4NWA36T-i6XjZJ8W.js → quadrantDiagram-O4NWA36T-DnYUxWll.js} +1 -1
  52. package/dist/public/assets/{railroadDiagram-XR7U4H2S-C7XoA5kk.js → railroadDiagram-XR7U4H2S-BKy_7ULV.js} +1 -1
  53. package/dist/public/assets/{requirementDiagram-PLB6GJNP-tq6onssc.js → requirementDiagram-PLB6GJNP-Ce5F4u8K.js} +1 -1
  54. package/dist/public/assets/{sankeyDiagram-IPEJSGJF-DRW13BH8.js → sankeyDiagram-IPEJSGJF-CCJDrut_.js} +1 -1
  55. package/dist/public/assets/{sequenceDiagram-PO4LG4MO-BJqhIpnw.js → sequenceDiagram-PO4LG4MO-D5E8ISM1.js} +1 -1
  56. package/dist/public/assets/{sizeCapture-INFHLROL-BCpyNpYK.js → sizeCapture-INFHLROL-BW3KmxDN.js} +1 -1
  57. package/dist/public/assets/{stateDiagram-v2-GCMORJYK-Da3aSdeG.js → stateDiagram-v2-GCMORJYK-Bw2ZzQOE.js} +1 -1
  58. package/dist/public/assets/{swimlanes-2SLR337P-oT62nN2e.js → swimlanes-2SLR337P-CLJ-6Ex_.js} +1 -1
  59. package/dist/public/assets/swimlanesDiagram-TC7HE7FX-BD8rQfV7.js +8 -0
  60. package/dist/public/assets/{timeline-definition-EJHVYXUP-CQ9Q15bt.js → timeline-definition-EJHVYXUP-C_lFJ-4W.js} +1 -1
  61. package/dist/public/assets/{usecaseDiagram-POWQR4AR-De1gJb8v.js → usecaseDiagram-POWQR4AR-DWXawL2A.js} +1 -1
  62. package/dist/public/assets/{vennDiagram-UO4OBE2U-BusPyTiq.js → vennDiagram-UO4OBE2U-D4O5oZal.js} +1 -1
  63. package/dist/public/assets/{wardleyDiagram-VNRHLVJA-D-vaN_gJ.js → wardleyDiagram-VNRHLVJA-B6HElk__.js} +1 -1
  64. package/dist/public/assets/{xychartDiagram-PMCCYNJV-BcOmOj-j.js → xychartDiagram-PMCCYNJV-C5OAXnJy.js} +1 -1
  65. package/dist/public/index.html +2 -2
  66. package/dist/src/agent-runtime/adapter.js +54 -10
  67. package/dist/src/agent-runtime/builtinRuntime.js +67 -6
  68. package/dist/src/agent-runtime/conversation.js +49 -9
  69. package/dist/src/agent-runtime/interaction.js +26 -12
  70. package/dist/src/agent-runtime/interactionLiveHub.js +4 -0
  71. package/dist/src/agent-runtime/runtime.js +83 -27
  72. package/dist/src/agent-runtime/tmuxRuntime.js +36 -6
  73. package/dist/src/agents/claude.js +2 -19
  74. package/dist/src/agents/claudeInteraction.js +2 -132
  75. package/dist/src/agents/claudePaneInput.js +22 -22
  76. package/dist/src/agents/codebuddy.js +100 -0
  77. package/dist/src/agents/codebuddyConversation.js +414 -0
  78. package/dist/src/agents/codebuddyInteraction.js +4 -0
  79. package/dist/src/agents/codebuddyNativeTail.js +206 -0
  80. package/dist/src/agents/codebuddyPaneInput.js +76 -0
  81. package/dist/src/agents/codebuddyTranscriptParse.js +178 -0
  82. package/dist/src/agents/hookEvents.js +143 -0
  83. package/dist/src/agents/hookInteraction.js +178 -0
  84. package/dist/src/agents/index.js +2 -1
  85. package/dist/src/claudeEvents.js +4 -5
  86. package/dist/src/cli/agentIntegration.js +31 -2
  87. package/dist/src/cli/codebuddyHooks.js +286 -0
  88. package/dist/src/cli/hookScaffold.js +25 -12
  89. package/dist/src/cli/i18n/en.js +1 -1
  90. package/dist/src/cli/i18n/zh.js +1 -1
  91. package/dist/src/cli/state.js +4 -0
  92. package/dist/src/cli/supervisor.js +2 -1
  93. package/dist/src/codebuddyEvents.js +151 -0
  94. package/dist/src/docs.js +17 -6
  95. package/dist/src/logDetail.js +27 -0
  96. package/dist/src/paneInput.js +107 -10
  97. package/dist/src/pendingPrompt.js +21 -5
  98. package/dist/src/routes/system.js +12 -2
  99. package/dist/src/server.js +69 -8
  100. package/dist/src/workspace/checkpointer.js +48 -4
  101. package/dist/src/workspace/lock.js +54 -10
  102. package/dist/src/workspace/runtime.js +23 -8
  103. package/dist/src/workspaceProtocol.js +1 -0
  104. package/package.json +3 -3
  105. package/dist/public/assets/channel-kkiOw5AC.js +0 -1
  106. package/dist/public/assets/index-DqCUBYR8.css +0 -32
  107. package/dist/public/assets/index-OW7snGiD.js +0 -362
  108. package/dist/public/assets/swimlanesDiagram-TC7HE7FX-YHG5AQi4.js +0 -8
@@ -1,42 +1,42 @@
1
- import { serializePaneInput } from '../paneInput.js';
1
+ import { describeEditorArea, serializePaneInput, singleLineDraft } from '../paneInput.js';
2
2
  const SUBMIT_GAP_MS = 120;
3
3
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4
- // Read the entire one-line native editor, bounded by its two rules. Wrapped input, attachments,
5
- // selection menus and unknown layouts fail closed. End is sent first: placeholder text is painted
6
- // after the cursor but isn't part of the editor; actual text places the cursor at its end.
4
+ // Claude's editor is the shared one-line shape, with `❯` as its prompt.
7
5
  export function claudeSingleLineDraft(screen, cursor) {
8
- const lines = screen.split('\n');
9
- const line = lines[cursor.cursorY];
10
- if (!line || !/^─{3,}$/.test(lines[cursor.cursorY - 1]?.trim() ?? '')
11
- || !/^─{3,}$/.test(lines[cursor.cursorY + 1]?.trim() ?? '')
12
- || !/^❯[ \u00a0]/.test(line))
13
- return null;
14
- const value = line.slice(2).trimEnd();
15
- if (cursor.cursorX === 2)
16
- return ''; // Native suggestions are painted here but End does not enter them.
17
- if (!value || /[\x00-\x1f\x7f]/.test(value) || cursor.cursorX <= 2)
18
- return null;
19
- return value;
6
+ return singleLineDraft(screen, cursor);
20
7
  }
21
- export function sendClaudePanePrompt(commands, paneId, text, restoredPrompt, guard) {
8
+ export function sendClaudePanePrompt(commands, paneId, text, restoredPrompt, guard, reportUnreadable) {
22
9
  return serializePaneInput(paneId, async () => {
23
10
  if (guard && !await guard.validate())
24
11
  return { nativeMutation: false };
25
12
  await commands.exitCopyModeIfActive(paneId);
26
13
  await commands.sendKey(paneId, 'End');
27
14
  await delay(SUBMIT_GAP_MS);
28
- const readDraft = async () => claudeSingleLineDraft(await commands.capturePlain(paneId), await commands.paneInfo(paneId));
29
- const draft = await readDraft();
30
- if (draft === null || (draft !== '' && draft !== restoredPrompt())) {
15
+ const readEditor = async () => {
16
+ const screen = await commands.capturePlain(paneId);
17
+ const cursor = await commands.paneInfo(paneId);
18
+ return { screen, cursor, draft: claudeSingleLineDraft(screen, cursor) };
19
+ };
20
+ const draft = await readEditor();
21
+ if (draft.draft === null) {
22
+ // Unreadable: record the shape, never the text we could not read (see describeEditorArea).
23
+ reportUnreadable?.(describeEditorArea(draft.screen, draft.cursor));
24
+ return { nativeMutation: false, reason: 'terminal_draft_conflict' };
25
+ }
26
+ if (draft.draft !== '' && draft.draft !== restoredPrompt()) {
31
27
  return { nativeMutation: false, reason: 'terminal_draft_conflict' };
32
28
  }
33
29
  if (guard && !await guard.validate())
34
30
  return { nativeMutation: false };
35
- if (draft) {
31
+ if (draft.draft) {
36
32
  await commands.sendKey(paneId, 'C-u');
37
33
  await delay(SUBMIT_GAP_MS);
38
- if (await readDraft() !== '')
34
+ const cleared = await readEditor();
35
+ if (cleared.draft !== '') {
36
+ if (cleared.draft === null)
37
+ reportUnreadable?.(describeEditorArea(cleared.screen, cleared.cursor));
39
38
  return { nativeMutation: false, reason: 'terminal_draft_conflict' };
39
+ }
40
40
  }
41
41
  await commands.sendText(paneId, text);
42
42
  if (text)
@@ -0,0 +1,100 @@
1
+ // The CodeBuddy Code agent adapter. Everything here is what Handmux knows that is SPECIFIC to CodeBuddy;
2
+ // the shared engine consumes this descriptor like any other provider.
3
+ //
4
+ // CodeBuddy is npm-first. `codebuddy`, `codebuddy-code` and `cbc` are symlinks onto one bin/codebuddy entry,
5
+ // so tmux only reports a stable name for the native build. In the documented npm layout the CLI runs INSIDE
6
+ // a Node process (`node /usr/local/bin/codebuddy` — verified live on 2.154.0), which makes three of the usual
7
+ // identity routes unusable:
8
+ // - `#{pane_current_command}` is a bare "node", so no exact command can ever own the pane;
9
+ // - the process's real executable (lsof/proc) is the Node binary, so executable-backed proof — the Claude
10
+ // and Codex route — cannot name CodeBuddy;
11
+ // - the Agent never spawns a native child binary, so the single-leaf foreground view, which deliberately
12
+ // prefers a non-launcher descendant for ambiguous launchers, can hand back a transient tool child
13
+ // (an npm/ruby update check) instead of the Agent itself.
14
+ // Identity therefore comes from the pane's whole foreground group, matched at a path boundary against the
15
+ // published launch entry points. We only ever answer "yes" from positive evidence, and we stay inconclusive
16
+ // rather than negative when the group was not actually read.
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ // The three entries the CodeBuddy CLI installs, plus the package that owns the npm layout.
20
+ const LAUNCH_NAMES = new Set(['codebuddy', 'codebuddy-code', 'cbc']);
21
+ const NPM_PACKAGE_MARKER = '/@tencent-ai/codebuddy-code/';
22
+ const NODE_PROGRAM_RE = /^(\S*\/)?node$/;
23
+ const basename = (value) => value.split('/').at(-1) ?? '';
24
+ // CodeBuddy's own on-disk layout, in one place because three readers need the same answer: the conversation
25
+ // adapter reads a session's JSONL, the native tail resolves a pane's session from its registry row, and the
26
+ // session binding reads the hook state file. A session log is
27
+ // `<projects>/<cwd with its slashes replaced by dashes>/<session-id>.jsonl`; a running session publishes
28
+ // `~/.codebuddy/sessions/<pid>.json` (pid, sessionId, cwd, heartbeat — never a status).
29
+ export const codebuddyProjectsDir = (home = os.homedir()) => path.join(home, '.codebuddy', 'projects');
30
+ export const codebuddySessionsDir = (home = os.homedir()) => path.join(home, '.codebuddy', 'sessions');
31
+ // Node's entry argument is the first non-flag token after the program. Nothing beyond it may be searched:
32
+ // the agent's own arguments (a prompt, a file path, a session id) are free to contain any word, and matching
33
+ // those would turn "some Node script that was passed the word codebuddy" into a false identity.
34
+ function nodeEntryArgument(rest) {
35
+ return rest.split(/\s+/).find((token) => token.length > 0 && !token.startsWith('-')) ?? '';
36
+ }
37
+ // Exported for the contract tests that freeze the accepted launch shapes.
38
+ export function isCodeBuddyCommandLine(value) {
39
+ const trimmed = value.trim();
40
+ if (!trimmed)
41
+ return false;
42
+ const segments = trimmed.split(/\s+/);
43
+ const program = (segments[0] ?? '').replace(/^-/, '');
44
+ // Native build: the launcher itself is the program token.
45
+ if (LAUNCH_NAMES.has(basename(program)))
46
+ return true;
47
+ // npm / Node launcher: `node <entry> …`. The entry must carry one of the published names AND sit in a
48
+ // recognised install layout — a bare `node codebuddy`, or an unrelated file that merely shares the name,
49
+ // is not proof.
50
+ if (!NODE_PROGRAM_RE.test(program))
51
+ return false;
52
+ const entry = nodeEntryArgument(segments.slice(1).join(' '));
53
+ if (!entry || !LAUNCH_NAMES.has(basename(entry)))
54
+ return false;
55
+ return entry.includes(NPM_PACKAGE_MARKER) || /(?:^|\/)(?:\.bin|bin)\//.test(entry);
56
+ }
57
+ // Returns the matched row rather than a bare `true`: that row is CodeBuddy's process, and the Runtime needs
58
+ // it as the lease anchor precisely because the pane's foreground leaf is NOT CodeBuddy. A row whose start time
59
+ // could not be resolved is still returned — the Runtime then declines to publish a lease until it can name a
60
+ // process generation, which is the same rule it applies to every other Agent.
61
+ export async function verifyCodeBuddyProcess(pane, context) {
62
+ const group = await context.inspectForegroundGroup?.(pane);
63
+ // A host that cannot supply the group cannot confirm a CodeBuddy pane (the single-leaf view may return a
64
+ // transient tool child), so CodeBuddy goes unidentified there. That is deliberately a plain `false` and not
65
+ // a thrown error: an inconclusive verdict is contagious — resolveAgentIdentity downgrades the WHOLE pane to
66
+ // `unknown` when any ambiguous candidate is unresolved, which would poison Codex/Pi on those hosts. Every
67
+ // production host builds its ProcessContext from createLocalAgentProcessContext, which does supply the group.
68
+ if (!group)
69
+ return false;
70
+ return group.find((entry) => isCodeBuddyCommandLine(entry.commandLine ?? '')) ?? false;
71
+ }
72
+ export const codebuddy = {
73
+ adapterApiVersion: 1,
74
+ id: 'codebuddy',
75
+ label: 'CodeBuddy',
76
+ process: {
77
+ commands: ['codebuddy', 'codebuddy-code', 'cbc'],
78
+ ambiguousCommands: ['node'],
79
+ // Process presence alone establishes the sessionless run. Beyond being the base every later capability
80
+ // builds on, this is what puts CodeBuddy on the pane roster the phone reads: the per-window Agent badge
81
+ // for windows you are NOT looking at comes from the Runtime's active runs (`/states`), not from pane
82
+ // identity — the pane you have selected is the only one resolved by `identifyPanes`.
83
+ runtimeAttach: true,
84
+ verify: verifyCodeBuddyProcess,
85
+ },
86
+ presentation: { iconId: 'codebuddy' },
87
+ // Only what is actually implemented. Inbox is delivered by CodeBuddy's Claude-compatible Hooks through
88
+ // its own Connector (connectors/codebuddy) + the Bridge durable lane; Conversation (with composer and
89
+ // interrupt, like Claude's) reads the session JSONL through ../../agents/codebuddyConversation.ts;
90
+ // Interaction reads the pending menu off the pane through ../../agents/codebuddyInteraction.ts — its
91
+ // question, review and permission screens were captured from a live 2.156.0 pane and all three parse with
92
+ // the shared parser, with the option digit as the key that drives them.
93
+ // The classification of its `src`→kind events lives in ../../codebuddyEvents.ts, next to the shared
94
+ // Hook vocabulary, because that is the module the Connector consumes.
95
+ capabilities: {
96
+ inbox: { apiVersion: 1 },
97
+ conversation: { apiVersion: 1, experimental: true },
98
+ interaction: { apiVersion: 1 },
99
+ },
100
+ };
@@ -0,0 +1,414 @@
1
+ // The CodeBuddy Conversation adapter: the binding between a CodeBuddy session's JSONL log and the shared
2
+ // conversation model. Everything generic is reused — the append-aware reader (transcriptReader), the item
3
+ // model and its safety clipping (conversationProjectionSafety), the pump/Core in agent-runtime/conversation
4
+ // — so this module answers only what is CodeBuddy's: where its logs live, how they parse, and what a
5
+ // delivery or an interrupt means for its pane.
6
+ //
7
+ // The shape mirrors Claude's adapter on purpose: same page/cursor semantics, same live-poll reconciliation
8
+ // (a CodeBuddy session writes its JSONL itself, so there is no push channel to subscribe to), same receipt
9
+ // vocabulary for a send. Two deliberate differences:
10
+ // - No diff is read from a structured patch: CodeBuddy logs no patch. Its Edit result DOES carry the
11
+ // provider's own `renderer: {type:'diff'}` plus the call's old/new strings, so a diff item is derived
12
+ // from those — a file RENDERED as a diff by the provider, never a guess about what changed.
13
+ // - No history reordering: CodeBuddy appends in display order (Claude needs an adjacency fix for its
14
+ // compaction scaffold), so the session id alone is the view epoch.
15
+ import { createHash } from 'node:crypto';
16
+ import { promises as fsp } from 'node:fs';
17
+ import path from 'node:path';
18
+ import { createCodeBuddyTranscriptParser } from './codebuddyTranscriptParse.js';
19
+ import { transcriptReader } from '../transcriptReader.js';
20
+ import { codebuddyProjectsDir } from './codebuddy.js';
21
+ import { isSessionUuid } from './scanUtils.js';
22
+ import { clipConversationText as clipped, safeProviderDiffPath, sanitizeToolInputWithMetadata, sanitizeToolResultText, } from './conversationProjectionSafety.js';
23
+ function isRun(target) {
24
+ return 'runId' in target;
25
+ }
26
+ function inside(root, candidate) {
27
+ const relative = path.relative(root, candidate);
28
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..'
29
+ && !path.isAbsolute(relative));
30
+ }
31
+ async function safeRoot(root) {
32
+ try {
33
+ const resolved = await fsp.realpath(root);
34
+ return (await fsp.stat(resolved)).isDirectory() ? resolved : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ async function safeBoundFile(root, sessionId, candidate) {
41
+ if (!path.isAbsolute(candidate) || path.basename(candidate) !== `${sessionId}.jsonl`)
42
+ return null;
43
+ const resolvedRoot = await safeRoot(root);
44
+ if (!resolvedRoot)
45
+ return null;
46
+ try {
47
+ const parent = await fsp.realpath(path.dirname(candidate));
48
+ if (!inside(resolvedRoot, parent))
49
+ return null;
50
+ try {
51
+ const resolvedFile = await fsp.realpath(candidate);
52
+ const stat = await fsp.stat(resolvedFile);
53
+ return stat.isFile() && inside(resolvedRoot, resolvedFile) ? resolvedFile : null;
54
+ }
55
+ catch {
56
+ // The session can be bound just before CodeBuddy creates its JSONL: the verified parent and the exact
57
+ // UUID filename still make this a safe empty history, and a later read picks the file up.
58
+ return path.join(parent, path.basename(candidate));
59
+ }
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ // CodeBuddy stores one session per encoded-cwd project directory, exactly like Claude. Discovery scans for
66
+ // the exact UUID filename and rejects ambiguity rather than guessing by cwd or mtime.
67
+ export async function findCodeBuddySessionFile(root, sessionId) {
68
+ if (!isSessionUuid(sessionId))
69
+ return null;
70
+ const resolvedRoot = await safeRoot(root);
71
+ if (!resolvedRoot)
72
+ return null;
73
+ let projects;
74
+ try {
75
+ projects = await fsp.readdir(resolvedRoot, { withFileTypes: true });
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ const matches = [];
81
+ for (const project of projects) {
82
+ if (!project.isDirectory() || project.isSymbolicLink())
83
+ continue;
84
+ const candidate = path.join(resolvedRoot, project.name, `${sessionId}.jsonl`);
85
+ try {
86
+ const resolved = await fsp.realpath(candidate);
87
+ if (inside(resolvedRoot, resolved) && (await fsp.stat(resolved)).isFile())
88
+ matches.push(resolved);
89
+ }
90
+ catch { /* not this project */ }
91
+ if (matches.length > 1)
92
+ return null;
93
+ }
94
+ return matches[0] ?? null;
95
+ }
96
+ function sourceViewId(sessionId) {
97
+ return `codebuddy-session:${sessionId}`;
98
+ }
99
+ function sourceTime(value) {
100
+ if (typeof value !== 'string')
101
+ return undefined;
102
+ const parsed = Date.parse(value);
103
+ return Number.isFinite(parsed) ? parsed : undefined;
104
+ }
105
+ function itemBase(message, sessionId, id) {
106
+ const createdAt = sourceTime(message.ts);
107
+ return {
108
+ id,
109
+ sessionId,
110
+ status: 'complete',
111
+ ...(createdAt === undefined ? {} : { sourceCreatedAt: createdAt }),
112
+ };
113
+ }
114
+ function textItem(message, sessionId, id, role, value) {
115
+ const output = clipped(value);
116
+ return {
117
+ ...itemBase(message, sessionId, id),
118
+ kind: 'message',
119
+ role,
120
+ content: [{ type: 'text', text: output.text }],
121
+ ...(output.truncated ? {
122
+ status: 'truncated',
123
+ truncation: { reason: 'size_limit', originalBytes: output.originalBytes },
124
+ } : {}),
125
+ };
126
+ }
127
+ // The call's own old/new strings, in the same +/- line shape Claude's structured patch produces, so the
128
+ // shared diff chip renders it without a provider-specific branch.
129
+ function derivedPatch(oldText, newText) {
130
+ const lines = [];
131
+ for (const line of oldText.split('\n'))
132
+ if (line)
133
+ lines.push(`-${line}`);
134
+ for (const line of newText.split('\n'))
135
+ if (line)
136
+ lines.push(`+${line}`);
137
+ return lines.join('\n');
138
+ }
139
+ function editedStrings(input) {
140
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
141
+ return null;
142
+ const fields = input;
143
+ const oldText = typeof fields.old_string === 'string' ? fields.old_string : null;
144
+ const newText = typeof fields.new_string === 'string' ? fields.new_string : null;
145
+ // Only a replacement carries both halves; a Write/create has content only, and inventing the "before"
146
+ // side of a new file would be a guess, so it stays a plain tool call.
147
+ if (oldText === null || newText === null)
148
+ return null;
149
+ return { oldText, newText };
150
+ }
151
+ function toolItems(message, sessionId, id, tool) {
152
+ const callId = `${id}:call`;
153
+ const name = clipped(tool.name || 'tool', 512).text || 'tool';
154
+ const inputProjection = sanitizeToolInputWithMetadata(tool.input);
155
+ const input = inputProjection.value;
156
+ const items = [{
157
+ ...itemBase(message, sessionId, callId),
158
+ kind: 'tool_call',
159
+ callId,
160
+ name,
161
+ ...(input === undefined ? {} : { input }),
162
+ ...(inputProjection.truncated ? {
163
+ status: 'truncated',
164
+ truncation: { reason: 'size_limit', originalBytes: inputProjection.originalBytes },
165
+ } : {}),
166
+ }];
167
+ if (tool.result !== null && tool.result.length > 0) {
168
+ const output = sanitizeToolResultText(tool.result);
169
+ items.push({
170
+ ...itemBase(message, sessionId, `${id}:result`),
171
+ kind: 'tool_result',
172
+ callId,
173
+ content: [{ type: 'text', text: output.text }],
174
+ ...(tool.isError ? { isError: true } : {}),
175
+ ...(output.truncated ? {
176
+ status: 'truncated',
177
+ truncation: { reason: 'size_limit', originalBytes: output.originalBytes },
178
+ } : {}),
179
+ });
180
+ }
181
+ const edited = editedStrings(tool.input);
182
+ if (edited && !tool.isError) {
183
+ const rawPath = tool.input.file_path;
184
+ const providerPath = safeProviderDiffPath(rawPath);
185
+ const patch = sanitizeToolResultText(derivedPatch(edited.oldText, edited.newText));
186
+ const removed = edited.oldText.split('\n').filter((line) => line).length;
187
+ const added = edited.newText.split('\n').filter((line) => line).length;
188
+ items.push({
189
+ ...itemBase(message, sessionId, `${id}:diff`),
190
+ kind: 'diff',
191
+ ...(providerPath === undefined ? {} : { path: providerPath }),
192
+ ...(patch.text ? { patch: patch.text } : {}),
193
+ summary: `+${added} -${removed}`,
194
+ ...(patch.truncated ? {
195
+ status: 'truncated',
196
+ truncation: { reason: 'size_limit', originalBytes: patch.originalBytes },
197
+ } : {}),
198
+ });
199
+ }
200
+ return items;
201
+ }
202
+ function projectMessage(message, sessionId, ordinal) {
203
+ const id = `codebuddy:${message.i}:${ordinal}:${message.type}`;
204
+ // The parser keeps a public reasoning projection, but the shared model has no place to show it (Claude's
205
+ // adapter drops thinking for the same reason), so it never becomes an item.
206
+ if (message.type === 'thinking')
207
+ return [];
208
+ if (message.type === 'text' && message.role && typeof message.text === 'string' && message.text) {
209
+ return [textItem(message, sessionId, id, message.role, message.text)];
210
+ }
211
+ if (message.type === 'tool' && message.tool)
212
+ return toolItems(message, sessionId, id, message.tool);
213
+ if (message.type === 'compact') {
214
+ const summary = typeof message.summary === 'string' && message.summary
215
+ ? clipped(message.summary) : null;
216
+ const truncated = message.summaryTruncated === true || summary?.truncated === true;
217
+ const originalBytes = typeof message.summaryOriginalBytes === 'number'
218
+ ? message.summaryOriginalBytes : summary?.originalBytes;
219
+ return [{
220
+ ...itemBase(message, sessionId, id), kind: 'compaction',
221
+ ...(summary ? { summary: summary.text } : {}),
222
+ ...(truncated ? {
223
+ status: 'truncated',
224
+ truncation: { reason: 'size_limit', originalBytes: originalBytes ?? 0 },
225
+ } : {}),
226
+ }];
227
+ }
228
+ if (message.type === 'slash') {
229
+ const command = `${message.name ?? '/command'}${message.args ? ` ${message.args}` : ''}`;
230
+ // /compact begins as the user's own message: keeping that role lets the Core replace the optimistic
231
+ // local bubble with the canonical occurrence, exactly as Claude's adapter does.
232
+ if (message.name?.toLowerCase() === '/compact') {
233
+ return [textItem(message, sessionId, id, 'user', command)];
234
+ }
235
+ return [{
236
+ ...itemBase(message, sessionId, id), kind: 'notice', level: 'info',
237
+ code: 'slash_command', message: clipped(command, 4096).text,
238
+ }];
239
+ }
240
+ return [];
241
+ }
242
+ export function createCodeBuddyConversationAdapter({ projectsRoot = codebuddyProjectsDir(), sessions = null, reader = transcriptReader, findSessionFile = findCodeBuddySessionFile, control, livePollMs = 750, } = {}) {
243
+ if (!path.isAbsolute(projectsRoot)) {
244
+ throw new TypeError('CodeBuddy Conversation adapter requires an absolute projects root');
245
+ }
246
+ if (!Number.isFinite(livePollMs) || livePollMs <= 0) {
247
+ throw new TypeError('CodeBuddy Conversation adapter requires a positive live poll interval');
248
+ }
249
+ const boundFiles = new Map();
250
+ async function fileForSession(sessionId) {
251
+ const bound = boundFiles.get(sessionId);
252
+ if (bound)
253
+ return bound;
254
+ return findSessionFile(projectsRoot, sessionId);
255
+ }
256
+ async function discoverFile(target) {
257
+ if (!isSessionUuid(target.sessionId))
258
+ return null;
259
+ if (!isRun(target))
260
+ return fileForSession(target.sessionId);
261
+ const binding = sessions?.paneSession(target.paneId);
262
+ if (!binding || (binding.agent !== undefined && binding.agent !== null && binding.agent !== 'codebuddy')) {
263
+ return null;
264
+ }
265
+ const bindingId = binding.sessionId
266
+ ?? (binding.transcriptPath ? path.basename(binding.transcriptPath, '.jsonl') : null);
267
+ if (bindingId !== target.sessionId)
268
+ return null;
269
+ if (!binding.transcriptPath)
270
+ return fileForSession(target.sessionId);
271
+ const file = await safeBoundFile(projectsRoot, target.sessionId, binding.transcriptPath);
272
+ if (file)
273
+ boundFiles.set(target.sessionId, file);
274
+ return file;
275
+ }
276
+ function project(messages, sessionId) {
277
+ return messages.flatMap((message, ordinal) => projectMessage(message, sessionId, ordinal));
278
+ }
279
+ async function readPage(session, request) {
280
+ const file = await fileForSession(session.sessionId);
281
+ const parsed = file ? await reader.read(file, createCodeBuddyTranscriptParser) : [];
282
+ const all = project(parsed, session.sessionId);
283
+ let end = all.length;
284
+ if (request.beforeSourceCursor !== undefined) {
285
+ if (!/^\d+$/.test(request.beforeSourceCursor))
286
+ throw new Error('Invalid CodeBuddy source cursor');
287
+ const cursor = Number(request.beforeSourceCursor);
288
+ if (!Number.isSafeInteger(cursor))
289
+ throw new Error('Invalid CodeBuddy source cursor');
290
+ end = Math.min(cursor, all.length);
291
+ }
292
+ const start = Math.max(0, end - request.limit);
293
+ return {
294
+ sessionId: session.sessionId,
295
+ sourceViewId: sourceViewId(session.sessionId),
296
+ sourceHistoryToken: createHash('sha256').update(JSON.stringify(all)).digest('hex'),
297
+ items: all.slice(start, end),
298
+ ...(start > 0 ? { previousSourceCursor: String(start) } : {}),
299
+ hasMore: start > 0,
300
+ };
301
+ }
302
+ return {
303
+ apiVersion: 1,
304
+ async discoverNative(target) {
305
+ if (target.agentId !== 'codebuddy' || !target.sessionId)
306
+ return null;
307
+ const file = await discoverFile(target);
308
+ if (!file)
309
+ return null;
310
+ boundFiles.set(target.sessionId, file);
311
+ return {
312
+ session: { agentId: 'codebuddy', sessionId: target.sessionId },
313
+ ...(isRun(target) ? { run: target } : {}),
314
+ sourceViewId: sourceViewId(target.sessionId),
315
+ capabilities: isRun(target) && control ? {
316
+ history: true, live: 'settled', sendable: true, send: ['prompt'], interrupt: true,
317
+ // Verified live on 2.156.0: a prompt typed while a tool is running is accepted by the editor and
318
+ // the TUI reports "Messages to be submitted after next tool call", then submits it into the same
319
+ // turn. So an ordinary send does not have to wait for idle.
320
+ promptWhileActive: true,
321
+ } : { history: true, live: 'poll' },
322
+ };
323
+ },
324
+ readNativePage: readPage,
325
+ ...(control ? {
326
+ async observeNative(run, sink) {
327
+ const sessionId = run.ref.sessionId;
328
+ if (!sessionId)
329
+ throw new Error('CodeBuddy Conversation run has no session');
330
+ const session = { agentId: 'codebuddy', sessionId };
331
+ const baseline = await readPage(session, { limit: 1 });
332
+ let sourceSequence = 0;
333
+ let historyToken = baseline.sourceHistoryToken;
334
+ let closed = false;
335
+ let timer;
336
+ let tail = Promise.resolve();
337
+ const close = () => {
338
+ closed = true;
339
+ if (timer)
340
+ clearTimeout(timer);
341
+ timer = undefined;
342
+ };
343
+ const schedule = () => {
344
+ if (closed || run.signal.aborted)
345
+ return;
346
+ timer = setTimeout(() => {
347
+ tail = tail.then(async () => {
348
+ if (closed || run.signal.aborted)
349
+ return;
350
+ const next = await readPage(session, { limit: 1 });
351
+ if (next.sourceViewId !== baseline.sourceViewId) {
352
+ close();
353
+ await sink({
354
+ type: 'stream.gap', sourceSequence: ++sourceSequence,
355
+ afterSourceSequence: sourceSequence - 1,
356
+ });
357
+ return;
358
+ }
359
+ if (next.sourceHistoryToken !== historyToken) {
360
+ historyToken = next.sourceHistoryToken;
361
+ await sink({
362
+ type: 'history.committed',
363
+ sourceSequence: ++sourceSequence,
364
+ sourceViewId: next.sourceViewId,
365
+ sourceHistoryToken: next.sourceHistoryToken,
366
+ });
367
+ }
368
+ }).catch(async () => {
369
+ if (closed || run.signal.aborted)
370
+ return;
371
+ await Promise.resolve(sink({
372
+ type: 'stream.gap', sourceSequence: ++sourceSequence,
373
+ afterSourceSequence: Math.max(0, sourceSequence - 1),
374
+ })).catch(close);
375
+ }).finally(schedule);
376
+ }, livePollMs);
377
+ timer.unref?.();
378
+ };
379
+ const onAbort = () => close();
380
+ run.signal.addEventListener('abort', onAbort, { once: true });
381
+ schedule();
382
+ return {
383
+ checkpoint: { sourceViewId: baseline.sourceViewId, sourceSequence },
384
+ close() {
385
+ run.signal.removeEventListener('abort', onAbort);
386
+ close();
387
+ },
388
+ };
389
+ },
390
+ async dispatchPrompt(run, request, guard) {
391
+ try {
392
+ const result = await (guard
393
+ ? control.sendPrompt(run.ref.paneId, request.text, guard)
394
+ : control.sendPrompt(run.ref.paneId, request.text));
395
+ if (result && typeof result === 'object'
396
+ && result.nativeMutation === false) {
397
+ if (result.reason === 'terminal_draft_conflict') {
398
+ return { outcome: 'rejected', nativeMutation: false, reason: 'terminal_draft_conflict' };
399
+ }
400
+ return { outcome: 'busy', nativeMutation: false };
401
+ }
402
+ return { outcome: 'accepted' };
403
+ }
404
+ catch {
405
+ return { outcome: 'unknown', nativeMutation: 'unknown', reason: 'delivery_unconfirmed' };
406
+ }
407
+ },
408
+ async dispatchInterrupt(run) {
409
+ await control.interrupt(run.ref.paneId);
410
+ return { status: 'accepted' };
411
+ },
412
+ } : {}),
413
+ };
414
+ }
@@ -0,0 +1,4 @@
1
+ import { createHookInteractionAdapter } from './hookInteraction.js';
2
+ export function createCodeBuddyInteractionAdapter(control, pollMs = 750, reportHealth = () => { }) {
3
+ return createHookInteractionAdapter(control, { id: 'codebuddy', label: 'CodeBuddy' }, pollMs, reportHealth);
4
+ }