create-expert 0.0.20 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js CHANGED
@@ -4,11 +4,11 @@ import { parseWithFriendlyError, perstackConfigSchema, startCommandInputSchema,
4
4
  import { readFile, mkdir, writeFile } from 'fs/promises';
5
5
  import path5 from 'path';
6
6
  import { findLockfile, loadLockfile, runtimeVersion, run } from '@perstack/runtime';
7
+ import dotenv from 'dotenv';
8
+ import TOML from 'smol-toml';
7
9
  import { render, useApp, useInput, Box, Text } from 'ink';
8
10
  import { createContext, useMemo, useReducer, useState, useEffect, useCallback, useRef, useInsertionEffect, useContext } from 'react';
9
11
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
10
- import dotenv from 'dotenv';
11
- import TOML from 'smol-toml';
12
12
  import { Command } from 'commander';
13
13
 
14
14
  // ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_u64.js
@@ -1635,7 +1635,7 @@ function toFixedPoint(str, e, z) {
1635
1635
  var BigNumber = clone();
1636
1636
  var bignumber_default = BigNumber;
1637
1637
 
1638
- // ../../node_modules/.pnpm/@paralleldrive+cuid2@3.0.6/node_modules/@paralleldrive/cuid2/src/index.js
1638
+ // ../../node_modules/.pnpm/@paralleldrive+cuid2@3.3.0/node_modules/@paralleldrive/cuid2/src/index.js
1639
1639
  var defaultLength = 24;
1640
1640
  var bigLength = 32;
1641
1641
  var createRandom = () => {
@@ -1887,2308 +1887,2318 @@ function getRunIdsByJobId(jobId) {
1887
1887
  }
1888
1888
  return readdirSync(runsDir, { withFileTypes: true }).filter((dir) => dir.isDirectory()).map((dir) => dir.name);
1889
1889
  }
1890
-
1891
- // ../../packages/tui-components/src/utils/event-queue.ts
1892
- var defaultErrorLogger = (message, error) => {
1893
- console.error(message, error);
1894
- };
1895
- var EventQueue = class _EventQueue {
1896
- static MAX_PENDING_EVENTS = 1e3;
1897
- pendingEvents = [];
1898
- handler = null;
1899
- onError;
1900
- errorLogger;
1901
- constructor(options) {
1902
- this.onError = options?.onError;
1903
- this.errorLogger = options?.errorLogger ?? defaultErrorLogger;
1890
+ function getEnv(envPath) {
1891
+ const env = Object.fromEntries(
1892
+ Object.entries(process.env).filter(([_, value]) => !!value).map(([key, value]) => [key, value])
1893
+ );
1894
+ dotenv.config({ path: envPath, processEnv: env, quiet: true });
1895
+ return env;
1896
+ }
1897
+ var ALLOWED_CONFIG_HOSTS = ["raw.githubusercontent.com"];
1898
+ async function getPerstackConfig(configPath) {
1899
+ const configString = await findPerstackConfigString(configPath);
1900
+ if (configString === null) {
1901
+ throw new Error("perstack.toml not found. Create one or specify --config path.");
1904
1902
  }
1905
- setHandler(fn) {
1906
- this.handler = fn;
1907
- for (const event of this.pendingEvents) {
1908
- this.safeHandle(event);
1909
- }
1910
- this.pendingEvents.length = 0;
1903
+ return await parsePerstackConfig(configString);
1904
+ }
1905
+ function isRemoteUrl(configPath) {
1906
+ const lower = configPath.toLowerCase();
1907
+ return lower.startsWith("https://") || lower.startsWith("http://");
1908
+ }
1909
+ async function fetchRemoteConfig(url) {
1910
+ let parsed;
1911
+ try {
1912
+ parsed = new URL(url);
1913
+ } catch {
1914
+ throw new Error(`Invalid remote config URL: ${url}`);
1911
1915
  }
1912
- emit(event) {
1913
- if (this.handler) {
1914
- this.safeHandle(event);
1915
- } else {
1916
- if (this.pendingEvents.length >= _EventQueue.MAX_PENDING_EVENTS) {
1917
- this.pendingEvents.shift();
1918
- }
1919
- this.pendingEvents.push(event);
1916
+ if (parsed.protocol !== "https:") {
1917
+ throw new Error("Remote config requires HTTPS");
1918
+ }
1919
+ if (!ALLOWED_CONFIG_HOSTS.includes(parsed.hostname)) {
1920
+ throw new Error(`Remote config only allowed from: ${ALLOWED_CONFIG_HOSTS.join(", ")}`);
1921
+ }
1922
+ try {
1923
+ const response = await fetch(url, { redirect: "error" });
1924
+ if (!response.ok) {
1925
+ throw new Error(`${response.status} ${response.statusText}`);
1920
1926
  }
1927
+ return await response.text();
1928
+ } catch (error) {
1929
+ const message = error instanceof Error ? error.message : String(error);
1930
+ throw new Error(`Failed to fetch remote config: ${message}`);
1921
1931
  }
1922
- safeHandle(event) {
1932
+ }
1933
+ async function findPerstackConfigString(configPath) {
1934
+ if (configPath) {
1935
+ if (isRemoteUrl(configPath)) {
1936
+ return await fetchRemoteConfig(configPath);
1937
+ }
1923
1938
  try {
1924
- this.handler?.(event);
1925
- } catch (error) {
1926
- if (this.onError) {
1927
- this.onError(error);
1928
- } else {
1929
- this.errorLogger("EventQueue handler error:", error);
1930
- }
1939
+ const tomlString = await readFile(path5.resolve(process.cwd(), configPath), "utf-8");
1940
+ return tomlString;
1941
+ } catch {
1942
+ throw new Error(`Given config path "${configPath}" is not found`);
1931
1943
  }
1932
1944
  }
1933
- };
1934
- var InputAreaContext = createContext(null);
1935
- var InputAreaProvider = InputAreaContext.Provider;
1936
- var useInputAreaContext = () => {
1937
- const context = useContext(InputAreaContext);
1938
- if (!context) {
1939
- throw new Error("useInputAreaContext must be used within InputAreaProvider");
1945
+ return await findPerstackConfigStringRecursively(path5.resolve(process.cwd()));
1946
+ }
1947
+ async function findPerstackConfigStringRecursively(cwd) {
1948
+ try {
1949
+ const tomlString = await readFile(path5.resolve(cwd, "perstack.toml"), "utf-8");
1950
+ return tomlString;
1951
+ } catch {
1952
+ if (cwd === path5.parse(cwd).root) {
1953
+ return null;
1954
+ }
1955
+ return await findPerstackConfigStringRecursively(path5.dirname(cwd));
1940
1956
  }
1941
- return context;
1942
- };
1943
-
1944
- // ../../packages/tui-components/src/helpers.ts
1945
- var truncateText = (text, maxLength) => {
1946
- if (text.length <= maxLength) return text;
1947
- return `${text.slice(0, maxLength)}...`;
1948
- };
1949
- var assertNever = (x) => {
1950
- throw new Error(`Unexpected value: ${x}`);
1951
- };
1952
- var formatTimestamp = (timestamp) => new Date(timestamp).toLocaleString();
1953
- var shortenPath = (fullPath, maxLength = 60) => {
1954
- if (fullPath.length <= maxLength) return fullPath;
1955
- const parts = fullPath.split("/");
1956
- if (parts.length <= 2) return fullPath;
1957
- const filename = parts[parts.length - 1] ?? "";
1958
- const parentDir = parts[parts.length - 2] ?? "";
1959
- const shortened = `.../${parentDir}/${filename}`;
1960
- if (shortened.length <= maxLength) return shortened;
1961
- return `.../${filename}`;
1962
- };
1963
- var summarizeOutput = (lines, maxLines) => {
1964
- const filtered = lines.filter((l) => l.trim());
1965
- const visible = filtered.slice(0, maxLines);
1966
- const remaining = filtered.length - visible.length;
1967
- return { visible, remaining };
1968
- };
1957
+ }
1958
+ async function parsePerstackConfig(config2) {
1959
+ const toml = TOML.parse(config2 ?? "");
1960
+ return parseWithFriendlyError(perstackConfigSchema, toml, "perstack.toml");
1961
+ }
1969
1962
 
1970
- // ../../packages/tui-components/src/constants.ts
1971
- var UI_CONSTANTS = {
1972
- MAX_VISIBLE_LIST_ITEMS: 25,
1973
- TRUNCATE_TEXT_MEDIUM: 80,
1974
- TRUNCATE_TEXT_DEFAULT: 100};
1975
- var RENDER_CONSTANTS = {
1976
- EXEC_OUTPUT_MAX_LINES: 4,
1977
- NEW_TODO_MAX_PREVIEW: 3,
1978
- LIST_DIR_MAX_ITEMS: 4
1979
- };
1980
- var INDICATOR = {
1981
- BULLET: "\u25CF",
1982
- TREE: "\u2514",
1983
- ELLIPSIS: "..."
1963
+ // ../../packages/tui/src/lib/provider-config.ts
1964
+ var PROVIDER_ENV_MAP = {
1965
+ anthropic: "ANTHROPIC_API_KEY",
1966
+ google: "GOOGLE_GENERATIVE_AI_API_KEY",
1967
+ openai: "OPENAI_API_KEY",
1968
+ deepseek: "DEEPSEEK_API_KEY",
1969
+ "azure-openai": "AZURE_API_KEY",
1970
+ "amazon-bedrock": "AWS_ACCESS_KEY_ID",
1971
+ "google-vertex": "GOOGLE_APPLICATION_CREDENTIALS",
1972
+ ollama: void 0
1984
1973
  };
1985
- var STOP_EVENT_TYPES = [
1986
- "stopRunByInteractiveTool",
1987
- "stopRunByDelegate",
1988
- "stopRunByExceededMaxSteps"
1989
- ];
1990
- var KEY_BINDINGS = {
1991
- NAVIGATE_UP: "\u2191",
1992
- NAVIGATE_DOWN: "\u2193",
1993
- SELECT: "Enter",
1994
- BACK: "b",
1995
- ESCAPE: "Esc",
1996
- INPUT_MODE: "i",
1997
- HISTORY: "h",
1998
- NEW: "n",
1999
- CHECKPOINTS: "c",
2000
- EVENTS: "e",
2001
- RESUME: "Enter"};
2002
- var KEY_HINTS = {
2003
- NAVIGATE: `${KEY_BINDINGS.NAVIGATE_UP}${KEY_BINDINGS.NAVIGATE_DOWN}:Navigate`,
2004
- SELECT: `${KEY_BINDINGS.SELECT}:Select`,
2005
- RESUME: `${KEY_BINDINGS.RESUME}:Resume`,
2006
- BACK: `${KEY_BINDINGS.BACK}:Back`,
2007
- CANCEL: `${KEY_BINDINGS.ESCAPE}:Cancel`,
2008
- INPUT: `${KEY_BINDINGS.INPUT_MODE}:Input`,
2009
- HISTORY: `${KEY_BINDINGS.HISTORY}:History`,
2010
- NEW: `${KEY_BINDINGS.NEW}:New Run`,
2011
- CHECKPOINTS: `${KEY_BINDINGS.CHECKPOINTS}:Checkpoints`,
2012
- EVENTS: `${KEY_BINDINGS.EVENTS}:Events`};
2013
- var useListNavigation = (options) => {
2014
- const { items, onSelect, onBack } = options;
2015
- const [selectedIndex, setSelectedIndex] = useState(0);
2016
- useEffect(() => {
2017
- if (selectedIndex >= items.length && items.length > 0) {
2018
- setSelectedIndex(items.length - 1);
1974
+ function getProviderConfig(provider, env, providerTable) {
1975
+ const setting = providerTable?.setting ?? {};
1976
+ switch (provider) {
1977
+ case "anthropic": {
1978
+ const apiKey = env.ANTHROPIC_API_KEY;
1979
+ if (!apiKey) throw new Error("ANTHROPIC_API_KEY is not set");
1980
+ return {
1981
+ providerName: "anthropic",
1982
+ apiKey,
1983
+ baseUrl: setting.baseUrl ?? env.ANTHROPIC_BASE_URL,
1984
+ headers: setting.headers
1985
+ };
2019
1986
  }
2020
- }, [items.length, selectedIndex]);
2021
- const handleNavigation = useCallback(
2022
- (inputChar, key) => {
2023
- if (key.upArrow && items.length > 0) {
2024
- setSelectedIndex((prev) => Math.max(0, prev - 1));
2025
- return true;
2026
- }
2027
- if (key.downArrow && items.length > 0) {
2028
- setSelectedIndex((prev) => Math.min(items.length - 1, prev + 1));
2029
- return true;
2030
- }
2031
- if (key.return && items[selectedIndex]) {
2032
- onSelect?.(items[selectedIndex]);
2033
- return true;
2034
- }
2035
- if ((key.escape || inputChar === "b") && onBack) {
2036
- onBack();
2037
- return true;
2038
- }
2039
- return false;
2040
- },
2041
- [items, selectedIndex, onSelect, onBack]
2042
- );
2043
- return { selectedIndex, handleNavigation };
2044
- };
2045
- var ListBrowser = ({
2046
- title,
2047
- items,
2048
- renderItem,
2049
- onSelect,
2050
- emptyMessage = "No items found",
2051
- extraKeyHandler,
2052
- onBack,
2053
- maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS
2054
- }) => {
2055
- const { selectedIndex, handleNavigation } = useListNavigation({
2056
- items,
2057
- onSelect,
2058
- onBack
2059
- });
2060
- useInput((inputChar, key) => {
2061
- if (extraKeyHandler?.(inputChar, key, items[selectedIndex])) return;
2062
- handleNavigation(inputChar, key);
2063
- });
2064
- const { scrollOffset, displayItems } = useMemo(() => {
2065
- const offset = Math.max(0, Math.min(selectedIndex - maxItems + 1, items.length - maxItems));
2066
- return {
2067
- scrollOffset: offset,
2068
- displayItems: items.slice(offset, offset + maxItems)
2069
- };
2070
- }, [items, selectedIndex, maxItems]);
2071
- const hasMoreAbove = scrollOffset > 0;
2072
- const hasMoreBelow = scrollOffset + maxItems < items.length;
2073
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2074
- /* @__PURE__ */ jsxs(Box, { children: [
2075
- /* @__PURE__ */ jsx(Text, { color: "cyan", children: title }),
2076
- items.length > maxItems && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
2077
- " ",
2078
- "(",
2079
- selectedIndex + 1,
2080
- "/",
2081
- items.length,
2082
- ")"
2083
- ] })
2084
- ] }),
2085
- hasMoreAbove && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS }),
2086
- /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: displayItems.length === 0 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: emptyMessage }) : displayItems.map((item, index) => {
2087
- const actualIndex = scrollOffset + index;
2088
- return renderItem(item, actualIndex === selectedIndex, actualIndex);
2089
- }) }),
2090
- hasMoreBelow && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS })
2091
- ] });
2092
- };
2093
- var BrowsingCheckpointsInput = ({
2094
- job,
2095
- checkpoints,
2096
- onCheckpointSelect,
2097
- onCheckpointResume,
2098
- onBack,
2099
- showEventsHint = true
2100
- }) => /* @__PURE__ */ jsx(
2101
- ListBrowser,
2102
- {
2103
- title: `Checkpoints for ${job.expertKey} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${showEventsHint ? KEY_HINTS.EVENTS : ""} ${KEY_HINTS.BACK}`.trim(),
2104
- items: checkpoints,
2105
- onSelect: onCheckpointResume,
2106
- onBack,
2107
- emptyMessage: "No checkpoints found",
2108
- extraKeyHandler: (char, _key, selected) => {
2109
- if (char === "e" && selected) {
2110
- onCheckpointSelect(selected);
2111
- return true;
2112
- }
2113
- return false;
2114
- },
2115
- renderItem: (cp, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2116
- isSelected ? ">" : " ",
2117
- " Step ",
2118
- cp.stepNumber,
2119
- " (",
2120
- cp.id,
2121
- ")"
2122
- ] }, cp.id)
2123
- }
2124
- );
2125
- var BrowsingEventDetailInput = ({ event, onBack }) => {
2126
- useInput((input, key) => {
2127
- if (input === "b" || key.escape) {
2128
- onBack();
1987
+ case "google": {
1988
+ const apiKey = env.GOOGLE_GENERATIVE_AI_API_KEY;
1989
+ if (!apiKey) throw new Error("GOOGLE_GENERATIVE_AI_API_KEY is not set");
1990
+ return {
1991
+ providerName: "google",
1992
+ apiKey,
1993
+ baseUrl: setting.baseUrl ?? env.GOOGLE_GENERATIVE_AI_BASE_URL,
1994
+ headers: setting.headers
1995
+ };
1996
+ }
1997
+ case "openai": {
1998
+ const apiKey = env.OPENAI_API_KEY;
1999
+ if (!apiKey) throw new Error("OPENAI_API_KEY is not set");
2000
+ return {
2001
+ providerName: "openai",
2002
+ apiKey,
2003
+ baseUrl: setting.baseUrl ?? env.OPENAI_BASE_URL,
2004
+ organization: setting.organization ?? env.OPENAI_ORGANIZATION,
2005
+ project: setting.project ?? env.OPENAI_PROJECT,
2006
+ name: setting.name,
2007
+ headers: setting.headers
2008
+ };
2009
+ }
2010
+ case "ollama": {
2011
+ return {
2012
+ providerName: "ollama",
2013
+ baseUrl: setting.baseUrl ?? env.OLLAMA_BASE_URL,
2014
+ headers: setting.headers
2015
+ };
2016
+ }
2017
+ case "azure-openai": {
2018
+ const apiKey = env.AZURE_API_KEY;
2019
+ if (!apiKey) throw new Error("AZURE_API_KEY is not set");
2020
+ const resourceName = setting.resourceName ?? env.AZURE_RESOURCE_NAME;
2021
+ const baseUrl = setting.baseUrl ?? env.AZURE_BASE_URL;
2022
+ if (!resourceName && !baseUrl) throw new Error("AZURE_RESOURCE_NAME or baseUrl is not set");
2023
+ return {
2024
+ providerName: "azure-openai",
2025
+ apiKey,
2026
+ resourceName,
2027
+ apiVersion: setting.apiVersion ?? env.AZURE_API_VERSION,
2028
+ baseUrl,
2029
+ headers: setting.headers,
2030
+ useDeploymentBasedUrls: setting.useDeploymentBasedUrls
2031
+ };
2032
+ }
2033
+ case "amazon-bedrock": {
2034
+ const accessKeyId = env.AWS_ACCESS_KEY_ID;
2035
+ const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
2036
+ const sessionToken = env.AWS_SESSION_TOKEN;
2037
+ if (!accessKeyId) throw new Error("AWS_ACCESS_KEY_ID is not set");
2038
+ if (!secretAccessKey) throw new Error("AWS_SECRET_ACCESS_KEY is not set");
2039
+ const region = setting.region ?? env.AWS_REGION;
2040
+ if (!region) throw new Error("AWS_REGION is not set");
2041
+ return {
2042
+ providerName: "amazon-bedrock",
2043
+ accessKeyId,
2044
+ secretAccessKey,
2045
+ region,
2046
+ sessionToken
2047
+ };
2048
+ }
2049
+ case "google-vertex": {
2050
+ return {
2051
+ providerName: "google-vertex",
2052
+ project: setting.project ?? env.GOOGLE_VERTEX_PROJECT,
2053
+ location: setting.location ?? env.GOOGLE_VERTEX_LOCATION,
2054
+ baseUrl: setting.baseUrl ?? env.GOOGLE_VERTEX_BASE_URL,
2055
+ headers: setting.headers
2056
+ };
2057
+ }
2058
+ case "deepseek": {
2059
+ const apiKey = env.DEEPSEEK_API_KEY;
2060
+ if (!apiKey) throw new Error("DEEPSEEK_API_KEY is not set");
2061
+ return {
2062
+ providerName: "deepseek",
2063
+ apiKey,
2064
+ baseUrl: setting.baseUrl ?? env.DEEPSEEK_BASE_URL,
2065
+ headers: setting.headers
2066
+ };
2129
2067
  }
2130
- });
2131
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
2132
- /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
2133
- /* @__PURE__ */ jsx(Text, { bold: true, children: "Event Detail" }),
2134
- /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
2135
- " ",
2136
- KEY_HINTS.BACK
2137
- ] })
2138
- ] }),
2139
- /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 2, children: [
2140
- /* @__PURE__ */ jsxs(Text, { children: [
2141
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type: " }),
2142
- /* @__PURE__ */ jsx(Text, { color: "cyan", children: event.type })
2143
- ] }),
2144
- /* @__PURE__ */ jsxs(Text, { children: [
2145
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Step: " }),
2146
- /* @__PURE__ */ jsx(Text, { children: event.stepNumber })
2147
- ] }),
2148
- /* @__PURE__ */ jsxs(Text, { children: [
2149
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Timestamp: " }),
2150
- /* @__PURE__ */ jsx(Text, { children: formatTimestamp(event.timestamp) })
2151
- ] }),
2152
- /* @__PURE__ */ jsxs(Text, { children: [
2153
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "ID: " }),
2154
- /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.id })
2155
- ] }),
2156
- /* @__PURE__ */ jsxs(Text, { children: [
2157
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Run ID: " }),
2158
- /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.runId })
2159
- ] })
2160
- ] })
2161
- ] });
2162
- };
2163
- var BrowsingEventsInput = ({
2164
- checkpoint,
2165
- events,
2166
- onEventSelect,
2167
- onBack
2168
- }) => /* @__PURE__ */ jsx(
2169
- ListBrowser,
2170
- {
2171
- title: `Events for Step ${checkpoint.stepNumber} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.BACK}`,
2172
- items: events,
2173
- onSelect: onEventSelect,
2174
- onBack,
2175
- emptyMessage: "No events found",
2176
- renderItem: (ev, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2177
- isSelected ? ">" : " ",
2178
- " [",
2179
- ev.type,
2180
- "] Step ",
2181
- ev.stepNumber,
2182
- " (",
2183
- formatTimestamp(ev.timestamp),
2184
- ")"
2185
- ] }, ev.id)
2186
2068
  }
2187
- );
2188
- var TOOL_RESULT_EVENT_TYPES = /* @__PURE__ */ new Set(["resolveToolResults", "attemptCompletion"]);
2189
- function toolToActivity(toolCall, toolResult, reasoning, meta) {
2190
- const { skillName, toolName } = toolCall;
2191
- const baseActivity = skillName.startsWith(BASE_SKILL_PREFIX) ? createBaseToolActivity(toolName, toolCall, toolResult, reasoning) : createGeneralToolActivity(skillName, toolName, toolCall, toolResult, reasoning);
2192
- return {
2193
- ...baseActivity,
2194
- id: meta.id,
2195
- expertKey: meta.expertKey,
2196
- runId: meta.runId,
2197
- previousActivityId: meta.previousActivityId,
2198
- delegatedBy: meta.delegatedBy
2199
- };
2200
2069
  }
