@powerhousedao/clint 0.0.0-stage → 6.2.3-dev.57

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 (49) hide show
  1. package/LICENSE +661 -0
  2. package/dist/build-skills-C1Vr_kQh.mjs +293 -0
  3. package/dist/build-skills-C1Vr_kQh.mjs.map +1 -0
  4. package/dist/dist-CUltriBW.mjs +1628 -0
  5. package/dist/dist-CUltriBW.mjs.map +1 -0
  6. package/dist/drive-CNCPoCNs.mjs +82 -0
  7. package/dist/drive-CNCPoCNs.mjs.map +1 -0
  8. package/dist/esm-C1DOsF1a.mjs +13140 -0
  9. package/dist/esm-C1DOsF1a.mjs.map +1 -0
  10. package/dist/events-DkzJFZeW.mjs +237 -0
  11. package/dist/events-DkzJFZeW.mjs.map +1 -0
  12. package/dist/folders-mLL9D5Ck.mjs +254 -0
  13. package/dist/folders-mLL9D5Ck.mjs.map +1 -0
  14. package/dist/index.d.mts +1005 -0
  15. package/dist/index.d.mts.map +1 -0
  16. package/dist/index.mjs +6 -0
  17. package/dist/local-signer-EFzJV3bn.mjs +128 -0
  18. package/dist/local-signer-EFzJV3bn.mjs.map +1 -0
  19. package/dist/markdown-C1TFXoB6.mjs +275 -0
  20. package/dist/markdown-C1TFXoB6.mjs.map +1 -0
  21. package/dist/reactor-C9VIUX1H.mjs +51 -0
  22. package/dist/reactor-C9VIUX1H.mjs.map +1 -0
  23. package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
  24. package/dist/runners/clint-runner.d.mts +109 -0
  25. package/dist/runners/clint-runner.d.mts.map +1 -0
  26. package/dist/runners/clint-runner.mjs +202 -0
  27. package/dist/runners/clint-runner.mjs.map +1 -0
  28. package/dist/runners/mastra-runner.d.mts +100 -0
  29. package/dist/runners/mastra-runner.d.mts.map +1 -0
  30. package/dist/runners/mastra-runner.mjs +309 -0
  31. package/dist/runners/mastra-runner.mjs.map +1 -0
  32. package/dist/services-BvLvP5Qh.mjs +1210 -0
  33. package/dist/services-BvLvP5Qh.mjs.map +1 -0
  34. package/dist/src-DRDGtXYJ.mjs +5061 -0
  35. package/dist/src-DRDGtXYJ.mjs.map +1 -0
  36. package/dist/start-CKRhuB1Y.mjs +1526 -0
  37. package/dist/start-CKRhuB1Y.mjs.map +1 -0
  38. package/dist/stdin-BjAO9gPK.mjs +17 -0
  39. package/dist/stdin-BjAO9gPK.mjs.map +1 -0
  40. package/dist/stream-DVuufwIj.mjs +148 -0
  41. package/dist/stream-DVuufwIj.mjs.map +1 -0
  42. package/dist/subscriptions-CfiflAsI.mjs +38 -0
  43. package/dist/subscriptions-CfiflAsI.mjs.map +1 -0
  44. package/dist/switchboard-DAS-5x53.mjs +48 -0
  45. package/dist/switchboard-DAS-5x53.mjs.map +1 -0
  46. package/dist/types-DrLfp2dR.d.mts +1766 -0
  47. package/dist/types-DrLfp2dR.d.mts.map +1 -0
  48. package/package.json +101 -3
  49. package/README.md +0 -3
