perstack 0.0.78 → 0.0.80

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.
@@ -0,0 +1,1992 @@
1
+ import { createId } from '@paralleldrive/cuid2';
2
+ import { parseWithFriendlyError, startCommandInputSchema, defaultMaxRetries, defaultTimeout, checkpointSchema, perstackConfigSchema } from '@perstack/core';
3
+ import { createInitialJob, retrieveJob, storeJob, defaultRetrieveCheckpoint, defaultStoreEvent, defaultStoreCheckpoint, getAllJobs as getAllJobs$1, getCheckpointPath, getRunIdsByJobId, getEventContents, getAllRuns as getAllRuns$1, getCheckpointsByJobId as getCheckpointsByJobId$1 } from '@perstack/filesystem-storage';
4
+ import { findLockfile, loadLockfile, runtimeVersion, run } from '@perstack/runtime';
5
+ import { Command } from 'commander';
6
+ import dotenv from 'dotenv';
7
+ import { readFile } from 'fs/promises';
8
+ import path from 'path';
9
+ import TOML from 'smol-toml';
10
+ import { existsSync, readFileSync } from 'fs';
11
+ import { render, useApp, useInput, Box, Text } from 'ink';
12
+ import { createContext, useMemo, useReducer, useState, useEffect, useCallback, useRef, useInsertionEffect, useContext } from 'react';
13
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
14
+ import { useRun } from '@perstack/react';
15
+
16
+ // src/start.ts
17
+ function getEnv(envPath) {
18
+ const env = Object.fromEntries(
19
+ Object.entries(process.env).filter(([_, value]) => !!value).map(([key, value]) => [key, value])
20
+ );
21
+ dotenv.config({ path: envPath, processEnv: env, quiet: true });
22
+ return env;
23
+ }
24
+ var ALLOWED_CONFIG_HOSTS = ["raw.githubusercontent.com"];
25
+ async function getPerstackConfig(configPath) {
26
+ const configString = await findPerstackConfigString(configPath);
27
+ if (configString === null) {
28
+ throw new Error("perstack.toml not found. Create one or specify --config path.");
29
+ }
30
+ return await parsePerstackConfig(configString);
31
+ }
32
+ function isRemoteUrl(configPath) {
33
+ const lower = configPath.toLowerCase();
34
+ return lower.startsWith("https://") || lower.startsWith("http://");
35
+ }
36
+ async function fetchRemoteConfig(url) {
37
+ let parsed;
38
+ try {
39
+ parsed = new URL(url);
40
+ } catch {
41
+ throw new Error(`Invalid remote config URL: ${url}`);
42
+ }
43
+ if (parsed.protocol !== "https:") {
44
+ throw new Error("Remote config requires HTTPS");
45
+ }
46
+ if (!ALLOWED_CONFIG_HOSTS.includes(parsed.hostname)) {
47
+ throw new Error(`Remote config only allowed from: ${ALLOWED_CONFIG_HOSTS.join(", ")}`);
48
+ }
49
+ try {
50
+ const response = await fetch(url, { redirect: "error" });
51
+ if (!response.ok) {
52
+ throw new Error(`${response.status} ${response.statusText}`);
53
+ }
54
+ return await response.text();
55
+ } catch (error) {
56
+ const message = error instanceof Error ? error.message : String(error);
57
+ throw new Error(`Failed to fetch remote config: ${message}`);
58
+ }
59
+ }
60
+ async function findPerstackConfigString(configPath) {
61
+ if (configPath) {
62
+ if (isRemoteUrl(configPath)) {
63
+ return await fetchRemoteConfig(configPath);
64
+ }
65
+ try {
66
+ const tomlString = await readFile(path.resolve(process.cwd(), configPath), "utf-8");
67
+ return tomlString;
68
+ } catch {
69
+ throw new Error(`Given config path "${configPath}" is not found`);
70
+ }
71
+ }
72
+ return await findPerstackConfigStringRecursively(path.resolve(process.cwd()));
73
+ }
74
+ async function findPerstackConfigStringRecursively(cwd) {
75
+ try {
76
+ const tomlString = await readFile(path.resolve(cwd, "perstack.toml"), "utf-8");
77
+ return tomlString;
78
+ } catch {
79
+ if (cwd === path.parse(cwd).root) {
80
+ return null;
81
+ }
82
+ return await findPerstackConfigStringRecursively(path.dirname(cwd));
83
+ }
84
+ }
85
+ async function parsePerstackConfig(config) {
86
+ const toml = TOML.parse(config ?? "");
87
+ return parseWithFriendlyError(perstackConfigSchema, toml, "perstack.toml");
88
+ }
89
+
90
+ // src/lib/provider-config.ts
91
+ function getProviderConfig(provider, env, providerTable) {
92
+ const setting = providerTable?.setting ?? {};
93
+ switch (provider) {
94
+ case "anthropic": {
95
+ const apiKey = env.ANTHROPIC_API_KEY;
96
+ if (!apiKey) throw new Error("ANTHROPIC_API_KEY is not set");
97
+ return {
98
+ providerName: "anthropic",
99
+ apiKey,
100
+ baseUrl: setting.baseUrl ?? env.ANTHROPIC_BASE_URL,
101
+ headers: setting.headers
102
+ };
103
+ }
104
+ case "google": {
105
+ const apiKey = env.GOOGLE_GENERATIVE_AI_API_KEY;
106
+ if (!apiKey) throw new Error("GOOGLE_GENERATIVE_AI_API_KEY is not set");
107
+ return {
108
+ providerName: "google",
109
+ apiKey,
110
+ baseUrl: setting.baseUrl ?? env.GOOGLE_GENERATIVE_AI_BASE_URL,
111
+ headers: setting.headers
112
+ };
113
+ }
114
+ case "openai": {
115
+ const apiKey = env.OPENAI_API_KEY;
116
+ if (!apiKey) throw new Error("OPENAI_API_KEY is not set");
117
+ return {
118
+ providerName: "openai",
119
+ apiKey,
120
+ baseUrl: setting.baseUrl ?? env.OPENAI_BASE_URL,
121
+ organization: setting.organization ?? env.OPENAI_ORGANIZATION,
122
+ project: setting.project ?? env.OPENAI_PROJECT,
123
+ name: setting.name,
124
+ headers: setting.headers
125
+ };
126
+ }
127
+ case "ollama": {
128
+ return {
129
+ providerName: "ollama",
130
+ baseUrl: setting.baseUrl ?? env.OLLAMA_BASE_URL,
131
+ headers: setting.headers
132
+ };
133
+ }
134
+ case "azure-openai": {
135
+ const apiKey = env.AZURE_API_KEY;
136
+ if (!apiKey) throw new Error("AZURE_API_KEY is not set");
137
+ const resourceName = setting.resourceName ?? env.AZURE_RESOURCE_NAME;
138
+ const baseUrl = setting.baseUrl ?? env.AZURE_BASE_URL;
139
+ if (!resourceName && !baseUrl) throw new Error("AZURE_RESOURCE_NAME or baseUrl is not set");
140
+ return {
141
+ providerName: "azure-openai",
142
+ apiKey,
143
+ resourceName,
144
+ apiVersion: setting.apiVersion ?? env.AZURE_API_VERSION,
145
+ baseUrl,
146
+ headers: setting.headers,
147
+ useDeploymentBasedUrls: setting.useDeploymentBasedUrls
148
+ };
149
+ }
150
+ case "amazon-bedrock": {
151
+ const accessKeyId = env.AWS_ACCESS_KEY_ID;
152
+ const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
153
+ const sessionToken = env.AWS_SESSION_TOKEN;
154
+ if (!accessKeyId) throw new Error("AWS_ACCESS_KEY_ID is not set");
155
+ if (!secretAccessKey) throw new Error("AWS_SECRET_ACCESS_KEY is not set");
156
+ const region = setting.region ?? env.AWS_REGION;
157
+ if (!region) throw new Error("AWS_REGION is not set");
158
+ return {
159
+ providerName: "amazon-bedrock",
160
+ accessKeyId,
161
+ secretAccessKey,
162
+ region,
163
+ sessionToken
164
+ };
165
+ }
166
+ case "google-vertex": {
167
+ return {
168
+ providerName: "google-vertex",
169
+ project: setting.project ?? env.GOOGLE_VERTEX_PROJECT,
170
+ location: setting.location ?? env.GOOGLE_VERTEX_LOCATION,
171
+ baseUrl: setting.baseUrl ?? env.GOOGLE_VERTEX_BASE_URL,
172
+ headers: setting.headers
173
+ };
174
+ }
175
+ case "deepseek": {
176
+ const apiKey = env.DEEPSEEK_API_KEY;
177
+ if (!apiKey) throw new Error("DEEPSEEK_API_KEY is not set");
178
+ return {
179
+ providerName: "deepseek",
180
+ apiKey,
181
+ baseUrl: setting.baseUrl ?? env.DEEPSEEK_BASE_URL,
182
+ headers: setting.headers
183
+ };
184
+ }
185
+ }
186
+ }
187
+ function getAllJobs() {
188
+ return getAllJobs$1();
189
+ }
190
+ function getAllRuns() {
191
+ return getAllRuns$1();
192
+ }
193
+ function getMostRecentRun() {
194
+ const runs = getAllRuns();
195
+ if (runs.length === 0) {
196
+ throw new Error("No runs found");
197
+ }
198
+ return runs[0];
199
+ }
200
+ function getCheckpointsByJobId(jobId) {
201
+ return getCheckpointsByJobId$1(jobId);
202
+ }
203
+ function getMostRecentCheckpoint(jobId) {
204
+ const targetJobId = jobId ?? getMostRecentRun().jobId;
205
+ const checkpoints = getCheckpointsByJobId(targetJobId);
206
+ if (checkpoints.length === 0) {
207
+ throw new Error(`No checkpoints found for job ${targetJobId}`);
208
+ }
209
+ return checkpoints[checkpoints.length - 1];
210
+ }
211
+ function getRecentExperts(limit) {
212
+ const runs = getAllRuns();
213
+ const expertMap = /* @__PURE__ */ new Map();
214
+ for (const setting of runs) {
215
+ const expertKey = setting.expertKey;
216
+ if (!expertMap.has(expertKey) || expertMap.get(expertKey).lastUsed < setting.updatedAt) {
217
+ expertMap.set(expertKey, {
218
+ key: expertKey,
219
+ name: expertKey,
220
+ lastUsed: setting.updatedAt
221
+ });
222
+ }
223
+ }
224
+ return Array.from(expertMap.values()).sort((a, b) => b.lastUsed - a.lastUsed).slice(0, limit);
225
+ }
226
+ function getCheckpointById(jobId, checkpointId) {
227
+ const checkpointPath = getCheckpointPath(jobId, checkpointId);
228
+ if (!existsSync(checkpointPath)) {
229
+ throw new Error(`Checkpoint ${checkpointId} not found in job ${jobId}`);
230
+ }
231
+ const checkpoint = readFileSync(checkpointPath, "utf-8");
232
+ return checkpointSchema.parse(JSON.parse(checkpoint));
233
+ }
234
+ function getCheckpointsWithDetails(jobId) {
235
+ return getCheckpointsByJobId(jobId).map((cp) => ({
236
+ id: cp.id,
237
+ runId: cp.runId,
238
+ stepNumber: cp.stepNumber,
239
+ contextWindowUsage: cp.contextWindowUsage ?? 0
240
+ })).sort((a, b) => b.stepNumber - a.stepNumber);
241
+ }
242
+ function getAllEventContentsForJob(jobId, maxStepNumber) {
243
+ const runIds = getRunIdsByJobId(jobId);
244
+ const allEvents = [];
245
+ for (const runId of runIds) {
246
+ const events = getEventContents(jobId, runId, maxStepNumber);
247
+ allEvents.push(...events);
248
+ }
249
+ return allEvents.sort((a, b) => a.timestamp - b.timestamp);
250
+ }
251
+
252
+ // src/lib/context.ts
253
+ var defaultProvider = "anthropic";
254
+ var defaultModel = "claude-sonnet-4-5";
255
+ async function resolveRunContext(input) {
256
+ const perstackConfig = input.perstackConfig ?? await getPerstackConfig(input.configPath);
257
+ let checkpoint;
258
+ if (input.resumeFrom) {
259
+ if (!input.continueJob) {
260
+ throw new Error("--resume-from requires --continue-job");
261
+ }
262
+ checkpoint = getCheckpointById(input.continueJob, input.resumeFrom);
263
+ } else if (input.continueJob) {
264
+ checkpoint = getMostRecentCheckpoint(input.continueJob);
265
+ } else if (input.continue) {
266
+ checkpoint = getMostRecentCheckpoint();
267
+ }
268
+ if ((input.continue || input.continueJob || input.resumeFrom) && !checkpoint) {
269
+ throw new Error("No checkpoint found");
270
+ }
271
+ if (checkpoint && input.expertKey && checkpoint.expert.key !== input.expertKey) {
272
+ throw new Error(
273
+ `Checkpoint expert key ${checkpoint.expert.key} does not match input expert key ${input.expertKey}`
274
+ );
275
+ }
276
+ const envPath = input.envPath && input.envPath.length > 0 ? input.envPath : perstackConfig.envPath ?? [".env", ".env.local"];
277
+ const env = getEnv(envPath);
278
+ const provider = input.provider ?? perstackConfig.provider?.providerName ?? defaultProvider;
279
+ const model = input.model ?? perstackConfig.model ?? defaultModel;
280
+ const providerConfig = getProviderConfig(provider, env, perstackConfig.provider);
281
+ const experts = Object.fromEntries(
282
+ Object.entries(perstackConfig.experts ?? {}).map(([name, expert]) => {
283
+ return [
284
+ name,
285
+ {
286
+ name,
287
+ version: expert.version ?? "1.0.0",
288
+ description: expert.description,
289
+ instruction: expert.instruction,
290
+ skills: expert.skills,
291
+ delegates: expert.delegates,
292
+ tags: expert.tags
293
+ }
294
+ ];
295
+ })
296
+ );
297
+ return {
298
+ perstackConfig,
299
+ checkpoint,
300
+ env,
301
+ providerConfig,
302
+ model,
303
+ experts
304
+ };
305
+ }
306
+
307
+ // src/lib/interactive.ts
308
+ function parseInteractiveToolCallResult(query, checkpoint) {
309
+ const lastMessage = checkpoint.messages[checkpoint.messages.length - 1];
310
+ if (lastMessage.type !== "expertMessage") {
311
+ throw new Error("Last message is not a expert message");
312
+ }
313
+ const content = lastMessage.contents.find((c) => c.type === "toolCallPart");
314
+ if (!content || content.type !== "toolCallPart") {
315
+ throw new Error("Last message content is not a tool call part");
316
+ }
317
+ const toolCallId = content.toolCallId;
318
+ const toolName = content.toolName;
319
+ const pendingToolCall = checkpoint.pendingToolCalls?.find((tc) => tc.id === toolCallId);
320
+ const skillName = pendingToolCall?.skillName ?? "";
321
+ return {
322
+ interactiveToolCallResult: {
323
+ toolCallId,
324
+ toolName,
325
+ skillName,
326
+ text: query
327
+ }
328
+ };
329
+ }
330
+ function parseInteractiveToolCallResultJson(query) {
331
+ try {
332
+ const parsed = JSON.parse(query);
333
+ if (typeof parsed === "object" && parsed !== null && "toolCallId" in parsed && "toolName" in parsed && "skillName" in parsed && "text" in parsed) {
334
+ return {
335
+ interactiveToolCallResult: parsed
336
+ };
337
+ }
338
+ return null;
339
+ } catch {
340
+ return null;
341
+ }
342
+ }
343
+
344
+ // src/tui/utils/event-queue.ts
345
+ var defaultErrorLogger = (message, error) => {
346
+ console.error(message, error);
347
+ };
348
+ var EventQueue = class _EventQueue {
349
+ static MAX_PENDING_EVENTS = 1e3;
350
+ pendingEvents = [];
351
+ handler = null;
352
+ onError;
353
+ errorLogger;
354
+ constructor(options) {
355
+ this.onError = options?.onError;
356
+ this.errorLogger = options?.errorLogger ?? defaultErrorLogger;
357
+ }
358
+ setHandler(fn) {
359
+ this.handler = fn;
360
+ for (const event of this.pendingEvents) {
361
+ this.safeHandle(event);
362
+ }
363
+ this.pendingEvents.length = 0;
364
+ }
365
+ emit(event) {
366
+ if (this.handler) {
367
+ this.safeHandle(event);
368
+ } else {
369
+ if (this.pendingEvents.length >= _EventQueue.MAX_PENDING_EVENTS) {
370
+ this.pendingEvents.shift();
371
+ }
372
+ this.pendingEvents.push(event);
373
+ }
374
+ }
375
+ safeHandle(event) {
376
+ try {
377
+ this.handler?.(event);
378
+ } catch (error) {
379
+ if (this.onError) {
380
+ this.onError(error);
381
+ } else {
382
+ this.errorLogger("EventQueue handler error:", error);
383
+ }
384
+ }
385
+ }
386
+ };
387
+ var InputAreaContext = createContext(null);
388
+ var InputAreaProvider = InputAreaContext.Provider;
389
+ var useInputAreaContext = () => {
390
+ const context = useContext(InputAreaContext);
391
+ if (!context) {
392
+ throw new Error("useInputAreaContext must be used within InputAreaProvider");
393
+ }
394
+ return context;
395
+ };
396
+
397
+ // src/tui/helpers.ts
398
+ var truncateText = (text, maxLength) => {
399
+ if (text.length <= maxLength) return text;
400
+ return `${text.slice(0, maxLength)}...`;
401
+ };
402
+ var assertNever = (x) => {
403
+ throw new Error(`Unexpected value: ${x}`);
404
+ };
405
+ var formatTimestamp = (timestamp) => new Date(timestamp).toLocaleString();
406
+ var shortenPath = (fullPath, maxLength = 60) => {
407
+ if (fullPath.length <= maxLength) return fullPath;
408
+ const parts = fullPath.split("/");
409
+ if (parts.length <= 2) return fullPath;
410
+ const filename = parts[parts.length - 1] ?? "";
411
+ const parentDir = parts[parts.length - 2] ?? "";
412
+ const shortened = `.../${parentDir}/${filename}`;
413
+ if (shortened.length <= maxLength) return shortened;
414
+ return `.../${filename}`;
415
+ };
416
+ var summarizeOutput = (lines, maxLines) => {
417
+ const filtered = lines.filter((l) => l.trim());
418
+ const visible = filtered.slice(0, maxLines);
419
+ const remaining = filtered.length - visible.length;
420
+ return { visible, remaining };
421
+ };
422
+
423
+ // src/tui/constants.ts
424
+ var UI_CONSTANTS = {
425
+ MAX_VISIBLE_LIST_ITEMS: 25,
426
+ TRUNCATE_TEXT_MEDIUM: 80,
427
+ TRUNCATE_TEXT_DEFAULT: 100};
428
+ var RENDER_CONSTANTS = {
429
+ EXEC_OUTPUT_MAX_LINES: 4,
430
+ NEW_TODO_MAX_PREVIEW: 3,
431
+ LIST_DIR_MAX_ITEMS: 4
432
+ };
433
+ var INDICATOR = {
434
+ BULLET: "\u25CF",
435
+ TREE: "\u2514",
436
+ ELLIPSIS: "..."
437
+ };
438
+ var STOP_EVENT_TYPES = [
439
+ "stopRunByInteractiveTool",
440
+ "stopRunByDelegate",
441
+ "stopRunByExceededMaxSteps"
442
+ ];
443
+ var KEY_BINDINGS = {
444
+ NAVIGATE_UP: "\u2191",
445
+ NAVIGATE_DOWN: "\u2193",
446
+ SELECT: "Enter",
447
+ BACK: "b",
448
+ ESCAPE: "Esc",
449
+ INPUT_MODE: "i",
450
+ HISTORY: "h",
451
+ NEW: "n",
452
+ CHECKPOINTS: "c",
453
+ EVENTS: "e",
454
+ RESUME: "Enter"};
455
+ var KEY_HINTS = {
456
+ NAVIGATE: `${KEY_BINDINGS.NAVIGATE_UP}${KEY_BINDINGS.NAVIGATE_DOWN}:Navigate`,
457
+ SELECT: `${KEY_BINDINGS.SELECT}:Select`,
458
+ RESUME: `${KEY_BINDINGS.RESUME}:Resume`,
459
+ BACK: `${KEY_BINDINGS.BACK}:Back`,
460
+ CANCEL: `${KEY_BINDINGS.ESCAPE}:Cancel`,
461
+ INPUT: `${KEY_BINDINGS.INPUT_MODE}:Input`,
462
+ HISTORY: `${KEY_BINDINGS.HISTORY}:History`,
463
+ NEW: `${KEY_BINDINGS.NEW}:New Run`,
464
+ CHECKPOINTS: `${KEY_BINDINGS.CHECKPOINTS}:Checkpoints`,
465
+ EVENTS: `${KEY_BINDINGS.EVENTS}:Events`};
466
+ var useLatestRef = (value) => {
467
+ const ref = useRef(value);
468
+ useInsertionEffect(() => {
469
+ ref.current = value;
470
+ });
471
+ return ref;
472
+ };
473
+ var useListNavigation = (options) => {
474
+ const { items, onSelect, onBack } = options;
475
+ const [selectedIndex, setSelectedIndex] = useState(0);
476
+ useEffect(() => {
477
+ if (selectedIndex >= items.length && items.length > 0) {
478
+ setSelectedIndex(items.length - 1);
479
+ }
480
+ }, [items.length, selectedIndex]);
481
+ const handleNavigation = useCallback(
482
+ (inputChar, key) => {
483
+ if (key.upArrow && items.length > 0) {
484
+ setSelectedIndex((prev) => Math.max(0, prev - 1));
485
+ return true;
486
+ }
487
+ if (key.downArrow && items.length > 0) {
488
+ setSelectedIndex((prev) => Math.min(items.length - 1, prev + 1));
489
+ return true;
490
+ }
491
+ if (key.return && items[selectedIndex]) {
492
+ onSelect?.(items[selectedIndex]);
493
+ return true;
494
+ }
495
+ if ((key.escape || inputChar === "b") && onBack) {
496
+ onBack();
497
+ return true;
498
+ }
499
+ return false;
500
+ },
501
+ [items, selectedIndex, onSelect, onBack]
502
+ );
503
+ return { selectedIndex, handleNavigation };
504
+ };
505
+ var useTextInput = (options) => {
506
+ const [input, setInput] = useState("");
507
+ const inputRef = useLatestRef(input);
508
+ const onSubmitRef = useLatestRef(options.onSubmit);
509
+ const onCancelRef = useLatestRef(options.onCancel);
510
+ const handleInput = useCallback(
511
+ (inputChar, key) => {
512
+ if (key.escape) {
513
+ setInput("");
514
+ onCancelRef.current?.();
515
+ return;
516
+ }
517
+ if (key.return && inputRef.current.trim()) {
518
+ onSubmitRef.current(inputRef.current.trim());
519
+ setInput("");
520
+ return;
521
+ }
522
+ if (key.backspace || key.delete) {
523
+ setInput((prev) => prev.slice(0, -1));
524
+ return;
525
+ }
526
+ if (!key.ctrl && !key.meta && inputChar) {
527
+ setInput((prev) => prev + inputChar);
528
+ }
529
+ },
530
+ [inputRef, onSubmitRef, onCancelRef]
531
+ );
532
+ const reset = useCallback(() => {
533
+ setInput("");
534
+ }, []);
535
+ return { input, handleInput, reset };
536
+ };
537
+ var ListBrowser = ({
538
+ title,
539
+ items,
540
+ renderItem,
541
+ onSelect,
542
+ emptyMessage = "No items found",
543
+ extraKeyHandler,
544
+ onBack,
545
+ maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS
546
+ }) => {
547
+ const { selectedIndex, handleNavigation } = useListNavigation({
548
+ items,
549
+ onSelect,
550
+ onBack
551
+ });
552
+ useInput((inputChar, key) => {
553
+ if (extraKeyHandler?.(inputChar, key, items[selectedIndex])) return;
554
+ handleNavigation(inputChar, key);
555
+ });
556
+ const { scrollOffset, displayItems } = useMemo(() => {
557
+ const offset = Math.max(0, Math.min(selectedIndex - maxItems + 1, items.length - maxItems));
558
+ return {
559
+ scrollOffset: offset,
560
+ displayItems: items.slice(offset, offset + maxItems)
561
+ };
562
+ }, [items, selectedIndex, maxItems]);
563
+ const hasMoreAbove = scrollOffset > 0;
564
+ const hasMoreBelow = scrollOffset + maxItems < items.length;
565
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
566
+ /* @__PURE__ */ jsxs(Box, { children: [
567
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: title }),
568
+ items.length > maxItems && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
569
+ " ",
570
+ "(",
571
+ selectedIndex + 1,
572
+ "/",
573
+ items.length,
574
+ ")"
575
+ ] })
576
+ ] }),
577
+ hasMoreAbove && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS }),
578
+ /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: displayItems.length === 0 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: emptyMessage }) : displayItems.map((item, index) => {
579
+ const actualIndex = scrollOffset + index;
580
+ return renderItem(item, actualIndex === selectedIndex, actualIndex);
581
+ }) }),
582
+ hasMoreBelow && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS })
583
+ ] });
584
+ };
585
+ var BrowsingCheckpointsInput = ({
586
+ job,
587
+ checkpoints,
588
+ onCheckpointSelect,
589
+ onCheckpointResume,
590
+ onBack,
591
+ showEventsHint = true
592
+ }) => /* @__PURE__ */ jsx(
593
+ ListBrowser,
594
+ {
595
+ title: `Checkpoints for ${job.expertKey} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${showEventsHint ? KEY_HINTS.EVENTS : ""} ${KEY_HINTS.BACK}`.trim(),
596
+ items: checkpoints,
597
+ onSelect: onCheckpointResume,
598
+ onBack,
599
+ emptyMessage: "No checkpoints found",
600
+ extraKeyHandler: (char, _key, selected) => {
601
+ if (char === "e" && selected) {
602
+ onCheckpointSelect(selected);
603
+ return true;
604
+ }
605
+ return false;
606
+ },
607
+ renderItem: (cp, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
608
+ isSelected ? ">" : " ",
609
+ " Step ",
610
+ cp.stepNumber,
611
+ " (",
612
+ cp.id,
613
+ ")"
614
+ ] }, cp.id)
615
+ }
616
+ );
617
+ var BrowsingEventDetailInput = ({ event, onBack }) => {
618
+ useInput((input, key) => {
619
+ if (input === "b" || key.escape) {
620
+ onBack();
621
+ }
622
+ });
623
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
624
+ /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
625
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Event Detail" }),
626
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
627
+ " ",
628
+ KEY_HINTS.BACK
629
+ ] })
630
+ ] }),
631
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 2, children: [
632
+ /* @__PURE__ */ jsxs(Text, { children: [
633
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type: " }),
634
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: event.type })
635
+ ] }),
636
+ /* @__PURE__ */ jsxs(Text, { children: [
637
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Step: " }),
638
+ /* @__PURE__ */ jsx(Text, { children: event.stepNumber })
639
+ ] }),
640
+ /* @__PURE__ */ jsxs(Text, { children: [
641
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Timestamp: " }),
642
+ /* @__PURE__ */ jsx(Text, { children: formatTimestamp(event.timestamp) })
643
+ ] }),
644
+ /* @__PURE__ */ jsxs(Text, { children: [
645
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "ID: " }),
646
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.id })
647
+ ] }),
648
+ /* @__PURE__ */ jsxs(Text, { children: [
649
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Run ID: " }),
650
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.runId })
651
+ ] })
652
+ ] })
653
+ ] });
654
+ };
655
+ var BrowsingEventsInput = ({
656
+ checkpoint,
657
+ events,
658
+ onEventSelect,
659
+ onBack
660
+ }) => /* @__PURE__ */ jsx(
661
+ ListBrowser,
662
+ {
663
+ title: `Events for Step ${checkpoint.stepNumber} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.BACK}`,
664
+ items: events,
665
+ onSelect: onEventSelect,
666
+ onBack,
667
+ emptyMessage: "No events found",
668
+ renderItem: (ev, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
669
+ isSelected ? ">" : " ",
670
+ " [",
671
+ ev.type,
672
+ "] Step ",
673
+ ev.stepNumber,
674
+ " (",
675
+ formatTimestamp(ev.timestamp),
676
+ ")"
677
+ ] }, ev.id)
678
+ }
679
+ );
680
+ var useRuntimeInfo = (options) => {
681
+ const [runtimeInfo, setRuntimeInfo] = useState({
682
+ status: "initializing",
683
+ runtimeVersion: options.initialConfig.runtimeVersion,
684
+ expertName: options.initialExpertName,
685
+ model: options.initialConfig.model,
686
+ maxSteps: options.initialConfig.maxSteps,
687
+ maxRetries: options.initialConfig.maxRetries,
688
+ timeout: options.initialConfig.timeout,
689
+ activeSkills: [],
690
+ contextWindowUsage: options.initialConfig.contextWindowUsage
691
+ });
692
+ const handleEvent = useCallback((event) => {
693
+ if (event.type === "initializeRuntime") {
694
+ setRuntimeInfo((prev) => ({
695
+ runtimeVersion: event.runtimeVersion,
696
+ expertName: event.expertName,
697
+ model: event.model,
698
+ maxSteps: event.maxSteps,
699
+ maxRetries: event.maxRetries,
700
+ timeout: event.timeout,
701
+ currentStep: 1,
702
+ status: "running",
703
+ query: event.query,
704
+ statusChangedAt: Date.now(),
705
+ activeSkills: [],
706
+ contextWindowUsage: prev.contextWindowUsage
707
+ }));
708
+ return { initialized: true };
709
+ }
710
+ if (event.type === "skillConnected") {
711
+ setRuntimeInfo((prev) => ({
712
+ ...prev,
713
+ activeSkills: [...prev.activeSkills, event.skillName]
714
+ }));
715
+ return null;
716
+ }
717
+ if (event.type === "skillDisconnected") {
718
+ setRuntimeInfo((prev) => ({
719
+ ...prev,
720
+ activeSkills: prev.activeSkills.filter((s) => s !== event.skillName)
721
+ }));
722
+ return null;
723
+ }
724
+ if ("stepNumber" in event) {
725
+ const isComplete = event.type === "completeRun";
726
+ const isStopped = STOP_EVENT_TYPES.includes(event.type);
727
+ const checkpoint = "nextCheckpoint" in event ? event.nextCheckpoint : "checkpoint" in event ? event.checkpoint : void 0;
728
+ setRuntimeInfo((prev) => ({
729
+ ...prev,
730
+ currentStep: event.stepNumber,
731
+ status: isComplete ? "completed" : isStopped ? "stopped" : "running",
732
+ ...isComplete || isStopped ? { statusChangedAt: Date.now() } : {},
733
+ ...checkpoint?.contextWindowUsage !== void 0 ? { contextWindowUsage: checkpoint.contextWindowUsage } : {}
734
+ }));
735
+ if (isComplete) return { completed: true };
736
+ if (isStopped) return { stopped: true };
737
+ }
738
+ return null;
739
+ }, []);
740
+ const setExpertName = useCallback((expertName) => {
741
+ setRuntimeInfo((prev) => ({ ...prev, expertName }));
742
+ }, []);
743
+ const setQuery = useCallback((query) => {
744
+ setRuntimeInfo((prev) => ({ ...prev, query }));
745
+ }, []);
746
+ const setCurrentStep = useCallback((step) => {
747
+ setRuntimeInfo((prev) => ({ ...prev, currentStep: step }));
748
+ }, []);
749
+ const setContextWindowUsage = useCallback((contextWindowUsage) => {
750
+ setRuntimeInfo((prev) => ({ ...prev, contextWindowUsage }));
751
+ }, []);
752
+ return {
753
+ runtimeInfo,
754
+ handleEvent,
755
+ setExpertName,
756
+ setQuery,
757
+ setCurrentStep,
758
+ setContextWindowUsage
759
+ };
760
+ };
761
+ var useExpertSelector = (options) => {
762
+ const { experts, onExpertSelect, extraKeyHandler } = options;
763
+ const [inputMode, setInputMode] = useState(false);
764
+ const { selectedIndex, handleNavigation } = useListNavigation({
765
+ items: experts,
766
+ onSelect: (expert) => onExpertSelect(expert.key)
767
+ });
768
+ const { input, handleInput, reset } = useTextInput({
769
+ onSubmit: (value) => {
770
+ onExpertSelect(value);
771
+ setInputMode(false);
772
+ },
773
+ onCancel: () => setInputMode(false)
774
+ });
775
+ const handleKeyInput = useCallback(
776
+ (inputChar, key) => {
777
+ if (inputMode) {
778
+ handleInput(inputChar, key);
779
+ return;
780
+ }
781
+ if (handleNavigation(inputChar, key)) return;
782
+ if (extraKeyHandler?.(inputChar, key)) return;
783
+ if (inputChar === "i") {
784
+ reset();
785
+ setInputMode(true);
786
+ }
787
+ },
788
+ [inputMode, handleInput, handleNavigation, extraKeyHandler, reset]
789
+ );
790
+ return {
791
+ inputMode,
792
+ input,
793
+ selectedIndex,
794
+ handleKeyInput
795
+ };
796
+ };
797
+ var ExpertList = ({
798
+ experts,
799
+ selectedIndex,
800
+ showSource = false,
801
+ inline = false,
802
+ maxItems
803
+ }) => {
804
+ const displayExperts = maxItems ? experts.slice(0, maxItems) : experts;
805
+ if (displayExperts.length === 0) {
806
+ return /* @__PURE__ */ jsx(Text, { color: "gray", children: "No experts found." });
807
+ }
808
+ const items = displayExperts.map((expert, index) => /* @__PURE__ */ jsxs(Text, { color: index === selectedIndex ? "cyan" : "gray", children: [
809
+ index === selectedIndex ? ">" : " ",
810
+ " ",
811
+ showSource ? expert.key : expert.name,
812
+ showSource && expert.source && /* @__PURE__ */ jsxs(Fragment, { children: [
813
+ " ",
814
+ /* @__PURE__ */ jsxs(Text, { color: expert.source === "configured" ? "green" : "yellow", children: [
815
+ "[",
816
+ expert.source === "configured" ? "config" : "recent",
817
+ "]"
818
+ ] })
819
+ ] }),
820
+ inline ? " " : ""
821
+ ] }, expert.key));
822
+ return inline ? /* @__PURE__ */ jsx(Box, { children: items }) : /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: items });
823
+ };
824
+ var ExpertSelectorBase = ({
825
+ experts,
826
+ hint,
827
+ onExpertSelect,
828
+ showSource = false,
829
+ inline = false,
830
+ maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
831
+ extraKeyHandler
832
+ }) => {
833
+ const { inputMode, input, selectedIndex, handleKeyInput } = useExpertSelector({
834
+ experts,
835
+ onExpertSelect,
836
+ extraKeyHandler
837
+ });
838
+ useInput(handleKeyInput);
839
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: inline ? "row" : "column", children: [
840
+ !inputMode && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
841
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "cyan", children: hint }) }),
842
+ /* @__PURE__ */ jsx(
843
+ ExpertList,
844
+ {
845
+ experts,
846
+ selectedIndex,
847
+ showSource,
848
+ inline,
849
+ maxItems
850
+ }
851
+ )
852
+ ] }),
853
+ inputMode && /* @__PURE__ */ jsxs(Box, { children: [
854
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
855
+ /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
856
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
857
+ ] })
858
+ ] });
859
+ };
860
+ var BrowsingExpertsInput = ({
861
+ experts,
862
+ onExpertSelect,
863
+ onSwitchToHistory
864
+ }) => {
865
+ const extraKeyHandler = useCallback(
866
+ (inputChar) => {
867
+ if (inputChar === "h") {
868
+ onSwitchToHistory();
869
+ return true;
870
+ }
871
+ return false;
872
+ },
873
+ [onSwitchToHistory]
874
+ );
875
+ const hint = `Experts ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.INPUT} ${KEY_HINTS.HISTORY} ${KEY_HINTS.CANCEL}`;
876
+ return /* @__PURE__ */ jsx(
877
+ ExpertSelectorBase,
878
+ {
879
+ experts,
880
+ hint,
881
+ onExpertSelect,
882
+ showSource: true,
883
+ maxItems: UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
884
+ extraKeyHandler
885
+ }
886
+ );
887
+ };
888
+ var BrowsingHistoryInput = ({
889
+ jobs,
890
+ onJobSelect,
891
+ onJobResume,
892
+ onSwitchToExperts
893
+ }) => /* @__PURE__ */ jsx(
894
+ ListBrowser,
895
+ {
896
+ title: `Job History ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${KEY_HINTS.CHECKPOINTS} ${KEY_HINTS.NEW}`,
897
+ items: jobs,
898
+ onSelect: onJobResume,
899
+ emptyMessage: "No jobs found. Press n to start a new job.",
900
+ extraKeyHandler: (char, _key, selected) => {
901
+ if (char === "c" && selected) {
902
+ onJobSelect(selected);
903
+ return true;
904
+ }
905
+ if (char === "n") {
906
+ onSwitchToExperts();
907
+ return true;
908
+ }
909
+ return false;
910
+ },
911
+ renderItem: (job, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
912
+ isSelected ? ">" : " ",
913
+ " ",
914
+ job.expertKey,
915
+ " - ",
916
+ job.totalSteps,
917
+ " steps (",
918
+ job.jobId,
919
+ ") (",
920
+ formatTimestamp(job.startedAt),
921
+ ")"
922
+ ] }, job.jobId)
923
+ }
924
+ );
925
+ var BrowserRouter = ({ inputState, showEventsHint = true }) => {
926
+ const ctx = useInputAreaContext();
927
+ const handleEventSelect = useCallback(
928
+ (event) => {
929
+ if (inputState.type === "browsingEvents") {
930
+ ctx.onEventSelect(inputState, event);
931
+ }
932
+ },
933
+ [ctx.onEventSelect, inputState]
934
+ );
935
+ switch (inputState.type) {
936
+ case "browsingHistory":
937
+ return /* @__PURE__ */ jsx(
938
+ BrowsingHistoryInput,
939
+ {
940
+ jobs: inputState.jobs,
941
+ onJobSelect: ctx.onJobSelect,
942
+ onJobResume: ctx.onJobResume,
943
+ onSwitchToExperts: ctx.onSwitchToExperts
944
+ }
945
+ );
946
+ case "browsingExperts":
947
+ return /* @__PURE__ */ jsx(
948
+ BrowsingExpertsInput,
949
+ {
950
+ experts: inputState.experts,
951
+ onExpertSelect: ctx.onExpertSelect,
952
+ onSwitchToHistory: ctx.onSwitchToHistory
953
+ }
954
+ );
955
+ case "browsingCheckpoints":
956
+ return /* @__PURE__ */ jsx(
957
+ BrowsingCheckpointsInput,
958
+ {
959
+ job: inputState.job,
960
+ checkpoints: inputState.checkpoints,
961
+ onCheckpointSelect: ctx.onCheckpointSelect,
962
+ onCheckpointResume: ctx.onCheckpointResume,
963
+ onBack: ctx.onBack,
964
+ showEventsHint
965
+ }
966
+ );
967
+ case "browsingEvents":
968
+ return /* @__PURE__ */ jsx(
969
+ BrowsingEventsInput,
970
+ {
971
+ checkpoint: inputState.checkpoint,
972
+ events: inputState.events,
973
+ onEventSelect: handleEventSelect,
974
+ onBack: ctx.onBack
975
+ }
976
+ );
977
+ case "browsingEventDetail":
978
+ return /* @__PURE__ */ jsx(BrowsingEventDetailInput, { event: inputState.selectedEvent, onBack: ctx.onBack });
979
+ default:
980
+ return assertNever(inputState);
981
+ }
982
+ };
983
+ var ActionRowSimple = ({
984
+ indicatorColor,
985
+ text,
986
+ textDimColor = false
987
+ }) => /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
988
+ /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }) }),
989
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: textDimColor, children: text })
990
+ ] }) });
991
+ var ActionRow = ({ indicatorColor, label, summary, children }) => /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
992
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
993
+ /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }),
994
+ /* @__PURE__ */ jsx(Text, { color: "white", children: label }),
995
+ summary && /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: summary })
996
+ ] }),
997
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
998
+ /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: INDICATOR.TREE }) }),
999
+ children
1000
+ ] })
1001
+ ] });
1002
+ var CheckpointActionRow = ({ action }) => {
1003
+ if (action.type === "parallelGroup") {
1004
+ return renderParallelGroup(action);
1005
+ }
1006
+ const actionElement = renderAction(action);
1007
+ if (!actionElement) return null;
1008
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1009
+ action.reasoning && renderReasoning(action.reasoning),
1010
+ actionElement
1011
+ ] });
1012
+ };
1013
+ function renderParallelGroup(group) {
1014
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1015
+ group.reasoning && renderReasoning(group.reasoning),
1016
+ group.activities.map((activity, index) => {
1017
+ const actionElement = renderAction(activity);
1018
+ if (!actionElement) return null;
1019
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: actionElement }, activity.id || `${activity.type}-${index}`);
1020
+ })
1021
+ ] });
1022
+ }
1023
+ function renderReasoning(text) {
1024
+ const lines = text.split("\n");
1025
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "white", label: "Reasoning", children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, wrap: "wrap", children: line }, `reasoning-${idx}`)) }) });
1026
+ }
1027
+ function renderAction(action) {
1028
+ const color = action.type === "error" || "error" in action && action.error ? "red" : "green";
1029
+ switch (action.type) {
1030
+ case "query":
1031
+ return renderQuery(action.text, action.runId);
1032
+ case "retry":
1033
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Retry", children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: action.message || action.error }) });
1034
+ case "complete":
1035
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "green", label: "Run Results", children: /* @__PURE__ */ jsx(Text, { children: action.text }) });
1036
+ case "attemptCompletion": {
1037
+ if (action.error) {
1038
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: "Completion Failed", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error }) });
1039
+ }
1040
+ const remaining = action.remainingTodos?.filter((t) => !t.completed) ?? [];
1041
+ if (remaining.length > 0) {
1042
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Completion Blocked", children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1043
+ remaining.length,
1044
+ " remaining task",
1045
+ remaining.length > 1 ? "s" : ""
1046
+ ] }) });
1047
+ }
1048
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: "green", text: "Completion Accepted" });
1049
+ }
1050
+ case "todo":
1051
+ return renderTodo(action, color);
1052
+ case "clearTodo":
1053
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo Cleared" });
1054
+ case "readTextFile":
1055
+ return renderReadTextFile(action, color);
1056
+ case "writeTextFile":
1057
+ return renderWriteTextFile(action, color);
1058
+ case "editTextFile":
1059
+ return renderEditTextFile(action, color);
1060
+ case "appendTextFile":
1061
+ return renderAppendTextFile(action, color);
1062
+ case "deleteFile":
1063
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Removed" }) });
1064
+ case "deleteDirectory":
1065
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete Dir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1066
+ "Removed",
1067
+ action.recursive ? " (recursive)" : ""
1068
+ ] }) });
1069
+ case "moveFile":
1070
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Move", summary: shortenPath(action.source), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1071
+ "\u2192 ",
1072
+ shortenPath(action.destination, 30)
1073
+ ] }) });
1074
+ case "createDirectory":
1075
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Mkdir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Created" }) });
1076
+ case "listDirectory":
1077
+ return renderListDirectory(action, color);
1078
+ case "getFileInfo":
1079
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Info", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Fetched" }) });
1080
+ case "readPdfFile":
1081
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "PDF", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
1082
+ case "readImageFile":
1083
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Image", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
1084
+ case "exec":
1085
+ return renderExec(action, color);
1086
+ case "delegate":
1087
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: action.delegateExpertKey, children: /* @__PURE__ */ jsx(
1088
+ Text,
1089
+ {
1090
+ dimColor: true,
1091
+ children: `{"query":"${truncateText(action.query, UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM)}"}`
1092
+ }
1093
+ ) });
1094
+ case "delegationComplete":
1095
+ return /* @__PURE__ */ jsx(
1096
+ ActionRowSimple,
1097
+ {
1098
+ indicatorColor: "green",
1099
+ text: `Delegation Complete (${action.count} delegate${action.count > 1 ? "s" : ""} returned)`
1100
+ }
1101
+ );
1102
+ case "interactiveTool":
1103
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: `Interactive: ${action.toolName}`, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(JSON.stringify(action.args), UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM) }) });
1104
+ case "generalTool":
1105
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: action.toolName, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(JSON.stringify(action.args), UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM) }) });
1106
+ case "error":
1107
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: action.errorName ?? "Error", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error ?? "Unknown error" }) });
1108
+ default: {
1109
+ return null;
1110
+ }
1111
+ }
1112
+ }
1113
+ function renderTodo(action, color) {
1114
+ const { newTodos, completedTodos, todos } = action;
1115
+ const hasNewTodos = newTodos && newTodos.length > 0;
1116
+ const hasCompletedTodos = completedTodos && completedTodos.length > 0;
1117
+ if (!hasNewTodos && !hasCompletedTodos) {
1118
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo No changes" });
1119
+ }
1120
+ const labelParts = [];
1121
+ if (hasNewTodos) {
1122
+ labelParts.push(`Added ${newTodos.length} task${newTodos.length > 1 ? "s" : ""}`);
1123
+ }
1124
+ if (hasCompletedTodos) {
1125
+ labelParts.push(
1126
+ `Completed ${completedTodos.length} task${completedTodos.length > 1 ? "s" : ""}`
1127
+ );
1128
+ }
1129
+ const label = `Todo ${labelParts.join(", ")}`;
1130
+ const completedTitles = hasCompletedTodos ? completedTodos.map((id) => todos.find((t) => t.id === id)?.title).filter((t) => t !== void 0) : [];
1131
+ if (!hasNewTodos && completedTitles.length === 0) {
1132
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: label });
1133
+ }
1134
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1135
+ hasNewTodos && newTodos.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((todo, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1136
+ "\u25CB ",
1137
+ todo
1138
+ ] }, `todo-${idx}`)),
1139
+ hasNewTodos && newTodos.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1140
+ "... +",
1141
+ newTodos.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
1142
+ " more"
1143
+ ] }),
1144
+ completedTitles.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((title, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1145
+ "\u2713 ",
1146
+ title
1147
+ ] }, `completed-${idx}`)),
1148
+ completedTitles.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1149
+ "... +",
1150
+ completedTitles.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
1151
+ " more"
1152
+ ] })
1153
+ ] }) });
1154
+ }
1155
+ function renderReadTextFile(action, color) {
1156
+ const { path: path2, content, from, to } = action;
1157
+ const lineRange = from !== void 0 && to !== void 0 ? `#${from}-${to}` : "";
1158
+ const lines = content?.split("\n") ?? [];
1159
+ return /* @__PURE__ */ jsx(
1160
+ ActionRow,
1161
+ {
1162
+ indicatorColor: color,
1163
+ label: "Read Text File",
1164
+ summary: `${shortenPath(path2)}${lineRange}`,
1165
+ children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Box, { flexDirection: "row", gap: 1, children: /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line }) }, `read-${idx}`)) })
1166
+ }
1167
+ );
1168
+ }
1169
+ function renderWriteTextFile(action, color) {
1170
+ const { path: path2, text } = action;
1171
+ const lines = text.split("\n");
1172
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Write Text File", summary: shortenPath(path2), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
1173
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
1174
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
1175
+ ] }, `write-${idx}`)) }) });
1176
+ }
1177
+ function renderEditTextFile(action, color) {
1178
+ const { path: path2, oldText, newText } = action;
1179
+ const oldLines = oldText.split("\n");
1180
+ const newLines = newText.split("\n");
1181
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Edit Text File", summary: shortenPath(path2), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1182
+ oldLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
1183
+ /* @__PURE__ */ jsx(Text, { color: "red", dimColor: true, children: "-" }),
1184
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
1185
+ ] }, `old-${idx}`)),
1186
+ newLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
1187
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
1188
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: line })
1189
+ ] }, `new-${idx}`))
1190
+ ] }) });
1191
+ }
1192
+ function renderAppendTextFile(action, color) {
1193
+ const { path: path2, text } = action;
1194
+ const lines = text.split("\n");
1195
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Append Text File", summary: shortenPath(path2), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
1196
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
1197
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
1198
+ ] }, `append-${idx}`)) }) });
1199
+ }
1200
+ function renderListDirectory(action, color) {
1201
+ const { path: path2, items } = action;
1202
+ const itemLines = items?.map((item) => `${item.type === "directory" ? "\u{1F4C1}" : "\u{1F4C4}"} ${item.name}`) ?? [];
1203
+ const { visible, remaining } = summarizeOutput(itemLines, RENDER_CONSTANTS.LIST_DIR_MAX_ITEMS);
1204
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "List", summary: shortenPath(path2), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1205
+ visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `dir-${idx}`)),
1206
+ remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1207
+ "... +",
1208
+ remaining,
1209
+ " more"
1210
+ ] })
1211
+ ] }) });
1212
+ }
1213
+ function renderExec(action, color) {
1214
+ const { command, args, cwd, output } = action;
1215
+ const cwdPart = cwd ? ` ${shortenPath(cwd, 40)}` : "";
1216
+ const cmdLine = truncateText(
1217
+ `${command} ${args.join(" ")}${cwdPart}`,
1218
+ UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT
1219
+ );
1220
+ const outputLines = output?.split("\n") ?? [];
1221
+ const { visible, remaining } = summarizeOutput(
1222
+ outputLines,
1223
+ RENDER_CONSTANTS.EXEC_OUTPUT_MAX_LINES
1224
+ );
1225
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: `Bash ${cmdLine}`, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1226
+ visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `out-${idx}`)),
1227
+ remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1228
+ "... +",
1229
+ remaining,
1230
+ " more"
1231
+ ] })
1232
+ ] }) });
1233
+ }
1234
+ function renderQuery(text, runId) {
1235
+ const lines = text.split("\n");
1236
+ const shortRunId = runId.slice(0, 8);
1237
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "cyan", label: "Query", summary: `(${shortRunId})`, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, wrap: "wrap", children: line }, `query-${idx}`)) }) });
1238
+ }
1239
+ var RunSetting = ({
1240
+ info,
1241
+ eventCount,
1242
+ isEditing,
1243
+ expertName,
1244
+ onQuerySubmit
1245
+ }) => {
1246
+ const { input, handleInput } = useTextInput({
1247
+ onSubmit: onQuerySubmit ?? (() => {
1248
+ })
1249
+ });
1250
+ useInput(handleInput, { isActive: isEditing });
1251
+ const displayExpertName = expertName ?? info.expertName;
1252
+ const skills = info.activeSkills.length > 0 ? info.activeSkills.join(", ") : "";
1253
+ const step = info.currentStep !== void 0 ? String(info.currentStep) : "";
1254
+ const usagePercent = (info.contextWindowUsage * 100).toFixed(1);
1255
+ return /* @__PURE__ */ jsxs(
1256
+ Box,
1257
+ {
1258
+ flexDirection: "column",
1259
+ borderStyle: "single",
1260
+ borderColor: "gray",
1261
+ borderTop: true,
1262
+ borderBottom: false,
1263
+ borderLeft: false,
1264
+ borderRight: false,
1265
+ children: [
1266
+ /* @__PURE__ */ jsxs(Text, { children: [
1267
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "Perstack" }),
1268
+ info.runtimeVersion && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
1269
+ " (v",
1270
+ info.runtimeVersion,
1271
+ ")"
1272
+ ] })
1273
+ ] }),
1274
+ /* @__PURE__ */ jsxs(Text, { children: [
1275
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
1276
+ /* @__PURE__ */ jsx(Text, { color: "white", children: displayExpertName }),
1277
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Skills: " }),
1278
+ /* @__PURE__ */ jsx(Text, { color: "green", children: skills })
1279
+ ] }),
1280
+ /* @__PURE__ */ jsxs(Text, { children: [
1281
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Status: " }),
1282
+ /* @__PURE__ */ jsx(
1283
+ Text,
1284
+ {
1285
+ color: info.status === "running" ? "green" : info.status === "completed" ? "cyan" : "yellow",
1286
+ children: info.status
1287
+ }
1288
+ ),
1289
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Step: " }),
1290
+ /* @__PURE__ */ jsx(Text, { color: "white", children: step }),
1291
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Events: " }),
1292
+ /* @__PURE__ */ jsx(Text, { color: "white", children: eventCount }),
1293
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Usage: " }),
1294
+ /* @__PURE__ */ jsxs(Text, { color: "white", children: [
1295
+ usagePercent,
1296
+ "%"
1297
+ ] })
1298
+ ] }),
1299
+ /* @__PURE__ */ jsxs(Text, { children: [
1300
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Model: " }),
1301
+ /* @__PURE__ */ jsx(Text, { color: "white", children: info.model })
1302
+ ] }),
1303
+ /* @__PURE__ */ jsxs(Box, { children: [
1304
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
1305
+ isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
1306
+ /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
1307
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
1308
+ ] }) : /* @__PURE__ */ jsx(Text, { color: "white", children: info.query })
1309
+ ] })
1310
+ ]
1311
+ }
1312
+ );
1313
+ };
1314
+ var StreamingDisplay = ({ streaming }) => {
1315
+ const activeRuns = Object.entries(streaming.runs).filter(
1316
+ ([, run]) => run.isReasoningActive || run.isRunResultActive
1317
+ );
1318
+ if (activeRuns.length === 0) return null;
1319
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginY: 1, children: activeRuns.map(([runId, run]) => /* @__PURE__ */ jsx(StreamingRunSection, { run }, runId)) });
1320
+ };
1321
+ function StreamingRunSection({ run }) {
1322
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1323
+ run.isReasoningActive && run.reasoning !== void 0 && /* @__PURE__ */ jsx(StreamingReasoning, { expertKey: run.expertKey, text: run.reasoning }),
1324
+ run.isRunResultActive && run.runResult !== void 0 && /* @__PURE__ */ jsx(StreamingRunResult, { expertKey: run.expertKey, text: run.runResult })
1325
+ ] });
1326
+ }
1327
+ function StreamingReasoning({
1328
+ expertKey,
1329
+ text
1330
+ }) {
1331
+ const lines = text.split("\n");
1332
+ const label = `[${formatExpertKey(expertKey)}] Reasoning...`;
1333
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "cyan", label, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, wrap: "wrap", children: line }, `streaming-reasoning-${idx}`)) }) });
1334
+ }
1335
+ function StreamingRunResult({
1336
+ expertKey,
1337
+ text
1338
+ }) {
1339
+ const lines = text.split("\n");
1340
+ const label = `[${formatExpertKey(expertKey)}] Generating...`;
1341
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "green", label, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: line }, `streaming-run-result-${idx}`)) }) });
1342
+ }
1343
+ function formatExpertKey(expertKey) {
1344
+ const atIndex = expertKey.lastIndexOf("@");
1345
+ if (atIndex > 0) {
1346
+ return expertKey.substring(0, atIndex);
1347
+ }
1348
+ return expertKey;
1349
+ }
1350
+ function getActivityKey(activityOrGroup, index) {
1351
+ return activityOrGroup.id || `activity-${index}`;
1352
+ }
1353
+ var RunBox = ({ node, isRoot }) => {
1354
+ if (isRoot) {
1355
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1356
+ node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
1357
+ node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
1358
+ ] });
1359
+ }
1360
+ const shortRunId = node.runId.slice(0, 8);
1361
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", marginLeft: 1, children: [
1362
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, bold: true, children: [
1363
+ "[",
1364
+ node.expertKey,
1365
+ "] ",
1366
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
1367
+ "(",
1368
+ shortRunId,
1369
+ ")"
1370
+ ] })
1371
+ ] }),
1372
+ node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
1373
+ node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
1374
+ ] });
1375
+ };
1376
+ function getActivityProps(activityOrGroup) {
1377
+ if (activityOrGroup.type === "parallelGroup") {
1378
+ const group = activityOrGroup;
1379
+ const firstActivity = group.activities[0];
1380
+ return {
1381
+ runId: group.runId,
1382
+ expertKey: group.expertKey,
1383
+ delegatedBy: firstActivity?.delegatedBy
1384
+ };
1385
+ }
1386
+ return activityOrGroup;
1387
+ }
1388
+ var ActivityLogPanel = ({ activities }) => {
1389
+ const rootNodes = useMemo(() => {
1390
+ const nodeMap = /* @__PURE__ */ new Map();
1391
+ const roots = [];
1392
+ const orphanChildren = /* @__PURE__ */ new Map();
1393
+ for (const activityOrGroup of activities) {
1394
+ const { runId, expertKey, delegatedBy } = getActivityProps(activityOrGroup);
1395
+ let node = nodeMap.get(runId);
1396
+ if (!node) {
1397
+ node = {
1398
+ runId,
1399
+ expertKey,
1400
+ activities: [],
1401
+ children: []
1402
+ };
1403
+ nodeMap.set(runId, node);
1404
+ const waitingChildren = orphanChildren.get(runId);
1405
+ if (waitingChildren) {
1406
+ for (const child of waitingChildren) {
1407
+ node.children.push(child);
1408
+ const rootIndex = roots.indexOf(child);
1409
+ if (rootIndex !== -1) {
1410
+ roots.splice(rootIndex, 1);
1411
+ }
1412
+ }
1413
+ orphanChildren.delete(runId);
1414
+ }
1415
+ if (delegatedBy) {
1416
+ const parentNode = nodeMap.get(delegatedBy.runId);
1417
+ if (parentNode) {
1418
+ parentNode.children.push(node);
1419
+ } else {
1420
+ const orphans = orphanChildren.get(delegatedBy.runId) ?? [];
1421
+ orphans.push(node);
1422
+ orphanChildren.set(delegatedBy.runId, orphans);
1423
+ roots.push(node);
1424
+ }
1425
+ } else {
1426
+ roots.push(node);
1427
+ }
1428
+ }
1429
+ node.activities.push(activityOrGroup);
1430
+ }
1431
+ return roots;
1432
+ }, [activities]);
1433
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: rootNodes.map((node) => /* @__PURE__ */ jsx(RunBox, { node, isRoot: true }, node.runId)) });
1434
+ };
1435
+ var ContinueInputPanel = ({
1436
+ isActive,
1437
+ runStatus,
1438
+ onSubmit
1439
+ }) => {
1440
+ const { input, handleInput } = useTextInput({
1441
+ onSubmit: (newQuery) => {
1442
+ if (isActive && newQuery.trim()) {
1443
+ onSubmit(newQuery.trim());
1444
+ }
1445
+ }
1446
+ });
1447
+ useInput(handleInput, { isActive });
1448
+ if (runStatus === "running") {
1449
+ return null;
1450
+ }
1451
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
1452
+ /* @__PURE__ */ jsxs(Text, { children: [
1453
+ /* @__PURE__ */ jsx(Text, { color: runStatus === "completed" ? "green" : "yellow", bold: true, children: runStatus === "completed" ? "Completed" : "Stopped" }),
1454
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " - Enter a follow-up query or wait to exit" })
1455
+ ] }),
1456
+ /* @__PURE__ */ jsxs(Box, { children: [
1457
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Continue: " }),
1458
+ /* @__PURE__ */ jsx(Text, { children: input }),
1459
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
1460
+ ] })
1461
+ ] });
1462
+ };
1463
+ var StatusPanel = ({
1464
+ runtimeInfo,
1465
+ eventCount,
1466
+ runStatus
1467
+ }) => {
1468
+ if (runStatus !== "running") {
1469
+ return null;
1470
+ }
1471
+ return /* @__PURE__ */ jsx(RunSetting, { info: runtimeInfo, eventCount, isEditing: false });
1472
+ };
1473
+ var useExecutionState = (options) => {
1474
+ const { expertKey, query, config, continueTimeoutMs, historicalEvents, onReady, onComplete } = options;
1475
+ const { exit } = useApp();
1476
+ const runState = useRun();
1477
+ const { runtimeInfo, handleEvent, setQuery } = useRuntimeInfo({
1478
+ initialExpertName: expertKey,
1479
+ initialConfig: config
1480
+ });
1481
+ const [runStatus, setRunStatus] = useState("running");
1482
+ const [isAcceptingContinue, setIsAcceptingContinue] = useState(false);
1483
+ const timeoutRef = useRef(null);
1484
+ const clearTimeoutIfExists = useCallback(() => {
1485
+ if (timeoutRef.current) {
1486
+ clearTimeout(timeoutRef.current);
1487
+ timeoutRef.current = null;
1488
+ }
1489
+ }, []);
1490
+ const startExitTimeout = useCallback(() => {
1491
+ clearTimeoutIfExists();
1492
+ timeoutRef.current = setTimeout(() => {
1493
+ onComplete({ nextQuery: null });
1494
+ exit();
1495
+ }, continueTimeoutMs);
1496
+ }, [clearTimeoutIfExists, continueTimeoutMs, onComplete, exit]);
1497
+ useEffect(() => {
1498
+ setQuery(query);
1499
+ }, [query, setQuery]);
1500
+ useEffect(() => {
1501
+ if (historicalEvents && historicalEvents.length > 0) {
1502
+ runState.appendHistoricalEvents(historicalEvents);
1503
+ }
1504
+ }, [historicalEvents, runState.appendHistoricalEvents]);
1505
+ useEffect(() => {
1506
+ onReady((event) => {
1507
+ runState.addEvent(event);
1508
+ const result = handleEvent(event);
1509
+ if (result?.completed) {
1510
+ setRunStatus("completed");
1511
+ setIsAcceptingContinue(true);
1512
+ startExitTimeout();
1513
+ } else if (result?.stopped) {
1514
+ setRunStatus("stopped");
1515
+ setIsAcceptingContinue(true);
1516
+ startExitTimeout();
1517
+ }
1518
+ });
1519
+ }, [onReady, runState.addEvent, handleEvent, startExitTimeout]);
1520
+ useEffect(() => {
1521
+ return () => {
1522
+ clearTimeoutIfExists();
1523
+ };
1524
+ }, [clearTimeoutIfExists]);
1525
+ const handleContinueSubmit = useCallback(
1526
+ (newQuery) => {
1527
+ if (isAcceptingContinue && newQuery.trim()) {
1528
+ clearTimeoutIfExists();
1529
+ onComplete({ nextQuery: newQuery.trim() });
1530
+ exit();
1531
+ }
1532
+ },
1533
+ [isAcceptingContinue, clearTimeoutIfExists, onComplete, exit]
1534
+ );
1535
+ return {
1536
+ activities: runState.activities,
1537
+ streaming: runState.streaming,
1538
+ eventCount: runState.eventCount,
1539
+ runtimeInfo,
1540
+ runStatus,
1541
+ isAcceptingContinue,
1542
+ handleContinueSubmit,
1543
+ clearTimeout: clearTimeoutIfExists
1544
+ };
1545
+ };
1546
+ var ExecutionApp = (props) => {
1547
+ const { expertKey, query, config, continueTimeoutMs, historicalEvents, onReady, onComplete } = props;
1548
+ const { exit } = useApp();
1549
+ const state = useExecutionState({
1550
+ expertKey,
1551
+ query,
1552
+ config,
1553
+ continueTimeoutMs,
1554
+ historicalEvents,
1555
+ onReady,
1556
+ onComplete
1557
+ });
1558
+ useInput((input, key) => {
1559
+ if (key.ctrl && input === "c") {
1560
+ state.clearTimeout();
1561
+ exit();
1562
+ }
1563
+ });
1564
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1565
+ /* @__PURE__ */ jsx(ActivityLogPanel, { activities: state.activities }),
1566
+ /* @__PURE__ */ jsx(StreamingDisplay, { streaming: state.streaming }),
1567
+ /* @__PURE__ */ jsx(
1568
+ StatusPanel,
1569
+ {
1570
+ runtimeInfo: state.runtimeInfo,
1571
+ eventCount: state.eventCount,
1572
+ runStatus: state.runStatus
1573
+ }
1574
+ ),
1575
+ /* @__PURE__ */ jsx(
1576
+ ContinueInputPanel,
1577
+ {
1578
+ isActive: state.isAcceptingContinue,
1579
+ runStatus: state.runStatus,
1580
+ onSubmit: state.handleContinueSubmit
1581
+ }
1582
+ )
1583
+ ] });
1584
+ };
1585
+ function renderExecution(params) {
1586
+ const eventQueue = new EventQueue();
1587
+ const result = new Promise((resolve, reject) => {
1588
+ let resolved = false;
1589
+ const { waitUntilExit } = render(
1590
+ /* @__PURE__ */ jsx(
1591
+ ExecutionApp,
1592
+ {
1593
+ ...params,
1594
+ onReady: (handler) => {
1595
+ eventQueue.setHandler(handler);
1596
+ },
1597
+ onComplete: (result2) => {
1598
+ resolved = true;
1599
+ resolve(result2);
1600
+ }
1601
+ }
1602
+ )
1603
+ );
1604
+ waitUntilExit().then(() => {
1605
+ if (!resolved) {
1606
+ reject(new Error("Execution cancelled"));
1607
+ }
1608
+ }).catch(reject);
1609
+ });
1610
+ return {
1611
+ result,
1612
+ eventListener: (event) => {
1613
+ eventQueue.emit(event);
1614
+ }
1615
+ };
1616
+ }
1617
+ var selectionReducer = (_state, action) => {
1618
+ switch (action.type) {
1619
+ case "BROWSE_HISTORY":
1620
+ return { type: "browsingHistory", jobs: action.jobs };
1621
+ case "BROWSE_EXPERTS":
1622
+ return { type: "browsingExperts", experts: action.experts };
1623
+ case "SELECT_EXPERT":
1624
+ return { type: "enteringQuery", expertKey: action.expertKey };
1625
+ case "SELECT_JOB":
1626
+ return { type: "browsingCheckpoints", job: action.job, checkpoints: action.checkpoints };
1627
+ case "GO_BACK_FROM_CHECKPOINTS":
1628
+ return { type: "browsingHistory", jobs: action.jobs };
1629
+ default:
1630
+ return assertNever(action);
1631
+ }
1632
+ };
1633
+ var SelectionApp = (props) => {
1634
+ const {
1635
+ showHistory,
1636
+ initialExpertKey,
1637
+ initialQuery,
1638
+ initialCheckpoint,
1639
+ configuredExperts,
1640
+ recentExperts,
1641
+ historyJobs,
1642
+ onLoadCheckpoints,
1643
+ onComplete
1644
+ } = props;
1645
+ const { exit } = useApp();
1646
+ const allExperts = useMemo(() => {
1647
+ const configured = configuredExperts.map((e) => ({ ...e, source: "configured" }));
1648
+ const recent = recentExperts.filter((e) => !configured.some((c) => c.key === e.key)).map((e) => ({ ...e, source: "recent" }));
1649
+ return [...configured, ...recent];
1650
+ }, [configuredExperts, recentExperts]);
1651
+ const getInitialState = () => {
1652
+ if (initialExpertKey && !initialQuery) {
1653
+ return { type: "enteringQuery", expertKey: initialExpertKey };
1654
+ }
1655
+ if (showHistory && historyJobs.length > 0) {
1656
+ return { type: "browsingHistory", jobs: historyJobs };
1657
+ }
1658
+ return { type: "browsingExperts", experts: allExperts };
1659
+ };
1660
+ const [state, dispatch] = useReducer(selectionReducer, void 0, getInitialState);
1661
+ const [selectedCheckpoint, setSelectedCheckpoint] = useState(
1662
+ initialCheckpoint
1663
+ );
1664
+ useEffect(() => {
1665
+ if (initialExpertKey && initialQuery) {
1666
+ onComplete({
1667
+ expertKey: initialExpertKey,
1668
+ query: initialQuery,
1669
+ checkpoint: initialCheckpoint
1670
+ });
1671
+ exit();
1672
+ }
1673
+ }, [initialExpertKey, initialQuery, initialCheckpoint, onComplete, exit]);
1674
+ const { input: queryInput, handleInput: handleQueryInput } = useTextInput({
1675
+ onSubmit: (query) => {
1676
+ if (state.type === "enteringQuery" && query.trim()) {
1677
+ onComplete({
1678
+ expertKey: state.expertKey,
1679
+ query: query.trim(),
1680
+ checkpoint: selectedCheckpoint
1681
+ });
1682
+ exit();
1683
+ }
1684
+ }
1685
+ });
1686
+ useInput(handleQueryInput, { isActive: state.type === "enteringQuery" });
1687
+ const handleExpertSelect = useCallback((expertKey) => {
1688
+ dispatch({ type: "SELECT_EXPERT", expertKey });
1689
+ }, []);
1690
+ const handleJobSelect = useCallback(
1691
+ async (job) => {
1692
+ try {
1693
+ const checkpoints = await onLoadCheckpoints(job);
1694
+ dispatch({ type: "SELECT_JOB", job, checkpoints });
1695
+ } catch {
1696
+ dispatch({ type: "SELECT_JOB", job, checkpoints: [] });
1697
+ }
1698
+ },
1699
+ [onLoadCheckpoints]
1700
+ );
1701
+ const handleJobResume = useCallback(
1702
+ async (job) => {
1703
+ try {
1704
+ const checkpoints = await onLoadCheckpoints(job);
1705
+ const latestCheckpoint = checkpoints[0];
1706
+ if (latestCheckpoint) {
1707
+ setSelectedCheckpoint(latestCheckpoint);
1708
+ }
1709
+ dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
1710
+ } catch {
1711
+ dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
1712
+ }
1713
+ },
1714
+ [onLoadCheckpoints]
1715
+ );
1716
+ const handleCheckpointResume = useCallback(
1717
+ (checkpoint) => {
1718
+ setSelectedCheckpoint(checkpoint);
1719
+ if (state.type === "browsingCheckpoints") {
1720
+ dispatch({ type: "SELECT_EXPERT", expertKey: state.job.expertKey });
1721
+ }
1722
+ },
1723
+ [state]
1724
+ );
1725
+ const handleBack = useCallback(() => {
1726
+ if (state.type === "browsingCheckpoints") {
1727
+ dispatch({ type: "GO_BACK_FROM_CHECKPOINTS", jobs: historyJobs });
1728
+ }
1729
+ }, [state, historyJobs]);
1730
+ const handleSwitchToExperts = useCallback(() => {
1731
+ dispatch({ type: "BROWSE_EXPERTS", experts: allExperts });
1732
+ }, [allExperts]);
1733
+ const handleSwitchToHistory = useCallback(() => {
1734
+ dispatch({ type: "BROWSE_HISTORY", jobs: historyJobs });
1735
+ }, [historyJobs]);
1736
+ useInput((input, key) => {
1737
+ if (key.ctrl && input === "c") {
1738
+ exit();
1739
+ }
1740
+ });
1741
+ const contextValue = useMemo(
1742
+ () => ({
1743
+ onExpertSelect: handleExpertSelect,
1744
+ onQuerySubmit: () => {
1745
+ },
1746
+ // Not used in browser
1747
+ onJobSelect: handleJobSelect,
1748
+ onJobResume: handleJobResume,
1749
+ onCheckpointSelect: () => {
1750
+ },
1751
+ // Not used in selection (no event browsing)
1752
+ onCheckpointResume: handleCheckpointResume,
1753
+ onEventSelect: () => {
1754
+ },
1755
+ // Not used in selection
1756
+ onBack: handleBack,
1757
+ onSwitchToExperts: handleSwitchToExperts,
1758
+ onSwitchToHistory: handleSwitchToHistory
1759
+ }),
1760
+ [
1761
+ handleExpertSelect,
1762
+ handleJobSelect,
1763
+ handleJobResume,
1764
+ handleCheckpointResume,
1765
+ handleBack,
1766
+ handleSwitchToExperts,
1767
+ handleSwitchToHistory
1768
+ ]
1769
+ );
1770
+ if (initialExpertKey && initialQuery) {
1771
+ return null;
1772
+ }
1773
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
1774
+ /* @__PURE__ */ jsx(InputAreaProvider, { value: contextValue, children: (state.type === "browsingHistory" || state.type === "browsingExperts" || state.type === "browsingCheckpoints") && /* @__PURE__ */ jsx(
1775
+ BrowserRouter,
1776
+ {
1777
+ inputState: state,
1778
+ showEventsHint: false
1779
+ }
1780
+ ) }),
1781
+ state.type === "enteringQuery" && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
1782
+ /* @__PURE__ */ jsxs(Text, { children: [
1783
+ /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, children: "Expert:" }),
1784
+ " ",
1785
+ /* @__PURE__ */ jsx(Text, { children: state.expertKey }),
1786
+ selectedCheckpoint && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
1787
+ " (resuming from step ",
1788
+ selectedCheckpoint.stepNumber,
1789
+ ")"
1790
+ ] })
1791
+ ] }),
1792
+ /* @__PURE__ */ jsxs(Box, { children: [
1793
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
1794
+ /* @__PURE__ */ jsx(Text, { children: queryInput }),
1795
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
1796
+ ] }),
1797
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press Enter to start" })
1798
+ ] })
1799
+ ] });
1800
+ };
1801
+ async function renderSelection(params) {
1802
+ return new Promise((resolve, reject) => {
1803
+ let resolved = false;
1804
+ const { waitUntilExit } = render(
1805
+ /* @__PURE__ */ jsx(
1806
+ SelectionApp,
1807
+ {
1808
+ ...params,
1809
+ onComplete: (result) => {
1810
+ resolved = true;
1811
+ resolve(result);
1812
+ }
1813
+ }
1814
+ )
1815
+ );
1816
+ waitUntilExit().then(() => {
1817
+ if (!resolved) {
1818
+ reject(new Error("Selection cancelled"));
1819
+ }
1820
+ }).catch(reject);
1821
+ });
1822
+ }
1823
+
1824
+ // src/start.ts
1825
+ var CONTINUE_TIMEOUT_MS = 6e4;
1826
+ async function startHandler(expertKey, query, options, handlerOptions) {
1827
+ const input = parseWithFriendlyError(startCommandInputSchema, { expertKey, query, options });
1828
+ try {
1829
+ const { perstackConfig, checkpoint, env, providerConfig, model, experts } = await resolveRunContext({
1830
+ configPath: input.options.config,
1831
+ provider: input.options.provider,
1832
+ model: input.options.model,
1833
+ envPath: input.options.envPath,
1834
+ continue: input.options.continue,
1835
+ continueJob: input.options.continueJob,
1836
+ resumeFrom: input.options.resumeFrom,
1837
+ expertKey: input.expertKey,
1838
+ perstackConfig: handlerOptions?.perstackConfig
1839
+ });
1840
+ if (handlerOptions?.additionalEnv) {
1841
+ Object.assign(env, handlerOptions.additionalEnv(env));
1842
+ }
1843
+ const maxSteps = input.options.maxSteps ?? perstackConfig.maxSteps;
1844
+ const maxRetries = input.options.maxRetries ?? perstackConfig.maxRetries ?? defaultMaxRetries;
1845
+ const timeout = input.options.timeout ?? perstackConfig.timeout ?? defaultTimeout;
1846
+ const configuredExperts = Object.keys(perstackConfig.experts ?? {}).map((key) => ({
1847
+ key,
1848
+ name: key
1849
+ }));
1850
+ const recentExperts = getRecentExperts(10);
1851
+ const showHistory = !input.expertKey && !input.query && !checkpoint;
1852
+ const historyJobs = showHistory ? getAllJobs().map((j) => ({
1853
+ jobId: j.id,
1854
+ status: j.status,
1855
+ expertKey: j.coordinatorExpertKey,
1856
+ totalSteps: j.totalSteps,
1857
+ startedAt: j.startedAt,
1858
+ finishedAt: j.finishedAt
1859
+ })) : [];
1860
+ const selection = await renderSelection({
1861
+ showHistory,
1862
+ initialExpertKey: input.expertKey,
1863
+ initialQuery: input.query,
1864
+ initialCheckpoint: checkpoint ? {
1865
+ id: checkpoint.id,
1866
+ jobId: checkpoint.jobId,
1867
+ runId: checkpoint.runId,
1868
+ stepNumber: checkpoint.stepNumber,
1869
+ contextWindowUsage: checkpoint.contextWindowUsage ?? 0
1870
+ } : void 0,
1871
+ configuredExperts,
1872
+ recentExperts,
1873
+ historyJobs,
1874
+ onLoadCheckpoints: async (j) => {
1875
+ const checkpoints = getCheckpointsWithDetails(j.jobId);
1876
+ return checkpoints.map((cp) => ({ ...cp, jobId: j.jobId }));
1877
+ }
1878
+ });
1879
+ if (!selection.expertKey) {
1880
+ console.error("Expert key is required");
1881
+ return;
1882
+ }
1883
+ if (!selection.query && !selection.checkpoint) {
1884
+ console.error("Query is required");
1885
+ return;
1886
+ }
1887
+ let currentCheckpoint = selection.checkpoint ? getCheckpointById(selection.checkpoint.jobId, selection.checkpoint.id) : checkpoint;
1888
+ if (currentCheckpoint && currentCheckpoint.expert.key !== selection.expertKey) {
1889
+ console.error(
1890
+ `Checkpoint expert key ${currentCheckpoint.expert.key} does not match input expert key ${selection.expertKey}`
1891
+ );
1892
+ return;
1893
+ }
1894
+ const lockfilePath = findLockfile();
1895
+ const lockfile = lockfilePath ? loadLockfile(lockfilePath) ?? void 0 : void 0;
1896
+ let currentQuery = selection.query;
1897
+ let currentJobId = currentCheckpoint?.jobId ?? input.options.jobId ?? createId();
1898
+ let isNextQueryInteractiveToolResult = input.options.interactiveToolCallResult ?? false;
1899
+ let isFirstIteration = true;
1900
+ const initialHistoricalEvents = currentCheckpoint ? getAllEventContentsForJob(currentCheckpoint.jobId, currentCheckpoint.stepNumber) : void 0;
1901
+ while (currentQuery !== null) {
1902
+ const historicalEvents = isFirstIteration ? initialHistoricalEvents : void 0;
1903
+ const runId = createId();
1904
+ const { result: executionResult, eventListener } = renderExecution({
1905
+ expertKey: selection.expertKey,
1906
+ query: currentQuery,
1907
+ config: {
1908
+ runtimeVersion,
1909
+ model,
1910
+ maxSteps,
1911
+ maxRetries,
1912
+ timeout,
1913
+ contextWindowUsage: currentCheckpoint?.contextWindowUsage ?? 0
1914
+ },
1915
+ continueTimeoutMs: CONTINUE_TIMEOUT_MS,
1916
+ historicalEvents
1917
+ });
1918
+ const runResult = await run(
1919
+ {
1920
+ setting: {
1921
+ jobId: currentJobId,
1922
+ runId,
1923
+ expertKey: selection.expertKey,
1924
+ input: isNextQueryInteractiveToolResult && currentCheckpoint ? parseInteractiveToolCallResult(currentQuery, currentCheckpoint) : { text: currentQuery },
1925
+ experts,
1926
+ model,
1927
+ providerConfig,
1928
+ reasoningBudget: input.options.reasoningBudget ?? perstackConfig.reasoningBudget,
1929
+ maxSteps: input.options.maxSteps ?? perstackConfig.maxSteps,
1930
+ maxRetries: input.options.maxRetries ?? perstackConfig.maxRetries,
1931
+ timeout: input.options.timeout ?? perstackConfig.timeout,
1932
+ perstackApiBaseUrl: perstackConfig.perstackApiBaseUrl,
1933
+ perstackApiKey: env.PERSTACK_API_KEY,
1934
+ perstackBaseSkillCommand: perstackConfig.perstackBaseSkillCommand,
1935
+ env,
1936
+ verbose: input.options.verbose
1937
+ },
1938
+ checkpoint: currentCheckpoint
1939
+ },
1940
+ {
1941
+ eventListener,
1942
+ storeCheckpoint: defaultStoreCheckpoint,
1943
+ storeEvent: defaultStoreEvent,
1944
+ retrieveCheckpoint: defaultRetrieveCheckpoint,
1945
+ storeJob,
1946
+ retrieveJob,
1947
+ createJob: createInitialJob,
1948
+ lockfile
1949
+ }
1950
+ );
1951
+ const result = await executionResult;
1952
+ const canContinue = runResult.status === "completed" || runResult.status === "stoppedByExceededMaxSteps" || runResult.status === "stoppedByError" || runResult.status === "stoppedByInteractiveTool";
1953
+ if (result.nextQuery && canContinue) {
1954
+ currentQuery = result.nextQuery;
1955
+ currentCheckpoint = runResult;
1956
+ currentJobId = runResult.jobId;
1957
+ isNextQueryInteractiveToolResult = runResult.status === "stoppedByInteractiveTool";
1958
+ isFirstIteration = false;
1959
+ } else {
1960
+ currentQuery = null;
1961
+ }
1962
+ }
1963
+ } catch (error) {
1964
+ if (error instanceof Error) {
1965
+ console.error(error.message);
1966
+ } else {
1967
+ console.error(error);
1968
+ }
1969
+ }
1970
+ }
1971
+ var startCommand = new Command().command("start").description("Start Perstack with interactive TUI").argument("[expertKey]", "Expert key to run (optional, will prompt if not provided)").argument("[query]", "Query to run (optional, will prompt if not provided)").option("--config <configPath>", "Path to perstack.toml config file").option("--provider <provider>", "Provider to use").option("--model <model>", "Model to use").option(
1972
+ "--reasoning-budget <budget>",
1973
+ "Reasoning budget for native LLM reasoning (minimal, low, medium, high, or token count)"
1974
+ ).option(
1975
+ "--max-steps <maxSteps>",
1976
+ "Maximum number of steps to run, default is undefined (no limit)"
1977
+ ).option("--max-retries <maxRetries>", "Maximum number of generation retries, default is 5").option(
1978
+ "--timeout <timeout>",
1979
+ "Timeout for each generation in milliseconds, default is 300000 (5 minutes)"
1980
+ ).option("--job-id <jobId>", "Job ID for identifying the job").option(
1981
+ "--env-path <path>",
1982
+ "Path to the environment file (can be specified multiple times), default is .env and .env.local",
1983
+ (value, previous) => previous.concat(value),
1984
+ []
1985
+ ).option("--verbose", "Enable verbose logging").option("--continue", "Continue the most recent job with new query").option("--continue-job <jobId>", "Continue the specified job with new query").option(
1986
+ "--resume-from <checkpointId>",
1987
+ "Resume from a specific checkpoint (requires --continue or --continue-job)"
1988
+ ).option("-i, --interactive-tool-call-result", "Query is interactive tool call result").action((expertKey, query, options) => startHandler(expertKey, query, options));
1989
+
1990
+ export { getEnv, getPerstackConfig, parseInteractiveToolCallResult, parseInteractiveToolCallResultJson, resolveRunContext, startCommand, startHandler };
1991
+ //# sourceMappingURL=chunk-7D4GKG4H.js.map
1992
+ //# sourceMappingURL=chunk-7D4GKG4H.js.map