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.
- package/dist/connectors/claude/index.js +33 -562
- package/dist/connectors/codebuddy/index.js +49 -0
- package/dist/connectors/hookBridge.js +560 -0
- package/dist/hooks/handmux-codebuddy-notify.sh +116 -0
- package/dist/hooks/handmux-notify.sh +2 -0
- package/dist/hooks/handmux-write.cjs +72 -5
- package/dist/package.json +7 -7
- package/dist/public/assets/{abnfDiagram-O67JEVCF-CmVVGJqt.js → abnfDiagram-O67JEVCF-BsRDIQEB.js} +1 -1
- package/dist/public/assets/{arc-aYtCI03A.js → arc-DLtLfMnX.js} +1 -1
- package/dist/public/assets/{architectureDiagram-NJMV4G6O-CyZZDTaL.js → architectureDiagram-NJMV4G6O-DoIXhWqZ.js} +1 -1
- package/dist/public/assets/{blockDiagram-BEXU5L5S-D_ODtFS0.js → blockDiagram-BEXU5L5S-W0HiOcVA.js} +1 -1
- package/dist/public/assets/{c4Diagram-YGBWAQC7-C8qZFFmC.js → c4Diagram-YGBWAQC7-72uAUMvX.js} +1 -1
- package/dist/public/assets/channel-CzALSnb0.js +1 -0
- package/dist/public/assets/{chunk-2Q5K7J3B-Bo85fSxI.js → chunk-2Q5K7J3B-B9wSRFQ0.js} +1 -1
- package/dist/public/assets/{chunk-3FUC2YCW-BnET3fKr.js → chunk-3FUC2YCW-ryphp4s0.js} +2 -2
- package/dist/public/assets/{chunk-5VM5RSS4-DDw_KNv1.js → chunk-5VM5RSS4-Cm4KeKby.js} +1 -1
- package/dist/public/assets/{chunk-GTNCS2PH-B_K2164R.js → chunk-GTNCS2PH-Du4_i7r3.js} +1 -1
- package/dist/public/assets/{chunk-GWA4HPMP-1GA2Su8A.js → chunk-GWA4HPMP-CL1biVIA.js} +1 -1
- package/dist/public/assets/{chunk-JWPE2WC7-Cfc-8kSE.js → chunk-JWPE2WC7-B8eAVfuB.js} +1 -1
- package/dist/public/assets/{chunk-NETBCI7D-C7zyDFCq.js → chunk-NETBCI7D-D273GzYg.js} +1 -1
- package/dist/public/assets/{chunk-WEXAMYUT-BI2Zijn_.js → chunk-WEXAMYUT-DipTfRbc.js} +1 -1
- package/dist/public/assets/{chunk-XXDRQBXY-Bl50fDL9.js → chunk-XXDRQBXY-D4SqXrQ8.js} +1 -1
- package/dist/public/assets/{classDiagram-v2-NBCMYWYE-BMWMChZ4.js → classDiagram-v2-NBCMYWYE-PrpnIXcA.js} +1 -1
- package/dist/public/assets/{cose-bilkent-JH36ORCC-B_HUrBN4.js → cose-bilkent-JH36ORCC-BfcYMYTa.js} +1 -1
- package/dist/public/assets/{cynefin-OW5HDTMX-2jTRe-JA.js → cynefin-OW5HDTMX-Du659bmz.js} +1 -1
- package/dist/public/assets/{cynefinDiagram-VND7K2PF-ClDtZNOK.js → cynefinDiagram-VND7K2PF-DR_2Copy.js} +1 -1
- package/dist/public/assets/{dagre-6A5THRUB-CJS3bbcm.js → dagre-6A5THRUB-COsChaV5.js} +1 -1
- package/dist/public/assets/{diagram-22UHCM2B-BpRgaKhU.js → diagram-22UHCM2B-Cx2T1HvL.js} +1 -1
- package/dist/public/assets/{diagram-3UASUU5V-BNwvXb9K.js → diagram-3UASUU5V-Cp04LOka.js} +1 -1
- package/dist/public/assets/{diagram-ATOU4E4O-DyphKhOl.js → diagram-ATOU4E4O-DlqFSshY.js} +1 -1
- package/dist/public/assets/{diagram-CDSNMT55-BRazAxS2.js → diagram-CDSNMT55-goq40ctA.js} +1 -1
- package/dist/public/assets/{diagram-MLGK6HIB-NN_P6wZp.js → diagram-MLGK6HIB-Bdzjsy4r.js} +1 -1
- package/dist/public/assets/{diagram-MPIPVDR6-DHBe5DA4.js → diagram-MPIPVDR6-DtU7cM6P.js} +1 -1
- package/dist/public/assets/{ebnfDiagram-ZINNZB2B-BCTHXp7J.js → ebnfDiagram-ZINNZB2B-XyVCfmED.js} +1 -1
- package/dist/public/assets/{elk-276RUBZZ-yXNwrgXQ.js → elk-276RUBZZ-aHVIw-2x.js} +1 -1
- package/dist/public/assets/{erDiagram-OPXOYQCR-YsAJcCqg.js → erDiagram-OPXOYQCR-Bq_PhTIL.js} +1 -1
- package/dist/public/assets/{flowDiagram-KWPJA3E3-CyX8qF-3.js → flowDiagram-KWPJA3E3-WuqnDSiF.js} +1 -1
- package/dist/public/assets/{ganttDiagram-FUAMR5RP-BMFOvdDK.js → ganttDiagram-FUAMR5RP-DZ4lXzkC.js} +1 -1
- package/dist/public/assets/{gitGraphDiagram-X574FWY7-D1sZiiWD.js → gitGraphDiagram-X574FWY7-t6l07b9g.js} +1 -1
- package/dist/public/assets/index-DiYff8oR.css +32 -0
- package/dist/public/assets/index-YZNK723o.js +203 -0
- package/dist/public/assets/{infoDiagram-VRGFBTTK-CiayIr0f.js → infoDiagram-VRGFBTTK-iUGqoOFp.js} +1 -1
- package/dist/public/assets/{ishikawaDiagram-OU5B5YK6-Bf4mzvKk.js → ishikawaDiagram-OU5B5YK6-B0TmoUOK.js} +1 -1
- package/dist/public/assets/{journeyDiagram-ZHPQQLJL-mvwzOMZ7.js → journeyDiagram-ZHPQQLJL-CQE61MCu.js} +1 -1
- package/dist/public/assets/{kanban-definition-PNTS6WVX-CMFYAtvx.js → kanban-definition-PNTS6WVX-D2MWCUyS.js} +1 -1
- package/dist/public/assets/{linear-BcK1QK3e.js → linear-WKGxVNP1.js} +1 -1
- package/dist/public/assets/{mermaid.core-BmCR7le1.js → mermaid.core-DPEwUsaj.js} +4 -4
- package/dist/public/assets/{mindmap-definition-NLK3R4M7-hvUFWkg7.js → mindmap-definition-NLK3R4M7-DsYEsBsI.js} +1 -1
- package/dist/public/assets/{pegDiagram-GJSIUBJH-B8FGnth6.js → pegDiagram-GJSIUBJH-BS52Fbxt.js} +1 -1
- package/dist/public/assets/{pieDiagram-5QR66LMP-BdhppGvz.js → pieDiagram-5QR66LMP-D4o8g7nW.js} +1 -1
- package/dist/public/assets/{quadrantDiagram-O4NWA36T-i6XjZJ8W.js → quadrantDiagram-O4NWA36T-DnYUxWll.js} +1 -1
- package/dist/public/assets/{railroadDiagram-XR7U4H2S-C7XoA5kk.js → railroadDiagram-XR7U4H2S-BKy_7ULV.js} +1 -1
- package/dist/public/assets/{requirementDiagram-PLB6GJNP-tq6onssc.js → requirementDiagram-PLB6GJNP-Ce5F4u8K.js} +1 -1
- package/dist/public/assets/{sankeyDiagram-IPEJSGJF-DRW13BH8.js → sankeyDiagram-IPEJSGJF-CCJDrut_.js} +1 -1
- package/dist/public/assets/{sequenceDiagram-PO4LG4MO-BJqhIpnw.js → sequenceDiagram-PO4LG4MO-D5E8ISM1.js} +1 -1
- package/dist/public/assets/{sizeCapture-INFHLROL-BCpyNpYK.js → sizeCapture-INFHLROL-BW3KmxDN.js} +1 -1
- package/dist/public/assets/{stateDiagram-v2-GCMORJYK-Da3aSdeG.js → stateDiagram-v2-GCMORJYK-Bw2ZzQOE.js} +1 -1
- package/dist/public/assets/{swimlanes-2SLR337P-oT62nN2e.js → swimlanes-2SLR337P-CLJ-6Ex_.js} +1 -1
- package/dist/public/assets/swimlanesDiagram-TC7HE7FX-BD8rQfV7.js +8 -0
- package/dist/public/assets/{timeline-definition-EJHVYXUP-CQ9Q15bt.js → timeline-definition-EJHVYXUP-C_lFJ-4W.js} +1 -1
- package/dist/public/assets/{usecaseDiagram-POWQR4AR-De1gJb8v.js → usecaseDiagram-POWQR4AR-DWXawL2A.js} +1 -1
- package/dist/public/assets/{vennDiagram-UO4OBE2U-BusPyTiq.js → vennDiagram-UO4OBE2U-D4O5oZal.js} +1 -1
- package/dist/public/assets/{wardleyDiagram-VNRHLVJA-D-vaN_gJ.js → wardleyDiagram-VNRHLVJA-B6HElk__.js} +1 -1
- package/dist/public/assets/{xychartDiagram-PMCCYNJV-BcOmOj-j.js → xychartDiagram-PMCCYNJV-C5OAXnJy.js} +1 -1
- package/dist/public/index.html +2 -2
- package/dist/src/agent-runtime/adapter.js +54 -10
- package/dist/src/agent-runtime/builtinRuntime.js +67 -6
- package/dist/src/agent-runtime/conversation.js +49 -9
- package/dist/src/agent-runtime/interaction.js +26 -12
- package/dist/src/agent-runtime/interactionLiveHub.js +4 -0
- package/dist/src/agent-runtime/runtime.js +83 -27
- package/dist/src/agent-runtime/tmuxRuntime.js +36 -6
- package/dist/src/agents/claude.js +2 -19
- package/dist/src/agents/claudeInteraction.js +2 -132
- package/dist/src/agents/claudePaneInput.js +22 -22
- package/dist/src/agents/codebuddy.js +100 -0
- package/dist/src/agents/codebuddyConversation.js +414 -0
- package/dist/src/agents/codebuddyInteraction.js +4 -0
- package/dist/src/agents/codebuddyNativeTail.js +206 -0
- package/dist/src/agents/codebuddyPaneInput.js +76 -0
- package/dist/src/agents/codebuddyTranscriptParse.js +178 -0
- package/dist/src/agents/hookEvents.js +143 -0
- package/dist/src/agents/hookInteraction.js +178 -0
- package/dist/src/agents/index.js +2 -1
- package/dist/src/claudeEvents.js +4 -5
- package/dist/src/cli/agentIntegration.js +31 -2
- package/dist/src/cli/codebuddyHooks.js +286 -0
- package/dist/src/cli/hookScaffold.js +25 -12
- package/dist/src/cli/i18n/en.js +1 -1
- package/dist/src/cli/i18n/zh.js +1 -1
- package/dist/src/cli/state.js +4 -0
- package/dist/src/cli/supervisor.js +2 -1
- package/dist/src/codebuddyEvents.js +151 -0
- package/dist/src/docs.js +17 -6
- package/dist/src/logDetail.js +27 -0
- package/dist/src/paneInput.js +107 -10
- package/dist/src/pendingPrompt.js +21 -5
- package/dist/src/routes/system.js +12 -2
- package/dist/src/server.js +69 -8
- package/dist/src/workspace/checkpointer.js +48 -4
- package/dist/src/workspace/lock.js +54 -10
- package/dist/src/workspace/runtime.js +23 -8
- package/dist/src/workspaceProtocol.js +1 -0
- package/package.json +3 -3
- package/dist/public/assets/channel-kkiOw5AC.js +0 -1
- package/dist/public/assets/index-DqCUBYR8.css +0 -32
- package/dist/public/assets/index-OW7snGiD.js +0 -362
- package/dist/public/assets/swimlanesDiagram-TC7HE7FX-YHG5AQi4.js +0 -8
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// The CodeBuddy out-of-band reconciliation. CodeBuddy fires NO Hook when the user answers a
|
|
2
|
+
// PermissionRequest, so an answered pane keeps its 需要你 gate lit until whatever Hook comes next — for a
|
|
3
|
+
// tool outside the PostToolUse matcher, until the turn ends. Claude closes the same gap from its own session
|
|
4
|
+
// registry (`status: idle|busy|waiting`, which flips back to busy the moment the user answers). CodeBuddy
|
|
5
|
+
// keeps no such status anywhere readable: its registry file carries only a heartbeat, its per-session local
|
|
6
|
+
// HTTP endpoint exposes no session state, and its live event channel is a Centrifugo WebSocket. The one
|
|
7
|
+
// artifact that does move is the session transcript, where the granted tool lands its result record.
|
|
8
|
+
//
|
|
9
|
+
// The verdict is deliberately one-sided: a result record strictly newer than the gate proves the pane's tool
|
|
10
|
+
// ran after the user answered, so the gate is over. Everything else — no transcript, an unparsable file, a
|
|
11
|
+
// result older than the gate, a row that is not a gate, or a tail that happens to hold no result at all —
|
|
12
|
+
// says nothing, leaving the Hook's own state exactly as it was.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { codebuddyProjectsDir, codebuddySessionsDir } from './codebuddy.js';
|
|
17
|
+
const record = (value) => (value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null);
|
|
18
|
+
// A transcript is append-only and a result is written when it happens, so the newest one is always in the
|
|
19
|
+
// last chunk. A chunk with no result at all (a very large tool output ahead of it) closes nothing.
|
|
20
|
+
const MAX_TAIL_BYTES = 262_144;
|
|
21
|
+
const MAX_CACHED_TRANSCRIPTS = 64;
|
|
22
|
+
// The rows that can latch a gate. Only they are worth reading a transcript for, which keeps this reader at
|
|
23
|
+
// zero cost on a pane that is simply working.
|
|
24
|
+
function isGateRow(src, payload) {
|
|
25
|
+
return src === 'permreq'
|
|
26
|
+
|| (src === 'notify' && payload.notification_type === 'permission_prompt');
|
|
27
|
+
}
|
|
28
|
+
// The transcript for a gate row. Three AUTHORITATIVE names, in order — never a guess: a path the Hook
|
|
29
|
+
// carried, the session id the Hook carried, then the pid's own registry row. The registry one matters
|
|
30
|
+
// because a Notification payload carries neither a session id nor a transcript path (measured) and it is
|
|
31
|
+
// the row a gate is often latched from; the session-id one matters because a registry row can be stale
|
|
32
|
+
// (observed: a resumed session keeps the pid file's older id), which would otherwise leave the gate unclosed
|
|
33
|
+
// on a pane whose Hook did name its session.
|
|
34
|
+
function transcriptFor(payload, pid, home, locate) {
|
|
35
|
+
const explicit = payload.transcript_path;
|
|
36
|
+
if (typeof explicit === 'string' && path.isAbsolute(explicit)
|
|
37
|
+
&& path.basename(explicit).endsWith('.jsonl'))
|
|
38
|
+
return explicit;
|
|
39
|
+
const projects = codebuddyProjectsDir(home);
|
|
40
|
+
const payloadSession = payload.session_id;
|
|
41
|
+
if (typeof payloadSession === 'string' && payloadSession) {
|
|
42
|
+
const found = locate(projects, payloadSession);
|
|
43
|
+
if (found)
|
|
44
|
+
return found;
|
|
45
|
+
}
|
|
46
|
+
if (!Number.isSafeInteger(pid) || Number(pid) <= 0)
|
|
47
|
+
return null;
|
|
48
|
+
let registry = null;
|
|
49
|
+
try {
|
|
50
|
+
registry = record(JSON.parse(fs.readFileSync(path.join(codebuddySessionsDir(home), `${Number(pid)}.json`), 'utf8')));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const sessionId = registry?.sessionId;
|
|
56
|
+
const cwd = registry?.cwd;
|
|
57
|
+
if (typeof sessionId !== 'string' || !sessionId)
|
|
58
|
+
return null;
|
|
59
|
+
// CodeBuddy names a project directory after the cwd with the separating slashes replaced by dashes
|
|
60
|
+
// (verified: /home/user/x → Users-admin-x, /private/tmp/cb-sim → private-tmp-cb-sim). It is only a
|
|
61
|
+
// shortcut past the scan — the session UUID is what actually names the file, so a miss costs nothing.
|
|
62
|
+
if (typeof cwd === 'string' && cwd) {
|
|
63
|
+
const direct = path.join(projects, cwd.replace(/^\//, '').replace(/\//g, '-'), `${sessionId}.jsonl`);
|
|
64
|
+
try {
|
|
65
|
+
if (fs.statSync(direct).isFile())
|
|
66
|
+
return direct;
|
|
67
|
+
}
|
|
68
|
+
catch { /* scan below */ }
|
|
69
|
+
}
|
|
70
|
+
return locate(projects, sessionId);
|
|
71
|
+
}
|
|
72
|
+
// The newest tool result timestamp in the transcript's tail, or null when the tail holds none.
|
|
73
|
+
function newestResultAt(file) {
|
|
74
|
+
let descriptor = null;
|
|
75
|
+
try {
|
|
76
|
+
const stat = fs.statSync(file);
|
|
77
|
+
if (!stat.isFile() || stat.size === 0)
|
|
78
|
+
return null;
|
|
79
|
+
const length = Math.min(stat.size, MAX_TAIL_BYTES);
|
|
80
|
+
descriptor = fs.openSync(file, 'r');
|
|
81
|
+
const buffer = Buffer.alloc(length);
|
|
82
|
+
fs.readSync(descriptor, buffer, 0, length, stat.size - length);
|
|
83
|
+
const lines = buffer.toString('utf8').split('\n');
|
|
84
|
+
// A read that started mid-file begins with a fragment of a line: it cannot parse, but drop it anyway so
|
|
85
|
+
// a truncated record can never be mistaken for one.
|
|
86
|
+
if (stat.size > length)
|
|
87
|
+
lines.shift();
|
|
88
|
+
let newest = null;
|
|
89
|
+
for (const line of lines) {
|
|
90
|
+
const trimmed = line.trim();
|
|
91
|
+
if (!trimmed)
|
|
92
|
+
continue;
|
|
93
|
+
let row = null;
|
|
94
|
+
try {
|
|
95
|
+
row = record(JSON.parse(trimmed));
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
continue;
|
|
99
|
+
} // a half-written last line
|
|
100
|
+
if (!row || row.type !== 'function_call_result')
|
|
101
|
+
continue;
|
|
102
|
+
const timestamp = row.timestamp;
|
|
103
|
+
if (typeof timestamp !== 'number' || !Number.isFinite(timestamp))
|
|
104
|
+
continue;
|
|
105
|
+
if (newest === null || timestamp > newest)
|
|
106
|
+
newest = timestamp;
|
|
107
|
+
}
|
|
108
|
+
return newest;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
if (descriptor !== null) {
|
|
115
|
+
try {
|
|
116
|
+
fs.closeSync(descriptor);
|
|
117
|
+
}
|
|
118
|
+
catch { /* already closed */ }
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
export class CodeBuddyNativeTailReader {
|
|
123
|
+
#home;
|
|
124
|
+
// Keyed by transcript file and bounded: an unchanged file costs one `stat`, and the gate rows that get
|
|
125
|
+
// here are few. `retain` is deliberately a no-op — the cache is not keyed by session, and the rows that
|
|
126
|
+
// need it (a gate latched from a Notification) carry no session id to retain it by.
|
|
127
|
+
#tails = new Map();
|
|
128
|
+
// Memoized `<sessionId>.jsonl` lookups: a session's path never moves, and the walk only ever runs for a
|
|
129
|
+
// session a gate actually named.
|
|
130
|
+
#paths = new Map();
|
|
131
|
+
constructor({ home = os.homedir() } = {}) {
|
|
132
|
+
this.#home = home;
|
|
133
|
+
}
|
|
134
|
+
read(payload, after, now, process, src) {
|
|
135
|
+
const body = record(payload) ?? {};
|
|
136
|
+
if (!isGateRow(String(src ?? ''), body))
|
|
137
|
+
return {};
|
|
138
|
+
const file = transcriptFor(body, process?.pid, this.#home, (projects, sessionId) => this.#locate(projects, sessionId));
|
|
139
|
+
if (!file)
|
|
140
|
+
return {};
|
|
141
|
+
const at = this.#resultAt(file);
|
|
142
|
+
// Strictly after the gate, and never in the future: a result from before the request cannot close it,
|
|
143
|
+
// and a clock that ran away must not either.
|
|
144
|
+
if (at === null || at <= after || at > now)
|
|
145
|
+
return {};
|
|
146
|
+
const sessionId = typeof body.session_id === 'string' ? body.session_id : '';
|
|
147
|
+
return {
|
|
148
|
+
status: 'busy',
|
|
149
|
+
statusEventId: `codebuddy-native:${sessionId}:${process?.pid ?? 0}:${at}`,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
retain() { }
|
|
153
|
+
clear() {
|
|
154
|
+
this.#tails.clear();
|
|
155
|
+
this.#paths.clear();
|
|
156
|
+
}
|
|
157
|
+
#locate(projects, sessionId) {
|
|
158
|
+
const key = `${projects}\0${sessionId}`;
|
|
159
|
+
const cached = this.#paths.get(key);
|
|
160
|
+
if (cached !== undefined)
|
|
161
|
+
return cached;
|
|
162
|
+
let found = null;
|
|
163
|
+
try {
|
|
164
|
+
for (const entry of fs.readdirSync(projects)) {
|
|
165
|
+
const candidate = path.join(projects, entry, `${sessionId}.jsonl`);
|
|
166
|
+
try {
|
|
167
|
+
if (fs.statSync(candidate).isFile()) {
|
|
168
|
+
found = candidate;
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch { /* next entry */ }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
catch { /* no projects directory */ }
|
|
176
|
+
this.#paths.delete(key);
|
|
177
|
+
this.#paths.set(key, found);
|
|
178
|
+
if (this.#paths.size > MAX_CACHED_TRANSCRIPTS) {
|
|
179
|
+
this.#paths.delete(this.#paths.keys().next().value);
|
|
180
|
+
}
|
|
181
|
+
return found;
|
|
182
|
+
}
|
|
183
|
+
#resultAt(file) {
|
|
184
|
+
let fingerprint;
|
|
185
|
+
try {
|
|
186
|
+
const stat = fs.statSync(file);
|
|
187
|
+
if (!stat.isFile())
|
|
188
|
+
return null;
|
|
189
|
+
fingerprint = [stat.dev, stat.ino, stat.size, stat.mtimeMs].join(':');
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
this.#tails.delete(file);
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
const cached = this.#tails.get(file);
|
|
196
|
+
if (cached?.fingerprint === fingerprint)
|
|
197
|
+
return cached.at;
|
|
198
|
+
const at = newestResultAt(file);
|
|
199
|
+
this.#tails.delete(file);
|
|
200
|
+
this.#tails.set(file, { fingerprint, at });
|
|
201
|
+
if (this.#tails.size > MAX_CACHED_TRANSCRIPTS) {
|
|
202
|
+
this.#tails.delete(this.#tails.keys().next().value);
|
|
203
|
+
}
|
|
204
|
+
return at;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// CodeBuddy's pane input: the delivery and interrupt semantics for its TUI. The mechanics are shared
|
|
2
|
+
// (paneInput.ts owns the per-pane critical section, the text+submit gap and the one-line editor reader);
|
|
3
|
+
// what is CodeBuddy's is the editor's own shape and the keys its keybindings document.
|
|
4
|
+
//
|
|
5
|
+
// Measured on 2.156.0, its editor is the same one-line box Claude draws, with `>` as the prompt and a
|
|
6
|
+
// right-aligned `↵ send` footer painted inside the same line once there is draft text:
|
|
7
|
+
//
|
|
8
|
+
// ────────────────────────────────────────────────
|
|
9
|
+
// > 检查文件是否创建成功 ↵ send
|
|
10
|
+
// ────────────────────────────────────────────────
|
|
11
|
+
// ? for shortcuts ← for agents
|
|
12
|
+
//
|
|
13
|
+
// With no draft text the capture arrives as the bare `>`: the plain space CodeBuddy paints after its prompt
|
|
14
|
+
// is a trailing blank, which `capture-pane` drops (Claude's non-breaking space survives). The reader treats
|
|
15
|
+
// that as the empty editor it is — see `singleLineDraft`. The distinction matters downstream: the same line
|
|
16
|
+
// is what a cleared editor looks like, so reading it as unrecognizable refused both the send itself and the
|
|
17
|
+
// check that our own stale prompt had been cleared.
|
|
18
|
+
//
|
|
19
|
+
// Interrupt is `esc`: the pane's own footer says so (`✹ Buzzing… (esc to interrupt)`) and Escape really does
|
|
20
|
+
// stop it — measured, see `interruptAgentPane` in paneInput.ts. CodeBuddy's published keybindings list
|
|
21
|
+
// `ctrl+c → app:interrupt` (ctrl+d is exit); sending that one mid-tool did nothing at all.
|
|
22
|
+
import { describeEditorArea, serializePaneInput, singleLineDraft } from '../paneInput.js';
|
|
23
|
+
const SUBMIT_GAP_MS = 120;
|
|
24
|
+
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
25
|
+
// The footer the editor paints at the right edge of the draft line. Stripped before the draft is judged,
|
|
26
|
+
// so `> draft ↵ send` reads as `draft` while the footer itself can never be mistaken for typed text.
|
|
27
|
+
const EDITOR_HINT_RE = /[\s\u00a0]*↵\s*\S+[\s\u00a0]*$/;
|
|
28
|
+
export function codebuddySingleLineDraft(screen, cursor) {
|
|
29
|
+
return singleLineDraft(screen, cursor, '>', EDITOR_HINT_RE);
|
|
30
|
+
}
|
|
31
|
+
// Send a prompt the way the composer means it: replace only a draft this pane is KNOWN to own (the prompt
|
|
32
|
+
// we restored from the run's own submission) and never a draft a human typed — that is a refusal the caller
|
|
33
|
+
// can surface, not a silent deletion. Anything the reader cannot recognize refuses too.
|
|
34
|
+
export function sendCodeBuddyPanePrompt(commands, paneId, text, restoredPrompt, guard, reportUnreadable) {
|
|
35
|
+
return serializePaneInput(paneId, async () => {
|
|
36
|
+
if (guard && !await guard.validate())
|
|
37
|
+
return { nativeMutation: false };
|
|
38
|
+
await commands.exitCopyModeIfActive(paneId);
|
|
39
|
+
await commands.sendKey(paneId, 'End');
|
|
40
|
+
await delay(SUBMIT_GAP_MS);
|
|
41
|
+
const readEditor = async () => {
|
|
42
|
+
const screen = await commands.capturePlain(paneId);
|
|
43
|
+
const cursor = await commands.paneInfo(paneId);
|
|
44
|
+
return { screen, cursor, draft: codebuddySingleLineDraft(screen, cursor) };
|
|
45
|
+
};
|
|
46
|
+
const draft = await readEditor();
|
|
47
|
+
if (draft.draft === null) {
|
|
48
|
+
// Unreadable: record the shape, never the text we could not read (see describeEditorArea).
|
|
49
|
+
reportUnreadable?.(describeEditorArea(draft.screen, draft.cursor));
|
|
50
|
+
return { nativeMutation: false, reason: 'terminal_draft_conflict' };
|
|
51
|
+
}
|
|
52
|
+
if (draft.draft !== '' && draft.draft !== restoredPrompt()) {
|
|
53
|
+
return { nativeMutation: false, reason: 'terminal_draft_conflict' };
|
|
54
|
+
}
|
|
55
|
+
if (guard && !await guard.validate())
|
|
56
|
+
return { nativeMutation: false };
|
|
57
|
+
if (draft.draft) {
|
|
58
|
+
// Clear our own stale prompt. The key is unverified against a live CodeBuddy editor (its published
|
|
59
|
+
// keybindings cover app-level keys only), so the result is verified before anything is sent — a
|
|
60
|
+
// binding that does not clear leaves us refusing, never appending to unseen text.
|
|
61
|
+
await commands.sendKey(paneId, 'C-u');
|
|
62
|
+
await delay(SUBMIT_GAP_MS);
|
|
63
|
+
const cleared = await readEditor();
|
|
64
|
+
if (cleared.draft !== '') {
|
|
65
|
+
if (cleared.draft === null)
|
|
66
|
+
reportUnreadable?.(describeEditorArea(cleared.screen, cleared.cursor));
|
|
67
|
+
return { nativeMutation: false, reason: 'terminal_draft_conflict' };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
await commands.sendText(paneId, text);
|
|
71
|
+
if (text)
|
|
72
|
+
await delay(SUBMIT_GAP_MS);
|
|
73
|
+
await commands.sendEnter(paneId);
|
|
74
|
+
return { nativeMutation: true };
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
const record = (value) => (value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null);
|
|
2
|
+
// A bare slash command (`/compact`, `/clear`, `/model sonnet`) is logged as an ordinary user turn. It IS
|
|
3
|
+
// part of the conversation, so it becomes a quiet 'slash' marker instead of a prominent bubble. Anchored to
|
|
4
|
+
// a single leading lowercase command token followed by whitespace/EOL, so "/Users/demo/foo.js" (uppercase,
|
|
5
|
+
// then a path separator) and prose mentioning a path are never eaten.
|
|
6
|
+
const SLASH_CMD_RE = /^\s*\/([a-z][\w-]*)(?:\s+([\s\S]*?))?\s*$/i;
|
|
7
|
+
// The compaction summary wrapper: `<cb_summary>` / `<conversation_history_summary>` around the real text.
|
|
8
|
+
const SUMMARY_WRAP_RE = /^\s*<(?:cb_summary|conversation_history_summary)>([\s\S]*?)(?:<\/(?:cb_summary|conversation_history_summary)>)?\s*$/i;
|
|
9
|
+
const SUMMARY_LEAD_RE = /^\s*Summary(?: of the conversation so far)?:\s*/i;
|
|
10
|
+
const SUMMARY_CAP = 4_096;
|
|
11
|
+
function text(value) {
|
|
12
|
+
return typeof value === 'string' ? value : '';
|
|
13
|
+
}
|
|
14
|
+
// The record's wall-clock, in the ISO form the shared model carries. CodeBuddy logs epoch milliseconds
|
|
15
|
+
// (Claude logs an ISO string), and a record without a usable one simply gets no time.
|
|
16
|
+
function isoTime(value) {
|
|
17
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
18
|
+
return undefined;
|
|
19
|
+
const date = new Date(value);
|
|
20
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
21
|
+
}
|
|
22
|
+
// `arguments` is a JSON STRING (measured). Parse it so the projection can sanitize a real object; an
|
|
23
|
+
// unparsable payload is passed through as the raw string rather than dropped — a tool call the user cannot
|
|
24
|
+
// see is worse than one whose arguments are opaque.
|
|
25
|
+
function toolInput(value) {
|
|
26
|
+
if (typeof value !== 'string')
|
|
27
|
+
return value ?? {};
|
|
28
|
+
const trimmed = value.trim();
|
|
29
|
+
if (!trimmed)
|
|
30
|
+
return {};
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(trimmed);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return trimmed;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function contentText(value) {
|
|
39
|
+
if (typeof value === 'string')
|
|
40
|
+
return value;
|
|
41
|
+
if (!Array.isArray(value))
|
|
42
|
+
return '';
|
|
43
|
+
return value
|
|
44
|
+
.map(record)
|
|
45
|
+
.filter((block) => block !== null)
|
|
46
|
+
.map((block) => text(block.text))
|
|
47
|
+
.join('');
|
|
48
|
+
}
|
|
49
|
+
export function createCodeBuddyTranscriptParser() {
|
|
50
|
+
const messages = [];
|
|
51
|
+
const pending = new Map();
|
|
52
|
+
let i = 0;
|
|
53
|
+
function push(lines) {
|
|
54
|
+
for (const raw of lines) {
|
|
55
|
+
const line = typeof raw === 'string' ? raw.trim() : '';
|
|
56
|
+
if (!line) {
|
|
57
|
+
i++;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(line);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
i++;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const row = record(parsed);
|
|
69
|
+
const type = text(row?.type);
|
|
70
|
+
if (!row || !type) {
|
|
71
|
+
i++;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const provider = record(row.providerData) ?? {};
|
|
75
|
+
const ts = isoTime(row.timestamp);
|
|
76
|
+
const index = i;
|
|
77
|
+
if (type === 'message') {
|
|
78
|
+
if (provider.isMeta === true || provider.skipRun === true || provider.isPartialAborted === true) {
|
|
79
|
+
i++;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const role = row.role === 'user' ? 'user' : row.role === 'assistant' ? 'assistant' : null;
|
|
83
|
+
if (!role) {
|
|
84
|
+
i++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const body = contentText(row.content);
|
|
88
|
+
if (provider.isCompacted === true || provider.isSummary === true) {
|
|
89
|
+
// A compaction happened here. Keep the divider (the 对话 lens shows "上下文已压缩"), cap the text.
|
|
90
|
+
const wrapped = SUMMARY_WRAP_RE.exec(body);
|
|
91
|
+
const summary = (wrapped?.[1] ?? body).replace(SUMMARY_LEAD_RE, '').trim();
|
|
92
|
+
const message = { i, type: 'compact', ts };
|
|
93
|
+
if (summary) {
|
|
94
|
+
message.summary = summary.length > SUMMARY_CAP ? summary.slice(0, SUMMARY_CAP - 1) + '…' : summary;
|
|
95
|
+
if (summary.length > SUMMARY_CAP) {
|
|
96
|
+
message.summaryTruncated = true;
|
|
97
|
+
message.summaryOriginalBytes = Buffer.byteLength(summary, 'utf8');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
messages.push(message);
|
|
101
|
+
i++;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
// The synthetic "continue from the summary" prompt is not a human turn.
|
|
105
|
+
if (provider.isCompactInternal === true) {
|
|
106
|
+
i++;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (role === 'user') {
|
|
110
|
+
const command = SLASH_CMD_RE.exec(body);
|
|
111
|
+
if (command?.[1]) {
|
|
112
|
+
const message = { i, type: 'slash', name: `/${command[1]}`, ts };
|
|
113
|
+
if (command[2]?.trim())
|
|
114
|
+
message.args = command[2].trim();
|
|
115
|
+
messages.push(message);
|
|
116
|
+
i++;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!body.trim()) {
|
|
121
|
+
i++;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const message = { i, type: 'text', role, text: body, ts };
|
|
125
|
+
messages.push(message);
|
|
126
|
+
i++;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (type === 'reasoning') {
|
|
130
|
+
// Only the provider's PUBLIC projection; `rawContent` is the raw chain of thought.
|
|
131
|
+
const reasoning = contentText(row.content).trim();
|
|
132
|
+
if (reasoning) {
|
|
133
|
+
const message = { i, type: 'thinking', role: 'assistant', text: reasoning, ts };
|
|
134
|
+
messages.push(message);
|
|
135
|
+
}
|
|
136
|
+
i++;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (type === 'function_call') {
|
|
140
|
+
const tool = {
|
|
141
|
+
name: text(row.name),
|
|
142
|
+
input: toolInput(row.arguments),
|
|
143
|
+
result: null,
|
|
144
|
+
isError: false,
|
|
145
|
+
};
|
|
146
|
+
const message = {
|
|
147
|
+
i, type: 'tool', role: 'assistant', ts, tool,
|
|
148
|
+
};
|
|
149
|
+
const callId = text(row.callId);
|
|
150
|
+
if (callId)
|
|
151
|
+
pending.set(callId, message);
|
|
152
|
+
messages.push(message);
|
|
153
|
+
i++;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (type === 'function_call_result') {
|
|
157
|
+
const message = pending.get(text(row.callId));
|
|
158
|
+
if (message) {
|
|
159
|
+
const result = record(row.providerData);
|
|
160
|
+
const toolResult = record(result?.toolResult);
|
|
161
|
+
const output = record(row.output);
|
|
162
|
+
const body = text(output?.text) || text(toolResult?.content);
|
|
163
|
+
message.tool.result = body;
|
|
164
|
+
// `status` is the provider's own verdict (measured: 'completed'); an `error` on the tool result
|
|
165
|
+
// is the same fact stated a second way. Either one marks the failure.
|
|
166
|
+
message.tool.isError = (text(row.status) !== 'completed' && text(row.status) !== '')
|
|
167
|
+
|| toolResult?.error !== undefined;
|
|
168
|
+
pending.delete(text(row.callId));
|
|
169
|
+
}
|
|
170
|
+
i++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
i++;
|
|
174
|
+
}
|
|
175
|
+
return messages;
|
|
176
|
+
}
|
|
177
|
+
return { push, messages };
|
|
178
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// The shared Hook-event layer. Claude Code and CodeBuddy both drive Handmux through filesystem Hooks, and
|
|
2
|
+
// CodeBuddy's Hook protocol is Claude Code's: the same `src` argument convention, the same raw payload on
|
|
3
|
+
// stdin, and the same JSON latest-state file plus bounded durable spool written by the SHARED
|
|
4
|
+
// server/hooks/handmux-write.cjs. So the two things those providers genuinely have in common live here:
|
|
5
|
+
//
|
|
6
|
+
// 1. the lifecycle VOCABULARY every Hook-driven Inbox state is normalized into;
|
|
7
|
+
// 2. the on-disk RECORD FORMAT (state row, spool event, owning-process fingerprint).
|
|
8
|
+
//
|
|
9
|
+
// What stays per-Agent — and therefore does NOT live here — is which `src` string means what, which payload
|
|
10
|
+
// fields carry the message, and how a pane proves the Agent is still its foreground process. Those are
|
|
11
|
+
// product facts and belong with the provider (agents/claude.ts, codebuddyEvents.ts).
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
const EVENT_KINDS = new Set([
|
|
14
|
+
'done', 'working', 'permission', 'compacting', 'error', 'end', 'idle',
|
|
15
|
+
]);
|
|
16
|
+
// Validate an untrusted kind string against the shared vocabulary.
|
|
17
|
+
export function hookEventKind(value) {
|
|
18
|
+
return typeof value === 'string' && EVENT_KINDS.has(value)
|
|
19
|
+
? value : null;
|
|
20
|
+
}
|
|
21
|
+
// A normalized kind → the Inbox state the Core understands, or null when it carries no state at all
|
|
22
|
+
// (`end`/`idle`/unknown). Compacted work is still work; a permission gate is waiting on the user.
|
|
23
|
+
export function canonicalInboxState(kind) {
|
|
24
|
+
if (kind === 'working' || kind === 'compacting')
|
|
25
|
+
return 'working';
|
|
26
|
+
if (kind === 'permission')
|
|
27
|
+
return 'waiting';
|
|
28
|
+
if (kind === 'done')
|
|
29
|
+
return 'done';
|
|
30
|
+
if (kind === 'error')
|
|
31
|
+
return 'error';
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
35
|
+
const bounded = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
|
|
36
|
+
// ---------------------------------------------------------------------------------------------
|
|
37
|
+
// On-disk format shared with server/hooks/handmux-write.cjs
|
|
38
|
+
// ---------------------------------------------------------------------------------------------
|
|
39
|
+
export const HOOK_EVENT_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/;
|
|
40
|
+
export function parseHookProcessFingerprint(value) {
|
|
41
|
+
if (!isRecord(value) || !Number.isSafeInteger(value.pid) || Number(value.pid) <= 0
|
|
42
|
+
|| typeof value.startedAt !== 'number' || !Number.isFinite(value.startedAt)
|
|
43
|
+
|| value.startedAt < 0 || !bounded(value.tty, 1024))
|
|
44
|
+
return null;
|
|
45
|
+
return { pid: Number(value.pid), startedAt: value.startedAt, tty: value.tty };
|
|
46
|
+
}
|
|
47
|
+
export function normalizedTty(value) {
|
|
48
|
+
if (!value)
|
|
49
|
+
return undefined;
|
|
50
|
+
return value.startsWith('/dev/') ? value : `/dev/${value}`;
|
|
51
|
+
}
|
|
52
|
+
// An absent fingerprint is accepted: it is the additive field of a newer writer, and records produced by an
|
|
53
|
+
// older installed Hook must keep working.
|
|
54
|
+
export function matchesHookProcess(source, current) {
|
|
55
|
+
if (!source)
|
|
56
|
+
return true;
|
|
57
|
+
return source.pid === current.pid
|
|
58
|
+
&& source.startedAt === current.startedAt
|
|
59
|
+
&& normalizedTty(source.tty) === normalizedTty(current.tty);
|
|
60
|
+
}
|
|
61
|
+
// `acceptAgent` decides which provider's marking a row may carry: an absent `agent` is always legacy
|
|
62
|
+
// compatibility, and every explicit foreign marking must fail closed rather than borrow another Agent's state.
|
|
63
|
+
export function readHookStateRows(file, acceptAgent) {
|
|
64
|
+
try {
|
|
65
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
66
|
+
if (!isRecord(value))
|
|
67
|
+
return new Map();
|
|
68
|
+
return new Map(Object.entries(value).flatMap(([paneId, raw]) => {
|
|
69
|
+
const row = isRecord(raw) ? raw : null;
|
|
70
|
+
const payload = isRecord(row?.payload) ? row.payload : null;
|
|
71
|
+
if (!bounded(paneId, 256) || !row || !payload || !bounded(row.src, 64)
|
|
72
|
+
|| (row.agent !== undefined && !acceptAgent(row.agent)))
|
|
73
|
+
return [];
|
|
74
|
+
const ts = typeof row.ts === 'number' && Number.isFinite(row.ts) ? row.ts : 0;
|
|
75
|
+
const sequence = Number.isSafeInteger(row.sequence) && Number(row.sequence) > 0
|
|
76
|
+
? Number(row.sequence) : undefined;
|
|
77
|
+
const process = row.process === undefined ? undefined : parseHookProcessFingerprint(row.process);
|
|
78
|
+
if (process === null)
|
|
79
|
+
return [];
|
|
80
|
+
return [[paneId, {
|
|
81
|
+
ts,
|
|
82
|
+
src: row.src,
|
|
83
|
+
...(typeof row.agent === 'string' ? { agent: row.agent } : {}),
|
|
84
|
+
payload,
|
|
85
|
+
...(sequence === undefined ? {} : { sequence }),
|
|
86
|
+
...(process === undefined ? {} : { process }),
|
|
87
|
+
}]];
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return new Map();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function parseHookBridgeEvent(value, acceptAgent) {
|
|
95
|
+
if (!isRecord(value) || value.version !== 1 || (value.type !== 'event' && value.type !== 'gap')
|
|
96
|
+
|| (value.agent !== undefined && !acceptAgent(value.agent))
|
|
97
|
+
|| !bounded(value.eventId, 256) || !HOOK_EVENT_ID_RE.test(value.eventId)
|
|
98
|
+
|| !bounded(value.paneId, 256)
|
|
99
|
+
|| (value.sequence !== undefined && (!Number.isSafeInteger(value.sequence) || Number(value.sequence) <= 0))
|
|
100
|
+
|| (value.src !== undefined && !bounded(value.src, 64))
|
|
101
|
+
|| (value.sessionId !== undefined && !bounded(value.sessionId, 1024))
|
|
102
|
+
|| (value.sourceOccurredAt !== undefined
|
|
103
|
+
&& (typeof value.sourceOccurredAt !== 'number' || !Number.isFinite(value.sourceOccurredAt)))
|
|
104
|
+
|| (value.process !== undefined && parseHookProcessFingerprint(value.process) === null)
|
|
105
|
+
|| (value.payload !== undefined && !isRecord(value.payload)))
|
|
106
|
+
return null;
|
|
107
|
+
return {
|
|
108
|
+
...value,
|
|
109
|
+
...(value.process === undefined ? {} : { process: parseHookProcessFingerprint(value.process) }),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
// The durable source sequence embedded in a spool event ID (`<agent>-hook-<n>`). The writer is shared, so
|
|
113
|
+
// this deliberately reads the suffix rather than pinning one Agent's prefix: the prefix is the writer's
|
|
114
|
+
// choice, not a contract this reader may tighten.
|
|
115
|
+
export function hookEventSequence(eventId) {
|
|
116
|
+
const match = /^[a-z][a-z0-9-]*-hook-([1-9]\d*)$/.exec(eventId);
|
|
117
|
+
if (!match)
|
|
118
|
+
return null;
|
|
119
|
+
const sequence = Number(match[1]);
|
|
120
|
+
return Number.isSafeInteger(sequence) ? sequence : null;
|
|
121
|
+
}
|
|
122
|
+
// Friendly Chinese for an API-error turn end. The payload shape for a StopFailure is not verified against
|
|
123
|
+
// every provider, so read the type defensively from several likely fields and always fall back to a bare
|
|
124
|
+
// 本轮出错 — a wrong field name degrades to the generic label, never throws.
|
|
125
|
+
const ERROR_LABEL = {
|
|
126
|
+
rate_limit: '触发限流', overloaded: '服务过载', authentication_failed: '认证失败',
|
|
127
|
+
oauth_org_not_allowed: '组织未授权', billing_error: '额度/账单问题', invalid_request: '请求无效',
|
|
128
|
+
model_not_found: '模型不可用', server_error: '服务端错误', max_output_tokens: '输出超长', unknown: '未知错误',
|
|
129
|
+
};
|
|
130
|
+
export function hookErrorMessage(body) {
|
|
131
|
+
const error = isRecord(body.error) ? body.error : null;
|
|
132
|
+
const type = typeof body.error_type === 'string' ? body.error_type
|
|
133
|
+
: typeof body.reason === 'string' ? body.reason
|
|
134
|
+
: typeof body.type === 'string' ? body.type
|
|
135
|
+
: typeof body.error === 'string' ? body.error
|
|
136
|
+
: typeof error?.type === 'string' ? error.type : '';
|
|
137
|
+
const label = ERROR_LABEL[type];
|
|
138
|
+
if (label)
|
|
139
|
+
return label;
|
|
140
|
+
const raw = typeof body.error === 'string' ? body.error
|
|
141
|
+
: typeof body.message === 'string' ? body.message : '';
|
|
142
|
+
return raw ? raw.replace(/\s+/g, ' ').trim().slice(0, 80) : '';
|
|
143
|
+
}
|