2201
- function createInitialActivityProcessState() {
2202
- return {
2203
- tools: /* @__PURE__ */ new Map(),
2204
- runStates: /* @__PURE__ */ new Map()
2205
- };
2070
+ function getAllJobs2() {
2071
+ return getAllJobs();
2206
2072
  }
2207
- function getOrCreateRunState(state, runId, expertKey) {
2208
- let runState = state.runStates.get(runId);
2209
- if (!runState) {
2210
- runState = {
2211
- expertKey,
2212
- queryLogged: false,
2213
- completionLogged: false,
2214
- isComplete: false,
2215
- pendingDelegateCount: 0
2216
- };
2217
- state.runStates.set(runId, runState);
2073
+ function getAllRuns2() {
2074
+ return getAllRuns();
2075
+ }
2076
+ function getMostRecentRun() {
2077
+ const runs = getAllRuns2();
2078
+ if (runs.length === 0) {
2079
+ throw new Error("No runs found");
2218
2080
  }
2219
- return runState;
2081
+ return runs[0];
2220
2082
  }
2221
- var isRunEvent = (event) => "type" in event && "expertKey" in event;
2222
- var isCompleteStreamingReasoningEvent = (event) => "type" in event && event.type === "completeStreamingReasoning";
2223
- var isToolCallsEvent = (event) => event.type === "callTools" && "toolCalls" in event;
2224
- var isStopRunByDelegateEvent = (event) => event.type === "stopRunByDelegate" && "checkpoint" in event;
2225
- var isStopRunByInteractiveToolEvent = (event) => event.type === "stopRunByInteractiveTool" && "checkpoint" in event;
2226
- var isToolResultsEvent = (event) => event.type === "resolveToolResults" && "toolResults" in event;
2227
- var isToolResultEvent = (event) => TOOL_RESULT_EVENT_TYPES.has(event.type) && "toolResult" in event;
2228
- function wrapInGroupIfParallel(activities, reasoning, meta) {
2229
- if (activities.length <= 1) {
2230
- return activities;
2083
+ function getCheckpointsByJobId2(jobId) {
2084
+ return getCheckpointsByJobId(jobId);
2085
+ }
2086
+ function getMostRecentCheckpoint(jobId) {
2087
+ const targetJobId = jobId ?? getMostRecentRun().jobId;
2088
+ const checkpoints = getCheckpointsByJobId2(targetJobId);
2089
+ if (checkpoints.length === 0) {
2090
+ throw new Error(`No checkpoints found for job ${targetJobId}`);
2231
2091
  }
2232
- const activitiesWithoutReasoning = activities.map((a) => {
2233
- const { reasoning: _, ...rest } = a;
2234
- return rest;
2235
- });
2236
- const group = {
2237
- type: "parallelGroup",
2238
- id: `parallel-${activities[0].id}`,
2239
- expertKey: meta.expertKey,
2240
- runId: meta.runId,
2241
- reasoning,
2242
- activities: activitiesWithoutReasoning
2243
- };
2244
- return [group];
2092
+ return checkpoints[checkpoints.length - 1];
2245
2093
  }
2246
- function processRunEventToActivity(state, event, addActivity) {
2247
- if (isCompleteStreamingReasoningEvent(event)) {
2248
- const reasoningEvent = event;
2249
- const { runId, text, expertKey } = reasoningEvent;
2250
- const runState2 = state.runStates.get(runId);
2251
- if (runState2) {
2252
- runState2.completedReasoning = text;
2253
- } else {
2254
- state.runStates.set(runId, {
2255
- expertKey,
2256
- queryLogged: false,
2257
- completionLogged: false,
2258
- isComplete: false,
2259
- pendingDelegateCount: 0,
2260
- completedReasoning: text
2094
+ function getRecentExperts(limit) {
2095
+ const runs = getAllRuns2();
2096
+ const expertMap = /* @__PURE__ */ new Map();
2097
+ for (const setting of runs) {
2098
+ const expertKey = setting.expertKey;
2099
+ if (!expertMap.has(expertKey) || expertMap.get(expertKey).lastUsed < setting.updatedAt) {
2100
+ expertMap.set(expertKey, {
2101
+ key: expertKey,
2102
+ name: expertKey,
2103
+ lastUsed: setting.updatedAt
2261
2104
  });
2262
2105
  }
2263
- return;
2264
2106
  }
2265
- if (!isRunEvent(event)) {
2266
- return;
2107
+ return Array.from(expertMap.values()).sort((a, b) => b.lastUsed - a.lastUsed).slice(0, limit);
2108
+ }
2109
+ function getCheckpointById(jobId, checkpointId) {
2110
+ const checkpointPath = getCheckpointPath(jobId, checkpointId);
2111
+ if (!existsSync(checkpointPath)) {
2112
+ throw new Error(`Checkpoint ${checkpointId} not found in job ${jobId}`);
2267
2113
  }
2268
- const runState = getOrCreateRunState(state, event.runId, event.expertKey);
2269
- if (event.type === "startRun") {
2270
- const startRunEvent = event;
2271
- const userMessage = startRunEvent.inputMessages.find((m) => m.type === "userMessage");
2272
- const queryText = userMessage?.contents?.find((c) => c.type === "textPart")?.text;
2273
- if (!runState.delegatedBy) {
2274
- const delegatedByInfo = startRunEvent.initialCheckpoint?.delegatedBy;
2275
- if (delegatedByInfo) {
2276
- runState.delegatedBy = {
2277
- expertKey: delegatedByInfo.expert.key,
2278
- runId: delegatedByInfo.runId
2279
- };
2280
- }
2281
- }
2282
- const isDelegationReturn = startRunEvent.initialCheckpoint?.status === "stoppedByDelegate" || startRunEvent.initialCheckpoint?.status === "stoppedByInteractiveTool";
2283
- if (queryText && !runState.queryLogged && !isDelegationReturn) {
2284
- const activityId = `query-${event.runId}`;
2285
- addActivity({
2286
- type: "query",
2287
- id: activityId,
2288
- expertKey: event.expertKey,
2289
- runId: event.runId,
2290
- previousActivityId: runState.lastActivityId,
2291
- delegatedBy: runState.delegatedBy,
2292
- text: queryText
2293
- });
2294
- runState.lastActivityId = activityId;
2295
- runState.queryLogged = true;
2296
- }
2297
- return;
2114
+ const checkpoint = readFileSync(checkpointPath, "utf-8");
2115
+ return checkpointSchema.parse(JSON.parse(checkpoint));
2116
+ }
2117
+ function getCheckpointsWithDetails(jobId) {
2118
+ return getCheckpointsByJobId2(jobId).map((cp) => ({
2119
+ id: cp.id,
2120
+ runId: cp.runId,
2121
+ stepNumber: cp.stepNumber,
2122
+ contextWindowUsage: cp.contextWindowUsage ?? 0
2123
+ })).sort((a, b) => b.stepNumber - a.stepNumber);
2124
+ }
2125
+ function getAllEventContentsForJob(jobId, maxStepNumber) {
2126
+ const runIds = getRunIdsByJobId(jobId);
2127
+ const allEvents = [];
2128
+ for (const runId of runIds) {
2129
+ const events = getEventContents(jobId, runId, maxStepNumber);
2130
+ allEvents.push(...events);
2298
2131
  }
2299
- if (event.type === "resumeFromStop") {
2300
- if (!runState.delegatedBy) {
2301
- const resumeEvent = event;
2302
- const delegatedByInfo = resumeEvent.checkpoint?.delegatedBy;
2303
- if (delegatedByInfo) {
2304
- runState.delegatedBy = {
2305
- expertKey: delegatedByInfo.expert.key,
2306
- runId: delegatedByInfo.runId
2307
- };
2308
- }
2132
+ return allEvents.sort((a, b) => a.timestamp - b.timestamp);
2133
+ }
2134
+
2135
+ // ../../packages/tui/src/lib/context.ts
2136
+ var defaultProvider = "anthropic";
2137
+ var defaultModel = "claude-sonnet-4-5";
2138
+ async function resolveRunContext(input) {
2139
+ const perstackConfig = input.perstackConfig ?? await getPerstackConfig(input.configPath);
2140
+ let checkpoint;
2141
+ if (input.resumeFrom) {
2142
+ if (!input.continueJob) {
2143
+ throw new Error("--resume-from requires --continue-job");
2309
2144
  }
2310
- return;
2145
+ checkpoint = getCheckpointById(input.continueJob, input.resumeFrom);
2146
+ } else if (input.continueJob) {
2147
+ checkpoint = getMostRecentCheckpoint(input.continueJob);
2148
+ } else if (input.continue) {
2149
+ checkpoint = getMostRecentCheckpoint();
2311
2150
  }
2312
- if (event.type === "retry") {
2313
- const retryEvent = event;
2314
- const activityId = `retry-${event.id}`;
2315
- addActivity({
2316
- type: "retry",
2317
- id: activityId,
2318
- expertKey: event.expertKey,
2319
- runId: event.runId,
2320
- previousActivityId: runState.lastActivityId,
2321
- delegatedBy: runState.delegatedBy,
2322
- reasoning: runState.completedReasoning,
2323
- error: retryEvent.reason,
2324
- message: ""
2325
- });
2326
- runState.lastActivityId = activityId;
2327
- runState.completedReasoning = void 0;
2328
- return;
2151
+ if ((input.continue || input.continueJob || input.resumeFrom) && !checkpoint) {
2152
+ throw new Error("No checkpoint found");
2329
2153
  }
2330
- if (event.type === "completeRun") {
2331
- if (!runState.completionLogged) {
2332
- const text = event.text ?? "";
2333
- const activityId = `completion-${event.runId}`;
2334
- addActivity({
2335
- type: "complete",
2336
- id: activityId,
2337
- expertKey: event.expertKey,
2338
- runId: event.runId,
2339
- previousActivityId: runState.lastActivityId,
2340
- delegatedBy: runState.delegatedBy,
2341
- reasoning: runState.completedReasoning,
2342
- text
2343
- });
2344
- runState.lastActivityId = activityId;
2345
- runState.completionLogged = true;
2346
- runState.isComplete = true;
2347
- runState.completedReasoning = void 0;
2348
- }
2349
- return;
2154
+ if (checkpoint && input.expertKey && checkpoint.expert.key !== input.expertKey) {
2155
+ throw new Error(
2156
+ `Checkpoint expert key ${checkpoint.expert.key} does not match input expert key ${input.expertKey}`
2157
+ );
2350
2158
  }
2351
- if (event.type === "stopRunByError") {
2352
- const errorEvent = event;
2353
- const activityId = `error-${event.id}`;
2354
- addActivity({
2355
- type: "error",
2356
- id: activityId,
2357
- expertKey: event.expertKey,
2358
- runId: event.runId,
2359
- previousActivityId: runState.lastActivityId,
2360
- delegatedBy: runState.delegatedBy,
2361
- errorName: errorEvent.error.name,
2362
- error: errorEvent.error.message,
2363
- isRetryable: errorEvent.error.isRetryable
2364
- });
2365
- runState.lastActivityId = activityId;
2366
- runState.isComplete = true;
2367
- runState.completedReasoning = void 0;
2368
- return;
2159
+ const envPath = input.envPath && input.envPath.length > 0 ? input.envPath : perstackConfig.envPath ?? [".env", ".env.local"];
2160
+ const env = getEnv(envPath);
2161
+ const provider = input.provider ?? perstackConfig.provider?.providerName ?? defaultProvider;
2162
+ const model = input.model ?? perstackConfig.model ?? defaultModel;
2163
+ const providerConfig = getProviderConfig(provider, env, perstackConfig.provider);
2164
+ const experts = Object.fromEntries(
2165
+ Object.entries(perstackConfig.experts ?? {}).map(([name, expert]) => {
2166
+ return [
2167
+ name,
2168
+ {
2169
+ name,
2170
+ version: expert.version ?? "1.0.0",
2171
+ description: expert.description,
2172
+ instruction: expert.instruction,
2173
+ skills: expert.skills,
2174
+ delegates: expert.delegates,
2175
+ tags: expert.tags
2176
+ }
2177
+ ];
2178
+ })
2179
+ );
2180
+ return {
2181
+ perstackConfig,
2182
+ checkpoint,
2183
+ env,
2184
+ providerConfig,
2185
+ model,
2186
+ experts
2187
+ };
2188
+ }
2189
+
2190
+ // ../../packages/tui/src/lib/interactive.ts
2191
+ function parseInteractiveToolCallResult(query, checkpoint) {
2192
+ const lastMessage = checkpoint.messages[checkpoint.messages.length - 1];
2193
+ if (lastMessage.type !== "expertMessage") {
2194
+ throw new Error("Last message is not a expert message");
2369
2195
  }
2370
- if (isToolCallsEvent(event)) {
2371
- for (const toolCall of event.toolCalls) {
2372
- if (!state.tools.has(toolCall.id)) {
2373
- state.tools.set(toolCall.id, { id: toolCall.id, toolCall, logged: false });
2374
- }
2196
+ const content = lastMessage.contents.find((c) => c.type === "toolCallPart");
2197
+ if (!content || content.type !== "toolCallPart") {
2198
+ throw new Error("Last message content is not a tool call part");
2199
+ }
2200
+ const toolCallId = content.toolCallId;
2201
+ const toolName = content.toolName;
2202
+ const pendingToolCall = checkpoint.pendingToolCalls?.find((tc) => tc.id === toolCallId);
2203
+ const skillName = pendingToolCall?.skillName ?? "";
2204
+ return {
2205
+ interactiveToolCallResult: {
2206
+ toolCallId,
2207
+ toolName,
2208
+ skillName,
2209
+ text: query
2375
2210
  }
2211
+ };
2212
+ }
2213
+
2214
+ // ../../packages/tui-components/src/utils/event-queue.ts
2215
+ var defaultErrorLogger = (message, error) => {
2216
+ console.error(message, error);
2217
+ };
2218
+ var EventQueue = class _EventQueue {
2219
+ static MAX_PENDING_EVENTS = 1e3;
2220
+ pendingEvents = [];
2221
+ handler = null;
2222
+ onError;
2223
+ errorLogger;
2224
+ constructor(options) {
2225
+ this.onError = options?.onError;
2226
+ this.errorLogger = options?.errorLogger ?? defaultErrorLogger;
2376
2227
  }
2377
- if (isStopRunByDelegateEvent(event)) {
2378
- const reasoning = runState.completedReasoning;
2379
- const delegations = event.checkpoint.delegateTo ?? [];
2380
- runState.pendingDelegateCount += delegations.length;
2381
- const delegateActivities = [];
2382
- for (const delegation of delegations) {
2383
- const existingTool = state.tools.get(delegation.toolCallId);
2384
- if (!existingTool || !existingTool.logged) {
2385
- if (existingTool) {
2386
- existingTool.logged = true;
2387
- }
2388
- const activityId = `delegate-${delegation.toolCallId}`;
2389
- delegateActivities.push({
2390
- type: "delegate",
2391
- id: activityId,
2392
- expertKey: event.expertKey,
2393
- runId: event.runId,
2394
- previousActivityId: runState.lastActivityId,
2395
- delegatedBy: runState.delegatedBy,
2396
- delegateExpertKey: delegation.expert.key,
2397
- query: delegation.query,
2398
- reasoning
2399
- });
2400
- runState.lastActivityId = activityId;
2401
- }
2402
- }
2403
- const wrapped = wrapInGroupIfParallel(delegateActivities, reasoning, {
2404
- expertKey: event.expertKey,
2405
- runId: event.runId,
2406
- delegatedBy: runState.delegatedBy
2407
- });
2408
- for (const item of wrapped) {
2409
- addActivity(item);
2228
+ setHandler(fn) {
2229
+ this.handler = fn;
2230
+ for (const event of this.pendingEvents) {
2231
+ this.safeHandle(event);
2410
2232
  }
2411
- runState.completedReasoning = void 0;
2412
- return;
2233
+ this.pendingEvents.length = 0;
2413
2234
  }
2414
- if (isStopRunByInteractiveToolEvent(event)) {
2415
- const reasoning = runState.completedReasoning;
2416
- const pendingToolCalls = event.checkpoint.pendingToolCalls ?? [];
2417
- const interactiveActivities = [];
2418
- for (const toolCall of pendingToolCalls) {
2419
- const existingTool = state.tools.get(toolCall.id);
2420
- if (!existingTool || !existingTool.logged) {
2421
- if (existingTool) {
2422
- existingTool.logged = true;
2423
- }
2424
- const activityId = `interactive-${toolCall.id}`;
2425
- interactiveActivities.push({
2426
- type: "interactiveTool",
2427
- id: activityId,
2428
- expertKey: event.expertKey,
2429
- runId: event.runId,
2430
- previousActivityId: runState.lastActivityId,
2431
- delegatedBy: runState.delegatedBy,
2432
- skillName: toolCall.skillName,
2433
- toolName: toolCall.toolName,
2434
- args: toolCall.args,
2435
- reasoning
2436
- });
2437
- runState.lastActivityId = activityId;
2235
+ emit(event) {
2236
+ if (this.handler) {
2237
+ this.safeHandle(event);
2238
+ } else {
2239
+ if (this.pendingEvents.length >= _EventQueue.MAX_PENDING_EVENTS) {
2240
+ this.pendingEvents.shift();
2438
2241
  }
2242
+ this.pendingEvents.push(event);
2439
2243
  }
2440
- const wrapped = wrapInGroupIfParallel(interactiveActivities, reasoning, {
2441
- expertKey: event.expertKey,
2442
- runId: event.runId,
2443
- delegatedBy: runState.delegatedBy
2444
- });
2445
- for (const item of wrapped) {
2446
- addActivity(item);
2447
- }
2448
- runState.completedReasoning = void 0;
2449
- return;
2450
2244
  }
2451
- if (isToolResultsEvent(event)) {
2452
- const reasoning = runState.completedReasoning;
2453
- const toolActivities = [];
2454
- for (const toolResult of event.toolResults) {
2455
- const tool = state.tools.get(toolResult.id);
2456
- if (tool && !tool.logged) {
2457
- const activityId = `action-${tool.id}`;
2458
- const activity = toolToActivity(tool.toolCall, toolResult, reasoning, {
2459
- id: activityId,
2460
- expertKey: event.expertKey,
2461
- runId: event.runId,
2462
- previousActivityId: runState.lastActivityId,
2463
- delegatedBy: runState.delegatedBy
2464
- });
2465
- toolActivities.push(activity);
2466
- runState.lastActivityId = activityId;
2467
- tool.logged = true;
2468
- }
2469
- }
2470
- if (toolActivities.length > 0) {
2471
- const wrapped = wrapInGroupIfParallel(toolActivities, reasoning, {
2472
- expertKey: event.expertKey,
2473
- runId: event.runId,
2474
- delegatedBy: runState.delegatedBy
2475
- });
2476
- for (const item of wrapped) {
2477
- addActivity(item);
2245
+ safeHandle(event) {
2246
+ try {
2247
+ this.handler?.(event);
2248
+ } catch (error) {
2249
+ if (this.onError) {
2250
+ this.onError(error);
2251
+ } else {
2252
+ this.errorLogger("EventQueue handler error:", error);
2478
2253
  }
2479
- runState.completedReasoning = void 0;
2480
- }
2481
- } else if (isToolResultEvent(event)) {
2482
- const { toolResult } = event;
2483
- const tool = state.tools.get(toolResult.id);
2484
- if (tool && !tool.logged) {
2485
- const activityId = `action-${tool.id}`;
2486
- const activity = toolToActivity(tool.toolCall, toolResult, runState.completedReasoning, {
2487
- id: activityId,
2488
- expertKey: event.expertKey,
2489
- runId: event.runId,
2490
- previousActivityId: runState.lastActivityId,
2491
- delegatedBy: runState.delegatedBy
2492
- });
2493
- addActivity(activity);
2494
- runState.lastActivityId = activityId;
2495
- tool.logged = true;
2496
- runState.completedReasoning = void 0;
2497
2254
  }
2498
2255
  }
2499
- }
2256
+ };
2257
+ var InputAreaContext = createContext(null);
2258
+ var InputAreaProvider = InputAreaContext.Provider;
2259
+ var useInputAreaContext = () => {
2260
+ const context = useContext(InputAreaContext);
2261
+ if (!context) {
2262
+ throw new Error("useInputAreaContext must be used within InputAreaProvider");
2263
+ }
2264
+ return context;
2265
+ };
2500
2266
 
2501
- // ../../packages/react/src/hooks/use-run.ts
2502
- var STREAMING_EVENT_TYPES = /* @__PURE__ */ new Set([
2503
- "startStreamingReasoning",
2504
- "streamReasoning",
2505
- "completeStreamingReasoning",
2506
- "startStreamingRunResult",
2507
- "streamRunResult",
2508
- "completeStreamingRunResult"
2509
- ]);
2510
- var isStreamingEvent = (event) => "type" in event && "expertKey" in event && STREAMING_EVENT_TYPES.has(event.type);
2511
- function processStreamingEvent(event, prevState) {
2512
- const { runId, expertKey } = event;
2513
- switch (event.type) {
2514
- case "startStreamingReasoning": {
2515
- return {
2516
- newState: {
2517
- ...prevState,
2518
- runs: {
2519
- ...prevState.runs,
2520
- [runId]: {
2521
- expertKey,
2522
- reasoning: "",
2523
- isReasoningActive: true
2524
- }
2525
- }
2526
- },
2527
- handled: true
2528
- };
2267
+ // ../../packages/tui-components/src/helpers.ts
2268
+ var truncateText = (text, maxLength) => {
2269
+ if (text.length <= maxLength) return text;
2270
+ return `${text.slice(0, maxLength)}...`;
2271
+ };
2272
+ var assertNever = (x) => {
2273
+ throw new Error(`Unexpected value: ${x}`);
2274
+ };
2275
+ var formatTimestamp = (timestamp) => new Date(timestamp).toLocaleString();
2276
+ var shortenPath = (fullPath, maxLength = 60) => {
2277
+ if (fullPath.length <= maxLength) return fullPath;
2278
+ const parts = fullPath.split("/");
2279
+ if (parts.length <= 2) return fullPath;
2280
+ const filename = parts[parts.length - 1] ?? "";
2281
+ const parentDir = parts[parts.length - 2] ?? "";
2282
+ const shortened = `.../${parentDir}/${filename}`;
2283
+ if (shortened.length <= maxLength) return shortened;
2284
+ return `.../${filename}`;
2285
+ };
2286
+ var summarizeOutput = (lines, maxLines) => {
2287
+ const filtered = lines.filter((l) => l.trim());
2288
+ const visible = filtered.slice(0, maxLines);
2289
+ const remaining = filtered.length - visible.length;
2290
+ return { visible, remaining };
2291
+ };
2292
+
2293
+ // ../../packages/tui-components/src/constants.ts
2294
+ var UI_CONSTANTS = {
2295
+ MAX_VISIBLE_LIST_ITEMS: 25,
2296
+ TRUNCATE_TEXT_MEDIUM: 80,
2297
+ TRUNCATE_TEXT_DEFAULT: 100};
2298
+ var RENDER_CONSTANTS = {
2299
+ EXEC_OUTPUT_MAX_LINES: 4,
2300
+ NEW_TODO_MAX_PREVIEW: 3,
2301
+ LIST_DIR_MAX_ITEMS: 4
2302
+ };
2303
+ var INDICATOR = {
2304
+ BULLET: "\u25CF",
2305
+ TREE: "\u2514",
2306
+ ELLIPSIS: "..."
2307
+ };
2308
+ var STOP_EVENT_TYPES = [
2309
+ "stopRunByInteractiveTool",
2310
+ "stopRunByDelegate",
2311
+ "stopRunByExceededMaxSteps"
2312
+ ];
2313
+ var KEY_BINDINGS = {
2314
+ NAVIGATE_UP: "\u2191",
2315
+ NAVIGATE_DOWN: "\u2193",
2316
+ SELECT: "Enter",
2317
+ BACK: "b",
2318
+ ESCAPE: "Esc",
2319
+ INPUT_MODE: "i",
2320
+ HISTORY: "h",
2321
+ NEW: "n",
2322
+ CHECKPOINTS: "c",
2323
+ EVENTS: "e",
2324
+ RESUME: "Enter"};
2325
+ var KEY_HINTS = {
2326
+ NAVIGATE: `${KEY_BINDINGS.NAVIGATE_UP}${KEY_BINDINGS.NAVIGATE_DOWN}:Navigate`,
2327
+ SELECT: `${KEY_BINDINGS.SELECT}:Select`,
2328
+ RESUME: `${KEY_BINDINGS.RESUME}:Resume`,
2329
+ BACK: `${KEY_BINDINGS.BACK}:Back`,
2330
+ CANCEL: `${KEY_BINDINGS.ESCAPE}:Cancel`,
2331
+ INPUT: `${KEY_BINDINGS.INPUT_MODE}:Input`,
2332
+ HISTORY: `${KEY_BINDINGS.HISTORY}:History`,
2333
+ NEW: `${KEY_BINDINGS.NEW}:New Run`,
2334
+ CHECKPOINTS: `${KEY_BINDINGS.CHECKPOINTS}:Checkpoints`,
2335
+ EVENTS: `${KEY_BINDINGS.EVENTS}:Events`};
2336
+ var useListNavigation = (options) => {
2337
+ const { items, onSelect, onBack } = options;
2338
+ const [selectedIndex, setSelectedIndex] = useState(0);
2339
+ useEffect(() => {
2340
+ if (selectedIndex >= items.length && items.length > 0) {
2341
+ setSelectedIndex(items.length - 1);
2529
2342
  }
2530
- case "streamReasoning": {
2531
- return {
2532
- newState: {
2533
- ...prevState,
2534
- runs: {
2535
- ...prevState.runs,
2536
- [runId]: {
2537
- ...prevState.runs[runId],
2538
- expertKey,
2539
- reasoning: (prevState.runs[runId]?.reasoning ?? "") + event.delta
2540
- }
2541
- }
2542
- },
2543
- handled: true
2544
- };
2545
- }
2546
- case "completeStreamingReasoning": {
2547
- return {
2548
- newState: {
2549
- ...prevState,
2550
- runs: {
2551
- ...prevState.runs,
2552
- [runId]: {
2553
- ...prevState.runs[runId],
2554
- expertKey,
2555
- isReasoningActive: false
2556
- }
2557
- }
2558
- },
2559
- handled: false
2560
- };
2561
- }
2562
- case "startStreamingRunResult": {
2563
- return {
2564
- newState: {
2565
- ...prevState,
2566
- runs: {
2567
- ...prevState.runs,
2568
- [runId]: {
2569
- expertKey,
2570
- reasoning: void 0,
2571
- isReasoningActive: false,
2572
- runResult: "",
2573
- isRunResultActive: true
2574
- }
2575
- }
2576
- },
2577
- handled: true
2578
- };
2579
- }
2580
- case "streamRunResult": {
2581
- return {
2582
- newState: {
2583
- ...prevState,
2584
- runs: {
2585
- ...prevState.runs,
2586
- [runId]: {
2587
- ...prevState.runs[runId],
2588
- expertKey,
2589
- runResult: (prevState.runs[runId]?.runResult ?? "") + event.delta
2590
- }
2591
- }
2592
- },
2593
- handled: true
2594
- };
2595
- }
2596
- case "completeStreamingRunResult": {
2597
- return {
2598
- newState: {
2599
- ...prevState,
2600
- runs: {
2601
- ...prevState.runs,
2602
- [runId]: {
2603
- ...prevState.runs[runId],
2604
- expertKey,
2605
- isRunResultActive: false
2606
- }
2607
- }
2608
- },
2609
- handled: true
2610
- };
2611
- }
2612
- default:
2613
- return { newState: prevState, handled: false };
2614
- }
2615
- }
2616
- function useRun() {
2617
- const [activities, setActivities] = useState([]);
2618
- const [streaming, setStreaming] = useState({ runs: {} });
2619
- const [eventCount, setEventCount] = useState(0);
2620
- const [isComplete, setIsComplete] = useState(false);
2621
- const stateRef = useRef(createInitialActivityProcessState());
2622
- const clearStreaming = useCallback(() => {
2623
- setStreaming({ runs: {} });
2624
- }, []);
2625
- const handleStreamingEvent = useCallback((event) => {
2626
- let handled = false;
2627
- setStreaming((prev) => {
2628
- const result = processStreamingEvent(event, prev);
2629
- handled = result.handled;
2630
- return result.newState;
2631
- });
2632
- return handled;
2633
- }, []);
2634
- const processEvent = useCallback((event) => {
2635
- const newActivities = [];
2636
- const addActivity = (activity) => newActivities.push(activity);
2637
- processRunEventToActivity(stateRef.current, event, addActivity);
2638
- if (newActivities.length > 0) {
2639
- setActivities((prev) => [...prev, ...newActivities]);
2640
- }
2641
- const rootRunComplete = Array.from(stateRef.current.runStates.values()).some(
2642
- (rs) => rs.isComplete && !rs.delegatedBy
2643
- );
2644
- setIsComplete(rootRunComplete);
2645
- }, []);
2646
- const clearRunStreaming = useCallback((runId) => {
2647
- setStreaming((prev) => {
2648
- const { [runId]: _, ...rest } = prev.runs;
2649
- return { runs: rest };
2650
- });
2651
- }, []);
2652
- const addEvent = useCallback(
2653
- (event) => {
2654
- if (isStreamingEvent(event)) {
2655
- const handled = handleStreamingEvent(event);
2656
- if (handled) {
2657
- setEventCount((prev) => prev + 1);
2658
- return;
2659
- }
2343
+ }, [items.length, selectedIndex]);
2344
+ const handleNavigation = useCallback(
2345
+ (inputChar, key) => {
2346
+ if (key.upArrow && items.length > 0) {
2347
+ setSelectedIndex((prev) => Math.max(0, prev - 1));
2348
+ return true;
2660
2349
  }
2661
- if ("type" in event && "runId" in event && (event.type === "completeRun" || event.type === "stopRunByError")) {
2662
- clearRunStreaming(event.runId);
2350
+ if (key.downArrow && items.length > 0) {
2351
+ setSelectedIndex((prev) => Math.min(items.length - 1, prev + 1));
2352
+ return true;
2663
2353
  }
2664
- processEvent(event);
2665
- setEventCount((prev) => prev + 1);
2354
+ if (key.return && items[selectedIndex]) {
2355
+ onSelect?.(items[selectedIndex]);
2356
+ return true;
2357
+ }
2358
+ if ((key.escape || inputChar === "b") && onBack) {
2359
+ onBack();
2360
+ return true;
2361
+ }
2362
+ return false;
2666
2363
  },
2667
- [handleStreamingEvent, clearRunStreaming, processEvent]
2364
+ [items, selectedIndex, onSelect, onBack]
2668
2365
  );
2669
- const appendHistoricalEvents = useCallback((historicalEvents) => {
2670
- const newActivities = [];
2671
- const addActivity = (activity) => newActivities.push(activity);
2672
- for (const event of historicalEvents) {
2673
- processRunEventToActivity(stateRef.current, event, addActivity);
2674
- }
2675
- if (newActivities.length > 0) {
2676
- setActivities((prev) => [...prev, ...newActivities]);
2677
- }
2678
- setEventCount((prev) => prev + historicalEvents.length);
2679
- const rootRunComplete = Array.from(stateRef.current.runStates.values()).some(
2680
- (rs) => rs.isComplete && !rs.delegatedBy
2681
- );
2682
- setIsComplete(rootRunComplete);
2683
- }, []);
2684
- return {
2685
- activities,
2686
- streaming,
2687
- isComplete,
2688
- eventCount,
2689
- addEvent,
2690
- appendHistoricalEvents,
2691
- clearStreaming
2692
- };
2693
- }
2694
- var useRuntimeInfo = (options) => {
2695
- const [runtimeInfo, setRuntimeInfo] = useState({
2696
- status: "initializing",
2697
- runtimeVersion: options.initialConfig.runtimeVersion,
2698
- expertName: options.initialExpertName,
2699
- model: options.initialConfig.model,
2700
- maxSteps: options.initialConfig.maxSteps,
2701
- maxRetries: options.initialConfig.maxRetries,
2702
- timeout: options.initialConfig.timeout,
2703
- activeSkills: [],
2704
- contextWindowUsage: options.initialConfig.contextWindowUsage
2705
- });
2706
- const handleEvent = useCallback((event) => {
2707
- if (event.type === "initializeRuntime") {
2708
- setRuntimeInfo((prev) => ({
2709
- runtimeVersion: event.runtimeVersion,
2710
- expertName: event.expertName,
2711
- model: event.model,
2712
- maxSteps: event.maxSteps,
2713
- maxRetries: event.maxRetries,
2714
- timeout: event.timeout,
2715
- currentStep: 1,
2716
- status: "running",
2717
- query: event.query,
2718
- statusChangedAt: Date.now(),
2719
- activeSkills: [],
2720
- contextWindowUsage: prev.contextWindowUsage
2721
- }));
2722
- return { initialized: true };
2723
- }
2724
- if (event.type === "skillConnected") {
2725
- setRuntimeInfo((prev) => ({
2726
- ...prev,
2727
- activeSkills: [...prev.activeSkills, event.skillName]
2728
- }));
2729
- return null;
2730
- }
2731
- if (event.type === "skillDisconnected") {
2732
- setRuntimeInfo((prev) => ({
2733
- ...prev,
2734
- activeSkills: prev.activeSkills.filter((s) => s !== event.skillName)
2735
- }));
2736
- return null;
2737
- }
2738
- if ("stepNumber" in event) {
2739
- const isComplete = event.type === "completeRun";
2740
- const isStopped = STOP_EVENT_TYPES.includes(event.type);
2741
- const checkpoint = "nextCheckpoint" in event ? event.nextCheckpoint : "checkpoint" in event ? event.checkpoint : void 0;
2742
- setRuntimeInfo((prev) => ({
2743
- ...prev,
2744
- currentStep: event.stepNumber,
2745
- status: isComplete ? "completed" : isStopped ? "stopped" : "running",
2746
- ...isComplete || isStopped ? { statusChangedAt: Date.now() } : {},
2747
- ...checkpoint?.contextWindowUsage !== void 0 ? { contextWindowUsage: checkpoint.contextWindowUsage } : {}
2748
- }));
2749
- if (isComplete) return { completed: true };
2750
- if (isStopped) return { stopped: true };
2751
- }
2752
- return null;
2753
- }, []);
2754
- const setExpertName = useCallback((expertName) => {
2755
- setRuntimeInfo((prev) => ({ ...prev, expertName }));
2756
- }, []);
2757
- const setQuery = useCallback((query) => {
2758
- setRuntimeInfo((prev) => ({ ...prev, query }));
2759
- }, []);
2760
- const setCurrentStep = useCallback((step) => {
2761
- setRuntimeInfo((prev) => ({ ...prev, currentStep: step }));
2762
- }, []);
2763
- const setContextWindowUsage = useCallback((contextWindowUsage) => {
2764
- setRuntimeInfo((prev) => ({ ...prev, contextWindowUsage }));
2765
- }, []);
2766
- return {
2767
- runtimeInfo,
2768
- handleEvent,
2769
- setExpertName,
2770
- setQuery,
2771
- setCurrentStep,
2772
- setContextWindowUsage
2773
- };
2774
- };
2775
- var useLatestRef = (value) => {
2776
- const ref = useRef(value);
2777
- useInsertionEffect(() => {
2778
- ref.current = value;
2779
- });
2780
- return ref;
2366
+ return { selectedIndex, handleNavigation };
2781
2367
  };
2782
-
2783
- // ../../packages/tui-components/src/hooks/use-text-input.ts
2784
- var useTextInput = (options) => {
2785
- const [input, setInput] = useState("");
2786
- const inputRef = useLatestRef(input);
2787
- const onSubmitRef = useLatestRef(options.onSubmit);
2788
- const onCancelRef = useLatestRef(options.onCancel);
2789
- const handleInput = useCallback(
2790
- (inputChar, key) => {
2791
- if (key.escape) {
2792
- setInput("");
2793
- onCancelRef.current?.();
2794
- return;
2795
- }
2796
- if (key.return && inputRef.current.trim()) {
2797
- onSubmitRef.current(inputRef.current.trim());
2798
- setInput("");
2799
- return;
2800
- }
2801
- if (key.backspace || key.delete) {
2802
- setInput((prev) => prev.slice(0, -1));
2803
- return;
2804
- }
2805
- if (!key.ctrl && !key.meta && inputChar) {
2806
- setInput((prev) => prev + inputChar);
2807
- }
2808
- },
2809
- [inputRef, onSubmitRef, onCancelRef]
2810
- );
2811
- const reset = useCallback(() => {
2812
- setInput("");
2813
- }, []);
2814
- return { input, handleInput, reset };
2815
- };
2816
-
2817
- // ../../packages/tui-components/src/hooks/ui/use-expert-selector.ts
2818
- var useExpertSelector = (options) => {
2819
- const { experts, onExpertSelect, extraKeyHandler } = options;
2820
- const [inputMode, setInputMode] = useState(false);
2368
+ var ListBrowser = ({
2369
+ title,
2370
+ items,
2371
+ renderItem,
2372
+ onSelect,
2373
+ emptyMessage = "No items found",
2374
+ extraKeyHandler,
2375
+ onBack,
2376
+ maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS
2377
+ }) => {
2821
2378
  const { selectedIndex, handleNavigation } = useListNavigation({
2822
- items: experts,
2823
- onSelect: (expert) => onExpertSelect(expert.key)
2379
+ items,
2380
+ onSelect,
2381
+ onBack
2824
2382
  });
2825
- const { input, handleInput, reset } = useTextInput({
2826
- onSubmit: (value) => {
2827
- onExpertSelect(value);
2828
- setInputMode(false);
2829
- },
2830
- onCancel: () => setInputMode(false)
2383
+ useInput((inputChar, key) => {
2384
+ if (extraKeyHandler?.(inputChar, key, items[selectedIndex])) return;
2385
+ handleNavigation(inputChar, key);
2831
2386
  });
2832
- const handleKeyInput = useCallback(
2833
- (inputChar, key) => {
2834
- if (inputMode) {
2835
- handleInput(inputChar, key);
2836
- return;
2837
- }
2838
- if (handleNavigation(inputChar, key)) return;
2839
- if (extraKeyHandler?.(inputChar, key)) return;
2840
- if (inputChar === "i") {
2841
- reset();
2842
- setInputMode(true);
2843
- }
2844
- },
2845
- [inputMode, handleInput, handleNavigation, extraKeyHandler, reset]
2846
- );
2847
- return {
2848
- inputMode,
2849
- input,
2850
- selectedIndex,
2851
- handleKeyInput
2852
- };
2853
- };
2854
- var ExpertList = ({
2855
- experts,
2856
- selectedIndex,
2857
- showSource = false,
2858
- inline = false,
2859
- maxItems
2860
- }) => {
2861
- const displayExperts = maxItems ? experts.slice(0, maxItems) : experts;
2862
- if (displayExperts.length === 0) {
2863
- return /* @__PURE__ */ jsx(Text, { color: "gray", children: "No experts found." });
2864
- }
2865
- const items = displayExperts.map((expert, index) => /* @__PURE__ */ jsxs(Text, { color: index === selectedIndex ? "cyan" : "gray", children: [
2866
- index === selectedIndex ? ">" : " ",
2867
- " ",
2868
- showSource ? expert.key : expert.name,
2869
- showSource && expert.source && /* @__PURE__ */ jsxs(Fragment, { children: [
2870
- " ",
2871
- /* @__PURE__ */ jsxs(Text, { color: expert.source === "configured" ? "green" : "yellow", children: [
2872
- "[",
2873
- expert.source === "configured" ? "config" : "recent",
2874
- "]"
2387
+ const { scrollOffset, displayItems } = useMemo(() => {
2388
+ const offset = Math.max(0, Math.min(selectedIndex - maxItems + 1, items.length - maxItems));
2389
+ return {
2390
+ scrollOffset: offset,
2391
+ displayItems: items.slice(offset, offset + maxItems)
2392
+ };
2393
+ }, [items, selectedIndex, maxItems]);
2394
+ const hasMoreAbove = scrollOffset > 0;
2395
+ const hasMoreBelow = scrollOffset + maxItems < items.length;
2396
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2397
+ /* @__PURE__ */ jsxs(Box, { children: [
2398
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: title }),
2399
+ items.length > maxItems && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
2400
+ " ",
2401
+ "(",
2402
+ selectedIndex + 1,
2403
+ "/",
2404
+ items.length,
2405
+ ")"
2875
2406
  ] })
2876
2407
  ] }),
2877
- inline ? " " : ""
2878
- ] }, expert.key));
2879
- return inline ? /* @__PURE__ */ jsx(Box, { children: items }) : /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: items });
2880
- };
2881
- var ExpertSelectorBase = ({
2882
- experts,
2883
- hint,
2884
- onExpertSelect,
2885
- showSource = false,
2886
- inline = false,
2887
- maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
2888
- extraKeyHandler
2889
- }) => {
2890
- const { inputMode, input, selectedIndex, handleKeyInput } = useExpertSelector({
2891
- experts,
2892
- onExpertSelect,
2893
- extraKeyHandler
2894
- });
2895
- useInput(handleKeyInput);
2896
- return /* @__PURE__ */ jsxs(Box, { flexDirection: inline ? "row" : "column", children: [
2897
- !inputMode && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2898
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "cyan", children: hint }) }),
2899
- /* @__PURE__ */ jsx(
2900
- ExpertList,
2901
- {
2902
- experts,
2903
- selectedIndex,
2904
- showSource,
2905
- inline,
2906
- maxItems
2907
- }
2908
- )
2909
- ] }),
2910
- inputMode && /* @__PURE__ */ jsxs(Box, { children: [
2911
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
2912
- /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
2913
- /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
2914
- ] })
2408
+ hasMoreAbove && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS }),
2409
+ /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: displayItems.length === 0 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: emptyMessage }) : displayItems.map((item, index) => {
2410
+ const actualIndex = scrollOffset + index;
2411
+ return renderItem(item, actualIndex === selectedIndex, actualIndex);
2412
+ }) }),
2413
+ hasMoreBelow && /* @__PURE__ */ jsx(Text, { color: "gray", children: INDICATOR.ELLIPSIS })
2915
2414
  ] });
2916
2415
  };
2917
- var BrowsingExpertsInput = ({
2918
- experts,
2919
- onExpertSelect,
2920
- onSwitchToHistory
2921
- }) => {
2922
- const extraKeyHandler = useCallback(
2923
- (inputChar) => {
2924
- if (inputChar === "h") {
2925
- onSwitchToHistory();
2926
- return true;
2927
- }
2928
- return false;
2929
- },
2930
- [onSwitchToHistory]
2931
- );
2932
- const hint = `Experts ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.INPUT} ${KEY_HINTS.HISTORY} ${KEY_HINTS.CANCEL}`;
2933
- return /* @__PURE__ */ jsx(
2934
- ExpertSelectorBase,
2935
- {
2936
- experts,
2937
- hint,
2938
- onExpertSelect,
2939
- showSource: true,
2940
- maxItems: UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
2941
- extraKeyHandler
2942
- }
2943
- );
2944
- };
2945
- var BrowsingHistoryInput = ({
2946
- jobs,
2947
- onJobSelect,
2948
- onJobResume,
2949
- onSwitchToExperts
2416
+ var BrowsingCheckpointsInput = ({
2417
+ job,
2418
+ checkpoints,
2419
+ onCheckpointSelect,
2420
+ onCheckpointResume,
2421
+ onBack,
2422
+ showEventsHint = true
2950
2423
  }) => /* @__PURE__ */ jsx(
2951
2424
  ListBrowser,
2952
2425
  {
2953
- title: `Job History ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${KEY_HINTS.CHECKPOINTS} ${KEY_HINTS.NEW}`,
2954
- items: jobs,
2955
- onSelect: onJobResume,
2956
- emptyMessage: "No jobs found. Press n to start a new job.",
2426
+ title: `Checkpoints for ${job.expertKey} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${showEventsHint ? KEY_HINTS.EVENTS : ""} ${KEY_HINTS.BACK}`.trim(),
2427
+ items: checkpoints,
2428
+ onSelect: onCheckpointResume,
2429
+ onBack,
2430
+ emptyMessage: "No checkpoints found",
2957
2431
  extraKeyHandler: (char, _key, selected) => {
2958
- if (char === "c" && selected) {
2959
- onJobSelect(selected);
2960
- return true;
2961
- }
2962
- if (char === "n") {
2963
- onSwitchToExperts();
2432
+ if (char === "e" && selected) {
2433
+ onCheckpointSelect(selected);
2964
2434
  return true;
2965
2435
  }
2966
2436
  return false;
2967
2437
  },
2968
- renderItem: (job, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2438
+ renderItem: (cp, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2969
2439
  isSelected ? ">" : " ",
2970
- " ",
2971
- job.expertKey,
2972
- " - ",
2973
- job.totalSteps,
2974
- " steps (",
2975
- job.jobId,
2976
- ") (",
2977
- formatTimestamp(job.startedAt),
2440
+ " Step ",
2441
+ cp.stepNumber,
2442
+ " (",
2443
+ cp.id,
2978
2444
  ")"
2979
- ] }, job.jobId)
2445
+ ] }, cp.id)
2980
2446
  }
2981
2447
  );
2982
- var BrowserRouter = ({ inputState, showEventsHint = true }) => {
2983
- const ctx = useInputAreaContext();
2984
- const handleEventSelect = useCallback(
2985
- (event) => {
2986
- if (inputState.type === "browsingEvents") {
2987
- ctx.onEventSelect(inputState, event);
2988
- }
2989
- },
2990
- [ctx.onEventSelect, inputState]
2991
- );
2992
- switch (inputState.type) {
2993
- case "browsingHistory":
2994
- return /* @__PURE__ */ jsx(
2995
- BrowsingHistoryInput,
2996
- {
2997
- jobs: inputState.jobs,
2998
- onJobSelect: ctx.onJobSelect,
2999
- onJobResume: ctx.onJobResume,
3000
- onSwitchToExperts: ctx.onSwitchToExperts
3001
- }
3002
- );
3003
- case "browsingExperts":
3004
- return /* @__PURE__ */ jsx(
3005
- BrowsingExpertsInput,
3006
- {
3007
- experts: inputState.experts,
3008
- onExpertSelect: ctx.onExpertSelect,
3009
- onSwitchToHistory: ctx.onSwitchToHistory
3010
- }
3011
- );
3012
- case "browsingCheckpoints":
3013
- return /* @__PURE__ */ jsx(
3014
- BrowsingCheckpointsInput,
3015
- {
3016
- job: inputState.job,
3017
- checkpoints: inputState.checkpoints,
3018
- onCheckpointSelect: ctx.onCheckpointSelect,
3019
- onCheckpointResume: ctx.onCheckpointResume,
3020
- onBack: ctx.onBack,
3021
- showEventsHint
3022
- }
3023
- );
3024
- case "browsingEvents":
3025
- return /* @__PURE__ */ jsx(
3026
- BrowsingEventsInput,
3027
- {
3028
- checkpoint: inputState.checkpoint,
3029
- events: inputState.events,
3030
- onEventSelect: handleEventSelect,
3031
- onBack: ctx.onBack
3032
- }
3033
- );
3034
- case "browsingEventDetail":
3035
- return /* @__PURE__ */ jsx(BrowsingEventDetailInput, { event: inputState.selectedEvent, onBack: ctx.onBack });
3036
- default:
3037
- return assertNever(inputState);
3038
- }
3039
- };
3040
- var ActionRowSimple = ({
3041
- indicatorColor,
3042
- text,
3043
- textDimColor = false
3044
- }) => /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
3045
- /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }) }),
3046
- /* @__PURE__ */ jsx(Text, { color: "white", dimColor: textDimColor, children: text })
3047
- ] }) });
3048
- var ActionRow = ({ indicatorColor, label, summary, children }) => /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3049
- /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3050
- /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }),
3051
- /* @__PURE__ */ jsx(Text, { color: "white", children: label }),
3052
- summary && /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: summary })
3053
- ] }),
3054
- /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
3055
- /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: INDICATOR.TREE }) }),
3056
- children
3057
- ] })
3058
- ] });
3059
- var CheckpointActionRow = ({ action }) => {
3060
- if (action.type === "parallelGroup") {
3061
- return renderParallelGroup(action);
3062
- }
3063
- const actionElement = renderAction(action);
3064
- if (!actionElement) return null;
3065
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3066
- action.reasoning && renderReasoning(action.reasoning),
3067
- actionElement
2448
+ var BrowsingEventDetailInput = ({ event, onBack }) => {
2449
+ useInput((input, key) => {
2450
+ if (input === "b" || key.escape) {
2451
+ onBack();
2452
+ }
2453
+ });
2454
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
2455
+ /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
2456
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Event Detail" }),
2457
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
2458
+ " ",
2459
+ KEY_HINTS.BACK
2460
+ ] })
2461
+ ] }),
2462
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 2, children: [
2463
+ /* @__PURE__ */ jsxs(Text, { children: [
2464
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type: " }),
2465
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: event.type })
2466
+ ] }),
2467
+ /* @__PURE__ */ jsxs(Text, { children: [
2468
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Step: " }),
2469
+ /* @__PURE__ */ jsx(Text, { children: event.stepNumber })
2470
+ ] }),
2471
+ /* @__PURE__ */ jsxs(Text, { children: [
2472
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Timestamp: " }),
2473
+ /* @__PURE__ */ jsx(Text, { children: formatTimestamp(event.timestamp) })
2474
+ ] }),
2475
+ /* @__PURE__ */ jsxs(Text, { children: [
2476
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "ID: " }),
2477
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.id })
2478
+ ] }),
2479
+ /* @__PURE__ */ jsxs(Text, { children: [
2480
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Run ID: " }),
2481
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: event.runId })
2482
+ ] })
2483
+ ] })
3068
2484
  ] });