@@ -0,0 +1,1526 @@
1
+ import { r as resolveServiceName } from "./services-BvLvP5Qh.mjs";
2
+ import { n as applyCompletion, o as formatStreamChunk, t as renderMarkdown } from "./markdown-C1TFXoB6.mjs";
3
+ import path from "node:path";
4
+ import { useCallback, useEffect, useRef, useState } from "react";
5
+ import { Box, Static, Text, render, useApp, useInput, useStdin, useStdout } from "ink";
6
+ import Spinner from "ink-spinner";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ //#region src/interactive/text-input.tsx
9
+ /** Test whether a character is a word boundary (whitespace). */
10
+ const isWordBoundary = (ch) => ch === " " || ch === "\n" || ch === " ";
11
+ /**
12
+ * Controlled text input with external cursor positioning.
13
+ *
14
+ * Based on ink-text-input but adds a `cursorOffset` prop so that
15
+ * tab-completion and other programmatic value changes can move
16
+ * the cursor to the correct position.
17
+ *
18
+ * Uses Ink's `<Text>` with `inverse` for cursor rendering instead of chalk,
19
+ * so no extra dependencies are needed.
20
+ */
21
+ function TextInput({ value: originalValue, placeholder = "", focus = true, showCursor = true, cursorOffset: externalCursorOffset, suggestion = "", onChange, onSubmit }) {
22
+ const [internalOffset, setInternalOffset] = useState((originalValue || "").length);
23
+ useEffect(() => {
24
+ if (externalCursorOffset !== void 0) setInternalOffset(externalCursorOffset);
25
+ }, [externalCursorOffset]);
26
+ useEffect(() => {
27
+ const len = (originalValue || "").length;
28
+ setInternalOffset((prev) => prev > len ? len : prev);
29
+ }, [originalValue]);
30
+ const cursorOffset = internalOffset;
31
+ const { stdin } = useStdin();
32
+ const isForwardDelete = useRef(false);
33
+ const isCtrlBackspace = useRef(false);
34
+ const isCtrlDelete = useRef(false);
35
+ useEffect(() => {
36
+ const onData = (data) => {
37
+ const s = data.toString();
38
+ isForwardDelete.current = s === "\x1B[3~" || s === "\x1B[3;5~";
39
+ isCtrlBackspace.current = s === "";
40
+ isCtrlDelete.current = s === "\x1B[3;5~" || s === "\x1Bd";
41
+ };
42
+ stdin.on("data", onData);
43
+ return () => {
44
+ stdin.off("data", onData);
45
+ };
46
+ }, [stdin]);
47
+ useInput((input, key) => {
48
+ if (input === "[I" || input === "[O" || key.escape && (input === "I" || input === "O")) return;
49
+ if (key.ctrl && input === "c" || key.tab || key.shift && key.tab) return;
50
+ if (isCtrlBackspace.current) {
51
+ isCtrlBackspace.current = false;
52
+ if (cursorOffset > 0) {
53
+ let i = cursorOffset - 1;
54
+ while (i > 0 && isWordBoundary(originalValue[i - 1])) i--;
55
+ while (i > 0 && !isWordBoundary(originalValue[i - 1])) i--;
56
+ const nextValue = originalValue.slice(0, i) + originalValue.slice(cursorOffset);
57
+ setInternalOffset(i);
58
+ if (nextValue !== originalValue) onChange(nextValue);
59
+ }
60
+ return;
61
+ }
62
+ if (isCtrlDelete.current) {
63
+ isCtrlDelete.current = false;
64
+ if (cursorOffset < originalValue.length) {
65
+ let i = cursorOffset;
66
+ while (i < originalValue.length && isWordBoundary(originalValue[i])) i++;
67
+ while (i < originalValue.length && !isWordBoundary(originalValue[i])) i++;
68
+ const nextValue = originalValue.slice(0, cursorOffset) + originalValue.slice(i);
69
+ if (nextValue !== originalValue) onChange(nextValue);
70
+ }
71
+ return;
72
+ }
73
+ if (key.upArrow || key.downArrow) {
74
+ const lines = originalValue.split("\n");
75
+ if (lines.length <= 1) return;
76
+ let charCount = 0;
77
+ let cursorLine = 0;
78
+ for (let i = 0; i < lines.length; i++) {
79
+ if (cursorOffset <= charCount + lines[i].length) {
80
+ cursorLine = i;
81
+ break;
82
+ }
83
+ charCount += lines[i].length + 1;
84
+ }
85
+ const colInLine = cursorOffset - charCount;
86
+ if (key.upArrow) {
87
+ if (cursorLine === 0) return;
88
+ const prevLineStart = charCount - lines[cursorLine - 1].length - 1;
89
+ const newCol = Math.min(colInLine, lines[cursorLine - 1].length);
90
+ setInternalOffset(prevLineStart + newCol);
91
+ } else {
92
+ if (cursorLine === lines.length - 1) return;
93
+ const nextLineStart = charCount + lines[cursorLine].length + 1;
94
+ const newCol = Math.min(colInLine, lines[cursorLine + 1].length);
95
+ setInternalOffset(nextLineStart + newCol);
96
+ }
97
+ return;
98
+ }
99
+ if (key.return) {
100
+ if (key.meta || key.shift) {
101
+ const nextVal = originalValue.slice(0, cursorOffset) + "\n" + originalValue.slice(cursorOffset);
102
+ setInternalOffset(cursorOffset + 1);
103
+ onChange(nextVal);
104
+ return;
105
+ }
106
+ onSubmit?.(originalValue);
107
+ return;
108
+ }
109
+ let nextOffset = cursorOffset;
110
+ let nextValue = originalValue;
111
+ if (key.home) nextOffset = 0;
112
+ else if (key.end) nextOffset = originalValue.length;
113
+ else if (key.leftArrow) {
114
+ if (showCursor) {
115
+ if (key.ctrl) {
116
+ let i = cursorOffset - 1;
117
+ while (i > 0 && isWordBoundary(originalValue[i - 1])) i--;
118
+ while (i > 0 && !isWordBoundary(originalValue[i - 1])) i--;
119
+ nextOffset = i;
120
+ } else nextOffset--;
121
+ }
122
+ } else if (key.rightArrow) {
123
+ if (showCursor) {
124
+ if (key.ctrl) {
125
+ let i = cursorOffset;
126
+ while (i < originalValue.length && !isWordBoundary(originalValue[i])) i++;
127
+ while (i < originalValue.length && isWordBoundary(originalValue[i])) i++;
128
+ nextOffset = i;
129
+ } else nextOffset++;
130
+ }
131
+ } else if ((key.delete || key.backspace) && isForwardDelete.current) {
132
+ if (cursorOffset < originalValue.length) nextValue = originalValue.slice(0, cursorOffset) + originalValue.slice(cursorOffset + 1);
133
+ } else if (key.delete || key.backspace) {
134
+ if (cursorOffset > 0) {
135
+ nextValue = originalValue.slice(0, cursorOffset - 1) + originalValue.slice(cursorOffset);
136
+ nextOffset--;
137
+ }
138
+ } else {
139
+ nextValue = originalValue.slice(0, cursorOffset) + input + originalValue.slice(cursorOffset);
140
+ nextOffset += input.length;
141
+ }
142
+ if (nextOffset < 0) nextOffset = 0;
143
+ if (nextOffset > nextValue.length) nextOffset = nextValue.length;
144
+ setInternalOffset(nextOffset);
145
+ if (nextValue !== originalValue) onChange(nextValue);
146
+ }, { isActive: focus });
147
+ if (!showCursor || !focus) {
148
+ if (originalValue.length > 0) return /* @__PURE__ */ jsx(Text, { children: originalValue });
149
+ return placeholder ? /* @__PURE__ */ jsx(Text, {
150
+ dimColor: true,
151
+ children: placeholder
152
+ }) : /* @__PURE__ */ jsx(Text, { children: " " });
153
+ }
154
+ if (originalValue.length === 0) {
155
+ if (placeholder) return /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
156
+ inverse: true,
157
+ children: placeholder[0]
158
+ }), /* @__PURE__ */ jsx(Text, {
159
+ dimColor: true,
160
+ children: placeholder.slice(1)
161
+ })] });
162
+ return /* @__PURE__ */ jsx(Text, {
163
+ inverse: true,
164
+ children: " "
165
+ });
166
+ }
167
+ const before = originalValue.slice(0, cursorOffset);
168
+ const atEnd = cursorOffset >= originalValue.length;
169
+ if (atEnd && suggestion) {
170
+ const ghost = suggestion.slice(originalValue.length);
171
+ if (ghost.length > 0) return /* @__PURE__ */ jsxs(Text, { children: [
172
+ before,
173
+ /* @__PURE__ */ jsx(Text, {
174
+ dimColor: true,
175
+ inverse: true,
176
+ children: ghost[0]
177
+ }),
178
+ /* @__PURE__ */ jsx(Text, {
179
+ dimColor: true,
180
+ children: ghost.slice(1)
181
+ })
182
+ ] });
183
+ }
184
+ const rawChar = !atEnd ? originalValue[cursorOffset] : " ";
185
+ const after = !atEnd ? originalValue.slice(cursorOffset + 1) : "";
186
+ return /* @__PURE__ */ jsxs(Text, { children: [
187
+ before,
188
+ /* @__PURE__ */ jsx(Text, {
189
+ inverse: true,
190
+ children: rawChar === "\n" ? " " : rawChar
191
+ }),
192
+ rawChar === "\n" ? "\n" : "",
193
+ after
194
+ ] });
195
+ }
196
+ //#endregion
197
+ //#region src/interactive/service-panel.tsx
198
+ function statusIcon(status) {
199
+ return status === "ready" ? "●" : status === "starting" ? "◐" : status === "failed" ? "✗" : status === "stopping" ? "◑" : status === "stopped" ? "■" : "○";
200
+ }
201
+ function statusColor(status) {
202
+ return status === "ready" ? "green" : status === "starting" ? "yellow" : status === "failed" ? "red" : "gray";
203
+ }
204
+ /**
205
+ * Build a combined list of instances + discovered projects.
206
+ * Projects whose path matches a running/stopped instance's workdir are excluded.
207
+ */
208
+ function buildPanelItems(statuses, services, workdir) {
209
+ const items = [];
210
+ const instanceWorkdirs = /* @__PURE__ */ new Set();
211
+ for (const svc of statuses) if (svc.workdir) instanceWorkdirs.add(svc.workdir);
212
+ const serviceIds = new Set(statuses.map((s) => s.serviceId));
213
+ let hasProjects = false;
214
+ const projectItems = [];
215
+ if (workdir) for (const sid of serviceIds) {
216
+ if (!services.getDefinition(sid)?.projectScanner) continue;
217
+ const projects = services.scanProjects(sid, workdir);
218
+ for (const proj of projects) if (!instanceWorkdirs.has(proj.path)) {
219
+ projectItems.push({
220
+ kind: "project",
221
+ data: proj,
222
+ serviceId: sid
223
+ });
224
+ hasProjects = true;
225
+ }
226
+ }
227
+ for (const svc of statuses) {
228
+ if (svc.status === "idle" && hasProjects) continue;
229
+ items.push({
230
+ kind: "instance",
231
+ data: svc
232
+ });
233
+ }
234
+ items.push(...projectItems);
235
+ return items;
236
+ }
237
+ /**
238
+ * Interactive service management panel for the REPL.
239
+ * Shows service status, supports start/stop, log viewing, and detail inspection.
240
+ * When a service has a projectScanner and workdir is provided, discovered projects
241
+ * are shown and can be started directly.
242
+ */
243
+ function ServicePanel({ services, onExit, serviceId, workdir }) {
244
+ const { stdout } = useStdout();
245
+ const columns = stdout?.columns || 80;
246
+ const [statuses, setStatuses] = useState(() => services.list(serviceId));
247
+ const [items, setItems] = useState(() => buildPanelItems(services.list(serviceId), services, workdir));
248
+ const [selected, setSelected] = useState(0);
249
+ const [view, setView] = useState("list");
250
+ const [busy, setBusy] = useState(null);
251
+ const [logLines, setLogLines] = useState([]);
252
+ const [detailServiceId, setDetailServiceId] = useState(null);
253
+ const [confirm, setConfirm] = useState(null);
254
+ const cleanupRef = useRef(null);
255
+ function refreshList() {
256
+ const newStatuses = services.list(serviceId);
257
+ setStatuses(newStatuses);
258
+ setItems(buildPanelItems(newStatuses, services, workdir));
259
+ }
260
+ useEffect(() => {
261
+ const timer = setInterval(refreshList, 2e3);
262
+ return () => clearInterval(timer);
263
+ }, [services, workdir]);
264
+ useEffect(() => {
265
+ return () => {
266
+ cleanupRef.current?.();
267
+ };
268
+ }, []);
269
+ const openLogs = useCallback((svcId, instId) => {
270
+ cleanupRef.current?.();
271
+ const initial = services.logs(svcId, instId, 30).split("\n");
272
+ setLogLines(initial);
273
+ setDetailServiceId(svcId);
274
+ setView("logs");
275
+ const cleanup = services.watchLogs(svcId, instId, (line) => {
276
+ setLogLines((prev) => [...prev.slice(-200), line]);
277
+ });
278
+ cleanupRef.current = cleanup;
279
+ }, [services]);
280
+ const closeSubview = useCallback(() => {
281
+ cleanupRef.current?.();
282
+ cleanupRef.current = null;
283
+ setLogLines([]);
284
+ setDetailServiceId(null);
285
+ setView("list");
286
+ refreshList();
287
+ }, [services, workdir]);
288
+ const openDetails = useCallback((svcId) => {
289
+ setDetailServiceId(svcId);
290
+ setView("details");
291
+ }, []);
292
+ const startProject = useCallback(async (projServiceId, projPath) => {
293
+ const def = services.getDefinition(projServiceId);
294
+ if (!def) return;
295
+ const maxInstances = def.maxInstances ?? 1;
296
+ const running = statuses.filter((s) => s.serviceId === projServiceId && (s.status === "ready" || s.status === "starting"));
297
+ if (running.length >= maxInstances) {
298
+ if (maxInstances === 1 && running.length === 1) {
299
+ setConfirm({
300
+ message: `${resolveServiceName(def)} is already running. Kill and start in ${path.basename(projPath)}? (y/n)`,
301
+ onConfirm: async () => {
302
+ setConfirm(null);
303
+ setBusy(`Restarting ${resolveServiceName(def)}...`);
304
+ try {
305
+ await services.stop(projServiceId);
306
+ await services.start(projServiceId, {
307
+ workdir: projPath,
308
+ cwd: projPath
309
+ });
310
+ } catch {}
311
+ setBusy(null);
312
+ refreshList();
313
+ }
314
+ });
315
+ return;
316
+ }
317
+ setBusy(`Instance limit reached (${maxInstances}). Stop an instance first.`);
318
+ setTimeout(() => setBusy(null), 3e3);
319
+ return;
320
+ }
321
+ setBusy(`Starting ${resolveServiceName(def)} in ${path.basename(projPath)}...`);
322
+ try {
323
+ await services.start(projServiceId, {
324
+ workdir: projPath,
325
+ cwd: projPath
326
+ });
327
+ } catch {}
328
+ setBusy(null);
329
+ refreshList();
330
+ }, [
331
+ services,
332
+ statuses,
333
+ workdir
334
+ ]);
335
+ const toggleInstance = useCallback(async (svc) => {
336
+ if (svc.status === "ready" || svc.status === "starting") {
337
+ setBusy(`Stopping ${svc.name}...`);
338
+ try {
339
+ await services.stop(svc.serviceId, svc.instanceId);
340
+ } catch {}
341
+ } else {
342
+ setBusy(`Starting ${svc.name}...`);
343
+ try {
344
+ await services.start(svc.serviceId, {
345
+ workdir: svc.workdir,
346
+ cwd: svc.workdir,
347
+ params: svc.params
348
+ });
349
+ } catch {}
350
+ }
351
+ setBusy(null);
352
+ refreshList();
353
+ }, [services, workdir]);
354
+ const handleAction = useCallback(async () => {
355
+ const item = items[selected];
356
+ if (!item || busy) return;
357
+ if (item.kind === "project") await startProject(item.serviceId, item.data.path);
358
+ else await toggleInstance(item.data);
359
+ }, [
360
+ items,
361
+ selected,
362
+ busy,
363
+ startProject,
364
+ toggleInstance
365
+ ]);
366
+ useInput((ch, key) => {
367
+ if (confirm) {
368
+ if (ch === "y" || ch === "Y") confirm.onConfirm();
369
+ else setConfirm(null);
370
+ return;
371
+ }
372
+ if (view === "logs" || view === "details") {
373
+ if (key.escape || ch === "q" || ch === "Q") {
374
+ closeSubview();
375
+ return;
376
+ }
377
+ if (view === "details" && (ch === "l" || ch === "L") && detailServiceId) {
378
+ const inst = statuses.find((s) => s.serviceId === detailServiceId);
379
+ if (inst) openLogs(detailServiceId, inst.instanceId);
380
+ return;
381
+ }
382
+ return;
383
+ }
384
+ if (key.escape || ch === "q" || ch === "Q") {
385
+ onExit();
386
+ return;
387
+ }
388
+ if (key.upArrow || ch === "k") {
389
+ setSelected((s) => Math.max(0, s - 1));
390
+ return;
391
+ }
392
+ if (key.downArrow || ch === "j") {
393
+ setSelected((s) => Math.min(items.length - 1, s + 1));
394
+ return;
395
+ }
396
+ if (key.return || ch === " ") {
397
+ handleAction();
398
+ return;
399
+ }
400
+ if (ch === "d" || ch === "D") {
401
+ const item = items[selected];
402
+ if (item?.kind === "instance") openDetails(item.data.serviceId);
403
+ return;
404
+ }
405
+ if (ch === "l" || ch === "L") {
406
+ const item = items[selected];
407
+ if (item?.kind === "instance") openLogs(item.data.serviceId, item.data.instanceId);
408
+ return;
409
+ }
410
+ if (ch === "r" || ch === "R") {
411
+ refreshList();
412
+ return;
413
+ }
414
+ });
415
+ const hr = /* @__PURE__ */ jsx(Text, {
416
+ color: "green",
417
+ children: "─".repeat(columns)
418
+ });
419
+ if (view === "details" && detailServiceId) {
420
+ const svc = statuses.find((s) => s.serviceId === detailServiceId);
421
+ const def = services.getDefinition(detailServiceId);
422
+ const patterns = def?.readiness?.patterns ?? (def?.readiness?.pattern ? [{
423
+ name: "_default",
424
+ pattern: def.readiness.pattern,
425
+ captures: def.readiness.captures
426
+ }] : []);
427
+ return /* @__PURE__ */ jsxs(Box, {
428
+ flexDirection: "column",
429
+ children: [
430
+ hr,
431
+ /* @__PURE__ */ jsxs(Box, {
432
+ justifyContent: "space-between",
433
+ children: [/* @__PURE__ */ jsxs(Text, {
434
+ bold: true,
435
+ color: "cyan",
436
+ children: [
437
+ " ",
438
+ svc?.name ?? detailServiceId,
439
+ " "
440
+ ]
441
+ }), /* @__PURE__ */ jsx(Text, {
442
+ dimColor: true,
443
+ children: " l logs q/Esc back "
444
+ })]
445
+ }),
446
+ hr,
447
+ /* @__PURE__ */ jsxs(Box, {
448
+ flexDirection: "column",
449
+ marginLeft: 2,
450
+ marginTop: 1,
451
+ children: [
452
+ /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
453
+ bold: true,
454
+ children: "ID: "
455
+ }), detailServiceId] }),
456
+ /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
457
+ bold: true,
458
+ children: "Status: "
459
+ }), /* @__PURE__ */ jsxs(Text, {
460
+ color: statusColor(svc?.status ?? "idle"),
461
+ children: [
462
+ statusIcon(svc?.status ?? "idle"),
463
+ " ",
464
+ svc?.status ?? "idle"
465
+ ]
466
+ })] }),
467
+ /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
468
+ bold: true,
469
+ children: "PID: "
470
+ }), String(svc?.pid ?? "—")] }),
471
+ /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
472
+ bold: true,
473
+ children: "Command: "
474
+ }), typeof def?.command === "function" ? "(dynamic)" : def?.command ?? "—"] }),
475
+ def?.shutdown && /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
476
+ bold: true,
477
+ children: "Shutdown:"
478
+ }), ` ${def.shutdown.signal} (timeout ${def.shutdown.timeout}ms)`] }),
479
+ def?.restart?.enabled && /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
480
+ bold: true,
481
+ children: "Restart: "
482
+ }), `enabled, max ${def.restart.maxRetries} retries, ${def.restart.delay}ms delay`] }),
483
+ svc?.error && /* @__PURE__ */ jsxs(Text, { children: [/* @__PURE__ */ jsx(Text, {
484
+ bold: true,
485
+ children: "Error: "
486
+ }), /* @__PURE__ */ jsx(Text, {
487
+ color: "red",
488
+ children: svc.error
489
+ })] }),
490
+ svc?.endpoints && Object.keys(svc.endpoints).length > 0 && /* @__PURE__ */ jsxs(Box, {
491
+ flexDirection: "column",
492
+ marginTop: 1,
493
+ children: [/* @__PURE__ */ jsx(Text, {
494
+ bold: true,
495
+ children: "Endpoints:"
496
+ }), Object.entries(svc.endpoints).map(([k, v]) => /* @__PURE__ */ jsxs(Text, { children: [
497
+ " ",
498
+ k,
499
+ ": ",
500
+ v
501
+ ] }, k))]
502
+ }),
503
+ patterns.length > 0 && /* @__PURE__ */ jsxs(Box, {
504
+ flexDirection: "column",
505
+ marginTop: 1,
506
+ children: [/* @__PURE__ */ jsxs(Text, {
507
+ bold: true,
508
+ children: [
509
+ "Readiness patterns",
510
+ def?.readiness?.timeout ? ` (timeout ${def.readiness.timeout}ms)` : "",
511
+ ":"
512
+ ]
513
+ }), patterns.map((p) => /* @__PURE__ */ jsxs(Box, {
514
+ flexDirection: "column",
515
+ children: [/* @__PURE__ */ jsxs(Text, { children: [
516
+ " ",
517
+ p.name,
518
+ ": ",
519
+ /* @__PURE__ */ jsx(Text, {
520
+ dimColor: true,
521
+ children: p.pattern.source
522
+ })
523
+ ] }), p.captures && Object.keys(p.captures).length > 0 && /* @__PURE__ */ jsxs(Text, {
524
+ dimColor: true,
525
+ children: [
526
+ " ",
527
+ "captures:",
528
+ " ",
529
+ Object.entries(p.captures).map(([k, v]) => `${k}→$${v}`).join(", ")
530
+ ]
531
+ })]
532
+ }, p.name))]
533
+ })
534
+ ]
535
+ }),
536
+ /* @__PURE__ */ jsx(Text, { children: "" }),
537
+ hr
538
+ ]
539
+ });
540
+ }
541
+ if (view === "logs" && detailServiceId) {
542
+ const svc = statuses.find((s) => s.serviceId === detailServiceId);
543
+ const visibleLines = logLines.slice(-20);
544
+ return /* @__PURE__ */ jsxs(Box, {
545
+ flexDirection: "column",
546
+ children: [
547
+ hr,
548
+ /* @__PURE__ */ jsxs(Box, {
549
+ justifyContent: "space-between",
550
+ children: [/* @__PURE__ */ jsxs(Text, {
551
+ bold: true,
552
+ color: "cyan",
553
+ children: [
554
+ " ",
555
+ "Logs: ",
556
+ svc?.name ?? detailServiceId,
557
+ " "
558
+ ]
559
+ }), /* @__PURE__ */ jsx(Text, {
560
+ dimColor: true,
561
+ children: " q/Esc back "
562
+ })]
563
+ }),
564
+ hr,
565
+ /* @__PURE__ */ jsxs(Box, {
566
+ flexDirection: "column",
567
+ marginLeft: 1,
568
+ marginTop: 1,
569
+ children: [visibleLines.map((line, i) => /* @__PURE__ */ jsx(Text, {
570
+ dimColor: true,
571
+ children: line
572
+ }, i)), visibleLines.length === 0 && /* @__PURE__ */ jsx(Text, {
573
+ dimColor: true,
574
+ children: "(no logs)"
575
+ })]
576
+ })
577
+ ]
578
+ });
579
+ }
580
+ return /* @__PURE__ */ jsxs(Box, {
581
+ flexDirection: "column",
582
+ children: [
583
+ hr,
584
+ /* @__PURE__ */ jsxs(Box, {
585
+ justifyContent: "space-between",
586
+ children: [/* @__PURE__ */ jsxs(Text, {
587
+ bold: true,
588
+ color: "cyan",
589
+ children: [
590
+ " ",
591
+ "Services",
592
+ " "
593
+ ]
594
+ }), /* @__PURE__ */ jsxs(Text, {
595
+ dimColor: true,
596
+ children: [
597
+ " ",
598
+ "↑↓ select Enter start/toggle d details l logs r refresh q close",
599
+ " "
600
+ ]
601
+ })]
602
+ }),
603
+ hr,
604
+ /* @__PURE__ */ jsx(Box, {
605
+ flexDirection: "column",
606
+ marginTop: 1,
607
+ marginLeft: 1,
608
+ children: items.map((item, i) => {
609
+ const isSelected = i === selected;
610
+ if (item.kind === "project") {
611
+ const rel = workdir ? path.relative(workdir, item.data.path) : item.data.path;
612
+ const display = rel ? "./" + rel : ".";
613
+ return /* @__PURE__ */ jsxs(Box, { children: [
614
+ /* @__PURE__ */ jsx(Text, {
615
+ color: isSelected ? "cyan" : void 0,
616
+ children: isSelected ? "▸ " : " "
617
+ }),
618
+ /* @__PURE__ */ jsx(Text, {
619
+ color: "blue",
620
+ children: "◇ "
621
+ }),
622
+ /* @__PURE__ */ jsx(Text, {
623
+ bold: isSelected,
624
+ children: item.data.name.padEnd(24)
625
+ }),
626
+ /* @__PURE__ */ jsxs(Text, {
627
+ dimColor: true,
628
+ children: [" ", display]
629
+ })
630
+ ] }, `proj-${item.data.path}`);
631
+ }
632
+ const svc = item.data;
633
+ const icon = statusIcon(svc.status);
634
+ const color = statusColor(svc.status);
635
+ const epParts = [];
636
+ if (svc.endpoints) for (const [k, v] of Object.entries(svc.endpoints)) epParts.push(`${k}=${v}`);
637
+ return /* @__PURE__ */ jsxs(Box, { children: [
638
+ /* @__PURE__ */ jsx(Text, {
639
+ color: isSelected ? "cyan" : void 0,
640
+ children: isSelected ? "▸ " : " "
641
+ }),
642
+ /* @__PURE__ */ jsxs(Text, {
643
+ color,
644
+ children: [icon, " "]
645
+ }),
646
+ /* @__PURE__ */ jsx(Text, {
647
+ bold: isSelected,
648
+ children: svc.name.padEnd(24)
649
+ }),
650
+ /* @__PURE__ */ jsxs(Text, {
651
+ dimColor: true,
652
+ children: [
653
+ " [",
654
+ svc.status,
655
+ "]"
656
+ ]
657
+ }),
658
+ svc.workdir && /* @__PURE__ */ jsxs(Text, {
659
+ dimColor: true,
660
+ children: [" ", path.basename(svc.workdir)]
661
+ }),
662
+ svc.pid != null && svc.pid > 0 && /* @__PURE__ */ jsxs(Text, {
663
+ dimColor: true,
664
+ children: [" pid ", String(svc.pid)]
665
+ }),
666
+ epParts.length > 0 && /* @__PURE__ */ jsxs(Text, {
667
+ dimColor: true,
668
+ children: [" ", epParts.join(" ")]
669
+ }),
670
+ svc.workdir && /* @__PURE__ */ jsxs(Text, {
671
+ dimColor: true,
672
+ children: [" ", svc.workdir]
673
+ }),
674
+ svc.error && /* @__PURE__ */ jsxs(Text, {
675
+ color: "red",
676
+ children: [" ", svc.error]
677
+ })
678
+ ] }, svc.instanceId);
679
+ })
680
+ }),
681
+ busy && /* @__PURE__ */ jsxs(Box, {
682
+ marginTop: 1,
683
+ marginLeft: 1,
684
+ children: [/* @__PURE__ */ jsx(Text, {
685
+ color: "yellow",
686
+ children: /* @__PURE__ */ jsx(Spinner, { type: "dots" })
687
+ }), /* @__PURE__ */ jsxs(Text, { children: [" ", busy] })]
688
+ }),
689
+ confirm && /* @__PURE__ */ jsx(Box, {
690
+ marginTop: 1,
691
+ marginLeft: 1,
692
+ children: /* @__PURE__ */ jsx(Text, {
693
+ color: "yellow",
694
+ children: confirm.message
695
+ })
696
+ }),
697
+ /* @__PURE__ */ jsx(Text, { children: "" }),
698
+ hr
699
+ ]
700
+ });
701
+ }
702
+ const DECELERATION = 10 / 20;
703
+ /**
704
+ * Pure state machine for the output throttle simulation.
705
+ *
706
+ * Characters accumulate in a backlog and are released at a velocity
707
+ * that ramps up with acceleration and decelerates when the backlog
708
+ * drains below BREAKING_POINT. Each call to tick() advances one frame.
709
+ */
710
+ var ThrottleState = class {
711
+ backlog = 0;
712
+ velocity = 4;
713
+ totalDrained = 0;
714
+ /** Add characters to the backlog. Ignores zero/negative values. */
715
+ addChars(n) {
716
+ if (n > 0) this.backlog += n;
717
+ }
718
+ /** Immediately release characters, bypassing the backlog. */
719
+ addImmediate(n) {
720
+ if (n > 0) this.totalDrained += n;
721
+ }
722
+ /**
723
+ * Advance one tick: adjust velocity, drain characters from backlog.
724
+ * Returns the number of characters drained this tick.
725
+ */
726
+ tick() {
727
+ if (this.backlog <= 0) return 0;
728
+ if (this.backlog > 75) this.velocity += 6;
729
+ else this.velocity -= DECELERATION;
730
+ this.velocity = Math.max(4, Math.min(30, this.velocity));
731
+ const drain = Math.min(this.velocity, this.backlog);
732
+ this.backlog -= drain;
733
+ this.totalDrained += drain;
734
+ if (this.backlog <= 0) {
735
+ this.backlog = 0;
736
+ this.velocity = 4;
737
+ }
738
+ return drain;
739
+ }
740
+ /** True when the backlog is fully drained. */
741
+ get isDrained() {
742
+ return this.backlog <= 0;
743
+ }
744
+ /** Reset all state to initial values. */
745
+ reset() {
746
+ this.backlog = 0;
747
+ this.velocity = 4;
748
+ this.totalDrained = 0;
749
+ }
750
+ };
751
+ /**
752
+ * Create a standalone output throttle with real setInterval timers.
753
+ *
754
+ * This is the testable core: no React, no hooks. The React hook
755
+ * (useOutputThrottle) is a thin wrapper that adds useState on top.
756
+ */
757
+ function createOutputThrottle(options) {
758
+ const ts = new ThrottleState();
759
+ let tickCount = 0;
760
+ let timer = null;
761
+ let drainResolve = null;
762
+ let _visibleChars = 0;
763
+ function startTimer() {
764
+ if (timer) return;
765
+ tickCount = 0;
766
+ timer = setInterval(() => {
767
+ tickCount++;
768
+ const drain = ts.tick();
769
+ _visibleChars += drain;
770
+ options?.onTick?.({
771
+ tick: tickCount,
772
+ backlog: ts.backlog,
773
+ velocity: ts.velocity,
774
+ drain,
775
+ totalDrained: ts.totalDrained
776
+ });
777
+ if (ts.isDrained) {
778
+ if (timer) {
779
+ clearInterval(timer);
780
+ timer = null;
781
+ }
782
+ if (drainResolve) {
783
+ drainResolve();
784
+ drainResolve = null;
785
+ }
786
+ }
787
+ }, 50);
788
+ }
789
+ return {
790
+ get visibleChars() {
791
+ return _visibleChars;
792
+ },
793
+ addChars(n) {
794
+ if (n <= 0) return;
795
+ ts.addChars(n);
796
+ startTimer();
797
+ },
798
+ addImmediate(n) {
799
+ if (n <= 0) return;
800
+ ts.addImmediate(n);
801
+ _visibleChars += n;
802
+ },
803
+ waitForDrain() {
804
+ if (ts.isDrained && !timer) return Promise.resolve();
805
+ return new Promise((resolve) => {
806
+ drainResolve = resolve;
807
+ });
808
+ },
809
+ reset() {
810
+ if (timer) {
811
+ clearInterval(timer);
812
+ timer = null;
813
+ }
814
+ ts.reset();
815
+ _visibleChars = 0;
816
+ }
817
+ };
818
+ }
819
+ /**
820
+ * React hook that smooths streaming output delivery.
821
+ *
822
+ * Delegates all simulation and timer logic to createOutputThrottle;
823
+ * this hook only adds React state updates for visibleChars.
824
+ */
825
+ function useOutputThrottle(options) {
826
+ const [visibleChars, setVisibleChars] = useState(0);
827
+ const throttle = useRef(createOutputThrottle({ onTick(event) {
828
+ setVisibleChars(event.totalDrained);
829
+ options?.onTick?.(event);
830
+ } }));
831
+ return {
832
+ visibleChars,
833
+ addChars: useCallback((n) => throttle.current.addChars(n), []),
834
+ addImmediate: useCallback((n) => {
835
+ throttle.current.addImmediate(n);
836
+ setVisibleChars((prev) => prev + n);
837
+ }, []),
838
+ waitForDrain: useCallback(() => throttle.current.waitForDrain(), []),
839
+ reset: useCallback(() => {
840
+ throttle.current.reset();
841
+ setVisibleChars(0);
842
+ }, [])
843
+ };
844
+ }
845
+ //#endregion
846
+ //#region src/interactive/repl.tsx
847
+ /** Default number of trailing lines shown in the rolling output window during streaming. */
848
+ const DEFAULT_OUTPUT_WINDOW = 6;
849
+ /** Number of lines revealed per chunk. */
850
+ const LINES_PER_CHUNK = 2;
851
+ /** Snap clip position to reveal lines in groups of LINES_PER_CHUNK.
852
+ * The last line (no trailing \n, i.e. actively streaming) renders char-by-char. */
853
+ function snapToLine(text, pos) {
854
+ if (pos <= 0) return 0;
855
+ if (pos >= text.length) return text.length;
856
+ let lines = 0;
857
+ let idx = 0;
858
+ while (idx < pos) {
859
+ const nl = text.indexOf("\n", idx);
860
+ if (nl < 0 || nl >= pos) break;
861
+ lines++;
862
+ idx = nl + 1;
863
+ }
864
+ const visibleLines = Math.floor(lines / LINES_PER_CHUNK) * LINES_PER_CHUNK;
865
+ if (visibleLines === 0) return 0;
866
+ let end = 0;
867
+ for (let i = 0; i < visibleLines; i++) {
868
+ const nl = text.indexOf("\n", end);
869
+ if (nl < 0) return end;
870
+ end = nl + 1;
871
+ }
872
+ return end;
873
+ }
874
+ /** Prefix for the first line of indented tool output. */
875
+ const INDENT_FIRST = " ⎿ ";
876
+ /** Prefix for continuation lines of indented tool output. */
877
+ const INDENT_REST = " ";
878
+ /** Strip ANSI escape codes for visible-width measurement. */
879
+ function stripAnsi(str) {
880
+ return str.replace(/\x1b\[[0-9;]*m/g, "");
881
+ }
882
+ /**
883
+ * Indent and truncate tool output lines for the rolling window.
884
+ * First line gets ` ⎿ `, subsequent lines get ` `.
885
+ * Lines are truncated to fit within `maxWidth` columns.
886
+ */
887
+ function formatToolLines(lines, maxWidth) {
888
+ return lines.map((line, i) => {
889
+ const prefix = i === 0 ? INDENT_FIRST : INDENT_REST;
890
+ const available = maxWidth - prefix.length;
891
+ if (available <= 0) return prefix;
892
+ if (stripAnsi(line).length <= available) return prefix + line;
893
+ let visCount = 0;
894
+ let cutIdx = line.length;
895
+ for (let j = 0; j < line.length; j++) {
896
+ if (line[j] === "\x1B") {
897
+ const end = line.indexOf("m", j);
898
+ if (end !== -1) {
899
+ j = end;
900
+ continue;
901
+ }
902
+ }
903
+ visCount++;
904
+ if (visCount >= available - 1) {
905
+ cutIdx = j + 1;
906
+ break;
907
+ }
908
+ }
909
+ return prefix + line.slice(0, cutIdx) + "…";
910
+ });
911
+ }
912
+ /** Reducer: append a new StreamChunk to the segment list. */
913
+ function updateSegments(prev, chunk) {
914
+ const next = prev.map((s) => ({
915
+ ...s,
916
+ lines: [...s.lines]
917
+ }));
918
+ switch (chunk.type) {
919
+ case "text-delta": {
920
+ const last = next[next.length - 1];
921
+ if (last && last.type === "text") last.lines = (last.lines.join("\n") + chunk.text).split("\n");
922
+ else next.push({
923
+ type: "text",
924
+ lines: chunk.text.split("\n"),
925
+ headerLines: 0,
926
+ complete: false
927
+ });
928
+ break;
929
+ }
930
+ case "tool-call": {
931
+ const headerLines = formatStreamChunk(chunk).split("\n").filter((l) => l !== "");
932
+ next.push({
933
+ type: "tool",
934
+ lines: headerLines,
935
+ toolCallId: chunk.toolCallId,
936
+ toolName: chunk.toolName,
937
+ headerLines: headerLines.length,
938
+ complete: false
939
+ });
940
+ break;
941
+ }
942
+ case "tool-result": {
943
+ const resultLines = formatStreamChunk(chunk).split("\n").filter((l) => l !== "");
944
+ const toolSeg = (chunk.toolCallId ? next.find((s) => s.type === "tool" && !s.complete && s.toolCallId === chunk.toolCallId) : void 0) ?? next.find((s) => s.type === "tool" && !s.complete && s.toolName === chunk.toolName) ?? next.find((s) => s.type === "tool" && !s.complete);
945
+ if (toolSeg) {
946
+ toolSeg.lines.push(...resultLines);
947
+ toolSeg.complete = true;
948
+ } else next.push({
949
+ type: "tool",
950
+ lines: resultLines,
951
+ toolCallId: chunk.toolCallId,
952
+ toolName: chunk.toolName,
953
+ headerLines: 0,
954
+ complete: true
955
+ });
956
+ break;
957
+ }
958
+ case "tool-output": {
959
+ const toolSeg = [...next].reverse().find((s) => s.type === "tool" && !s.complete);
960
+ if (toolSeg) {
961
+ const outputLines = chunk.text.split("\n").filter((l) => l !== "");
962
+ toolSeg.lines.push(...outputLines);
963
+ }
964
+ break;
965
+ }
966
+ case "error": {
967
+ const errorLines = formatStreamChunk(chunk).split("\n").filter((l) => l !== "");
968
+ const last = next[next.length - 1];
969
+ if (last) last.lines.push(...errorLines);
970
+ else next.push({
971
+ type: "text",
972
+ lines: errorLines,
973
+ headerLines: 0,
974
+ complete: false
975
+ });
976
+ break;
977
+ }
978
+ }
979
+ return next;
980
+ }
981
+ /**
982
+ * Main REPL component for interactive mode.
983
+ */
984
+ /** Track terminal column width reactively across resize events. */
985
+ function useTerminalColumns() {
986
+ const { stdout } = useStdout();
987
+ const [columns, setColumns] = useState(stdout?.columns || 80);
988
+ useEffect(() => {
989
+ const onResize = () => setColumns(stdout?.columns || 80);
990
+ stdout?.on("resize", onResize);
991
+ return () => {
992
+ stdout?.off("resize", onResize);
993
+ };
994
+ }, [stdout]);
995
+ return {
996
+ stdout,
997
+ columns
998
+ };
999
+ }
1000
+ function Repl({ session, services, workdir, onStart }) {
1001
+ const { exit } = useApp();
1002
+ const { stdout, columns } = useTerminalColumns();
1003
+ const isTTY = "isTTY" in stdout && stdout.isTTY;
1004
+ const [terminalFocused, setTerminalFocused] = useState(true);
1005
+ useEffect(() => {
1006
+ if (!isTTY) return;
1007
+ stdout.write("\x1B[?1004h");
1008
+ return () => {
1009
+ stdout.write("\x1B[?1004l");
1010
+ };
1011
+ }, [stdout, isTTY]);
1012
+ const [phase, setPhase] = useState(onStart ? "starting" : "idle");
1013
+ useEffect(() => {
1014
+ if (!onStart) return;
1015
+ const append = (msg) => setHistory((prev) => [...prev, {
1016
+ id: -(prev.length + 1),
1017
+ input: "",
1018
+ output: msg,
1019
+ type: "result"
1020
+ }]);
1021
+ onStart(append).then(() => setPhase("idle"), (err) => {
1022
+ append(`Error: ${err instanceof Error ? err.message : String(err)}`);
1023
+ setPhase("idle");
1024
+ });
1025
+ }, []);
1026
+ const [activePanelId, setActivePanelId] = useState(null);
1027
+ const [history, setHistory] = useState(() => {
1028
+ const initial = [];
1029
+ if (session.welcome) initial.push({
1030
+ id: -1,
1031
+ input: "",
1032
+ output: session.welcome,
1033
+ type: "result"
1034
+ });
1035
+ return initial;
1036
+ });
1037
+ const [input, setInput] = useState("");
1038
+ const [cursorOffset, setCursorOffset] = useState(void 0);
1039
+ const [suggestions, setSuggestions] = useState([]);
1040
+ const [promptLabel, setPromptLabel] = useState(null);
1041
+ const [segments, setSegments] = useState([]);
1042
+ const streamingFullRef = useRef("");
1043
+ const throttle = useOutputThrottle();
1044
+ const clipHighWaterRef = useRef(0);
1045
+ const [currentInput, setCurrentInput] = useState("");
1046
+ const nextId = useRef(0);
1047
+ const interruptedRef = useRef(false);
1048
+ useEffect(() => {
1049
+ if (!services) return;
1050
+ const cleanups = [];
1051
+ for (const inst of services.list()) cleanups.push(services.watchChunks(inst.serviceId, inst.instanceId, (chunk) => {
1052
+ setSegments((prev) => {
1053
+ const next = updateSegments(prev, chunk);
1054
+ if (chunk.type === "tool-result") {
1055
+ if (next.every((s) => s.type === "text" || s.complete) && next.length > 0) {
1056
+ const windowSize = session.outputWindow ?? DEFAULT_OUTPUT_WINDOW;
1057
+ const DIM = "\x1B[2m";
1058
+ const RESET = "\x1B[0m";
1059
+ const historyText = next.map((seg) => {
1060
+ if (seg.type === "text") return DIM + seg.lines.join("\n") + RESET;
1061
+ const header = seg.lines.slice(0, seg.headerLines);
1062
+ const body = seg.lines.slice(seg.headerLines);
1063
+ const visibleBody = body.slice(-windowSize);
1064
+ const hiddenCount = body.length - visibleBody.length;
1065
+ const bodyParts = [];
1066
+ if (hiddenCount > 0) bodyParts.push(`${INDENT_FIRST}... (${hiddenCount} more lines)`);
1067
+ bodyParts.push(...visibleBody.map((l, i) => (i === 0 && hiddenCount === 0 ? INDENT_FIRST : INDENT_REST) + l));
1068
+ return "\n" + header.join("\n") + (bodyParts.length > 0 ? "\n\x1B[2m" + bodyParts.join("\n") + RESET : "");
1069
+ }).join("\n");
1070
+ setHistory((prev) => [...prev, {
1071
+ id: -(prev.length + 1),
1072
+ input: "",
1073
+ output: historyText,
1074
+ type: "result"
1075
+ }]);
1076
+ return [];
1077
+ }
1078
+ }
1079
+ return next;
1080
+ });
1081
+ }));
1082
+ return () => {
1083
+ for (const fn of cleanups) fn();
1084
+ };
1085
+ }, [services]);
1086
+ const [mode, setMode] = useState("typing");
1087
+ const [tabIndex, setTabIndex] = useState(null);
1088
+ const tabCompletionsRef = useRef([]);
1089
+ const tabBaseInputRef = useRef("");
1090
+ const [historyIndex, setHistoryIndex] = useState(null);
1091
+ const [savedInput, setSavedInput] = useState("");
1092
+ const resetToTyping = useCallback(() => {
1093
+ setMode("typing");
1094
+ setTabIndex(null);
1095
+ tabCompletionsRef.current = [];
1096
+ tabBaseInputRef.current = "";
1097
+ setHistoryIndex(null);
1098
+ setSavedInput("");
1099
+ }, []);
1100
+ const setInputWithCursor = useCallback((value) => {
1101
+ setInput(value);
1102
+ setCursorOffset(value.length);
1103
+ }, []);
1104
+ const handleSubmit = useCallback(async (value) => {
1105
+ const trimmed = value.trim();
1106
+ if (!trimmed && !session.isPrompting) return;
1107
+ setInput("");
1108
+ setCursorOffset(0);
1109
+ setSuggestions([]);
1110
+ resetToTyping();
1111
+ setPhase("executing");
1112
+ setSegments([]);
1113
+ streamingFullRef.current = "";
1114
+ throttle.reset();
1115
+ clipHighWaterRef.current = 0;
1116
+ setCurrentInput(trimmed);
1117
+ interruptedRef.current = false;
1118
+ session.onStreamChunk = (chunk, fullText) => {
1119
+ streamingFullRef.current = fullText;
1120
+ setSegments((prev) => updateSegments(prev, chunk));
1121
+ const chunkLen = chunk.type === "text-delta" || chunk.type === "tool-output" ? chunk.text.length : formatStreamChunk(chunk).length;
1122
+ if (chunk.type === "text-delta") throttle.addChars(chunkLen);
1123
+ else throttle.addImmediate(chunkLen);
1124
+ };
1125
+ const result = await session.processInput(trimmed);
1126
+ session.onStreamChunk = void 0;
1127
+ await throttle.waitForDrain();
1128
+ setSegments([]);
1129
+ streamingFullRef.current = "";
1130
+ if (interruptedRef.current) {
1131
+ interruptedRef.current = false;
1132
+ return;
1133
+ }
1134
+ if (result.type === "exit") {
1135
+ setHistory((h) => [...h, {
1136
+ id: nextId.current++,
1137
+ input: trimmed,
1138
+ output: result.text,
1139
+ type: result.type
1140
+ }]);
1141
+ if (result.text) stdout.write(result.text + "\n\n");
1142
+ exit();
1143
+ return;
1144
+ }
1145
+ if (result.type === "panel") {
1146
+ setHistory((h) => [...h, {
1147
+ id: nextId.current++,
1148
+ input: trimmed,
1149
+ output: "",
1150
+ type: "empty"
1151
+ }]);
1152
+ setActivePanelId(result.panelId ?? null);
1153
+ setPhase("panel");
1154
+ return;
1155
+ }
1156
+ if (result.type === "prompt") {
1157
+ if (trimmed) setHistory((h) => [...h, {
1158
+ id: nextId.current++,
1159
+ input: trimmed,
1160
+ output: "",
1161
+ type: "empty"
1162
+ }]);
1163
+ setPromptLabel(result.promptLabel ?? null);
1164
+ setPhase("idle");
1165
+ return;
1166
+ }
1167
+ setPromptLabel(null);
1168
+ setHistory((h) => [...h, {
1169
+ id: nextId.current++,
1170
+ input: trimmed,
1171
+ output: result.text,
1172
+ type: result.type
1173
+ }]);
1174
+ setPhase("idle");
1175
+ }, [
1176
+ session,
1177
+ exit,
1178
+ resetToTyping
1179
+ ]);
1180
+ const getUniqueHistory = useCallback(() => {
1181
+ const inputs = [];
1182
+ for (let i = history.length - 1; i >= 0; i--) {
1183
+ const h = history[i].input;
1184
+ if (inputs.length === 0 || inputs[inputs.length - 1] !== h) inputs.push(h);
1185
+ }
1186
+ return inputs;
1187
+ }, [history]);
1188
+ useInput((ch, key) => {
1189
+ if (key.escape || ch === "[I" || ch === "[O") {
1190
+ if (ch === "I" || ch === "[I") {
1191
+ setTerminalFocused(true);
1192
+ return;
1193
+ }
1194
+ if (ch === "O" || ch === "[O") {
1195
+ setTerminalFocused(false);
1196
+ return;
1197
+ }
1198
+ }
1199
+ if (key.ctrl && ch === "c") {
1200
+ stdout.write("\n" + session.exitMessage + "\n\n");
1201
+ exit();
1202
+ return;
1203
+ }
1204
+ if (phase !== "idle") {
1205
+ if (key.escape) {
1206
+ if (phase === "executing") {
1207
+ interruptedRef.current = true;
1208
+ session.abortCurrentStream();
1209
+ setHistory((h) => [...h, {
1210
+ id: nextId.current++,
1211
+ input: currentInput,
1212
+ output: streamingFullRef.current || "(interrupted)",
1213
+ type: "result"
1214
+ }]);
1215
+ setSegments([]);
1216
+ streamingFullRef.current = "";
1217
+ }
1218
+ setPhase("idle");
1219
+ }
1220
+ return;
1221
+ }
1222
+ if (key.tab) {
1223
+ if (mode === "history-cycling") {
1224
+ resetToTyping();
1225
+ return;
1226
+ }
1227
+ const baseInput = mode === "tab-cycling" ? tabBaseInputRef.current : input;
1228
+ const completions = mode === "tab-cycling" ? tabCompletionsRef.current : session.getCompletions(baseInput);
1229
+ if (completions.length === 0) {
1230
+ const ghost = session.getGhostSuggestion(input);
1231
+ if (ghost) setInputWithCursor(ghost);
1232
+ return;
1233
+ }
1234
+ if (mode !== "tab-cycling") {
1235
+ tabBaseInputRef.current = input;
1236
+ tabCompletionsRef.current = completions;
1237
+ setMode("tab-cycling");
1238
+ }
1239
+ const nextIndex = tabIndex === null ? 0 : key.shift ? (tabIndex - 1 + completions.length) % completions.length : (tabIndex + 1) % completions.length;
1240
+ setTabIndex(nextIndex);
1241
+ const completed = applyCompletion(baseInput, completions[nextIndex]) + session.getCompletionSuffix(completions[nextIndex], baseInput);
1242
+ setInputWithCursor(completed);
1243
+ setSuggestions(completions);
1244
+ return;
1245
+ }
1246
+ if (key.upArrow || key.downArrow) {
1247
+ if (mode === "history-cycling") {
1248
+ const uniqueHistory = getUniqueHistory();
1249
+ if (uniqueHistory.length === 0) return;
1250
+ if (key.upArrow) {
1251
+ if (historyIndex !== null && historyIndex < uniqueHistory.length - 1) {
1252
+ const next = historyIndex + 1;
1253
+ setHistoryIndex(next);
1254
+ setInputWithCursor(uniqueHistory[next]);
1255
+ }
1256
+ } else if (historyIndex !== null && historyIndex > 0) {
1257
+ const next = historyIndex - 1;
1258
+ setHistoryIndex(next);
1259
+ setInputWithCursor(uniqueHistory[next]);
1260
+ } else if (historyIndex === 0) {
1261
+ setHistoryIndex(null);
1262
+ setInputWithCursor(savedInput);
1263
+ setMode("typing");
1264
+ }
1265
+ return;
1266
+ }
1267
+ if (mode === "tab-cycling") {
1268
+ const baseInput = tabBaseInputRef.current;
1269
+ const completions = tabCompletionsRef.current;
1270
+ if (completions.length === 0) return;
1271
+ const idx = tabIndex ?? 0;
1272
+ const nextIndex = key.upArrow ? (idx - 1 + completions.length) % completions.length : (idx + 1) % completions.length;
1273
+ setTabIndex(nextIndex);
1274
+ const completed = applyCompletion(baseInput, completions[nextIndex]) + session.getCompletionSuffix(completions[nextIndex], baseInput);
1275
+ setInputWithCursor(completed);
1276
+ setSuggestions(completions);
1277
+ return;
1278
+ }
1279
+ if (input.startsWith("/")) {
1280
+ const completions = session.getCompletions(input);
1281
+ if (completions.length > 0) {
1282
+ tabBaseInputRef.current = input;
1283
+ tabCompletionsRef.current = completions;
1284
+ setMode("tab-cycling");
1285
+ const nextIndex = key.upArrow ? completions.length - 1 : 0;
1286
+ setTabIndex(nextIndex);
1287
+ const completed = applyCompletion(input, completions[nextIndex]) + session.getCompletionSuffix(completions[nextIndex], input);
1288
+ setInputWithCursor(completed);
1289
+ setSuggestions(completions);
1290
+ return;
1291
+ }
1292
+ }
1293
+ if (key.upArrow) {
1294
+ const uniqueHistory = getUniqueHistory();
1295
+ if (uniqueHistory.length === 0) return;
1296
+ setMode("history-cycling");
1297
+ setSavedInput(input);
1298
+ setHistoryIndex(0);
1299
+ setInputWithCursor(uniqueHistory[0]);
1300
+ setSuggestions([]);
1301
+ setTabIndex(null);
1302
+ tabCompletionsRef.current = [];
1303
+ }
1304
+ return;
1305
+ }
1306
+ if (key.escape) {
1307
+ if (mode === "history-cycling") {
1308
+ setInputWithCursor(savedInput);
1309
+ resetToTyping();
1310
+ return;
1311
+ }
1312
+ if (mode === "tab-cycling") {
1313
+ resetToTyping();
1314
+ return;
1315
+ }
1316
+ return;
1317
+ }
1318
+ }, { isActive: true });
1319
+ const inlineSuggestion = mode === "typing" && phase === "idle" ? session.getGhostSuggestion(input) ?? "" : "";
1320
+ const handleChange = useCallback((value) => {
1321
+ setInput(value);
1322
+ setCursorOffset(void 0);
1323
+ resetToTyping();
1324
+ if (value.startsWith("/")) {
1325
+ const completions = session.getCompletions(value);
1326
+ setSuggestions(completions);
1327
+ } else setSuggestions([]);
1328
+ }, [session, resetToTyping]);
1329
+ return /* @__PURE__ */ jsxs(Box, {
1330
+ flexDirection: "column",
1331
+ children: [
1332
+ /* @__PURE__ */ jsx(Static, {
1333
+ items: history,
1334
+ children: (entry) => /* @__PURE__ */ jsxs(Box, {
1335
+ flexDirection: "column",
1336
+ marginBottom: 1,
1337
+ children: [entry.input ? /* @__PURE__ */ jsxs(Fragment, { children: [
1338
+ /* @__PURE__ */ jsx(Text, { children: " " }),
1339
+ /* @__PURE__ */ jsxs(Text, {
1340
+ backgroundColor: "#333333",
1341
+ color: "#eeeeee",
1342
+ children: [
1343
+ " > ",
1344
+ entry.input,
1345
+ " "
1346
+ ]
1347
+ }),
1348
+ /* @__PURE__ */ jsx(Text, { children: " " })
1349
+ ] }) : null, entry.output ? /* @__PURE__ */ jsx(Text, {
1350
+ color: entry.type === "error" ? "red" : void 0,
1351
+ bold: entry.id < 0,
1352
+ children: entry.output
1353
+ }) : null]
1354
+ }, entry.id)
1355
+ }),
1356
+ phase === "starting" ? /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Text, {
1357
+ color: "yellow",
1358
+ children: /* @__PURE__ */ jsx(Spinner, { type: "dots" })
1359
+ }), /* @__PURE__ */ jsx(Text, { children: " Starting…" })] }) : phase === "panel" && activePanelId?.startsWith("services:") && services ? /* @__PURE__ */ jsx(ServicePanel, {
1360
+ services,
1361
+ serviceId: activePanelId.split(":")[1],
1362
+ workdir,
1363
+ onExit: () => {
1364
+ setActivePanelId(null);
1365
+ setPhase("idle");
1366
+ }
1367
+ }) : phase === "executing" ? /* @__PURE__ */ jsxs(Box, {
1368
+ flexDirection: "column",
1369
+ children: [
1370
+ /* @__PURE__ */ jsx(Text, { children: " " }),
1371
+ /* @__PURE__ */ jsxs(Text, {
1372
+ backgroundColor: "#333333",
1373
+ color: "#eeeeee",
1374
+ children: [
1375
+ " > ",
1376
+ currentInput,
1377
+ " "
1378
+ ]
1379
+ }),
1380
+ /* @__PURE__ */ jsx(Text, { children: " " }),
1381
+ segments.length > 0 ? /* @__PURE__ */ jsx(Box, {
1382
+ flexDirection: "column",
1383
+ children: (() => {
1384
+ let charBudget = throttle.visibleChars;
1385
+ return segments.map((seg, i) => {
1386
+ if (charBudget <= 0) return null;
1387
+ const isLast = i === segments.length - 1;
1388
+ const windowSize = session.outputWindow ?? DEFAULT_OUTPUT_WINDOW;
1389
+ if (seg.type === "text") {
1390
+ if (!isLast) {
1391
+ const line = seg.lines[0] ?? "";
1392
+ charBudget -= line.length;
1393
+ return /* @__PURE__ */ jsx(Text, {
1394
+ dimColor: true,
1395
+ children: line
1396
+ }, i);
1397
+ }
1398
+ const rawText = seg.lines.join("\n");
1399
+ const snapped = snapToLine(rawText, Math.ceil(charBudget));
1400
+ const clipPos = Math.max(snapped, clipHighWaterRef.current);
1401
+ clipHighWaterRef.current = clipPos;
1402
+ const clipped = rawText.slice(0, clipPos);
1403
+ charBudget -= Math.min(Math.ceil(charBudget), rawText.length);
1404
+ return /* @__PURE__ */ jsx(Text, { children: renderMarkdown(clipped) || clipped }, i);
1405
+ }
1406
+ const header = seg.lines.slice(0, seg.headerLines);
1407
+ const body = seg.lines.slice(seg.headerLines);
1408
+ const visibleBody = body.slice(-windowSize);
1409
+ const hiddenCount = body.length - visibleBody.length;
1410
+ const parts = [];
1411
+ parts.push(...header);
1412
+ if (hiddenCount > 0) {
1413
+ parts.push(` ⎿ \x1b[2m... (${hiddenCount} more lines)\x1b[0m`);
1414
+ parts.push(...visibleBody.map((l) => INDENT_REST + l));
1415
+ } else parts.push(...formatToolLines(visibleBody, columns));
1416
+ const fullText = parts.join("\n");
1417
+ const snapped = snapToLine(fullText, Math.ceil(charBudget));
1418
+ const clipPos = Math.max(snapped, clipHighWaterRef.current);
1419
+ clipHighWaterRef.current = clipPos;
1420
+ const clipped = fullText.slice(0, clipPos);
1421
+ charBudget -= Math.min(Math.ceil(charBudget), fullText.length);
1422
+ const dimmed = seg.complete && !isLast;
1423
+ const leading = "\n";
1424
+ const trailing = seg.complete && !isLast ? "\n" : "";
1425
+ return /* @__PURE__ */ jsxs(Text, {
1426
+ dimColor: dimmed,
1427
+ children: [
1428
+ leading,
1429
+ clipped,
1430
+ trailing
1431
+ ]
1432
+ }, i);
1433
+ });
1434
+ })()
1435
+ }) : /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Text, {
1436
+ color: "yellow",
1437
+ children: /* @__PURE__ */ jsx(Spinner, { type: "dots" })
1438
+ }), /* @__PURE__ */ jsx(Text, { children: " Working…" })] })
1439
+ ]
1440
+ }) : null,
1441
+ phase === "idle" && segments.length > 0 && /* @__PURE__ */ jsx(Box, {
1442
+ flexDirection: "column",
1443
+ children: segments.map((seg, i) => {
1444
+ const windowSize = session.outputWindow ?? DEFAULT_OUTPUT_WINDOW;
1445
+ if (seg.type === "text") return /* @__PURE__ */ jsx(Text, {
1446
+ dimColor: true,
1447
+ children: seg.lines.join("\n")
1448
+ }, i);
1449
+ const header = seg.lines.slice(0, seg.headerLines);
1450
+ const body = seg.lines.slice(seg.headerLines);
1451
+ const visibleBody = body.slice(-windowSize);
1452
+ const hiddenCount = body.length - visibleBody.length;
1453
+ const bodyParts = [];
1454
+ if (hiddenCount > 0) {
1455
+ bodyParts.push(` ⎿ ... (${hiddenCount} more lines)`);
1456
+ bodyParts.push(...visibleBody.map((l) => INDENT_REST + l));
1457
+ } else bodyParts.push(...formatToolLines(visibleBody, columns));
1458
+ return /* @__PURE__ */ jsxs(Box, {
1459
+ flexDirection: "column",
1460
+ children: [/* @__PURE__ */ jsxs(Text, { children: ["\n", header.join("\n")] }), bodyParts.length > 0 && /* @__PURE__ */ jsx(Text, {
1461
+ dimColor: true,
1462
+ children: bodyParts.join("\n")
1463
+ })]
1464
+ }, i);
1465
+ })
1466
+ }),
1467
+ (phase === "idle" || phase === "executing") && /* @__PURE__ */ jsxs(Box, {
1468
+ flexDirection: "column",
1469
+ children: [
1470
+ /* @__PURE__ */ jsx(Text, {
1471
+ color: "green",
1472
+ children: "─".repeat(columns)
1473
+ }),
1474
+ /* @__PURE__ */ jsxs(Box, { children: [/* @__PURE__ */ jsx(Text, {
1475
+ color: promptLabel ? "cyan" : "green",
1476
+ children: promptLabel ? `${promptLabel}: ` : "> "
1477
+ }), /* @__PURE__ */ jsx(TextInput, {
1478
+ value: input,
1479
+ onChange: handleChange,
1480
+ onSubmit: handleSubmit,
1481
+ cursorOffset,
1482
+ focus: terminalFocused && phase === "idle",
1483
+ suggestion: phase === "idle" ? inlineSuggestion : void 0
1484
+ })] }),
1485
+ /* @__PURE__ */ jsx(Text, {
1486
+ color: "green",
1487
+ children: "─".repeat(columns)
1488
+ }),
1489
+ phase === "idle" && suggestions.length > 1 && /* @__PURE__ */ jsx(Box, {
1490
+ marginLeft: 2,
1491
+ children: /* @__PURE__ */ jsx(Text, {
1492
+ dimColor: true,
1493
+ children: suggestions.join(" ")
1494
+ })
1495
+ })
1496
+ ]
1497
+ })
1498
+ ]
1499
+ });
1500
+ }
1501
+ //#endregion
1502
+ //#region src/interactive/start.tsx
1503
+ /**
1504
+ * Start the Ink-based interactive REPL.
1505
+ * This function renders the Repl component and waits until the user exits.
1506
+ */
1507
+ async function startInkRepl(session, opts) {
1508
+ const origError = console.error;
1509
+ console.error = (...args) => {
1510
+ if (typeof args[0] === "string" && args[0].includes("SYNCHRONOUS TERMINATION NOTICE")) return;
1511
+ origError.apply(console, args);
1512
+ };
1513
+ await render(/* @__PURE__ */ jsx(Repl, {
1514
+ session,
1515
+ services: opts?.services,
1516
+ workdir: opts?.workdir,
1517
+ onStart: opts?.onStart
1518
+ }), {
1519
+ exitOnCtrlC: false,
1520
+ kittyKeyboard: { mode: "auto" }
1521
+ }).waitUntilExit();
1522
+ }
1523
+ //#endregion
1524
+ export { startInkRepl };
1525
+
1526
+ //# sourceMappingURL=start-CKRhuB1Y.mjs.map