@trans-ai/trans-code 0.0.0-stage → 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 +209 -2
- package/bin/transcode.ts +4 -0
- package/docs/ACP.md +231 -0
- package/package.json +42 -4
- package/src/acp/protocol.ts +115 -0
- package/src/acp/server.ts +202 -0
- package/src/acp/session.ts +269 -0
- package/src/acp/transport.ts +216 -0
- package/src/agent/loop.ts +334 -0
- package/src/agent/system-prompt.ts +86 -0
- package/src/agent/tools.ts +483 -0
- package/src/cli.ts +60 -0
- package/src/commands.ts +61 -0
- package/src/main.tsx +62 -0
- package/src/provider/provider.ts +373 -0
- package/src/screens/REPL.tsx +433 -0
- package/src/tui/cli.tsx +2 -0
- package/src/tui/keyed-stdin.ts +83 -0
- package/src/upgrade.ts +110 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
import { Box, Text, useInput, useApp } from 'ink';
|
|
2
|
+
import { useState, useCallback, useRef } from 'react';
|
|
3
|
+
import { findCommand, getCommands, type CommandContext } from '../commands.js';
|
|
4
|
+
import { getAvailableModels, createProviderWithKey, createProvider, type ModelId } from '../provider/provider.js';
|
|
5
|
+
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
6
|
+
import { buildSystemPrompt, loadProjectContext } from '../agent/system-prompt.js';
|
|
7
|
+
import { HumanMessage, SystemMessage, type BaseMessage } from '@langchain/core/messages';
|
|
8
|
+
|
|
9
|
+
interface HistoryEntry {
|
|
10
|
+
input: string;
|
|
11
|
+
output: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type PromptPhase = 'idle' | 'model_select' | 'model_apikey' | 'permission';
|
|
15
|
+
|
|
16
|
+
interface REPLProps {
|
|
17
|
+
ctx: CommandContext;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export default function REPL({ ctx }: REPLProps) {
|
|
21
|
+
const { exit } = useApp();
|
|
22
|
+
const [input, setInput] = useState('');
|
|
23
|
+
// Multiple keystrokes can be handled in one React batch before a
|
|
24
|
+
// re-render; closures over `input` would see stale values (e.g. the
|
|
25
|
+
// Enter after a fast paste would submit without the last characters).
|
|
26
|
+
// The ref is the source of truth; the state mirrors it for rendering.
|
|
27
|
+
const inputRef = useRef('');
|
|
28
|
+
const commitInput = useCallback((next: string) => {
|
|
29
|
+
inputRef.current = next;
|
|
30
|
+
setInput(next);
|
|
31
|
+
}, []);
|
|
32
|
+
const [history, setHistory] = useState<HistoryEntry[]>([]);
|
|
33
|
+
const [historyIndex, setHistoryIndex] = useState(-1);
|
|
34
|
+
const [savedInput, setSavedInput] = useState('');
|
|
35
|
+
const [phase, setPhase] = useState<PromptPhase>('idle');
|
|
36
|
+
const [pendingModel, setPendingModel] = useState<ModelId | null>(null);
|
|
37
|
+
const [modelCursor, setModelCursor] = useState(0);
|
|
38
|
+
|
|
39
|
+
const models = getAvailableModels();
|
|
40
|
+
// Bun's scheduler can drop the render flush for updates issued from the
|
|
41
|
+
// stdin event path (updates from timers always flush). Nudge a re-render
|
|
42
|
+
// on a timer so submitted commands are guaranteed to paint.
|
|
43
|
+
const [flushTick, setFlushTick] = useState(0);
|
|
44
|
+
const dragFlush = useCallback(() => {
|
|
45
|
+
setTimeout(() => setFlushTick(t => t + 1), 0);
|
|
46
|
+
}, []);
|
|
47
|
+
|
|
48
|
+
const addHistory = useCallback((entry: HistoryEntry) => {
|
|
49
|
+
setHistory(prev => [...prev, entry]);
|
|
50
|
+
}, []);
|
|
51
|
+
|
|
52
|
+
// ---- chat state ----
|
|
53
|
+
const [busy, setBusy] = useState(false);
|
|
54
|
+
const busyRef = useRef(false);
|
|
55
|
+
const abortRef = useRef<AbortController | undefined>(undefined);
|
|
56
|
+
const messagesRef = useRef<BaseMessage[]>([]);
|
|
57
|
+
const pendingPermissionRef = useRef<{
|
|
58
|
+
request: PermissionRequest;
|
|
59
|
+
resolve: (allow: boolean) => void;
|
|
60
|
+
} | null>(null);
|
|
61
|
+
|
|
62
|
+
const setBusyBoth = useCallback((v: boolean) => {
|
|
63
|
+
busyRef.current = v;
|
|
64
|
+
setBusy(v);
|
|
65
|
+
}, []);
|
|
66
|
+
|
|
67
|
+
const appendChatOutput = useCallback((chunk: string) => {
|
|
68
|
+
setHistory(prev => {
|
|
69
|
+
if (prev.length === 0) return prev;
|
|
70
|
+
const next = [...prev];
|
|
71
|
+
const last = next[next.length - 1];
|
|
72
|
+
next[next.length - 1] = { ...last, output: last.output + chunk };
|
|
73
|
+
return next;
|
|
74
|
+
});
|
|
75
|
+
}, []);
|
|
76
|
+
|
|
77
|
+
const askInTerminal = useCallback(
|
|
78
|
+
(request: PermissionRequest, signal: AbortSignal): Promise<boolean> => {
|
|
79
|
+
const mode = process.env.TRANSCODE_PERMISSION_MODE ?? 'ask';
|
|
80
|
+
if (mode === 'auto') return Promise.resolve(true);
|
|
81
|
+
if (mode === 'readonly') return Promise.resolve(false);
|
|
82
|
+
return new Promise<boolean>(resolve => {
|
|
83
|
+
const settle = (allow: boolean) => {
|
|
84
|
+
signal.removeEventListener('abort', onAbort);
|
|
85
|
+
pendingPermissionRef.current = null;
|
|
86
|
+
setPhase('idle');
|
|
87
|
+
resolve(allow);
|
|
88
|
+
};
|
|
89
|
+
const onAbort = () => settle(false);
|
|
90
|
+
signal.addEventListener('abort', onAbort);
|
|
91
|
+
pendingPermissionRef.current = { request, resolve: settle };
|
|
92
|
+
setPhase('permission');
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
[],
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
const runChat = useCallback(
|
|
99
|
+
async (text: string) => {
|
|
100
|
+
setBusyBoth(true);
|
|
101
|
+
const controller = new AbortController();
|
|
102
|
+
abortRef.current = controller;
|
|
103
|
+
addHistory({ input: text, output: '' });
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
const systemPrompt = buildSystemPrompt(await loadProjectContext(process.cwd()));
|
|
107
|
+
if (messagesRef.current[0]?.getType() === 'system') {
|
|
108
|
+
messagesRef.current[0] = new SystemMessage(systemPrompt);
|
|
109
|
+
} else {
|
|
110
|
+
messagesRef.current.unshift(new SystemMessage(systemPrompt));
|
|
111
|
+
}
|
|
112
|
+
messagesRef.current.push(new HumanMessage(text));
|
|
113
|
+
|
|
114
|
+
const provider =
|
|
115
|
+
process.env.TRANSCODE_MOCK === '1'
|
|
116
|
+
? undefined
|
|
117
|
+
: createProvider(ctx.modelId);
|
|
118
|
+
|
|
119
|
+
let lastWasTool = false;
|
|
120
|
+
const result = await runAgentLoop({
|
|
121
|
+
model: provider?.model,
|
|
122
|
+
cwd: process.cwd(),
|
|
123
|
+
messages: messagesRef.current,
|
|
124
|
+
systemPrompt,
|
|
125
|
+
signal: controller.signal,
|
|
126
|
+
onEvent: event => {
|
|
127
|
+
if (event.type === 'text') {
|
|
128
|
+
appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
|
|
129
|
+
lastWasTool = false;
|
|
130
|
+
} else if (event.type === 'tool_call') {
|
|
131
|
+
appendChatOutput(`\n⚙ ${event.title}`);
|
|
132
|
+
lastWasTool = true;
|
|
133
|
+
} else if (event.type === 'tool_result') {
|
|
134
|
+
appendChatOutput(event.ok ? ' ✓' : ' ✗');
|
|
135
|
+
lastWasTool = true;
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
requestPermission: request => askInTerminal(request, controller.signal),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
messagesRef.current = result.messages;
|
|
142
|
+
if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
|
|
143
|
+
} catch (error) {
|
|
144
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
145
|
+
appendChatOutput(`\n⚠ ${message}`);
|
|
146
|
+
if (/api.?key/i.test(message)) {
|
|
147
|
+
appendChatOutput(`\n(run "models" to switch model + set key, or export its env var)`);
|
|
148
|
+
}
|
|
149
|
+
} finally {
|
|
150
|
+
setBusyBoth(false);
|
|
151
|
+
abortRef.current = undefined;
|
|
152
|
+
dragFlush();
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
[ctx.modelId, addHistory, appendChatOutput, askInTerminal, setBusyBoth, dragFlush],
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
const enterModelSelect = useCallback(() => {
|
|
159
|
+
const currentIdx = models.findIndex(m => m.id === ctx.modelId);
|
|
160
|
+
setModelCursor(currentIdx >= 0 ? currentIdx : 0);
|
|
161
|
+
setPhase('model_select');
|
|
162
|
+
}, [ctx.modelId, models]);
|
|
163
|
+
|
|
164
|
+
const handleApiKey = useCallback((value: string) => {
|
|
165
|
+
const apiKey = value.trim();
|
|
166
|
+
const modelId = pendingModel!;
|
|
167
|
+
|
|
168
|
+
if (!apiKey) {
|
|
169
|
+
addHistory({ input: '••••••••', output: 'API key cannot be empty.' });
|
|
170
|
+
enterModelSelect();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
createProviderWithKey(modelId, apiKey);
|
|
176
|
+
ctx.setModelId(modelId);
|
|
177
|
+
const found = models.find(m => m.id === modelId);
|
|
178
|
+
addHistory({ input: '••••••••', output: `Switched to ${found?.name ?? modelId}` });
|
|
179
|
+
} catch {
|
|
180
|
+
addHistory({ input: '••••••••', output: 'Failed to switch model. Invalid API key.' });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
setPendingModel(null);
|
|
184
|
+
setPhase('idle');
|
|
185
|
+
}, [pendingModel, ctx, addHistory, enterModelSelect, models]);
|
|
186
|
+
|
|
187
|
+
const handleSubmit = useCallback(async (raw: string) => {
|
|
188
|
+
const trimmed = raw.trim();
|
|
189
|
+
if (!trimmed) return;
|
|
190
|
+
|
|
191
|
+
if (phase === 'model_apikey') {
|
|
192
|
+
handleApiKey(trimmed);
|
|
193
|
+
commitInput('');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const stripped = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;
|
|
198
|
+
const parts = stripped.split(/\s+/);
|
|
199
|
+
const cmdName = parts[0];
|
|
200
|
+
const args = parts.slice(1);
|
|
201
|
+
|
|
202
|
+
if (cmdName === 'models') {
|
|
203
|
+
addHistory({ input: trimmed, output: 'Select a model (↑↓ to navigate, Enter to select):' });
|
|
204
|
+
enterModelSelect();
|
|
205
|
+
commitInput('');
|
|
206
|
+
dragFlush();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const cmd = findCommand(cmdName);
|
|
211
|
+
|
|
212
|
+
if (cmd) {
|
|
213
|
+
const result = await cmd.execute(args, ctx);
|
|
214
|
+
|
|
215
|
+
if (result.exit) {
|
|
216
|
+
exit();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (cmdName === 'clear') {
|
|
221
|
+
ctx.clearHistory();
|
|
222
|
+
setHistory([]);
|
|
223
|
+
} else if (result.output) {
|
|
224
|
+
addHistory({ input: trimmed, output: result.output });
|
|
225
|
+
}
|
|
226
|
+
} else if (trimmed.startsWith('/')) {
|
|
227
|
+
// Explicit slash prefix means the user intended a command.
|
|
228
|
+
addHistory({ input: trimmed, output: `Unknown command: ${cmdName}. Type "help" for available commands.` });
|
|
229
|
+
} else {
|
|
230
|
+
// Free text — converse with the current model.
|
|
231
|
+
commitInput('');
|
|
232
|
+
setHistoryIndex(-1);
|
|
233
|
+
setSavedInput('');
|
|
234
|
+
await runChat(trimmed);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
dragFlush();
|
|
238
|
+
|
|
239
|
+
commitInput('');
|
|
240
|
+
setHistoryIndex(-1);
|
|
241
|
+
setSavedInput('');
|
|
242
|
+
}, [exit, ctx, phase, handleApiKey, addHistory, enterModelSelect, commitInput, dragFlush, runChat]);
|
|
243
|
+
|
|
244
|
+
useInput((ch, key) => {
|
|
245
|
+
if (process.env.TRANSCODE_DEBUG_KEYS === '1') {
|
|
246
|
+
// eslint-disable-next-line no-console
|
|
247
|
+
console.error(`CB ${JSON.stringify(ch)} ret=${key.return} esc=${key.escape}`);
|
|
248
|
+
}
|
|
249
|
+
if (key.escape) {
|
|
250
|
+
// While generating, Esc cancels instead of exiting.
|
|
251
|
+
if (busyRef.current && abortRef.current) {
|
|
252
|
+
abortRef.current.abort();
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (phase !== 'idle') {
|
|
256
|
+
setPhase('idle');
|
|
257
|
+
setPendingModel(null);
|
|
258
|
+
commitInput('');
|
|
259
|
+
addHistory({ input: '', output: 'Cancelled.' });
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
exit();
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (phase === 'permission') {
|
|
267
|
+
if (ch === 'y' || ch === 'Y' || key.return) {
|
|
268
|
+
pendingPermissionRef.current?.resolve(true);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (ch === 'n' || ch === 'N') {
|
|
272
|
+
pendingPermissionRef.current?.resolve(false);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (phase === 'model_select') {
|
|
279
|
+
if (key.return) {
|
|
280
|
+
const selected = models[modelCursor];
|
|
281
|
+
setPendingModel(selected.id);
|
|
282
|
+
setPhase('model_apikey');
|
|
283
|
+
commitInput('');
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (key.upArrow) {
|
|
287
|
+
setModelCursor(prev => (prev - 1 + models.length) % models.length);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if (key.downArrow) {
|
|
291
|
+
setModelCursor(prev => (prev + 1) % models.length);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (key.return) {
|
|
298
|
+
if (busyRef.current) return; // still generating; Esc cancels
|
|
299
|
+
handleSubmit(inputRef.current);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (key.backspace || key.delete) {
|
|
304
|
+
commitInput(inputRef.current.slice(0, -1));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (key.tab && phase === 'idle' && inputRef.current.startsWith('/')) {
|
|
309
|
+
const prefix = inputRef.current.slice(1).toLowerCase();
|
|
310
|
+
const matches = getCommands().filter(c => c.name.startsWith(prefix));
|
|
311
|
+
if (matches.length === 1) {
|
|
312
|
+
commitInput(`/${matches[0].name} `);
|
|
313
|
+
}
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (phase === 'idle' && key.upArrow) {
|
|
318
|
+
const inputs = history.map(h => h.input);
|
|
319
|
+
if (inputs.length === 0) return;
|
|
320
|
+
|
|
321
|
+
if (historyIndex === -1) {
|
|
322
|
+
setSavedInput(inputRef.current);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const newIndex = historyIndex === -1
|
|
326
|
+
? inputs.length - 1
|
|
327
|
+
: Math.max(0, historyIndex - 1);
|
|
328
|
+
|
|
329
|
+
setHistoryIndex(newIndex);
|
|
330
|
+
commitInput(inputs[newIndex]);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (phase === 'idle' && key.downArrow) {
|
|
335
|
+
if (historyIndex === -1) return;
|
|
336
|
+
|
|
337
|
+
const inputs = history.map(h => h.input);
|
|
338
|
+
const newIndex = historyIndex + 1;
|
|
339
|
+
|
|
340
|
+
if (newIndex >= inputs.length) {
|
|
341
|
+
setHistoryIndex(-1);
|
|
342
|
+
commitInput(savedInput);
|
|
343
|
+
} else {
|
|
344
|
+
setHistoryIndex(newIndex);
|
|
345
|
+
commitInput(inputs[newIndex]);
|
|
346
|
+
}
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (ch && !key.ctrl && !key.meta) {
|
|
351
|
+
commitInput(inputRef.current + ch);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
const promptLabel = phase === 'model_select'
|
|
356
|
+
? 'model> '
|
|
357
|
+
: phase === 'model_apikey'
|
|
358
|
+
? 'apikey> '
|
|
359
|
+
: phase === 'permission'
|
|
360
|
+
? 'allow?> '
|
|
361
|
+
: '> ';
|
|
362
|
+
|
|
363
|
+
return (
|
|
364
|
+
<Box flexDirection="column" paddingX={1}>
|
|
365
|
+
{history.map((entry, i) => (
|
|
366
|
+
<Box key={i} flexDirection="column">
|
|
367
|
+
{entry.input && (
|
|
368
|
+
<Box>
|
|
369
|
+
<Text color="green">> </Text>
|
|
370
|
+
<Text>{entry.input}</Text>
|
|
371
|
+
</Box>
|
|
372
|
+
)}
|
|
373
|
+
{entry.output && (
|
|
374
|
+
<Box marginLeft={2}>
|
|
375
|
+
<Text color="gray">{entry.output}</Text>
|
|
376
|
+
</Box>
|
|
377
|
+
)}
|
|
378
|
+
</Box>
|
|
379
|
+
))}
|
|
380
|
+
|
|
381
|
+
{phase === 'permission' && pendingPermissionRef.current && (
|
|
382
|
+
<Box marginLeft={2}>
|
|
383
|
+
<Text color="yellow">
|
|
384
|
+
⚙ {pendingPermissionRef.current.request.title} ({pendingPermissionRef.current.request.kind}) — allow? y/n
|
|
385
|
+
</Text>
|
|
386
|
+
</Box>
|
|
387
|
+
)}
|
|
388
|
+
|
|
389
|
+
{busy && phase === 'idle' && (
|
|
390
|
+
<Box marginLeft={2}>
|
|
391
|
+
<Text dimColor>… generating (Esc to cancel)</Text>
|
|
392
|
+
</Box>
|
|
393
|
+
)}
|
|
394
|
+
|
|
395
|
+
{phase === 'model_select' && (
|
|
396
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
397
|
+
{models.map((m, i) => (
|
|
398
|
+
<Box key={m.id}>
|
|
399
|
+
<Text color={i === modelCursor ? 'cyan' : undefined}>
|
|
400
|
+
{i === modelCursor ? '❯ ' : ' '}
|
|
401
|
+
{m.id.padEnd(10)} {m.name}
|
|
402
|
+
</Text>
|
|
403
|
+
{m.id === ctx.modelId && (
|
|
404
|
+
<Text color="yellow"> (current)</Text>
|
|
405
|
+
)}
|
|
406
|
+
</Box>
|
|
407
|
+
))}
|
|
408
|
+
</Box>
|
|
409
|
+
)}
|
|
410
|
+
|
|
411
|
+
{phase !== 'model_select' && (
|
|
412
|
+
<Box>
|
|
413
|
+
<Text color={phase === 'idle' ? 'green' : 'yellow'}>{promptLabel}</Text>
|
|
414
|
+
<Text>{phase === 'model_apikey' ? '*'.repeat(input.length) : input}</Text>
|
|
415
|
+
<Text color="gray">▎</Text>
|
|
416
|
+
</Box>
|
|
417
|
+
)}
|
|
418
|
+
|
|
419
|
+
{phase === 'idle' && input.startsWith('/') && (() => {
|
|
420
|
+
const prefix = input.slice(1).toLowerCase();
|
|
421
|
+
const matches = getCommands()
|
|
422
|
+
.filter(c => !prefix || c.name.startsWith(prefix))
|
|
423
|
+
.map(c => ` /${c.name.padEnd(10)} ${c.description}`);
|
|
424
|
+
if (matches.length === 0 || (prefix && matches.length === 1 && matches[0].slice(2, 2 + prefix.length).toLowerCase() === prefix)) return null;
|
|
425
|
+
return (
|
|
426
|
+
<Box marginLeft={2}>
|
|
427
|
+
<Text color="blue" dimColor>{matches.join('\n')}</Text>
|
|
428
|
+
</Box>
|
|
429
|
+
);
|
|
430
|
+
})()}
|
|
431
|
+
</Box>
|
|
432
|
+
);
|
|
433
|
+
}
|
package/src/tui/cli.tsx
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Ink reads stdin in paused mode ('readable' event + read() loop) and
|
|
5
|
+
* treats each chunk as a single keypress. Burst input (paste, terminal
|
|
6
|
+
* multiplexer send-keys, fast typing coalesced by the runtime) therefore
|
|
7
|
+
* arrives glued — e.g. "help\r" — and keys like Enter/Escape silently
|
|
8
|
+
* stop working. Bun's stdin layer makes this worse by merging even
|
|
9
|
+
* time-separated writes into one chunk.
|
|
10
|
+
*
|
|
11
|
+
* This proxy reads the real stdin in flowing mode, splits every buffer
|
|
12
|
+
* into discrete keystrokes (one escape sequence, or one character per
|
|
13
|
+
* key), and hands them to Ink ONE PER read() call — chunk coalescing is
|
|
14
|
+
* impossible on any runtime.
|
|
15
|
+
*
|
|
16
|
+
* Implements exactly the subset of the stdin API Ink uses:
|
|
17
|
+
* addListener/removeListener('readable'), read(), setEncoding(),
|
|
18
|
+
* setRawMode(), ref(), unref(), isTTY.
|
|
19
|
+
*/
|
|
20
|
+
class KeyedStdin extends EventEmitter {
|
|
21
|
+
readonly isTTY = true;
|
|
22
|
+
private queue: string[] = [];
|
|
23
|
+
private readonly realStdin: NodeJS.ReadStream & {
|
|
24
|
+
setRawMode(mode: boolean): unknown;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
constructor(realStdin: NodeJS.ReadStream & { setRawMode(mode: boolean): unknown }) {
|
|
28
|
+
super();
|
|
29
|
+
this.realStdin = realStdin;
|
|
30
|
+
realStdin.setEncoding('utf8');
|
|
31
|
+
realStdin.on('data', (chunk: string) => {
|
|
32
|
+
if (!chunk) return;
|
|
33
|
+
if (chunk.charCodeAt(0) === 0x1b) {
|
|
34
|
+
// Escape sequences arrive atomically — keep as one key.
|
|
35
|
+
this.pushKey(chunk);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
// Plain characters: enqueue one key per character (for..of splits
|
|
39
|
+
// by code point, so multi-byte input (e.g. CJK) stays intact).
|
|
40
|
+
for (const ch of chunk) this.pushKey(ch);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
setEncoding(_encoding: string): void {
|
|
45
|
+
// Chunks pushed in the constructor are already strings.
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
setRawMode(mode: boolean): void {
|
|
49
|
+
this.realStdin.setRawMode(mode);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
ref(): void {
|
|
53
|
+
// Real stdin stays ref'd for the lifetime of the process.
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Ink calls unref() when the last raw-mode consumer unmounts. The
|
|
58
|
+
* flowing-mode listener on the real stdin keeps the event loop alive,
|
|
59
|
+
* so it must be parked here or the process never exits after `exit`.
|
|
60
|
+
*/
|
|
61
|
+
unref(): void {
|
|
62
|
+
this.realStdin.pause();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Always returns at most one keystroke — never a merged chunk. */
|
|
66
|
+
read(): string | null {
|
|
67
|
+
return this.queue.shift() ?? null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
pushKey(key: string): void {
|
|
71
|
+
this.queue.push(key);
|
|
72
|
+
// Emit synchronously — every 'readable' sees exactly one queued key,
|
|
73
|
+
// and there is no scheduling window in which listeners can change.
|
|
74
|
+
this.emit('readable');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function createKeyedStdin(): NodeJS.ReadStream {
|
|
79
|
+
const proxy = new KeyedStdin(
|
|
80
|
+
process.stdin as NodeJS.ReadStream & { setRawMode(mode: boolean): unknown },
|
|
81
|
+
);
|
|
82
|
+
return proxy as unknown as NodeJS.ReadStream;
|
|
83
|
+
}
|
package/src/upgrade.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { VERSION } from './version.js';
|
|
6
|
+
|
|
7
|
+
const PKG = '@trans-ai/trans-code';
|
|
8
|
+
|
|
9
|
+
function sh(cmd: string, args: string[]): Promise<{ code: number; stdout: string }> {
|
|
10
|
+
return new Promise(resolve => {
|
|
11
|
+
const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'inherit'] });
|
|
12
|
+
let stdout = '';
|
|
13
|
+
child.stdout.on('data', (d: Buffer) => {
|
|
14
|
+
stdout += d.toString();
|
|
15
|
+
});
|
|
16
|
+
child.on('error', err => {
|
|
17
|
+
process.stderr.write(`[transcode] failed to run ${cmd}: ${err.message}\n`);
|
|
18
|
+
resolve({ code: 1, stdout });
|
|
19
|
+
});
|
|
20
|
+
child.on('close', code => resolve({ code: code ?? 1, stdout }));
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function shInherit(cmd: string, args: string[]): Promise<number> {
|
|
25
|
+
return new Promise(resolve => {
|
|
26
|
+
const child = spawn(cmd, args, { stdio: 'inherit' });
|
|
27
|
+
child.on('error', err => {
|
|
28
|
+
process.stderr.write(`[transcode] failed to run ${cmd}: ${err.message}\n`);
|
|
29
|
+
resolve(1);
|
|
30
|
+
});
|
|
31
|
+
child.on('close', code => resolve(code ?? 1));
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function npmRoot(): Promise<string> {
|
|
36
|
+
const r = await sh('npm', ['root', '-g']);
|
|
37
|
+
return r.stdout.trim();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function latestVersion(): Promise<string | null> {
|
|
41
|
+
const r = await sh('npm', ['view', `${PKG}@latest`, 'version']);
|
|
42
|
+
if (r.code !== 0) return null;
|
|
43
|
+
const v = r.stdout.trim();
|
|
44
|
+
return v || null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function installedVersionUnder(root: string): string | null {
|
|
48
|
+
try {
|
|
49
|
+
const pkg = JSON.parse(readFileSync(`${root}/${PKG}/package.json`, 'utf8'));
|
|
50
|
+
return typeof pkg.version === 'string' ? pkg.version : null;
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function runUpgrade(): Promise<void> {
|
|
57
|
+
process.stdout.write(`transcode v${VERSION} — checking for upgrades…\n`);
|
|
58
|
+
|
|
59
|
+
const entry = realpathSync(fileURLToPath(import.meta.url));
|
|
60
|
+
const root = await npmRoot();
|
|
61
|
+
// Normalize both sides through realpath — macOS aliases like /tmp vs
|
|
62
|
+
// /private/tmp would otherwise break prefix comparison.
|
|
63
|
+
const rootReal = root ? realpathSync(root) : '';
|
|
64
|
+
if (process.env.TRANSCODE_DEBUG_UPGRADE === '1') {
|
|
65
|
+
process.stdout.write(`[debug] entry=${entry}\n[debug] root=${rootReal}\n`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (!rootReal || !entry.startsWith(rootReal)) {
|
|
69
|
+
process.stdout.write(
|
|
70
|
+
[
|
|
71
|
+
'This looks like a development install (bun link / repo checkout),',
|
|
72
|
+
'not an npm global install — nothing to auto-upgrade.',
|
|
73
|
+
'',
|
|
74
|
+
'Options:',
|
|
75
|
+
' · pull the latest repo: git pull && bun install',
|
|
76
|
+
' · switch to npm install: npm i -g @trans-ai/trans-code',
|
|
77
|
+
].join('\n') + '\n',
|
|
78
|
+
);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const latest = await latestVersion();
|
|
83
|
+
if (!latest) {
|
|
84
|
+
process.stderr.write(
|
|
85
|
+
'[transcode] could not reach the npm registry to check the latest version.\n',
|
|
86
|
+
);
|
|
87
|
+
process.exitCode = 1;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (latest === VERSION) {
|
|
92
|
+
process.stdout.write(`Already up to date (v${VERSION}).\n`);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
process.stdout.write(`Upgrading ${VERSION} → ${latest}…\n`);
|
|
97
|
+
const code = await shInherit('npm', ['i', '-g', `${PKG}@latest`]);
|
|
98
|
+
if (code !== 0) {
|
|
99
|
+
process.stderr.write('[transcode] upgrade failed — see npm output above.\n');
|
|
100
|
+
process.exitCode = 1;
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const installed = installedVersionUnder(root);
|
|
105
|
+
if (installed) {
|
|
106
|
+
process.stdout.write(`Upgraded to v${installed}. Restart transcode if it is running.\n`);
|
|
107
|
+
} else {
|
|
108
|
+
process.stdout.write(`Upgrade finished. Restart transcode if it is running.\n`);
|
|
109
|
+
}
|
|
110
|
+
}
|
package/src/version.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = '0.1.0';
|