3069
2485
  };
3070
- function renderParallelGroup(group) {
3071
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3072
- group.reasoning && renderReasoning(group.reasoning),
3073
- group.activities.map((activity, index) => {
3074
- const actionElement = renderAction(activity);
3075
- if (!actionElement) return null;
3076
- return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: actionElement }, activity.id || `${activity.type}-${index}`);
3077
- })
3078
- ] });
2486
+ var BrowsingEventsInput = ({
2487
+ checkpoint,
2488
+ events,
2489
+ onEventSelect,
2490
+ onBack
2491
+ }) => /* @__PURE__ */ jsx(
2492
+ ListBrowser,
2493
+ {
2494
+ title: `Events for Step ${checkpoint.stepNumber} ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.BACK}`,
2495
+ items: events,
2496
+ onSelect: onEventSelect,
2497
+ onBack,
2498
+ emptyMessage: "No events found",
2499
+ renderItem: (ev, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
2500
+ isSelected ? ">" : " ",
2501
+ " [",
2502
+ ev.type,
2503
+ "] Step ",
2504
+ ev.stepNumber,
2505
+ " (",
2506
+ formatTimestamp(ev.timestamp),
2507
+ ")"
2508
+ ] }, ev.id)
2509
+ }
2510
+ );
2511
+ var TOOL_RESULT_EVENT_TYPES = /* @__PURE__ */ new Set(["resolveToolResults", "attemptCompletion"]);
2512
+ function toolToActivity(toolCall, toolResult, reasoning, meta) {
2513
+ const { skillName, toolName } = toolCall;
2514
+ const baseActivity = skillName.startsWith(BASE_SKILL_PREFIX) ? createBaseToolActivity(toolName, toolCall, toolResult, reasoning) : createGeneralToolActivity(skillName, toolName, toolCall, toolResult, reasoning);
2515
+ return {
2516
+ ...baseActivity,
2517
+ id: meta.id,
2518
+ expertKey: meta.expertKey,
2519
+ runId: meta.runId,
2520
+ previousActivityId: meta.previousActivityId,
2521
+ delegatedBy: meta.delegatedBy
2522
+ };
3079
2523
  }
