-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommandcode-hud.mod.ts
More file actions
258 lines (231 loc) · 8.57 KB
/
Copy pathcommandcode-hud.mod.ts
File metadata and controls
258 lines (231 loc) · 8.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import {readFileSync, statSync} from 'node:fs';
import type {ModApi} from '@commandcode/harness';
/**
* Command Code 1.14.1 UI surfaces (docs + dist/cli.mjs):
*
* Native footer (inside InputBox):
* `» permission bypass on [shift+tab]` / `? for shortcuts` / `taste on`
* → ModeIndicator + TasteStateBadge. Mods cannot write into that row.
*
* Mod footer line (BELOW the input box):
* `cmd.ui.setStatus(text)` → ModStatusLine
* One segment per mod; multiple mods join with " ".
* Updates replace THAT mod's segment only; they do NOT wipe native indicators.
* Render: segments.map(s => s.text).join(" ") under the input.
* ModStatusLine has hardcoded paddingLeft:2 and sits AFTER a divider line
* (`lt.line.repeat(width)`), so it will always appear one row below the footer.
*
* `cmd.ui.widget` / `refreshWidgets`:
* Public API exists, but runtime is a no-op in 1.14.1 (wire-up pending).
*
* `cmd.addRenderer` + `cmd.showEntry`:
* Feed rows ABOVE the input. Append-only; no update/replace entry API.
*
* Notes on persistence across /reload and /resume:
* - `setStatus(null)` clears the segment; calling it onSessionEnd wipes the
* status before the new session repaints → avoided.
* - State is persisted via cmd.session.appendCustomEntry and re-read on start.
*/
const ANSI_CYAN = '\u001b[36m';
const ANSI_DIM = '\u001b[2m';
const ANSI_RESET = '\u001b[0m';
const BRAIN = '\uD83E\uDDE0';
const STATE_ENTRY_TYPE = 'commandcode-hud/state-v1';
const record = (value: unknown): Record<string, unknown> =>
value !== null && typeof value === 'object' ? value as Record<string, unknown> : {};
const text = (value: unknown): string | undefined =>
typeof value === 'string' && value.trim() ? value.trim() : undefined;
const branchNameFromStatus = (stdout: string): string | undefined => {
const header = stdout.split(/\r?\n/).find(line => line.startsWith('## '));
const headerText = header?.slice(3).trim() ?? '';
if (!headerText) return undefined;
if (headerText.startsWith('No commits yet on ')) {
return headerText.slice('No commits yet on '.length).trim() || undefined;
}
const name = headerText.split('...')[0]?.trim() ?? '';
return name === 'HEAD (no branch)' ? 'detached' : name || undefined;
};
const resolveModelName = (model: unknown, fallback = ''): string => {
if (typeof model === 'string') return model || fallback;
const m = record(model);
return (
text(m.displayName) ??
text(m.display_name) ??
text(m.name) ??
text(m.id) ??
fallback
);
};
const shortModel = (full: string): string => {
const lower = full.toLowerCase();
if (lower.includes('sonnet')) return 'Sonnet';
if (lower.includes('opus')) return 'Opus';
if (lower.includes('haiku')) return 'Haiku';
const slash = full.lastIndexOf('/');
if (slash >= 0) return full.slice(slash + 1);
return full;
};
const modelFromArgs = (): string | undefined => {
const args = process.argv;
const index = args.indexOf('--model');
return index >= 0 ? text(args[index + 1]) : undefined;
};
const effortFromConfig = (model: string): string | undefined => {
try {
const config = JSON.parse(readFileSync(`${process.env.HOME}/.commandcode/config.json`, 'utf8')) as Record<string, unknown>;
const efforts = record(config.reasoningEffort);
return text(efforts[model]) ?? text(config.effort);
} catch {
return undefined;
}
};
const CONFIG_PATH = `${process.env.HOME}/.commandcode/config.json`;
const readModelConfig = (): {model?: string; effort?: string; mtimeMs?: number} => {
try {
const stat = statSync(CONFIG_PATH);
const parsed = JSON.parse(readFileSync(CONFIG_PATH, 'utf8')) as Record<string, unknown>;
const effortMap = record(parsed.reasoningEffort);
const model = text(parsed.model);
return {
model,
effort: model ? text(effortMap[model]) ?? undefined : text(parsed.effort) ?? undefined,
mtimeMs: stat.mtimeMs,
};
} catch {
return {};
}
};
// Export for tests.
export const __test = {branchNameFromStatus, readModelConfig};
export default function (cmd: ModApi): void {
let lastPublished = '';
let currentBranch: string | undefined;
const explicitModel = modelFromArgs();
const initialConfig = readModelConfig();
let currentModel = explicitModel ?? initialConfig.model ?? 'gpt-5.6-luna';
let currentEffort: string | undefined = initialConfig.effort ?? effortFromConfig(currentModel);
const render = (): string => {
const segments: string[] = [];
const modelParts: string[] = [];
if (currentModel) {
modelParts.push(`${ANSI_CYAN}${shortModel(currentModel)}${ANSI_RESET}`);
if (currentEffort) modelParts.push(`${BRAIN} ${currentEffort}`);
}
if (modelParts.length) segments.push(modelParts.join(' '));
if (currentBranch) segments.push(`${ANSI_CYAN}${currentBranch}${ANSI_RESET}`);
else segments.push(`${ANSI_DIM}no-branch${ANSI_RESET}`);
return segments.join(' · ');
};
const publish = (force = false): void => {
const next = render().trim();
if (!force && next === lastPublished) return;
lastPublished = next;
cmd.ui.setStatus(next);
};
const persist = (): void => {
cmd.session?.appendCustomEntry({
customType: STATE_ENTRY_TYPE,
data: {branch: currentBranch, model: currentModel, effort: currentEffort},
});
};
const restore = (): void => {
const session = cmd.session;
if (!session) return;
const last = session
.getCustomEntries({customType: STATE_ENTRY_TYPE})
.map(entry => record(entry).data)
.at(-1);
if (!last) return;
currentBranch = text(last['branch']);
currentModel = explicitModel ?? text(last['model']) ?? currentModel;
currentEffort = text(last['effort']) ?? currentEffort ?? effortFromConfig(currentModel);
lastPublished = '';
publish(true);
};
const refreshBranch = async (): Promise<void> => {
try {
const result = await cmd.exec({
command: 'git',
args: ['status', '--porcelain=1', '--branch'],
cwd: cmd.cwd,
});
currentBranch = result.code === 0 ? branchNameFromStatus(result.stdout) : undefined;
persist();
publish();
} catch {
currentBranch = undefined;
persist();
publish();
}
};
const captureModelAndEffort = (event: unknown, forcePublish = false): void => {
const value = record(event);
const modelRaw = resolveModelName(value.model);
// Effort comes as event.effort (string level) in 1.14.1; check string and object forms
const effortDirect = text(value.effort);
const effortObj = text(record(value.effort).level);
const effortNew = effortDirect ?? effortObj;
let changed = false;
if (modelRaw) {
currentModel = modelRaw;
changed = true;
}
// Only overwrite effort if present; don't clear an earlier effort on empty events
if (effortNew) {
currentEffort = effortNew;
changed = true;
}
if (changed) {
persist();
publish(forcePublish);
}
};
// `/model` writes ~/.commandcode/config.json. Poll its mtime so the HUD
// updates right after the user switches models, without waiting for the
// next model_request_start.
let lastConfigMtime = readModelConfig().mtimeMs ?? 0;
const pollModelConfig = (): void => {
const fresh = readModelConfig();
if (fresh.mtimeMs === undefined || fresh.mtimeMs === lastConfigMtime) return;
lastConfigMtime = fresh.mtimeMs;
if (fresh.model && fresh.model !== currentModel) {
currentModel = fresh.model;
currentEffort = fresh.effort ?? currentEffort;
persist();
publish(true);
}
};
setInterval(pollModelConfig, 2000).unref();
cmd.hooks({
onSessionStart: () => {
restore();
void refreshBranch();
},
});
// No onSessionEnd setStatus(null): it wipes the segment on /reload before the
// new session repaints. Persist instead so /resume and /new recover it.
cmd.on('model_request_start', event => {
captureModelAndEffort(event, true);
});
cmd.on('model_request_end', event => {
captureModelAndEffort(event, true);
});
cmd.on('config_setting_changed', event => {
const value = record(event);
if (value.setting !== 'model') return;
const model = resolveModelName(value.value, currentModel);
if (!model) return;
currentModel = model;
currentEffort = effortFromConfig(model) ?? currentEffort;
persist();
publish(true);
});
cmd.on('run_end', () => {
void refreshBranch();
});
// Immediate first paint for interactive sessions.
restore();
void refreshBranch();
// Also publish model context early if we restored it, before any model event fires
publish(true);
}