3080
- function renderReasoning(text) {
3081
- const lines = text.split("\n");
3082
- 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}`)) }) });
2524
+ function createInitialActivityProcessState() {
2525
+ return {
2526
+ tools: /* @__PURE__ */ new Map(),
2527
+ runStates: /* @__PURE__ */ new Map()
2528
+ };
3083
2529
  }
3084
- function renderAction(action) {
3085
- const color = action.type === "error" || "error" in action && action.error ? "red" : "green";
3086
- switch (action.type) {
3087
- case "query":
3088
- return renderQuery(action.text, action.runId);
3089
- case "retry":
3090
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Retry", children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: action.message || action.error }) });
3091
- case "complete":
3092
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "green", label: "Run Results", children: /* @__PURE__ */ jsx(Text, { children: action.text }) });
3093
- case "attemptCompletion": {
3094
- if (action.error) {
3095
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: "Completion Failed", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error }) });
3096
- }
3097
- const remaining = action.remainingTodos?.filter((t) => !t.completed) ?? [];
3098
- if (remaining.length > 0) {
3099
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Completion Blocked", children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3100
- remaining.length,
3101
- " remaining task",
3102
- remaining.length > 1 ? "s" : ""
3103
- ] }) });
3104
- }
3105
- return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: "green", text: "Completion Accepted" });
3106
- }
3107
- case "todo":
3108
- return renderTodo(action, color);
3109
- case "clearTodo":
3110
- return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo Cleared" });
3111
- case "readTextFile":
3112
- return renderReadTextFile(action, color);
3113
- case "writeTextFile":
3114
- return renderWriteTextFile(action, color);
3115
- case "editTextFile":
3116
- return renderEditTextFile(action, color);
3117
- case "appendTextFile":
3118
- return renderAppendTextFile(action, color);
3119
- case "deleteFile":
3120
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Removed" }) });
3121
- case "deleteDirectory":
3122
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete Dir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3123
- "Removed",
3124
- action.recursive ? " (recursive)" : ""
3125
- ] }) });
3126
- case "moveFile":
3127
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Move", summary: shortenPath(action.source), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3128
- "\u2192 ",
3129
- shortenPath(action.destination, 30)
3130
- ] }) });
3131
- case "createDirectory":
3132
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Mkdir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Created" }) });
3133
- case "listDirectory":
3134
- return renderListDirectory(action, color);
3135
- case "getFileInfo":
3136
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Info", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Fetched" }) });
3137
- case "readPdfFile":
3138
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "PDF", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
3139
- case "readImageFile":
3140
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Image", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
3141
- case "exec":
3142
- return renderExec(action, color);
3143
- case "delegate":
3144
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: action.delegateExpertKey, children: /* @__PURE__ */ jsx(
3145
- Text,
3146
- {
3147
- dimColor: true,
3148
- children: `{"query":"${truncateText(action.query, UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM)}"}`
3149
- }
3150
- ) });
3151
- case "delegationComplete":
3152
- return /* @__PURE__ */ jsx(
3153
- ActionRowSimple,
3154
- {
3155
- indicatorColor: "green",
3156
- text: `Delegation Complete (${action.count} delegate${action.count > 1 ? "s" : ""} returned)`
3157
- }
3158
- );
3159
- case "interactiveTool":
3160
- 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) }) });
3161
- case "generalTool":
3162
- 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) }) });
3163
- case "error":
3164
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: action.errorName ?? "Error", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error ?? "Unknown error" }) });
3165
- default: {
3166
- return null;
3167
- }
2530
+ function getOrCreateRunState(state, runId, expertKey) {
2531
+ let runState = state.runStates.get(runId);
2532
+ if (!runState) {
2533
+ runState = {
2534
+ expertKey,
2535
+ queryLogged: false,
2536
+ completionLogged: false,
2537
+ isComplete: false,
2538
+ pendingDelegateCount: 0
2539
+ };
2540
+ state.runStates.set(runId, runState);
3168
2541
  }
2542
+ return runState;
3169
2543
  }
3170
- function renderTodo(action, color) {
3171
- const { newTodos, completedTodos, todos } = action;
3172
- const hasNewTodos = newTodos && newTodos.length > 0;
3173
- const hasCompletedTodos = completedTodos && completedTodos.length > 0;
3174
- if (!hasNewTodos && !hasCompletedTodos) {
3175
- return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo No changes" });
2544
+ var isRunEvent = (event) => "type" in event && "expertKey" in event;
2545
+ var isCompleteStreamingReasoningEvent = (event) => "type" in event && event.type === "completeStreamingReasoning";
2546
+ var isToolCallsEvent = (event) => event.type === "callTools" && "toolCalls" in event;
2547
+ var isStopRunByDelegateEvent = (event) => event.type === "stopRunByDelegate" && "checkpoint" in event;
2548
+ var isStopRunByInteractiveToolEvent = (event) => event.type === "stopRunByInteractiveTool" && "checkpoint" in event;
2549
+ var isToolResultsEvent = (event) => event.type === "resolveToolResults" && "toolResults" in event;
2550
+ var isToolResultEvent = (event) => TOOL_RESULT_EVENT_TYPES.has(event.type) && "toolResult" in event;
2551
+ function wrapInGroupIfParallel(activities, reasoning, meta) {
2552
+ if (activities.length <= 1) {
2553
+ return activities;
3176
2554
  }
3177
- const labelParts = [];
3178
- if (hasNewTodos) {
3179
- labelParts.push(`Added ${newTodos.length} task${newTodos.length > 1 ? "s" : ""}`);
2555
+ const activitiesWithoutReasoning = activities.map((a) => {
2556
+ const { reasoning: _, ...rest } = a;
2557
+ return rest;
2558
+ });
2559
+ const group = {
2560
+ type: "parallelGroup",
2561
+ id: `parallel-${activities[0].id}`,
2562
+ expertKey: meta.expertKey,
2563
+ runId: meta.runId,
2564
+ reasoning,
2565
+ activities: activitiesWithoutReasoning
2566
+ };
2567
+ return [group];
2568
+ }
2569
+ function processRunEventToActivity(state, event, addActivity) {
2570
+ if (isCompleteStreamingReasoningEvent(event)) {
2571
+ const reasoningEvent = event;
2572
+ const { runId, text, expertKey } = reasoningEvent;
2573
+ const runState2 = state.runStates.get(runId);
2574
+ if (runState2) {
2575
+ runState2.completedReasoning = text;
2576
+ } else {
2577
+ state.runStates.set(runId, {
2578
+ expertKey,
2579
+ queryLogged: false,
2580
+ completionLogged: false,
2581
+ isComplete: false,
2582
+ pendingDelegateCount: 0,
2583
+ completedReasoning: text
2584
+ });
2585
+ }
2586
+ return;
3180
2587
  }
3181
- if (hasCompletedTodos) {
3182
- labelParts.push(
3183
- `Completed ${completedTodos.length} task${completedTodos.length > 1 ? "s" : ""}`
3184
- );
2588
+ if (!isRunEvent(event)) {
2589
+ return;
3185
2590
  }
3186
- const label = `Todo ${labelParts.join(", ")}`;
3187
- const completedTitles = hasCompletedTodos ? completedTodos.map((id) => todos.find((t) => t.id === id)?.title).filter((t) => t !== void 0) : [];
3188
- if (!hasNewTodos && completedTitles.length === 0) {
3189
- return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: label });
2591
+ const runState = getOrCreateRunState(state, event.runId, event.expertKey);
2592
+ if (event.type === "startRun") {
2593
+ const startRunEvent = event;
2594
+ const userMessage = startRunEvent.inputMessages.find((m) => m.type === "userMessage");
2595
+ const queryText = userMessage?.contents?.find((c) => c.type === "textPart")?.text;
2596
+ if (!runState.delegatedBy) {
2597
+ const delegatedByInfo = startRunEvent.initialCheckpoint?.delegatedBy;
2598
+ if (delegatedByInfo) {
2599
+ runState.delegatedBy = {
2600
+ expertKey: delegatedByInfo.expert.key,
2601
+ runId: delegatedByInfo.runId
2602
+ };
2603
+ }
2604
+ }
2605
+ const isDelegationReturn = startRunEvent.initialCheckpoint?.status === "stoppedByDelegate" || startRunEvent.initialCheckpoint?.status === "stoppedByInteractiveTool";
2606
+ if (queryText && !runState.queryLogged && !isDelegationReturn) {
2607
+ const activityId = `query-${event.runId}`;
2608
+ addActivity({
2609
+ type: "query",
2610
+ id: activityId,
2611
+ expertKey: event.expertKey,
2612
+ runId: event.runId,
2613
+ previousActivityId: runState.lastActivityId,
2614
+ delegatedBy: runState.delegatedBy,
2615
+ text: queryText
2616
+ });
2617
+ runState.lastActivityId = activityId;
2618
+ runState.queryLogged = true;
2619
+ }
2620
+ return;
3190
2621
  }
3191
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3192
- hasNewTodos && newTodos.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((todo, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3193
- "\u25CB ",
3194
- todo
3195
- ] }, `todo-${idx}`)),
3196
- hasNewTodos && newTodos.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3197
- "... +",
3198
- newTodos.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
3199
- " more"
3200
- ] }),
3201
- completedTitles.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((title, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3202
- "\u2713 ",
3203
- title
3204
- ] }, `completed-${idx}`)),
3205
- completedTitles.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3206
- "... +",
3207
- completedTitles.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
3208
- " more"
3209
- ] })
3210
- ] }) });
3211
- }
3212
- function renderReadTextFile(action, color) {
3213
- const { path: path6, content, from, to } = action;
3214
- const lineRange = from !== void 0 && to !== void 0 ? `#${from}-${to}` : "";
3215
- const lines = content?.split("\n") ?? [];
3216
- return /* @__PURE__ */ jsx(
3217
- ActionRow,
3218
- {
3219
- indicatorColor: color,
3220
- label: "Read Text File",
3221
- summary: `${shortenPath(path6)}${lineRange}`,
3222
- 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}`)) })
2622
+ if (event.type === "resumeFromStop") {
2623
+ if (!runState.delegatedBy) {
2624
+ const resumeEvent = event;
2625
+ const delegatedByInfo = resumeEvent.checkpoint?.delegatedBy;
2626
+ if (delegatedByInfo) {
2627
+ runState.delegatedBy = {
2628
+ expertKey: delegatedByInfo.expert.key,
2629
+ runId: delegatedByInfo.runId
2630
+ };
2631
+ }
3223
2632
  }
3224
- );
3225
- }
3226
- function renderWriteTextFile(action, color) {
3227
- const { path: path6, text } = action;
3228
- const lines = text.split("\n");
3229
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Write Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3230
- /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3231
- /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3232
- ] }, `write-${idx}`)) }) });
3233
- }
3234
- function renderEditTextFile(action, color) {
3235
- const { path: path6, oldText, newText } = action;
3236
- const oldLines = oldText.split("\n");
3237
- const newLines = newText.split("\n");
3238
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Edit Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3239
- oldLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3240
- /* @__PURE__ */ jsx(Text, { color: "red", dimColor: true, children: "-" }),
3241
- /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3242
- ] }, `old-${idx}`)),
3243
- newLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3244
- /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3245
- /* @__PURE__ */ jsx(Text, { dimColor: true, children: line })
3246
- ] }, `new-${idx}`))
3247
- ] }) });
3248
- }
3249
- function renderAppendTextFile(action, color) {
3250
- const { path: path6, text } = action;
3251
- const lines = text.split("\n");
3252
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Append Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3253
- /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3254
- /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3255
- ] }, `append-${idx}`)) }) });
3256
- }
3257
- function renderListDirectory(action, color) {
3258
- const { path: path6, items } = action;
3259
- const itemLines = items?.map((item) => `${item.type === "directory" ? "\u{1F4C1}" : "\u{1F4C4}"} ${item.name}`) ?? [];
3260
- const { visible, remaining } = summarizeOutput(itemLines, RENDER_CONSTANTS.LIST_DIR_MAX_ITEMS);
3261
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "List", summary: shortenPath(path6), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3262
- visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `dir-${idx}`)),
3263
- remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3264
- "... +",
3265
- remaining,
3266
- " more"
3267
- ] })
3268
- ] }) });
3269
- }
3270
- function renderExec(action, color) {
3271
- const { command, args, cwd, output } = action;
3272
- const cwdPart = cwd ? ` ${shortenPath(cwd, 40)}` : "";
3273
- const cmdLine = truncateText(
3274
- `${command} ${args.join(" ")}${cwdPart}`,
3275
- UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT
3276
- );
3277
- const outputLines = output?.split("\n") ?? [];
3278
- const { visible, remaining } = summarizeOutput(
3279
- outputLines,
3280
- RENDER_CONSTANTS.EXEC_OUTPUT_MAX_LINES
3281
- );
3282
- return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: `Bash ${cmdLine}`, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3283
- visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `out-${idx}`)),
3284
- remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3285
- "... +",
3286
- remaining,
3287
- " more"
3288
- ] })
3289
- ] }) });
3290
- }
3291
- function renderQuery(text, runId) {
3292
- const lines = text.split("\n");
3293
- const shortRunId = runId.slice(0, 8);
3294
- 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}`)) }) });
3295
- }
3296
- var RunSetting = ({
3297
- info,
3298
- eventCount,
3299
- isEditing,
3300
- expertName,
3301
- onQuerySubmit
3302
- }) => {
3303
- const { input, handleInput } = useTextInput({
3304
- onSubmit: onQuerySubmit ?? (() => {
3305
- })
3306
- });
3307
- useInput(handleInput, { isActive: isEditing });
3308
- const displayExpertName = expertName ?? info.expertName;
3309
- const skills = info.activeSkills.length > 0 ? info.activeSkills.join(", ") : "";
3310
- const step = info.currentStep !== void 0 ? String(info.currentStep) : "";
3311
- const usagePercent = (info.contextWindowUsage * 100).toFixed(1);
3312
- return /* @__PURE__ */ jsxs(
3313
- Box,
3314
- {
3315
- flexDirection: "column",
3316
- borderStyle: "single",
3317
- borderColor: "gray",
3318
- borderTop: true,
3319
- borderBottom: false,
3320
- borderLeft: false,
3321
- borderRight: false,
3322
- children: [
3323
- /* @__PURE__ */ jsxs(Text, { children: [
3324
- /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "Perstack" }),
3325
- info.runtimeVersion && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
3326
- " (v",
3327
- info.runtimeVersion,
3328
- ")"
3329
- ] })
3330
- ] }),
3331
- /* @__PURE__ */ jsxs(Text, { children: [
3332
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
3333
- /* @__PURE__ */ jsx(Text, { color: "white", children: displayExpertName }),
3334
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Skills: " }),
3335
- /* @__PURE__ */ jsx(Text, { color: "green", children: skills })
3336
- ] }),
3337
- /* @__PURE__ */ jsxs(Text, { children: [
3338
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Status: " }),
3339
- /* @__PURE__ */ jsx(
3340
- Text,
3341
- {
3342
- color: info.status === "running" ? "green" : info.status === "completed" ? "cyan" : "yellow",
3343
- children: info.status
3344
- }
3345
- ),
3346
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Step: " }),
3347
- /* @__PURE__ */ jsx(Text, { color: "white", children: step }),
3348
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Events: " }),
3349
- /* @__PURE__ */ jsx(Text, { color: "white", children: eventCount }),
3350
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Usage: " }),
3351
- /* @__PURE__ */ jsxs(Text, { color: "white", children: [
3352
- usagePercent,
3353
- "%"
3354
- ] })
3355
- ] }),
3356
- /* @__PURE__ */ jsxs(Text, { children: [
3357
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Model: " }),
3358
- /* @__PURE__ */ jsx(Text, { color: "white", children: info.model })
3359
- ] }),
3360
- /* @__PURE__ */ jsxs(Box, { children: [
3361
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
3362
- isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
3363
- /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
3364
- /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3365
- ] }) : /* @__PURE__ */ jsx(Text, { color: "white", children: info.query })
3366
- ] })
3367
- ]
2633
+ return;
2634
+ }
2635
+ if (event.type === "retry") {
2636
+ const retryEvent = event;
2637
+ const activityId = `retry-${event.id}`;
2638
+ addActivity({
2639
+ type: "retry",
2640
+ id: activityId,
2641
+ expertKey: event.expertKey,
2642
+ runId: event.runId,
2643
+ previousActivityId: runState.lastActivityId,
2644
+ delegatedBy: runState.delegatedBy,
2645
+ reasoning: runState.completedReasoning,
2646
+ error: retryEvent.reason,
2647
+ message: ""
2648
+ });
2649
+ runState.lastActivityId = activityId;
2650
+ runState.completedReasoning = void 0;
2651
+ return;
2652
+ }
2653
+ if (event.type === "completeRun") {
2654
+ if (!runState.completionLogged) {
2655
+ const text = event.text ?? "";
2656
+ const activityId = `completion-${event.runId}`;
2657
+ addActivity({
2658
+ type: "complete",
2659
+ id: activityId,
2660
+ expertKey: event.expertKey,
2661
+ runId: event.runId,
2662
+ previousActivityId: runState.lastActivityId,
2663
+ delegatedBy: runState.delegatedBy,
2664
+ reasoning: runState.completedReasoning,
2665
+ text
2666
+ });
2667
+ runState.lastActivityId = activityId;
2668
+ runState.completionLogged = true;
2669
+ runState.isComplete = true;
2670
+ runState.completedReasoning = void 0;
3368
2671
  }
3369
- );
3370
- };
3371
- var StreamingDisplay = ({ streaming }) => {
3372
- const activeRuns = Object.entries(streaming.runs).filter(
3373
- ([, run]) => run.isReasoningActive || run.isRunResultActive
3374
- );
3375
- if (activeRuns.length === 0) return null;
3376
- return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginY: 1, children: activeRuns.map(([runId, run]) => /* @__PURE__ */ jsx(StreamingRunSection, { run }, runId)) });
3377
- };
3378
- function StreamingRunSection({ run }) {
3379
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3380
- run.isReasoningActive && run.reasoning !== void 0 && /* @__PURE__ */ jsx(StreamingReasoning, { expertKey: run.expertKey, text: run.reasoning }),
3381
- run.isRunResultActive && run.runResult !== void 0 && /* @__PURE__ */ jsx(StreamingRunResult, { expertKey: run.expertKey, text: run.runResult })
3382
- ] });
3383
- }
3384
- function StreamingReasoning({
3385
- expertKey,
3386
- text
3387
- }) {
3388
- const lines = text.split("\n");
3389
- const label = `[${formatExpertKey(expertKey)}] Reasoning...`;
3390
- 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}`)) }) });
3391
- }
3392
- function StreamingRunResult({
3393
- expertKey,
3394
- text
3395
- }) {
3396
- const lines = text.split("\n");
3397
- const label = `[${formatExpertKey(expertKey)}] Generating...`;
3398
- 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}`)) }) });
3399
- }
3400
- function formatExpertKey(expertKey) {
3401
- const atIndex = expertKey.lastIndexOf("@");
3402
- if (atIndex > 0) {
3403
- return expertKey.substring(0, atIndex);
2672
+ return;
3404
2673
  }
3405
- return expertKey;
3406
- }
3407
- function getActivityKey(activityOrGroup, index) {
3408
- return activityOrGroup.id || `activity-${index}`;
3409
- }
3410
- var RunBox = ({ node, isRoot }) => {
3411
- if (isRoot) {
3412
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3413
- node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
3414
- node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
3415
- ] });
2674
+ if (event.type === "stopRunByError") {
2675
+ const errorEvent = event;
2676
+ const activityId = `error-${event.id}`;
2677
+ addActivity({
2678
+ type: "error",
2679
+ id: activityId,
2680
+ expertKey: event.expertKey,
2681
+ runId: event.runId,
2682
+ previousActivityId: runState.lastActivityId,
2683
+ delegatedBy: runState.delegatedBy,
2684
+ errorName: errorEvent.error.name,
2685
+ error: errorEvent.error.message,
2686
+ isRetryable: errorEvent.error.isRetryable
2687
+ });
2688
+ runState.lastActivityId = activityId;
2689
+ runState.isComplete = true;
2690
+ runState.completedReasoning = void 0;
2691
+ return;
3416
2692
  }
3417
- const shortRunId = node.runId.slice(0, 8);
3418
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", marginLeft: 1, children: [
3419
- /* @__PURE__ */ jsxs(Text, { dimColor: true, bold: true, children: [
3420
- "[",
3421
- node.expertKey,
3422
- "] ",
3423
- /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3424
- "(",
3425
- shortRunId,
3426
- ")"
3427
- ] })
3428
- ] }),
3429
- node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
3430
- node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
3431
- ] });
3432
- };
3433
- function getActivityProps(activityOrGroup) {
3434
- if (activityOrGroup.type === "parallelGroup") {
3435
- const group = activityOrGroup;
3436
- const firstActivity = group.activities[0];
3437
- return {
3438
- runId: group.runId,
3439
- expertKey: group.expertKey,
3440
- delegatedBy: firstActivity?.delegatedBy
3441
- };
2693
+ if (isToolCallsEvent(event)) {
2694
+ for (const toolCall of event.toolCalls) {
2695
+ if (!state.tools.has(toolCall.id)) {
2696
+ state.tools.set(toolCall.id, { id: toolCall.id, toolCall, logged: false });
2697
+ }
2698
+ }
2699
+ }
2700
+ if (isStopRunByDelegateEvent(event)) {
2701
+ const reasoning = runState.completedReasoning;
2702
+ const delegations = event.checkpoint.delegateTo ?? [];
2703
+ runState.pendingDelegateCount += delegations.length;
2704
+ const delegateActivities = [];
2705
+ for (const delegation of delegations) {
2706
+ const existingTool = state.tools.get(delegation.toolCallId);
2707
+ if (!existingTool || !existingTool.logged) {
2708
+ if (existingTool) {
2709
+ existingTool.logged = true;
2710
+ }
2711
+ const activityId = `delegate-${delegation.toolCallId}`;
2712
+ delegateActivities.push({
2713
+ type: "delegate",
2714
+ id: activityId,
2715
+ expertKey: event.expertKey,
2716
+ runId: event.runId,
2717
+ previousActivityId: runState.lastActivityId,
2718
+ delegatedBy: runState.delegatedBy,
2719
+ delegateExpertKey: delegation.expert.key,
2720
+ query: delegation.query,
2721
+ reasoning
2722
+ });
2723
+ runState.lastActivityId = activityId;
2724
+ }
2725
+ }
2726
+ const wrapped = wrapInGroupIfParallel(delegateActivities, reasoning, {
2727
+ expertKey: event.expertKey,
2728
+ runId: event.runId,
2729
+ delegatedBy: runState.delegatedBy
2730
+ });
2731
+ for (const item of wrapped) {
2732
+ addActivity(item);
2733
+ }
2734
+ runState.completedReasoning = void 0;
2735
+ return;
2736
+ }
2737
+ if (isStopRunByInteractiveToolEvent(event)) {
2738
+ const reasoning = runState.completedReasoning;
2739
+ const pendingToolCalls = event.checkpoint.pendingToolCalls ?? [];
2740
+ const interactiveActivities = [];
2741
+ for (const toolCall of pendingToolCalls) {
2742
+ const existingTool = state.tools.get(toolCall.id);
2743
+ if (!existingTool || !existingTool.logged) {
2744
+ if (existingTool) {
2745
+ existingTool.logged = true;
2746
+ }
2747
+ const activityId = `interactive-${toolCall.id}`;
2748
+ interactiveActivities.push({
2749
+ type: "interactiveTool",
2750
+ id: activityId,
2751
+ expertKey: event.expertKey,
2752
+ runId: event.runId,
2753
+ previousActivityId: runState.lastActivityId,
2754
+ delegatedBy: runState.delegatedBy,
2755
+ skillName: toolCall.skillName,
2756
+ toolName: toolCall.toolName,
2757
+ args: toolCall.args,
2758
+ reasoning
2759
+ });
2760
+ runState.lastActivityId = activityId;
2761
+ }
2762
+ }
2763
+ const wrapped = wrapInGroupIfParallel(interactiveActivities, reasoning, {
2764
+ expertKey: event.expertKey,
2765
+ runId: event.runId,
2766
+ delegatedBy: runState.delegatedBy
2767
+ });
2768
+ for (const item of wrapped) {
2769
+ addActivity(item);
2770
+ }
2771
+ runState.completedReasoning = void 0;
2772
+ return;
2773
+ }
2774
+ if (isToolResultsEvent(event)) {
2775
+ const reasoning = runState.completedReasoning;
2776
+ const toolActivities = [];
2777
+ for (const toolResult of event.toolResults) {
2778
+ const tool = state.tools.get(toolResult.id);
2779
+ if (tool && !tool.logged) {
2780
+ const activityId = `action-${tool.id}`;
2781
+ const activity = toolToActivity(tool.toolCall, toolResult, reasoning, {
2782
+ id: activityId,
2783
+ expertKey: event.expertKey,
2784
+ runId: event.runId,
2785
+ previousActivityId: runState.lastActivityId,
2786
+ delegatedBy: runState.delegatedBy
2787
+ });
2788
+ toolActivities.push(activity);
2789
+ runState.lastActivityId = activityId;
2790
+ tool.logged = true;
2791
+ }
2792
+ }
2793
+ if (toolActivities.length > 0) {
2794
+ const wrapped = wrapInGroupIfParallel(toolActivities, reasoning, {
2795
+ expertKey: event.expertKey,
2796
+ runId: event.runId,
2797
+ delegatedBy: runState.delegatedBy
2798
+ });
2799
+ for (const item of wrapped) {
2800
+ addActivity(item);
2801
+ }
2802
+ runState.completedReasoning = void 0;
2803
+ }
2804
+ } else if (isToolResultEvent(event)) {
2805
+ const { toolResult } = event;
2806
+ const tool = state.tools.get(toolResult.id);
2807
+ if (tool && !tool.logged) {
2808
+ const activityId = `action-${tool.id}`;
2809
+ const activity = toolToActivity(tool.toolCall, toolResult, runState.completedReasoning, {
2810
+ id: activityId,
2811
+ expertKey: event.expertKey,
2812
+ runId: event.runId,
2813
+ previousActivityId: runState.lastActivityId,
2814
+ delegatedBy: runState.delegatedBy
2815
+ });
2816
+ addActivity(activity);
2817
+ runState.lastActivityId = activityId;
2818
+ tool.logged = true;
2819
+ runState.completedReasoning = void 0;
2820
+ }
3442
2821
  }
3443
- return activityOrGroup;
3444
2822
  }
3445
- var ActivityLogPanel = ({ activities }) => {
3446
- const rootNodes = useMemo(() => {
3447
- const nodeMap = /* @__PURE__ */ new Map();
3448
- const roots = [];
3449
- const orphanChildren = /* @__PURE__ */ new Map();
3450
- for (const activityOrGroup of activities) {
3451
- const { runId, expertKey, delegatedBy } = getActivityProps(activityOrGroup);
3452
- let node = nodeMap.get(runId);
3453
- if (!node) {
3454
- node = {
3455
- runId,
3456
- expertKey,
3457
- activities: [],
3458
- children: []
3459
- };
3460
- nodeMap.set(runId, node);
3461
- const waitingChildren = orphanChildren.get(runId);
3462
- if (waitingChildren) {
3463
- for (const child of waitingChildren) {
3464
- node.children.push(child);
3465
- const rootIndex = roots.indexOf(child);
3466
- if (rootIndex !== -1) {
3467
- roots.splice(rootIndex, 1);
2823
+
2824
+ // ../../packages/react/src/hooks/use-run.ts
2825
+ var STREAMING_EVENT_TYPES = /* @__PURE__ */ new Set([
2826
+ "startStreamingReasoning",
2827
+ "streamReasoning",
2828
+ "completeStreamingReasoning",
2829
+ "startStreamingRunResult",
2830
+ "streamRunResult",
2831
+ "completeStreamingRunResult"
2832
+ ]);
2833
+ var isStreamingEvent = (event) => "type" in event && "expertKey" in event && STREAMING_EVENT_TYPES.has(event.type);
2834
+ function processStreamingEvent(event, prevState) {
2835
+ const { runId, expertKey } = event;
2836
+ switch (event.type) {
2837
+ case "startStreamingReasoning": {
2838
+ return {
2839
+ newState: {
2840
+ ...prevState,
2841
+ runs: {
2842
+ ...prevState.runs,
2843
+ [runId]: {
2844
+ expertKey,
2845
+ reasoning: "",
2846
+ isReasoningActive: true
3468
2847
  }
3469
2848
  }
3470
- orphanChildren.delete(runId);
3471
- }
3472
- if (delegatedBy) {
3473
- const parentNode = nodeMap.get(delegatedBy.runId);
3474
- if (parentNode) {
3475
- parentNode.children.push(node);
3476
- } else {
3477
- const orphans = orphanChildren.get(delegatedBy.runId) ?? [];
3478
- orphans.push(node);
3479
- orphanChildren.set(delegatedBy.runId, orphans);
3480
- roots.push(node);
2849
+ },
2850
+ handled: true
2851
+ };
2852
+ }
2853
+ case "streamReasoning": {
2854
+ return {
2855
+ newState: {
2856
+ ...prevState,
2857
+ runs: {
2858
+ ...prevState.runs,
2859
+ [runId]: {
2860
+ ...prevState.runs[runId],
2861
+ expertKey,
2862
+ reasoning: (prevState.runs[runId]?.reasoning ?? "") + event.delta
2863
+ }
3481
2864
  }
3482
- } else {
3483
- roots.push(node);
3484
- }
3485
- }
3486
- node.activities.push(activityOrGroup);
2865
+ },
2866
+ handled: true
2867
+ };
3487
2868
  }
3488
- return roots;
3489
- }, [activities]);
3490
- return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: rootNodes.map((node) => /* @__PURE__ */ jsx(RunBox, { node, isRoot: true }, node.runId)) });
3491
- };
3492
- var ContinueInputPanel = ({
3493
- isActive,
3494
- runStatus,
3495
- onSubmit
3496
- }) => {
3497
- const { input, handleInput } = useTextInput({
3498
- onSubmit: (newQuery) => {
3499
- if (isActive && newQuery.trim()) {
3500
- onSubmit(newQuery.trim());
2869
+ case "completeStreamingReasoning": {
2870
+ return {
2871
+ newState: {
2872
+ ...prevState,
2873
+ runs: {
2874
+ ...prevState.runs,
2875
+ [runId]: {
2876
+ ...prevState.runs[runId],
2877
+ expertKey,
2878
+ isReasoningActive: false
2879
+ }
2880
+ }
2881
+ },
2882
+ handled: false
2883
+ };
2884
+ }
2885
+ case "startStreamingRunResult": {
2886
+ return {
2887
+ newState: {
2888
+ ...prevState,
2889
+ runs: {
2890
+ ...prevState.runs,
2891
+ [runId]: {
2892
+ expertKey,
2893
+ reasoning: void 0,
2894
+ isReasoningActive: false,
2895
+ runResult: "",
2896
+ isRunResultActive: true
2897
+ }
2898
+ }
2899
+ },
2900
+ handled: true
2901
+ };
2902
+ }
2903
+ case "streamRunResult": {
2904
+ return {
2905
+ newState: {
2906
+ ...prevState,
2907
+ runs: {
2908
+ ...prevState.runs,
2909
+ [runId]: {
2910
+ ...prevState.runs[runId],
2911
+ expertKey,
2912
+ runResult: (prevState.runs[runId]?.runResult ?? "") + event.delta
2913
+ }
2914
+ }
2915
+ },
2916
+ handled: true
2917
+ };
2918
+ }
2919
+ case "completeStreamingRunResult": {
2920
+ return {
2921
+ newState: {
2922
+ ...prevState,
2923
+ runs: {
2924
+ ...prevState.runs,
2925
+ [runId]: {
2926
+ ...prevState.runs[runId],
2927
+ expertKey,
2928
+ isRunResultActive: false
2929
+ }
2930
+ }
2931
+ },
2932
+ handled: true
2933
+ };
2934
+ }
2935
+ default:
2936
+ return { newState: prevState, handled: false };
2937
+ }
2938
+ }
2939
+ function useRun() {
2940
+ const [activities, setActivities] = useState([]);
2941
+ const [streaming, setStreaming] = useState({ runs: {} });
2942
+ const [eventCount, setEventCount] = useState(0);
2943
+ const [isComplete, setIsComplete] = useState(false);
2944
+ const stateRef = useRef(createInitialActivityProcessState());
2945
+ const clearStreaming = useCallback(() => {
2946
+ setStreaming({ runs: {} });
2947
+ }, []);
2948
+ const handleStreamingEvent = useCallback((event) => {
2949
+ let handled = false;
2950
+ setStreaming((prev) => {
2951
+ const result = processStreamingEvent(event, prev);
2952
+ handled = result.handled;
2953
+ return result.newState;
2954
+ });
2955
+ return handled;
2956
+ }, []);
2957
+ const processEvent = useCallback((event) => {
2958
+ const newActivities = [];
2959
+ const addActivity = (activity) => newActivities.push(activity);
2960
+ processRunEventToActivity(stateRef.current, event, addActivity);
2961
+ if (newActivities.length > 0) {
2962
+ setActivities((prev) => [...prev, ...newActivities]);
2963
+ }
2964
+ const rootRunComplete = Array.from(stateRef.current.runStates.values()).some(
2965
+ (rs) => rs.isComplete && !rs.delegatedBy
2966
+ );
2967
+ setIsComplete(rootRunComplete);
2968
+ }, []);
2969
+ const clearRunStreaming = useCallback((runId) => {
2970
+ setStreaming((prev) => {
2971
+ const { [runId]: _, ...rest } = prev.runs;
2972
+ return { runs: rest };
2973
+ });
2974
+ }, []);
2975
+ const addEvent = useCallback(
2976
+ (event) => {
2977
+ if (isStreamingEvent(event)) {
2978
+ const handled = handleStreamingEvent(event);
2979
+ if (handled) {
2980
+ setEventCount((prev) => prev + 1);
2981
+ return;
2982
+ }
2983
+ }
2984
+ if ("type" in event && "runId" in event && (event.type === "completeRun" || event.type === "stopRunByError")) {
2985
+ clearRunStreaming(event.runId);
3501
2986
  }
2987
+ processEvent(event);
2988
+ setEventCount((prev) => prev + 1);
2989
+ },
2990
+ [handleStreamingEvent, clearRunStreaming, processEvent]
2991
+ );
2992
+ const appendHistoricalEvents = useCallback((historicalEvents) => {
2993
+ const newActivities = [];
2994
+ const addActivity = (activity) => newActivities.push(activity);
2995
+ for (const event of historicalEvents) {
2996
+ processRunEventToActivity(stateRef.current, event, addActivity);
2997
+ }
2998
+ if (newActivities.length > 0) {
2999
+ setActivities((prev) => [...prev, ...newActivities]);
3502
3000
  }
3001
+ setEventCount((prev) => prev + historicalEvents.length);
3002
+ const rootRunComplete = Array.from(stateRef.current.runStates.values()).some(
3003
+ (rs) => rs.isComplete && !rs.delegatedBy
3004
+ );
3005
+ setIsComplete(rootRunComplete);
3006
+ }, []);
3007
+ return {
3008
+ activities,
3009
+ streaming,
3010
+ isComplete,
3011
+ eventCount,
3012
+ addEvent,
3013
+ appendHistoricalEvents,
3014
+ clearStreaming
3015
+ };
3016
+ }
3017
+ var useRuntimeInfo = (options) => {
3018
+ const [runtimeInfo, setRuntimeInfo] = useState({
3019
+ status: "initializing",
3020
+ runtimeVersion: options.initialConfig.runtimeVersion,
3021
+ expertName: options.initialExpertName,
3022
+ model: options.initialConfig.model,
3023
+ maxSteps: options.initialConfig.maxSteps,
3024
+ maxRetries: options.initialConfig.maxRetries,
3025
+ timeout: options.initialConfig.timeout,
3026
+ activeSkills: [],
3027
+ contextWindowUsage: options.initialConfig.contextWindowUsage
3503
3028
  });
3504
- useInput(handleInput, { isActive });
3505
- if (runStatus === "running") {
3506
- return null;
3507
- }
3508
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
3509
- /* @__PURE__ */ jsxs(Text, { children: [
3510
- /* @__PURE__ */ jsx(Text, { color: runStatus === "completed" ? "green" : "yellow", bold: true, children: runStatus === "completed" ? "Completed" : "Stopped" }),
3511
- /* @__PURE__ */ jsx(Text, { color: "gray", children: " - Enter a follow-up query or wait to exit" })
3512
- ] }),
3513
- /* @__PURE__ */ jsxs(Box, { children: [
3514
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Continue: " }),
3515
- /* @__PURE__ */ jsx(Text, { children: input }),
3516
- /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3517
- ] })
3518
- ] });
3519
- };
3520
- var StatusPanel = ({
3521
- runtimeInfo,
3522
- eventCount,
3523
- runStatus
3524
- }) => {
3525
- if (runStatus !== "running") {
3029
+ const handleEvent = useCallback((event) => {
3030
+ if (event.type === "initializeRuntime") {
3031
+ setRuntimeInfo((prev) => ({
3032
+ runtimeVersion: event.runtimeVersion,
3033
+ expertName: event.expertName,
3034
+ model: event.model,
3035
+ maxSteps: event.maxSteps,
3036
+ maxRetries: event.maxRetries,
3037
+ timeout: event.timeout,
3038
+ currentStep: 1,
3039
+ status: "running",
3040
+ query: event.query,
3041
+ statusChangedAt: Date.now(),
3042
+ activeSkills: [],
3043
+ contextWindowUsage: prev.contextWindowUsage
3044
+ }));
3045
+ return { initialized: true };
3046
+ }
3047
+ if (event.type === "skillConnected") {
3048
+ setRuntimeInfo((prev) => ({
3049
+ ...prev,
3050
+ activeSkills: [...prev.activeSkills, event.skillName]
3051
+ }));
3052
+ return null;
3053
+ }
3054
+ if (event.type === "skillDisconnected") {
3055
+ setRuntimeInfo((prev) => ({
3056
+ ...prev,
3057
+ activeSkills: prev.activeSkills.filter((s) => s !== event.skillName)
3058
+ }));
3059
+ return null;
3060
+ }
3061
+ if ("stepNumber" in event) {
3062
+ const isComplete = event.type === "completeRun";
3063
+ const isStopped = STOP_EVENT_TYPES.includes(event.type);
3064
+ const checkpoint = "nextCheckpoint" in event ? event.nextCheckpoint : "checkpoint" in event ? event.checkpoint : void 0;
3065
+ setRuntimeInfo((prev) => ({
3066
+ ...prev,
3067
+ currentStep: event.stepNumber,
3068
+ status: isComplete ? "completed" : isStopped ? "stopped" : "running",
3069
+ ...isComplete || isStopped ? { statusChangedAt: Date.now() } : {},
3070
+ ...checkpoint?.contextWindowUsage !== void 0 ? { contextWindowUsage: checkpoint.contextWindowUsage } : {}
3071
+ }));
3072
+ if (isComplete) return { completed: true };
3073
+ if (isStopped) return { stopped: true };
3074
+ }
3526
3075
  return null;
3527
- }
3528
- return /* @__PURE__ */ jsx(RunSetting, { info: runtimeInfo, eventCount, isEditing: false });
3076
+ }, []);
3077
+ const setExpertName = useCallback((expertName) => {
3078
+ setRuntimeInfo((prev) => ({ ...prev, expertName }));
3079
+ }, []);
3080
+ const setQuery = useCallback((query) => {
3081
+ setRuntimeInfo((prev) => ({ ...prev, query }));
3082
+ }, []);
3083
+ const setCurrentStep = useCallback((step) => {
3084
+ setRuntimeInfo((prev) => ({ ...prev, currentStep: step }));
3085
+ }, []);
3086
+ const setContextWindowUsage = useCallback((contextWindowUsage) => {
3087
+ setRuntimeInfo((prev) => ({ ...prev, contextWindowUsage }));
3088
+ }, []);
3089
+ return {
3090
+ runtimeInfo,
3091
+ handleEvent,
3092
+ setExpertName,
3093
+ setQuery,
3094
+ setCurrentStep,
3095
+ setContextWindowUsage
3096
+ };
3529
3097
  };
3530
- var useExecutionState = (options) => {
3531
- const { expertKey, query, config: config2, continueTimeoutMs, historicalEvents, onReady, onComplete } = options;
3532
- const { exit } = useApp();
3533
- const runState = useRun();
3534
- const { runtimeInfo, handleEvent, setQuery } = useRuntimeInfo({
3535
- initialExpertName: expertKey,
3536
- initialConfig: config2
3098
+ var useLatestRef = (value) => {
3099
+ const ref = useRef(value);
3100
+ useInsertionEffect(() => {
3101
+ ref.current = value;
3537
3102
  });
3538
- const [runStatus, setRunStatus] = useState("running");
3539
- const [isAcceptingContinue, setIsAcceptingContinue] = useState(false);
3540
- const timeoutRef = useRef(null);
3541
- const clearTimeoutIfExists = useCallback(() => {
3542
- if (timeoutRef.current) {
3543
- clearTimeout(timeoutRef.current);
3544
- timeoutRef.current = null;
3545
- }
3546
- }, []);
3547
- const startExitTimeout = useCallback(() => {
3548
- clearTimeoutIfExists();
3549
- timeoutRef.current = setTimeout(() => {
3550
- onComplete({ nextQuery: null });
3551
- exit();
3552
- }, continueTimeoutMs);
3553
- }, [clearTimeoutIfExists, continueTimeoutMs, onComplete, exit]);
3554
- useEffect(() => {
3555
- setQuery(query);
3556
- }, [query, setQuery]);
3557
- useEffect(() => {
3558
- if (historicalEvents && historicalEvents.length > 0) {
3559
- runState.appendHistoricalEvents(historicalEvents);
3560
- }
3561
- }, [historicalEvents, runState.appendHistoricalEvents]);
3562
- useEffect(() => {
3563
- onReady((event) => {
3564
- runState.addEvent(event);
3565
- const result = handleEvent(event);
3566
- if (result?.completed) {
3567
- setRunStatus("completed");
3568
- setIsAcceptingContinue(true);
3569
- startExitTimeout();
3570
- } else if (result?.stopped) {
3571
- setRunStatus("stopped");
3572
- setIsAcceptingContinue(true);
3573
- startExitTimeout();
3103
+ return ref;
3104
+ };
3105
+
3106
+ // ../../packages/tui-components/src/hooks/use-text-input.ts
3107
+ var useTextInput = (options) => {
3108
+ const [input, setInput] = useState("");
3109
+ const inputRef = useLatestRef(input);
3110
+ const onSubmitRef = useLatestRef(options.onSubmit);
3111
+ const onCancelRef = useLatestRef(options.onCancel);
3112
+ const handleInput = useCallback(
3113
+ (inputChar, key) => {
3114
+ if (key.escape) {
3115
+ setInput("");
3116
+ onCancelRef.current?.();
3117
+ return;
3574
3118
  }
3575
- });
3576
- }, [onReady, runState.addEvent, handleEvent, startExitTimeout]);
3577
- useEffect(() => {
3578
- return () => {
3579
- clearTimeoutIfExists();
3580
- };
3581
- }, [clearTimeoutIfExists]);
3582
- const handleContinueSubmit = useCallback(
3583
- (newQuery) => {
3584
- if (isAcceptingContinue && newQuery.trim()) {
3585
- clearTimeoutIfExists();
3586
- onComplete({ nextQuery: newQuery.trim() });
3587
- exit();
3119
+ if (key.return && inputRef.current.trim()) {
3120
+ onSubmitRef.current(inputRef.current.trim());
3121
+ setInput("");
3122
+ return;
3123
+ }
3124
+ if (key.backspace || key.delete) {
3125
+ setInput((prev) => prev.slice(0, -1));
3126
+ return;
3127
+ }
3128
+ if (!key.ctrl && !key.meta && inputChar) {
3129
+ setInput((prev) => prev + inputChar);
3130
+ }
3131
+ },
3132
+ [inputRef, onSubmitRef, onCancelRef]
3133
+ );
3134
+ const reset = useCallback(() => {
3135
+ setInput("");
3136
+ }, []);
3137
+ return { input, handleInput, reset };
3138
+ };
3139
+
3140
+ // ../../packages/tui-components/src/hooks/ui/use-expert-selector.ts
3141
+ var useExpertSelector = (options) => {
3142
+ const { experts, onExpertSelect, extraKeyHandler } = options;
3143
+ const [inputMode, setInputMode] = useState(false);
3144
+ const { selectedIndex, handleNavigation } = useListNavigation({
3145
+ items: experts,
3146
+ onSelect: (expert) => onExpertSelect(expert.key)
3147
+ });
3148
+ const { input, handleInput, reset } = useTextInput({
3149
+ onSubmit: (value) => {
3150
+ onExpertSelect(value);
3151
+ setInputMode(false);
3152
+ },
3153
+ onCancel: () => setInputMode(false)
3154
+ });
3155
+ const handleKeyInput = useCallback(
3156
+ (inputChar, key) => {
3157
+ if (inputMode) {
3158
+ handleInput(inputChar, key);
3159
+ return;
3160
+ }
3161
+ if (handleNavigation(inputChar, key)) return;
3162
+ if (extraKeyHandler?.(inputChar, key)) return;
3163
+ if (inputChar === "i") {
3164
+ reset();
3165
+ setInputMode(true);
3588
3166
  }
3589
3167
  },
3590
- [isAcceptingContinue, clearTimeoutIfExists, onComplete, exit]
3168
+ [inputMode, handleInput, handleNavigation, extraKeyHandler, reset]
3591
3169
  );
3592
3170
  return {
3593
- activities: runState.activities,
3594
- streaming: runState.streaming,
3595
- eventCount: runState.eventCount,
3596
- runtimeInfo,
3597
- runStatus,
3598
- isAcceptingContinue,
3599
- handleContinueSubmit,
3600
- clearTimeout: clearTimeoutIfExists
3171
+ inputMode,
3172
+ input,
3173
+ selectedIndex,
3174
+ handleKeyInput
3601
3175
  };
3602
3176
  };
3603
- var ExecutionApp = (props) => {
3604
- const { expertKey, query, config: config2, continueTimeoutMs, historicalEvents, onReady, onComplete } = props;
3605
- const { exit } = useApp();
3606
- const state = useExecutionState({
3607
- expertKey,
3608
- query,
3609
- config: config2,
3610
- continueTimeoutMs,
3611
- historicalEvents,
3612
- onReady,
3613
- onComplete
3614
- });
3615
- useInput((input, key) => {
3616
- if (key.ctrl && input === "c") {
3617
- state.clearTimeout();
3618
- exit();
3619
- }
3620
- });
3621
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3622
- /* @__PURE__ */ jsx(ActivityLogPanel, { activities: state.activities }),
3623
- /* @__PURE__ */ jsx(StreamingDisplay, { streaming: state.streaming }),
3624
- /* @__PURE__ */ jsx(
3625
- StatusPanel,
3626
- {
3627
- runtimeInfo: state.runtimeInfo,
3628
- eventCount: state.eventCount,
3629
- runStatus: state.runStatus
3630
- }
3631
- ),
3632
- /* @__PURE__ */ jsx(
3633
- ContinueInputPanel,
3634
- {
3635
- isActive: state.isAcceptingContinue,
3636
- runStatus: state.runStatus,
3637
- onSubmit: state.handleContinueSubmit
3638
- }
3639
- )
3640
- ] });
3177
+ var ExpertList = ({
3178
+ experts,
3179
+ selectedIndex,
3180
+ showSource = false,
3181
+ inline = false,
3182
+ maxItems
3183
+ }) => {
3184
+ const displayExperts = maxItems ? experts.slice(0, maxItems) : experts;
3185
+ if (displayExperts.length === 0) {
3186
+ return /* @__PURE__ */ jsx(Text, { color: "gray", children: "No experts found." });
3187
+ }
3188
+ const items = displayExperts.map((expert, index) => /* @__PURE__ */ jsxs(Text, { color: index === selectedIndex ? "cyan" : "gray", children: [
3189
+ index === selectedIndex ? ">" : " ",
3190
+ " ",
3191
+ showSource ? expert.key : expert.name,
3192
+ showSource && expert.source && /* @__PURE__ */ jsxs(Fragment, { children: [
3193
+ " ",
3194
+ /* @__PURE__ */ jsxs(Text, { color: expert.source === "configured" ? "green" : "yellow", children: [
3195
+ "[",
3196
+ expert.source === "configured" ? "config" : "recent",
3197
+ "]"
3198
+ ] })
3199
+ ] }),
3200
+ inline ? " " : ""
3201
+ ] }, expert.key));
3202
+ return inline ? /* @__PURE__ */ jsx(Box, { children: items }) : /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: items });
3641
3203
  };
3642
- function renderExecution(params) {
3643
- const eventQueue = new EventQueue();
3644
- const result = new Promise((resolve, reject) => {
3645
- let resolved = false;
3646
- const { waitUntilExit } = render(
3204
+ var ExpertSelectorBase = ({
3205
+ experts,
3206
+ hint,
3207
+ onExpertSelect,
3208
+ showSource = false,
3209
+ inline = false,
3210
+ maxItems = UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
3211
+ extraKeyHandler
3212
+ }) => {
3213
+ const { inputMode, input, selectedIndex, handleKeyInput } = useExpertSelector({
3214
+ experts,
3215
+ onExpertSelect,
3216
+ extraKeyHandler
3217
+ });
3218
+ useInput(handleKeyInput);
3219
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: inline ? "row" : "column", children: [
3220
+ !inputMode && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3221
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { color: "cyan", children: hint }) }),
3647
3222
  /* @__PURE__ */ jsx(
3648
- ExecutionApp,
3223
+ ExpertList,
3649
3224
  {
3650
- ...params,
3651
- onReady: (handler) => {
3652
- eventQueue.setHandler(handler);
3653
- },
3654
- onComplete: (result2) => {
3655
- resolved = true;
3656
- resolve(result2);
3657
- }
3225
+ experts,
3226
+ selectedIndex,
3227
+ showSource,
3228
+ inline,
3229
+ maxItems
3658
3230
  }
3659
3231
  )
3660
- );
3661
- waitUntilExit().then(() => {
3662
- if (!resolved) {
3663
- reject(new Error("Execution cancelled"));
3664
- }
3665
- }).catch(reject);
3666
- });
3667
- return {
3668
- result,
3669
- eventListener: (event) => {
3670
- eventQueue.emit(event);
3671
- }
3672
- };
3673
- }
3674
- var selectionReducer = (_state, action) => {
3675
- switch (action.type) {
3676
- case "BROWSE_HISTORY":
3677
- return { type: "browsingHistory", jobs: action.jobs };
3678
- case "BROWSE_EXPERTS":
3679
- return { type: "browsingExperts", experts: action.experts };
3680
- case "SELECT_EXPERT":
3681
- return { type: "enteringQuery", expertKey: action.expertKey };
3682
- case "SELECT_JOB":
3683
- return { type: "browsingCheckpoints", job: action.job, checkpoints: action.checkpoints };
3684
- case "GO_BACK_FROM_CHECKPOINTS":
3685
- return { type: "browsingHistory", jobs: action.jobs };
3686
- default:
3687
- return assertNever(action);
3688
- }
3232
+ ] }),
3233
+ inputMode && /* @__PURE__ */ jsxs(Box, { children: [
3234
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
3235
+ /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
3236
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3237
+ ] })
3238
+ ] });
3689
3239
  };
3690
- var SelectionApp = (props) => {
3691
- const {
3692
- showHistory,
3693
- initialExpertKey,
3694
- initialQuery,
3695
- initialCheckpoint,
3696
- configuredExperts,
3697
- recentExperts,
3698
- historyJobs,
3699
- onLoadCheckpoints,
3700
- onComplete
3701
- } = props;
3702
- const { exit } = useApp();
3703
- const allExperts = useMemo(() => {
3704
- const configured = configuredExperts.map((e) => ({ ...e, source: "configured" }));
3705
- const recent = recentExperts.filter((e) => !configured.some((c) => c.key === e.key)).map((e) => ({ ...e, source: "recent" }));
3706
- return [...configured, ...recent];
3707
- }, [configuredExperts, recentExperts]);
3708
- const getInitialState = () => {
3709
- if (initialExpertKey && !initialQuery) {
3710
- return { type: "enteringQuery", expertKey: initialExpertKey };
3711
- }
3712
- if (showHistory && historyJobs.length > 0) {
3713
- return { type: "browsingHistory", jobs: historyJobs };
3714
- }
3715
- return { type: "browsingExperts", experts: allExperts };
3716
- };
3717
- const [state, dispatch] = useReducer(selectionReducer, void 0, getInitialState);
3718
- const [selectedCheckpoint, setSelectedCheckpoint] = useState(
3719
- initialCheckpoint
3720
- );
3721
- useEffect(() => {
3722
- if (initialExpertKey && initialQuery) {
3723
- onComplete({
3724
- expertKey: initialExpertKey,
3725
- query: initialQuery,
3726
- checkpoint: initialCheckpoint
3727
- });
3728
- exit();
3729
- }
3730
- }, [initialExpertKey, initialQuery, initialCheckpoint, onComplete, exit]);
3731
- const { input: queryInput, handleInput: handleQueryInput } = useTextInput({
3732
- onSubmit: (query) => {
3733
- if (state.type === "enteringQuery" && query.trim()) {
3734
- onComplete({
3735
- expertKey: state.expertKey,
3736
- query: query.trim(),
3737
- checkpoint: selectedCheckpoint
3738
- });
3739
- exit();
3240
+ var BrowsingExpertsInput = ({
3241
+ experts,
3242
+ onExpertSelect,
3243
+ onSwitchToHistory
3244
+ }) => {
3245
+ const extraKeyHandler = useCallback(
3246
+ (inputChar) => {
3247
+ if (inputChar === "h") {
3248
+ onSwitchToHistory();
3249
+ return true;
3740
3250
  }
3251
+ return false;
3252
+ },
3253
+ [onSwitchToHistory]
3254
+ );
3255
+ const hint = `Experts ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.SELECT} ${KEY_HINTS.INPUT} ${KEY_HINTS.HISTORY} ${KEY_HINTS.CANCEL}`;
3256
+ return /* @__PURE__ */ jsx(
3257
+ ExpertSelectorBase,
3258
+ {
3259
+ experts,
3260
+ hint,
3261
+ onExpertSelect,
3262
+ showSource: true,
3263
+ maxItems: UI_CONSTANTS.MAX_VISIBLE_LIST_ITEMS,
3264
+ extraKeyHandler
3741
3265
  }
3742
- });
3743
- useInput(handleQueryInput, { isActive: state.type === "enteringQuery" });
3744
- const handleExpertSelect = useCallback((expertKey) => {
3745
- dispatch({ type: "SELECT_EXPERT", expertKey });
3746
- }, []);
3747
- const handleJobSelect = useCallback(
3748
- async (job) => {
3749
- try {
3750
- const checkpoints = await onLoadCheckpoints(job);
3751
- dispatch({ type: "SELECT_JOB", job, checkpoints });
3752
- } catch {
3753
- dispatch({ type: "SELECT_JOB", job, checkpoints: [] });
3266
+ );
3267
+ };
3268
+ var BrowsingHistoryInput = ({
3269
+ jobs,
3270
+ onJobSelect,
3271
+ onJobResume,
3272
+ onSwitchToExperts
3273
+ }) => /* @__PURE__ */ jsx(
3274
+ ListBrowser,
3275
+ {
3276
+ title: `Job History ${KEY_HINTS.NAVIGATE} ${KEY_HINTS.RESUME} ${KEY_HINTS.CHECKPOINTS} ${KEY_HINTS.NEW}`,
3277
+ items: jobs,
3278
+ onSelect: onJobResume,
3279
+ emptyMessage: "No jobs found. Press n to start a new job.",
3280
+ extraKeyHandler: (char, _key, selected) => {
3281
+ if (char === "c" && selected) {
3282
+ onJobSelect(selected);
3283
+ return true;
3754
3284
  }
3755
- },
3756
- [onLoadCheckpoints]
3757
- );
3758
- const handleJobResume = useCallback(
3759
- async (job) => {
3760
- try {
3761
- const checkpoints = await onLoadCheckpoints(job);
3762
- const latestCheckpoint = checkpoints[0];
3763
- if (latestCheckpoint) {
3764
- setSelectedCheckpoint(latestCheckpoint);
3765
- }
3766
- dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
3767
- } catch {
3768
- dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
3285
+ if (char === "n") {
3286
+ onSwitchToExperts();
3287
+ return true;
3769
3288
  }
3289
+ return false;
3770
3290
  },
3771
- [onLoadCheckpoints]
3772
- );
3773
- const handleCheckpointResume = useCallback(
3774
- (checkpoint) => {
3775
- setSelectedCheckpoint(checkpoint);
3776
- if (state.type === "browsingCheckpoints") {
3777
- dispatch({ type: "SELECT_EXPERT", expertKey: state.job.expertKey });
3291
+ renderItem: (job, isSelected) => /* @__PURE__ */ jsxs(Text, { color: isSelected ? "cyan" : "gray", children: [
3292
+ isSelected ? ">" : " ",
3293
+ " ",
3294
+ job.expertKey,
3295
+ " - ",
3296
+ job.totalSteps,
3297
+ " steps (",
3298
+ job.jobId,
3299
+ ") (",
3300
+ formatTimestamp(job.startedAt),
3301
+ ")"
3302
+ ] }, job.jobId)
3303
+ }
3304
+ );
3305
+ var BrowserRouter = ({ inputState, showEventsHint = true }) => {
3306
+ const ctx = useInputAreaContext();
3307
+ const handleEventSelect = useCallback(
3308
+ (event) => {
3309
+ if (inputState.type === "browsingEvents") {
3310
+ ctx.onEventSelect(inputState, event);
3778
3311
  }
3779
3312
  },
3780
- [state]
3781
- );
3782
- const handleBack = useCallback(() => {
3783
- if (state.type === "browsingCheckpoints") {
3784
- dispatch({ type: "GO_BACK_FROM_CHECKPOINTS", jobs: historyJobs });
3785
- }
3786
- }, [state, historyJobs]);
3787
- const handleSwitchToExperts = useCallback(() => {
3788
- dispatch({ type: "BROWSE_EXPERTS", experts: allExperts });
3789
- }, [allExperts]);
3790
- const handleSwitchToHistory = useCallback(() => {
3791
- dispatch({ type: "BROWSE_HISTORY", jobs: historyJobs });
3792
- }, [historyJobs]);
3793
- useInput((input, key) => {
3794
- if (key.ctrl && input === "c") {
3795
- exit();
3796
- }
3797
- });
3798
- const contextValue = useMemo(
3799
- () => ({
3800
- onExpertSelect: handleExpertSelect,
3801
- onQuerySubmit: () => {
3802
- },
3803
- // Not used in browser
3804
- onJobSelect: handleJobSelect,
3805
- onJobResume: handleJobResume,
3806
- onCheckpointSelect: () => {
3807
- },
3808
- // Not used in selection (no event browsing)
3809
- onCheckpointResume: handleCheckpointResume,
3810
- onEventSelect: () => {
3811
- },
3812
- // Not used in selection
3813
- onBack: handleBack,
3814
- onSwitchToExperts: handleSwitchToExperts,
3815
- onSwitchToHistory: handleSwitchToHistory
3816
- }),
3817
- [
3818
- handleExpertSelect,
3819
- handleJobSelect,
3820
- handleJobResume,
3821
- handleCheckpointResume,
3822
- handleBack,
3823
- handleSwitchToExperts,
3824
- handleSwitchToHistory
3825
- ]
3313
+ [ctx.onEventSelect, inputState]
3826
3314
  );
3827
- if (initialExpertKey && initialQuery) {
3828
- return null;
3315
+ switch (inputState.type) {
3316
+ case "browsingHistory":
3317
+ return /* @__PURE__ */ jsx(
3318
+ BrowsingHistoryInput,
3319
+ {
3320
+ jobs: inputState.jobs,
3321
+ onJobSelect: ctx.onJobSelect,
3322
+ onJobResume: ctx.onJobResume,
3323
+ onSwitchToExperts: ctx.onSwitchToExperts
3324
+ }
3325
+ );
3326
+ case "browsingExperts":
3327
+ return /* @__PURE__ */ jsx(
3328
+ BrowsingExpertsInput,
3329
+ {
3330
+ experts: inputState.experts,
3331
+ onExpertSelect: ctx.onExpertSelect,
3332
+ onSwitchToHistory: ctx.onSwitchToHistory
3333
+ }
3334
+ );
3335
+ case "browsingCheckpoints":
3336
+ return /* @__PURE__ */ jsx(
3337
+ BrowsingCheckpointsInput,
3338
+ {
3339
+ job: inputState.job,
3340
+ checkpoints: inputState.checkpoints,
3341
+ onCheckpointSelect: ctx.onCheckpointSelect,
3342
+ onCheckpointResume: ctx.onCheckpointResume,
3343
+ onBack: ctx.onBack,
3344
+ showEventsHint
3345
+ }
3346
+ );
3347
+ case "browsingEvents":
3348
+ return /* @__PURE__ */ jsx(
3349
+ BrowsingEventsInput,
3350
+ {
3351
+ checkpoint: inputState.checkpoint,
3352
+ events: inputState.events,
3353
+ onEventSelect: handleEventSelect,
3354
+ onBack: ctx.onBack
3355
+ }
3356
+ );
3357
+ case "browsingEventDetail":
3358
+ return /* @__PURE__ */ jsx(BrowsingEventDetailInput, { event: inputState.selectedEvent, onBack: ctx.onBack });
3359
+ default:
3360
+ return assertNever(inputState);
3361
+ }
3362
+ };
3363
+ var ActionRowSimple = ({
3364
+ indicatorColor,
3365
+ text,
3366
+ textDimColor = false
3367
+ }) => /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
3368
+ /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }) }),
3369
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: textDimColor, children: text })
3370
+ ] }) });
3371
+ var ActionRow = ({ indicatorColor, label, summary, children }) => /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3372
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3373
+ /* @__PURE__ */ jsx(Text, { color: indicatorColor, children: INDICATOR.BULLET }),
3374
+ /* @__PURE__ */ jsx(Text, { color: "white", children: label }),
3375
+ summary && /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: summary })
3376
+ ] }),
3377
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
3378
+ /* @__PURE__ */ jsx(Box, { paddingRight: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: INDICATOR.TREE }) }),
3379
+ children
3380
+ ] })
3381
+ ] });
3382
+ var CheckpointActionRow = ({ action }) => {
3383
+ if (action.type === "parallelGroup") {
3384
+ return renderParallelGroup(action);
3829
3385
  }
3386
+ const actionElement = renderAction(action);
3387
+ if (!actionElement) return null;
3830
3388
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3831
- /* @__PURE__ */ jsx(InputAreaProvider, { value: contextValue, children: (state.type === "browsingHistory" || state.type === "browsingExperts" || state.type === "browsingCheckpoints") && /* @__PURE__ */ jsx(
3832
- BrowserRouter,
3833
- {
3834
- inputState: state,
3835
- showEventsHint: false
3836
- }
3837
- ) }),
3838
- state.type === "enteringQuery" && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
3839
- /* @__PURE__ */ jsxs(Text, { children: [
3840
- /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, children: "Expert:" }),
3841
- " ",
3842
- /* @__PURE__ */ jsx(Text, { children: state.expertKey }),
3843
- selectedCheckpoint && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
3844
- " (resuming from step ",
3845
- selectedCheckpoint.stepNumber,
3846
- ")"
3847
- ] })
3848
- ] }),
3849
- /* @__PURE__ */ jsxs(Box, { children: [
3850
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
3851
- /* @__PURE__ */ jsx(Text, { children: queryInput }),
3852
- /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3853
- ] }),
3854
- /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press Enter to start" })
3855
- ] })
3389
+ action.reasoning && renderReasoning(action.reasoning),
3390
+ actionElement
3856
3391
  ] });
3857
3392
  };
3858
- async function renderSelection(params) {
3859
- return new Promise((resolve, reject) => {
3860
- let resolved = false;
3861
- const { waitUntilExit } = render(
3862
- /* @__PURE__ */ jsx(
3863
- SelectionApp,
3393
+ function renderParallelGroup(group) {
3394
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3395
+ group.reasoning && renderReasoning(group.reasoning),
3396
+ group.activities.map((activity, index) => {
3397
+ const actionElement = renderAction(activity);
3398
+ if (!actionElement) return null;
3399
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: actionElement }, activity.id || `${activity.type}-${index}`);
3400
+ })
3401
+ ] });
3402
+ }
3403
+ function renderReasoning(text) {
3404
+ const lines = text.split("\n");
3405
+ 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}`)) }) });
3406
+ }
3407
+ function renderAction(action) {
3408
+ const color = action.type === "error" || "error" in action && action.error ? "red" : "green";
3409
+ switch (action.type) {
3410
+ case "query":
3411
+ return renderQuery(action.text, action.runId);
3412
+ case "retry":
3413
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Retry", children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: action.message || action.error }) });
3414
+ case "complete":
3415
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "green", label: "Run Results", children: /* @__PURE__ */ jsx(Text, { children: action.text }) });
3416
+ case "attemptCompletion": {
3417
+ if (action.error) {
3418
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: "Completion Failed", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error }) });
3419
+ }
3420
+ const remaining = action.remainingTodos?.filter((t) => !t.completed) ?? [];
3421
+ if (remaining.length > 0) {
3422
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: "Completion Blocked", children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3423
+ remaining.length,
3424
+ " remaining task",
3425
+ remaining.length > 1 ? "s" : ""
3426
+ ] }) });
3427
+ }
3428
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: "green", text: "Completion Accepted" });
3429
+ }
3430
+ case "todo":
3431
+ return renderTodo(action, color);
3432
+ case "clearTodo":
3433
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo Cleared" });
3434
+ case "readTextFile":
3435
+ return renderReadTextFile(action, color);
3436
+ case "writeTextFile":
3437
+ return renderWriteTextFile(action, color);
3438
+ case "editTextFile":
3439
+ return renderEditTextFile(action, color);
3440
+ case "appendTextFile":
3441
+ return renderAppendTextFile(action, color);
3442
+ case "deleteFile":
3443
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Removed" }) });
3444
+ case "deleteDirectory":
3445
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Delete Dir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3446
+ "Removed",
3447
+ action.recursive ? " (recursive)" : ""
3448
+ ] }) });
3449
+ case "moveFile":
3450
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Move", summary: shortenPath(action.source), children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3451
+ "\u2192 ",
3452
+ shortenPath(action.destination, 30)
3453
+ ] }) });
3454
+ case "createDirectory":
3455
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Mkdir", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Created" }) });
3456
+ case "listDirectory":
3457
+ return renderListDirectory(action, color);
3458
+ case "getFileInfo":
3459
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Info", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Fetched" }) });
3460
+ case "readPdfFile":
3461
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "PDF", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
3462
+ case "readImageFile":
3463
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Image", summary: shortenPath(action.path), children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Read" }) });
3464
+ case "exec":
3465
+ return renderExec(action, color);
3466
+ case "delegate":
3467
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "yellow", label: action.delegateExpertKey, children: /* @__PURE__ */ jsx(
3468
+ Text,
3864
3469
  {
3865
- ...params,
3866
- onComplete: (result) => {
3867
- resolved = true;
3868
- resolve(result);
3869
- }
3470
+ dimColor: true,
3471
+ children: `{"query":"${truncateText(action.query, UI_CONSTANTS.TRUNCATE_TEXT_MEDIUM)}"}`
3870
3472
  }
3871
- )
3872
- );
3873
- waitUntilExit().then(() => {
3874
- if (!resolved) {
3875
- reject(new Error("Selection cancelled"));
3876
- }
3877
- }).catch(reject);
3878
- });
3879
- }
3880
- function getEnv(envPath) {
3881
- const env = Object.fromEntries(
3882
- Object.entries(process.env).filter(([_, value]) => !!value).map(([key, value]) => [key, value])
3883
- );
3884
- dotenv.config({ path: envPath, processEnv: env, quiet: true });
3885
- return env;
3886
- }
3887
- var ALLOWED_CONFIG_HOSTS = ["raw.githubusercontent.com"];
3888
- async function getPerstackConfig(configPath) {
3889
- const configString = await findPerstackConfigString(configPath);
3890
- if (configString === null) {
3891
- throw new Error("perstack.toml not found. Create one or specify --config path.");
3473
+ ) });
3474
+ case "delegationComplete":
3475
+ return /* @__PURE__ */ jsx(
3476
+ ActionRowSimple,
3477
+ {
3478
+ indicatorColor: "green",
3479
+ text: `Delegation Complete (${action.count} delegate${action.count > 1 ? "s" : ""} returned)`
3480
+ }
3481
+ );
3482
+ case "interactiveTool":
3483
+ 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) }) });
3484
+ case "generalTool":
3485
+ 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) }) });
3486
+ case "error":
3487
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: "red", label: action.errorName ?? "Error", children: /* @__PURE__ */ jsx(Text, { color: "red", children: action.error ?? "Unknown error" }) });
3488
+ default: {
3489
+ return null;
3490
+ }
3892
3491
  }
3893
- return await parsePerstackConfig(configString);
3894
3492
  }
3895
- function isRemoteUrl(configPath) {
3896
- const lower = configPath.toLowerCase();
3897
- return lower.startsWith("https://") || lower.startsWith("http://");
3898
- }
3899
- async function fetchRemoteConfig(url) {
3900
- let parsed;
3901
- try {
3902
- parsed = new URL(url);
3903
- } catch {
3904
- throw new Error(`Invalid remote config URL: ${url}`);
3905
- }
3906
- if (parsed.protocol !== "https:") {
3907
- throw new Error("Remote config requires HTTPS");
3908
- }
3909
- if (!ALLOWED_CONFIG_HOSTS.includes(parsed.hostname)) {
3910
- throw new Error(`Remote config only allowed from: ${ALLOWED_CONFIG_HOSTS.join(", ")}`);
3493
+ function renderTodo(action, color) {
3494
+ const { newTodos, completedTodos, todos } = action;
3495
+ const hasNewTodos = newTodos && newTodos.length > 0;
3496
+ const hasCompletedTodos = completedTodos && completedTodos.length > 0;
3497
+ if (!hasNewTodos && !hasCompletedTodos) {
3498
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: "Todo No changes" });
3911
3499
  }
3912
- try {
3913
- const response = await fetch(url, { redirect: "error" });
3914
- if (!response.ok) {
3915
- throw new Error(`${response.status} ${response.statusText}`);
3916
- }
3917
- return await response.text();
3918
- } catch (error) {
3919
- const message = error instanceof Error ? error.message : String(error);
3920
- throw new Error(`Failed to fetch remote config: ${message}`);
3500
+ const labelParts = [];
3501
+ if (hasNewTodos) {
3502
+ labelParts.push(`Added ${newTodos.length} task${newTodos.length > 1 ? "s" : ""}`);
3921
3503
  }
3922
- }
3923
- async function findPerstackConfigString(configPath) {
3924
- if (configPath) {
3925
- if (isRemoteUrl(configPath)) {
3926
- return await fetchRemoteConfig(configPath);
3927
- }
3928
- try {
3929
- const tomlString = await readFile(path5.resolve(process.cwd(), configPath), "utf-8");
3930
- return tomlString;
3931
- } catch {
3932
- throw new Error(`Given config path "${configPath}" is not found`);
3933
- }
3504
+ if (hasCompletedTodos) {
3505
+ labelParts.push(
3506
+ `Completed ${completedTodos.length} task${completedTodos.length > 1 ? "s" : ""}`
3507
+ );
3934
3508
  }
3935
- return await findPerstackConfigStringRecursively(path5.resolve(process.cwd()));
3936
- }
3937
- async function findPerstackConfigStringRecursively(cwd) {
3938
- try {
3939
- const tomlString = await readFile(path5.resolve(cwd, "perstack.toml"), "utf-8");
3940
- return tomlString;
3941
- } catch {
3942
- if (cwd === path5.parse(cwd).root) {
3943
- return null;
3944
- }
3945
- return await findPerstackConfigStringRecursively(path5.dirname(cwd));
3509
+ const label = `Todo ${labelParts.join(", ")}`;
3510
+ const completedTitles = hasCompletedTodos ? completedTodos.map((id) => todos.find((t) => t.id === id)?.title).filter((t) => t !== void 0) : [];
3511
+ if (!hasNewTodos && completedTitles.length === 0) {
3512
+ return /* @__PURE__ */ jsx(ActionRowSimple, { indicatorColor: color, text: label });
3946
3513
  }
3514
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3515
+ hasNewTodos && newTodos.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((todo, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3516
+ "\u25CB ",
3517
+ todo
3518
+ ] }, `todo-${idx}`)),
3519
+ hasNewTodos && newTodos.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3520
+ "... +",
3521
+ newTodos.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
3522
+ " more"
3523
+ ] }),
3524
+ completedTitles.slice(0, RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW).map((title, idx) => /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3525
+ "\u2713 ",
3526
+ title
3527
+ ] }, `completed-${idx}`)),
3528
+ completedTitles.length > RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3529
+ "... +",
3530
+ completedTitles.length - RENDER_CONSTANTS.NEW_TODO_MAX_PREVIEW,
3531
+ " more"
3532
+ ] })
3533
+ ] }) });
3947
3534
  }
3948
- async function parsePerstackConfig(config2) {
3949
- const toml = TOML.parse(config2 ?? "");
3950
- return parseWithFriendlyError(perstackConfigSchema, toml, "perstack.toml");
3951
- }
3952
-
3953
- // ../../packages/tui/src/lib/provider-config.ts
3954
- function getProviderConfig(provider, env, providerTable) {
3955
- const setting = providerTable?.setting ?? {};
3956
- switch (provider) {
3957
- case "anthropic": {
3958
- const apiKey = env.ANTHROPIC_API_KEY;
3959
- if (!apiKey) throw new Error("ANTHROPIC_API_KEY is not set");
3960
- return {
3961
- providerName: "anthropic",
3962
- apiKey,
3963
- baseUrl: setting.baseUrl ?? env.ANTHROPIC_BASE_URL,
3964
- headers: setting.headers
3965
- };
3966
- }
3967
- case "google": {
3968
- const apiKey = env.GOOGLE_GENERATIVE_AI_API_KEY;
3969
- if (!apiKey) throw new Error("GOOGLE_GENERATIVE_AI_API_KEY is not set");
3970
- return {
3971
- providerName: "google",
3972
- apiKey,
3973
- baseUrl: setting.baseUrl ?? env.GOOGLE_GENERATIVE_AI_BASE_URL,
3974
- headers: setting.headers
3975
- };
3976
- }
3977
- case "openai": {
3978
- const apiKey = env.OPENAI_API_KEY;
3979
- if (!apiKey) throw new Error("OPENAI_API_KEY is not set");
3980
- return {
3981
- providerName: "openai",
3982
- apiKey,
3983
- baseUrl: setting.baseUrl ?? env.OPENAI_BASE_URL,
3984
- organization: setting.organization ?? env.OPENAI_ORGANIZATION,
3985
- project: setting.project ?? env.OPENAI_PROJECT,
3986
- name: setting.name,
3987
- headers: setting.headers
3988
- };
3989
- }
3990
- case "ollama": {
3991
- return {
3992
- providerName: "ollama",
3993
- baseUrl: setting.baseUrl ?? env.OLLAMA_BASE_URL,
3994
- headers: setting.headers
3995
- };
3996
- }
3997
- case "azure-openai": {
3998
- const apiKey = env.AZURE_API_KEY;
3999
- if (!apiKey) throw new Error("AZURE_API_KEY is not set");
4000
- const resourceName = setting.resourceName ?? env.AZURE_RESOURCE_NAME;
4001
- const baseUrl = setting.baseUrl ?? env.AZURE_BASE_URL;
4002
- if (!resourceName && !baseUrl) throw new Error("AZURE_RESOURCE_NAME or baseUrl is not set");
4003
- return {
4004
- providerName: "azure-openai",
4005
- apiKey,
4006
- resourceName,
4007
- apiVersion: setting.apiVersion ?? env.AZURE_API_VERSION,
4008
- baseUrl,
4009
- headers: setting.headers,
4010
- useDeploymentBasedUrls: setting.useDeploymentBasedUrls
4011
- };
4012
- }
4013
- case "amazon-bedrock": {
4014
- const accessKeyId = env.AWS_ACCESS_KEY_ID;
4015
- const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
4016
- const sessionToken = env.AWS_SESSION_TOKEN;
4017
- if (!accessKeyId) throw new Error("AWS_ACCESS_KEY_ID is not set");
4018
- if (!secretAccessKey) throw new Error("AWS_SECRET_ACCESS_KEY is not set");
4019
- const region = setting.region ?? env.AWS_REGION;
4020
- if (!region) throw new Error("AWS_REGION is not set");
4021
- return {
4022
- providerName: "amazon-bedrock",
4023
- accessKeyId,
4024
- secretAccessKey,
4025
- region,
4026
- sessionToken
4027
- };
4028
- }
4029
- case "google-vertex": {
4030
- return {
4031
- providerName: "google-vertex",
4032
- project: setting.project ?? env.GOOGLE_VERTEX_PROJECT,
4033
- location: setting.location ?? env.GOOGLE_VERTEX_LOCATION,
4034
- baseUrl: setting.baseUrl ?? env.GOOGLE_VERTEX_BASE_URL,
4035
- headers: setting.headers
4036
- };
4037
- }
4038
- case "deepseek": {
4039
- const apiKey = env.DEEPSEEK_API_KEY;
4040
- if (!apiKey) throw new Error("DEEPSEEK_API_KEY is not set");
4041
- return {
4042
- providerName: "deepseek",
4043
- apiKey,
4044
- baseUrl: setting.baseUrl ?? env.DEEPSEEK_BASE_URL,
4045
- headers: setting.headers
4046
- };
3535
+ function renderReadTextFile(action, color) {
3536
+ const { path: path6, content, from, to } = action;
3537
+ const lineRange = from !== void 0 && to !== void 0 ? `#${from}-${to}` : "";
3538
+ const lines = content?.split("\n") ?? [];
3539
+ return /* @__PURE__ */ jsx(
3540
+ ActionRow,
3541
+ {
3542
+ indicatorColor: color,
3543
+ label: "Read Text File",
3544
+ summary: `${shortenPath(path6)}${lineRange}`,
3545
+ 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}`)) })
4047
3546
  }
4048
- }
3547
+ );
4049
3548
  }
4050
- function getAllJobs2() {
4051
- return getAllJobs();
3549
+ function renderWriteTextFile(action, color) {
3550
+ const { path: path6, text } = action;
3551
+ const lines = text.split("\n");
3552
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Write Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3553
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3554
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3555
+ ] }, `write-${idx}`)) }) });
4052
3556
  }
4053
- function getAllRuns2() {
4054
- return getAllRuns();
3557
+ function renderEditTextFile(action, color) {
3558
+ const { path: path6, oldText, newText } = action;
3559
+ const oldLines = oldText.split("\n");
3560
+ const newLines = newText.split("\n");
3561
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Edit Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3562
+ oldLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3563
+ /* @__PURE__ */ jsx(Text, { color: "red", dimColor: true, children: "-" }),
3564
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3565
+ ] }, `old-${idx}`)),
3566
+ newLines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3567
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3568
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: line })
3569
+ ] }, `new-${idx}`))
3570
+ ] }) });
4055
3571
  }
4056
- function getMostRecentRun() {
4057
- const runs = getAllRuns2();
4058
- if (runs.length === 0) {
4059
- throw new Error("No runs found");
4060
- }
4061
- return runs[0];
3572
+ function renderAppendTextFile(action, color) {
3573
+ const { path: path6, text } = action;
3574
+ const lines = text.split("\n");
3575
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "Append Text File", summary: shortenPath(path6), children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: lines.map((line, idx) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", gap: 1, children: [
3576
+ /* @__PURE__ */ jsx(Text, { color: "green", dimColor: true, children: "+" }),
3577
+ /* @__PURE__ */ jsx(Text, { color: "white", dimColor: true, children: line })
3578
+ ] }, `append-${idx}`)) }) });
4062
3579
  }
4063
- function getCheckpointsByJobId2(jobId) {
4064
- return getCheckpointsByJobId(jobId);
3580
+ function renderListDirectory(action, color) {
3581
+ const { path: path6, items } = action;
3582
+ const itemLines = items?.map((item) => `${item.type === "directory" ? "\u{1F4C1}" : "\u{1F4C4}"} ${item.name}`) ?? [];
3583
+ const { visible, remaining } = summarizeOutput(itemLines, RENDER_CONSTANTS.LIST_DIR_MAX_ITEMS);
3584
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: "List", summary: shortenPath(path6), children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3585
+ visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `dir-${idx}`)),
3586
+ remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3587
+ "... +",
3588
+ remaining,
3589
+ " more"
3590
+ ] })
3591
+ ] }) });
4065
3592
  }
4066
- function getMostRecentCheckpoint(jobId) {
4067
- const targetJobId = jobId ?? getMostRecentRun().jobId;
4068
- const checkpoints = getCheckpointsByJobId2(targetJobId);
4069
- if (checkpoints.length === 0) {
4070
- throw new Error(`No checkpoints found for job ${targetJobId}`);
4071
- }
4072
- return checkpoints[checkpoints.length - 1];
3593
+ function renderExec(action, color) {
3594
+ const { command, args, cwd, output } = action;
3595
+ const cwdPart = cwd ? ` ${shortenPath(cwd, 40)}` : "";
3596
+ const cmdLine = truncateText(
3597
+ `${command} ${args.join(" ")}${cwdPart}`,
3598
+ UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT
3599
+ );
3600
+ const outputLines = output?.split("\n") ?? [];
3601
+ const { visible, remaining } = summarizeOutput(
3602
+ outputLines,
3603
+ RENDER_CONSTANTS.EXEC_OUTPUT_MAX_LINES
3604
+ );
3605
+ return /* @__PURE__ */ jsx(ActionRow, { indicatorColor: color, label: `Bash ${cmdLine}`, children: /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3606
+ visible.map((line, idx) => /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateText(line, UI_CONSTANTS.TRUNCATE_TEXT_DEFAULT) }, `out-${idx}`)),
3607
+ remaining > 0 && /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3608
+ "... +",
3609
+ remaining,
3610
+ " more"
3611
+ ] })
3612
+ ] }) });
4073
3613
  }
4074
- function getRecentExperts(limit) {
4075
- const runs = getAllRuns2();
4076
- const expertMap = /* @__PURE__ */ new Map();
4077
- for (const setting of runs) {
4078
- const expertKey = setting.expertKey;
4079
- if (!expertMap.has(expertKey) || expertMap.get(expertKey).lastUsed < setting.updatedAt) {
4080
- expertMap.set(expertKey, {
4081
- key: expertKey,
4082
- name: expertKey,
4083
- lastUsed: setting.updatedAt
4084
- });
3614
+ function renderQuery(text, runId) {
3615
+ const lines = text.split("\n");
3616
+ const shortRunId = runId.slice(0, 8);
3617
+ 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}`)) }) });
3618
+ }
3619
+ var RunSetting = ({
3620
+ info,
3621
+ eventCount,
3622
+ isEditing,
3623
+ expertName,
3624
+ onQuerySubmit
3625
+ }) => {
3626
+ const { input, handleInput } = useTextInput({
3627
+ onSubmit: onQuerySubmit ?? (() => {
3628
+ })
3629
+ });
3630
+ useInput(handleInput, { isActive: isEditing });
3631
+ const displayExpertName = expertName ?? info.expertName;
3632
+ const skills = info.activeSkills.length > 0 ? info.activeSkills.join(", ") : "";
3633
+ const step = info.currentStep !== void 0 ? String(info.currentStep) : "";
3634
+ const usagePercent = (info.contextWindowUsage * 100).toFixed(1);
3635
+ return /* @__PURE__ */ jsxs(
3636
+ Box,
3637
+ {
3638
+ flexDirection: "column",
3639
+ borderStyle: "single",
3640
+ borderColor: "gray",
3641
+ borderTop: true,
3642
+ borderBottom: false,
3643
+ borderLeft: false,
3644
+ borderRight: false,
3645
+ children: [
3646
+ /* @__PURE__ */ jsxs(Text, { children: [
3647
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "cyan", children: "Perstack" }),
3648
+ info.runtimeVersion && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
3649
+ " (v",
3650
+ info.runtimeVersion,
3651
+ ")"
3652
+ ] })
3653
+ ] }),
3654
+ /* @__PURE__ */ jsxs(Text, { children: [
3655
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Expert: " }),
3656
+ /* @__PURE__ */ jsx(Text, { color: "white", children: displayExpertName }),
3657
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Skills: " }),
3658
+ /* @__PURE__ */ jsx(Text, { color: "green", children: skills })
3659
+ ] }),
3660
+ /* @__PURE__ */ jsxs(Text, { children: [
3661
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Status: " }),
3662
+ /* @__PURE__ */ jsx(
3663
+ Text,
3664
+ {
3665
+ color: info.status === "running" ? "green" : info.status === "completed" ? "cyan" : "yellow",
3666
+ children: info.status
3667
+ }
3668
+ ),
3669
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Step: " }),
3670
+ /* @__PURE__ */ jsx(Text, { color: "white", children: step }),
3671
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Events: " }),
3672
+ /* @__PURE__ */ jsx(Text, { color: "white", children: eventCount }),
3673
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " / Usage: " }),
3674
+ /* @__PURE__ */ jsxs(Text, { color: "white", children: [
3675
+ usagePercent,
3676
+ "%"
3677
+ ] })
3678
+ ] }),
3679
+ /* @__PURE__ */ jsxs(Text, { children: [
3680
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Model: " }),
3681
+ /* @__PURE__ */ jsx(Text, { color: "white", children: info.model })
3682
+ ] }),
3683
+ /* @__PURE__ */ jsxs(Box, { children: [
3684
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
3685
+ isEditing ? /* @__PURE__ */ jsxs(Fragment, { children: [
3686
+ /* @__PURE__ */ jsx(Text, { color: "white", children: input }),
3687
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3688
+ ] }) : /* @__PURE__ */ jsx(Text, { color: "white", children: info.query })
3689
+ ] })
3690
+ ]
4085
3691
  }
4086
- }
4087
- return Array.from(expertMap.values()).sort((a, b) => b.lastUsed - a.lastUsed).slice(0, limit);
3692
+ );
3693
+ };
3694
+ var StreamingDisplay = ({ streaming }) => {
3695
+ const activeRuns = Object.entries(streaming.runs).filter(
3696
+ ([, run]) => run.isReasoningActive || run.isRunResultActive
3697
+ );
3698
+ if (activeRuns.length === 0) return null;
3699
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginY: 1, children: activeRuns.map(([runId, run]) => /* @__PURE__ */ jsx(StreamingRunSection, { run }, runId)) });
3700
+ };
3701
+ function StreamingRunSection({ run }) {
3702
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3703
+ run.isReasoningActive && run.reasoning !== void 0 && /* @__PURE__ */ jsx(StreamingReasoning, { expertKey: run.expertKey, text: run.reasoning }),
3704
+ run.isRunResultActive && run.runResult !== void 0 && /* @__PURE__ */ jsx(StreamingRunResult, { expertKey: run.expertKey, text: run.runResult })
3705
+ ] });
4088
3706
  }
4089
- function getCheckpointById(jobId, checkpointId) {
4090
- const checkpointPath = getCheckpointPath(jobId, checkpointId);
4091
- if (!existsSync(checkpointPath)) {
4092
- throw new Error(`Checkpoint ${checkpointId} not found in job ${jobId}`);
3707
+ function StreamingReasoning({
3708
+ expertKey,
3709
+ text
3710
+ }) {
3711
+ const lines = text.split("\n");
3712
+ const label = `[${formatExpertKey(expertKey)}] Reasoning...`;
3713
+ 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}`)) }) });
3714
+ }
3715
+ function StreamingRunResult({
3716
+ expertKey,
3717
+ text
3718
+ }) {
3719
+ const lines = text.split("\n");
3720
+ const label = `[${formatExpertKey(expertKey)}] Generating...`;
3721
+ 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}`)) }) });
3722
+ }
3723
+ function formatExpertKey(expertKey) {
3724
+ const atIndex = expertKey.lastIndexOf("@");
3725
+ if (atIndex > 0) {
3726
+ return expertKey.substring(0, atIndex);
4093
3727
  }
4094
- const checkpoint = readFileSync(checkpointPath, "utf-8");
4095
- return checkpointSchema.parse(JSON.parse(checkpoint));
3728
+ return expertKey;
4096
3729
  }
4097
- function getCheckpointsWithDetails(jobId) {
4098
- return getCheckpointsByJobId2(jobId).map((cp) => ({
4099
- id: cp.id,
4100
- runId: cp.runId,
4101
- stepNumber: cp.stepNumber,
4102
- contextWindowUsage: cp.contextWindowUsage ?? 0
4103
- })).sort((a, b) => b.stepNumber - a.stepNumber);
3730
+ function getActivityKey(activityOrGroup, index) {
3731
+ return activityOrGroup.id || `activity-${index}`;
4104
3732
  }
4105
- function getAllEventContentsForJob(jobId, maxStepNumber) {
4106
- const runIds = getRunIdsByJobId(jobId);
4107
- const allEvents = [];
4108
- for (const runId of runIds) {
4109
- const events = getEventContents(jobId, runId, maxStepNumber);
4110
- allEvents.push(...events);
3733
+ var RunBox = ({ node, isRoot }) => {
3734
+ if (isRoot) {
3735
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3736
+ node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
3737
+ node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
3738
+ ] });
3739
+ }
3740
+ const shortRunId = node.runId.slice(0, 8);
3741
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", marginLeft: 1, children: [
3742
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, bold: true, children: [
3743
+ "[",
3744
+ node.expertKey,
3745
+ "] ",
3746
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
3747
+ "(",
3748
+ shortRunId,
3749
+ ")"
3750
+ ] })
3751
+ ] }),
3752
+ node.activities.map((activity, index) => /* @__PURE__ */ jsx(CheckpointActionRow, { action: activity }, getActivityKey(activity, index))),
3753
+ node.children.map((child) => /* @__PURE__ */ jsx(RunBox, { node: child, isRoot: false }, child.runId))
3754
+ ] });
3755
+ };
3756
+ function getActivityProps(activityOrGroup) {
3757
+ if (activityOrGroup.type === "parallelGroup") {
3758
+ const group = activityOrGroup;
3759
+ const firstActivity = group.activities[0];
3760
+ return {
3761
+ runId: group.runId,
3762
+ expertKey: group.expertKey,
3763
+ delegatedBy: firstActivity?.delegatedBy
3764
+ };
4111
3765
  }
4112
- return allEvents.sort((a, b) => a.timestamp - b.timestamp);
3766
+ return activityOrGroup;
4113
3767
  }
4114
-
4115
- // ../../packages/tui/src/lib/context.ts
4116
- var defaultProvider = "anthropic";
4117
- var defaultModel = "claude-sonnet-4-5";
4118
- async function resolveRunContext(input) {
4119
- const perstackConfig = input.perstackConfig ?? await getPerstackConfig(input.configPath);
4120
- let checkpoint;
4121
- if (input.resumeFrom) {
4122
- if (!input.continueJob) {
4123
- throw new Error("--resume-from requires --continue-job");
3768
+ var ActivityLogPanel = ({ activities }) => {
3769
+ const rootNodes = useMemo(() => {
3770
+ const nodeMap = /* @__PURE__ */ new Map();
3771
+ const roots = [];
3772
+ const orphanChildren = /* @__PURE__ */ new Map();
3773
+ for (const activityOrGroup of activities) {
3774
+ const { runId, expertKey, delegatedBy } = getActivityProps(activityOrGroup);
3775
+ let node = nodeMap.get(runId);
3776
+ if (!node) {
3777
+ node = {
3778
+ runId,
3779
+ expertKey,
3780
+ activities: [],
3781
+ children: []
3782
+ };
3783
+ nodeMap.set(runId, node);
3784
+ const waitingChildren = orphanChildren.get(runId);
3785
+ if (waitingChildren) {
3786
+ for (const child of waitingChildren) {
3787
+ node.children.push(child);
3788
+ const rootIndex = roots.indexOf(child);
3789
+ if (rootIndex !== -1) {
3790
+ roots.splice(rootIndex, 1);
3791
+ }
3792
+ }
3793
+ orphanChildren.delete(runId);
3794
+ }
3795
+ if (delegatedBy) {
3796
+ const parentNode = nodeMap.get(delegatedBy.runId);
3797
+ if (parentNode) {
3798
+ parentNode.children.push(node);
3799
+ } else {
3800
+ const orphans = orphanChildren.get(delegatedBy.runId) ?? [];
3801
+ orphans.push(node);
3802
+ orphanChildren.set(delegatedBy.runId, orphans);
3803
+ roots.push(node);
3804
+ }
3805
+ } else {
3806
+ roots.push(node);
3807
+ }
3808
+ }
3809
+ node.activities.push(activityOrGroup);
4124
3810
  }
4125
- checkpoint = getCheckpointById(input.continueJob, input.resumeFrom);
4126
- } else if (input.continueJob) {
4127
- checkpoint = getMostRecentCheckpoint(input.continueJob);
4128
- } else if (input.continue) {
4129
- checkpoint = getMostRecentCheckpoint();
4130
- }
4131
- if ((input.continue || input.continueJob || input.resumeFrom) && !checkpoint) {
4132
- throw new Error("No checkpoint found");
3811
+ return roots;
3812
+ }, [activities]);
3813
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: rootNodes.map((node) => /* @__PURE__ */ jsx(RunBox, { node, isRoot: true }, node.runId)) });
3814
+ };
3815
+ var ContinueInputPanel = ({
3816
+ isActive,
3817
+ runStatus,
3818
+ onSubmit
3819
+ }) => {
3820
+ const { input, handleInput } = useTextInput({
3821
+ onSubmit: (newQuery) => {
3822
+ if (isActive && newQuery.trim()) {
3823
+ onSubmit(newQuery.trim());
3824
+ }
3825
+ }
3826
+ });
3827
+ useInput(handleInput, { isActive });
3828
+ if (runStatus === "running") {
3829
+ return null;
4133
3830
  }
4134
- if (checkpoint && input.expertKey && checkpoint.expert.key !== input.expertKey) {
4135
- throw new Error(
4136
- `Checkpoint expert key ${checkpoint.expert.key} does not match input expert key ${input.expertKey}`
4137
- );
3831
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
3832
+ /* @__PURE__ */ jsxs(Text, { children: [
3833
+ /* @__PURE__ */ jsx(Text, { color: runStatus === "completed" ? "green" : "yellow", bold: true, children: runStatus === "completed" ? "Completed" : "Stopped" }),
3834
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: " - Enter a follow-up query or wait to exit" })
3835
+ ] }),
3836
+ /* @__PURE__ */ jsxs(Box, { children: [
3837
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Continue: " }),
3838
+ /* @__PURE__ */ jsx(Text, { children: input }),
3839
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
3840
+ ] })
3841
+ ] });
3842
+ };
3843
+ var StatusPanel = ({
3844
+ runtimeInfo,
3845
+ eventCount,
3846
+ runStatus
3847
+ }) => {
3848
+ if (runStatus !== "running") {
3849
+ return null;
4138
3850
  }
4139
- const envPath = input.envPath && input.envPath.length > 0 ? input.envPath : perstackConfig.envPath ?? [".env", ".env.local"];
4140
- const env = getEnv(envPath);
4141
- const provider = input.provider ?? perstackConfig.provider?.providerName ?? defaultProvider;
4142
- const model = input.model ?? perstackConfig.model ?? defaultModel;
4143
- const providerConfig = getProviderConfig(provider, env, perstackConfig.provider);
4144
- const experts = Object.fromEntries(
4145
- Object.entries(perstackConfig.experts ?? {}).map(([name, expert]) => {
4146
- return [
4147
- name,
3851
+ return /* @__PURE__ */ jsx(RunSetting, { info: runtimeInfo, eventCount, isEditing: false });
3852
+ };
3853
+ var useExecutionState = (options) => {
3854
+ const { expertKey, query, config: config2, continueTimeoutMs, historicalEvents, onReady, onComplete } = options;
3855
+ const { exit } = useApp();
3856
+ const runState = useRun();
3857
+ const { runtimeInfo, handleEvent, setQuery } = useRuntimeInfo({
3858
+ initialExpertName: expertKey,
3859
+ initialConfig: config2
3860
+ });
3861
+ const [runStatus, setRunStatus] = useState("running");
3862
+ const [isAcceptingContinue, setIsAcceptingContinue] = useState(false);
3863
+ const timeoutRef = useRef(null);
3864
+ const clearTimeoutIfExists = useCallback(() => {
3865
+ if (timeoutRef.current) {
3866
+ clearTimeout(timeoutRef.current);
3867
+ timeoutRef.current = null;
3868
+ }
3869
+ }, []);
3870
+ const startExitTimeout = useCallback(() => {
3871
+ clearTimeoutIfExists();
3872
+ timeoutRef.current = setTimeout(() => {
3873
+ onComplete({ nextQuery: null });
3874
+ exit();
3875
+ }, continueTimeoutMs);
3876
+ }, [clearTimeoutIfExists, continueTimeoutMs, onComplete, exit]);
3877
+ useEffect(() => {
3878
+ setQuery(query);
3879
+ }, [query, setQuery]);
3880
+ useEffect(() => {
3881
+ if (historicalEvents && historicalEvents.length > 0) {
3882
+ runState.appendHistoricalEvents(historicalEvents);
3883
+ }
3884
+ }, [historicalEvents, runState.appendHistoricalEvents]);
3885
+ useEffect(() => {
3886
+ onReady((event) => {
3887
+ runState.addEvent(event);
3888
+ const result = handleEvent(event);
3889
+ if (result?.completed) {
3890
+ setRunStatus("completed");
3891
+ setIsAcceptingContinue(true);
3892
+ startExitTimeout();
3893
+ } else if (result?.stopped) {
3894
+ setRunStatus("stopped");
3895
+ setIsAcceptingContinue(true);
3896
+ startExitTimeout();
3897
+ }
3898
+ });
3899
+ }, [onReady, runState.addEvent, handleEvent, startExitTimeout]);
3900
+ useEffect(() => {
3901
+ return () => {
3902
+ clearTimeoutIfExists();
3903
+ };
3904
+ }, [clearTimeoutIfExists]);
3905
+ const handleContinueSubmit = useCallback(
3906
+ (newQuery) => {
3907
+ if (isAcceptingContinue && newQuery.trim()) {
3908
+ clearTimeoutIfExists();
3909
+ onComplete({ nextQuery: newQuery.trim() });
3910
+ exit();
3911
+ }
3912
+ },
3913
+ [isAcceptingContinue, clearTimeoutIfExists, onComplete, exit]
3914
+ );
3915
+ return {
3916
+ activities: runState.activities,
3917
+ streaming: runState.streaming,
3918
+ eventCount: runState.eventCount,
3919
+ runtimeInfo,
3920
+ runStatus,
3921
+ isAcceptingContinue,
3922
+ handleContinueSubmit,
3923
+ clearTimeout: clearTimeoutIfExists
3924
+ };
3925
+ };
3926
+ var ExecutionApp = (props) => {
3927
+ const { expertKey, query, config: config2, continueTimeoutMs, historicalEvents, onReady, onComplete } = props;
3928
+ const { exit } = useApp();
3929
+ const state = useExecutionState({
3930
+ expertKey,
3931
+ query,
3932
+ config: config2,
3933
+ continueTimeoutMs,
3934
+ historicalEvents,
3935
+ onReady,
3936
+ onComplete
3937
+ });
3938
+ useInput((input, key) => {
3939
+ if (key.ctrl && input === "c") {
3940
+ state.clearTimeout();
3941
+ exit();
3942
+ }
3943
+ });
3944
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3945
+ /* @__PURE__ */ jsx(ActivityLogPanel, { activities: state.activities }),
3946
+ /* @__PURE__ */ jsx(StreamingDisplay, { streaming: state.streaming }),
3947
+ /* @__PURE__ */ jsx(
3948
+ StatusPanel,
3949
+ {
3950
+ runtimeInfo: state.runtimeInfo,
3951
+ eventCount: state.eventCount,
3952
+ runStatus: state.runStatus
3953
+ }
3954
+ ),
3955
+ /* @__PURE__ */ jsx(
3956
+ ContinueInputPanel,
3957
+ {
3958
+ isActive: state.isAcceptingContinue,
3959
+ runStatus: state.runStatus,
3960
+ onSubmit: state.handleContinueSubmit
3961
+ }
3962
+ )
3963
+ ] });
3964
+ };
3965
+ function renderExecution(params) {
3966
+ const eventQueue = new EventQueue();
3967
+ const result = new Promise((resolve, reject) => {
3968
+ let resolved = false;
3969
+ const { waitUntilExit } = render(
3970
+ /* @__PURE__ */ jsx(
3971
+ ExecutionApp,
4148
3972
  {
4149
- name,
4150
- version: expert.version ?? "1.0.0",
4151
- description: expert.description,
4152
- instruction: expert.instruction,
4153
- skills: expert.skills,
4154
- delegates: expert.delegates,
4155
- tags: expert.tags
3973
+ ...params,
3974
+ onReady: (handler) => {
3975
+ eventQueue.setHandler(handler);
3976
+ },
3977
+ onComplete: (result2) => {
3978
+ resolved = true;
3979
+ resolve(result2);
3980
+ }
4156
3981
  }
4157
- ];
4158
- })
4159
- );
3982
+ )
3983
+ );
3984
+ waitUntilExit().then(() => {
3985
+ if (!resolved) {
3986
+ reject(new Error("Execution cancelled"));
3987
+ }
3988
+ }).catch(reject);
3989
+ });
4160
3990
  return {
4161
- perstackConfig,
4162
- checkpoint,
4163
- env,
4164
- providerConfig,
4165
- model,
4166
- experts
3991
+ result,
3992
+ eventListener: (event) => {
3993
+ eventQueue.emit(event);
3994
+ }
4167
3995
  };
4168
3996
  }
4169
-
4170
- // ../../packages/tui/src/lib/interactive.ts
4171
- function parseInteractiveToolCallResult(query, checkpoint) {
4172
- const lastMessage = checkpoint.messages[checkpoint.messages.length - 1];
4173
- if (lastMessage.type !== "expertMessage") {
4174
- throw new Error("Last message is not a expert message");
4175
- }
4176
- const content = lastMessage.contents.find((c) => c.type === "toolCallPart");
4177
- if (!content || content.type !== "toolCallPart") {
4178
- throw new Error("Last message content is not a tool call part");
3997
+ var selectionReducer = (_state, action) => {
3998
+ switch (action.type) {
3999
+ case "BROWSE_HISTORY":
4000
+ return { type: "browsingHistory", jobs: action.jobs };
4001
+ case "BROWSE_EXPERTS":
4002
+ return { type: "browsingExperts", experts: action.experts };
4003
+ case "SELECT_EXPERT":
4004
+ return { type: "enteringQuery", expertKey: action.expertKey };
4005
+ case "SELECT_JOB":
4006
+ return { type: "browsingCheckpoints", job: action.job, checkpoints: action.checkpoints };
4007
+ case "GO_BACK_FROM_CHECKPOINTS":
4008
+ return { type: "browsingHistory", jobs: action.jobs };
4009
+ default:
4010
+ return assertNever(action);
4179
4011
  }
4180
- const toolCallId = content.toolCallId;
4181
- const toolName = content.toolName;
4182
- const pendingToolCall = checkpoint.pendingToolCalls?.find((tc) => tc.id === toolCallId);
4183
- const skillName = pendingToolCall?.skillName ?? "";
4184
- return {
4185
- interactiveToolCallResult: {
4186
- toolCallId,
4187
- toolName,
4188
- skillName,
4189
- text: query
4012
+ };
4013
+ var SelectionApp = (props) => {
4014
+ const {
4015
+ showHistory,
4016
+ initialExpertKey,
4017
+ initialQuery,
4018
+ initialCheckpoint,
4019
+ configuredExperts,
4020
+ recentExperts,
4021
+ historyJobs,
4022
+ onLoadCheckpoints,
4023
+ onComplete
4024
+ } = props;
4025
+ const { exit } = useApp();
4026
+ const allExperts = useMemo(() => {
4027
+ const configured = configuredExperts.map((e) => ({ ...e, source: "configured" }));
4028
+ const recent = recentExperts.filter((e) => !configured.some((c) => c.key === e.key)).map((e) => ({ ...e, source: "recent" }));
4029
+ return [...configured, ...recent];
4030
+ }, [configuredExperts, recentExperts]);
4031
+ const getInitialState = () => {
4032
+ if (initialExpertKey && !initialQuery) {
4033
+ return { type: "enteringQuery", expertKey: initialExpertKey };
4190
4034
  }
4035
+ if (showHistory && historyJobs.length > 0) {
4036
+ return { type: "browsingHistory", jobs: historyJobs };
4037
+ }
4038
+ return { type: "browsingExperts", experts: allExperts };
4191
4039
  };
4040
+ const [state, dispatch] = useReducer(selectionReducer, void 0, getInitialState);
4041
+ const [selectedCheckpoint, setSelectedCheckpoint] = useState(
4042
+ initialCheckpoint
4043
+ );
4044
+ useEffect(() => {
4045
+ if (initialExpertKey && initialQuery) {
4046
+ onComplete({
4047
+ expertKey: initialExpertKey,
4048
+ query: initialQuery,
4049
+ checkpoint: initialCheckpoint
4050
+ });
4051
+ exit();
4052
+ }
4053
+ }, [initialExpertKey, initialQuery, initialCheckpoint, onComplete, exit]);
4054
+ const { input: queryInput, handleInput: handleQueryInput } = useTextInput({
4055
+ onSubmit: (query) => {
4056
+ if (state.type === "enteringQuery" && query.trim()) {
4057
+ onComplete({
4058
+ expertKey: state.expertKey,
4059
+ query: query.trim(),
4060
+ checkpoint: selectedCheckpoint
4061
+ });
4062
+ exit();
4063
+ }
4064
+ }
4065
+ });
4066
+ useInput(handleQueryInput, { isActive: state.type === "enteringQuery" });
4067
+ const handleExpertSelect = useCallback((expertKey) => {
4068
+ dispatch({ type: "SELECT_EXPERT", expertKey });
4069
+ }, []);
4070
+ const handleJobSelect = useCallback(
4071
+ async (job) => {
4072
+ try {
4073
+ const checkpoints = await onLoadCheckpoints(job);
4074
+ dispatch({ type: "SELECT_JOB", job, checkpoints });
4075
+ } catch {
4076
+ dispatch({ type: "SELECT_JOB", job, checkpoints: [] });
4077
+ }
4078
+ },
4079
+ [onLoadCheckpoints]
4080
+ );
4081
+ const handleJobResume = useCallback(
4082
+ async (job) => {
4083
+ try {
4084
+ const checkpoints = await onLoadCheckpoints(job);
4085
+ const latestCheckpoint = checkpoints[0];
4086
+ if (latestCheckpoint) {
4087
+ setSelectedCheckpoint(latestCheckpoint);
4088
+ }
4089
+ dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
4090
+ } catch {
4091
+ dispatch({ type: "SELECT_EXPERT", expertKey: job.expertKey });
4092
+ }
4093
+ },
4094
+ [onLoadCheckpoints]
4095
+ );
4096
+ const handleCheckpointResume = useCallback(
4097
+ (checkpoint) => {
4098
+ setSelectedCheckpoint(checkpoint);
4099
+ if (state.type === "browsingCheckpoints") {
4100
+ dispatch({ type: "SELECT_EXPERT", expertKey: state.job.expertKey });
4101
+ }
4102
+ },
4103
+ [state]
4104
+ );
4105
+ const handleBack = useCallback(() => {
4106
+ if (state.type === "browsingCheckpoints") {
4107
+ dispatch({ type: "GO_BACK_FROM_CHECKPOINTS", jobs: historyJobs });
4108
+ }
4109
+ }, [state, historyJobs]);
4110
+ const handleSwitchToExperts = useCallback(() => {
4111
+ dispatch({ type: "BROWSE_EXPERTS", experts: allExperts });
4112
+ }, [allExperts]);
4113
+ const handleSwitchToHistory = useCallback(() => {
4114
+ dispatch({ type: "BROWSE_HISTORY", jobs: historyJobs });
4115
+ }, [historyJobs]);
4116
+ useInput((input, key) => {
4117
+ if (key.ctrl && input === "c") {
4118
+ exit();
4119
+ }
4120
+ });
4121
+ const contextValue = useMemo(
4122
+ () => ({
4123
+ onExpertSelect: handleExpertSelect,
4124
+ onQuerySubmit: () => {
4125
+ },
4126
+ // Not used in browser
4127
+ onJobSelect: handleJobSelect,
4128
+ onJobResume: handleJobResume,
4129
+ onCheckpointSelect: () => {
4130
+ },
4131
+ // Not used in selection (no event browsing)
4132
+ onCheckpointResume: handleCheckpointResume,
4133
+ onEventSelect: () => {
4134
+ },
4135
+ // Not used in selection
4136
+ onBack: handleBack,
4137
+ onSwitchToExperts: handleSwitchToExperts,
4138
+ onSwitchToHistory: handleSwitchToHistory
4139
+ }),
4140
+ [
4141
+ handleExpertSelect,
4142
+ handleJobSelect,
4143
+ handleJobResume,
4144
+ handleCheckpointResume,
4145
+ handleBack,
4146
+ handleSwitchToExperts,
4147
+ handleSwitchToHistory
4148
+ ]
4149
+ );
4150
+ if (initialExpertKey && initialQuery) {
4151
+ return null;
4152
+ }
4153
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
4154
+ /* @__PURE__ */ jsx(InputAreaProvider, { value: contextValue, children: (state.type === "browsingHistory" || state.type === "browsingExperts" || state.type === "browsingCheckpoints") && /* @__PURE__ */ jsx(
4155
+ BrowserRouter,
4156
+ {
4157
+ inputState: state,
4158
+ showEventsHint: false
4159
+ }
4160
+ ) }),
4161
+ state.type === "enteringQuery" && /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", children: [
4162
+ /* @__PURE__ */ jsxs(Text, { children: [
4163
+ /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, children: "Expert:" }),
4164
+ " ",
4165
+ /* @__PURE__ */ jsx(Text, { children: state.expertKey }),
4166
+ selectedCheckpoint && /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
4167
+ " (resuming from step ",
4168
+ selectedCheckpoint.stepNumber,
4169
+ ")"
4170
+ ] })
4171
+ ] }),
4172
+ /* @__PURE__ */ jsxs(Box, { children: [
4173
+ /* @__PURE__ */ jsx(Text, { color: "gray", children: "Query: " }),
4174
+ /* @__PURE__ */ jsx(Text, { children: queryInput }),
4175
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "_" })
4176
+ ] }),
4177
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Press Enter to start" })
4178
+ ] })
4179
+ ] });
4180
+ };
4181
+ async function renderSelection(params) {
4182
+ return new Promise((resolve, reject) => {
4183
+ let resolved = false;
4184
+ const { waitUntilExit } = render(
4185
+ /* @__PURE__ */ jsx(
4186
+ SelectionApp,
4187
+ {
4188
+ ...params,
4189
+ onComplete: (result) => {
4190
+ resolved = true;
4191
+ resolve(result);
4192
+ }
4193
+ }
4194
+ )
4195
+ );
4196
+ waitUntilExit().then(() => {
4197
+ if (!resolved) {
4198
+ reject(new Error("Selection cancelled"));
4199
+ }
4200
+ }).catch(reject);
4201
+ });
4192
4202
  }
4193
4203
 
4194
4204
  // ../../packages/tui/src/start-handler.ts
@@ -4343,13 +4353,6 @@ var config = parseWithFriendlyError(
4343
4353
  perstackConfigSchema,
4344
4354
  TOML.parse(readFileSync(tomlPath, "utf-8"))
4345
4355
  );
4346
- var PROVIDER_ENV_MAP = {
4347
- anthropic: "ANTHROPIC_API_KEY",
4348
- google: "GOOGLE_GENERATIVE_AI_API_KEY",
4349
- openai: "OPENAI_API_KEY",
4350
- deepseek: "DEEPSEEK_API_KEY",
4351
- "azure-openai": "AZURE_API_KEY"
4352
- };
4353
4356
  new Command().name("create-expert").description("Create and modify Perstack expert definitions").argument("<query>", "Description of the expert to create or modify").action(async (query) => {
4354
4357
  await startHandler(
4355
4358
  "expert",