Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/extract-tui-packages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

refactor: extract TUI code into @perstack/tui-components and @perstack/tui packages
2 changes: 1 addition & 1 deletion apps/create-expert/bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import { readFileSync } from "node:fs"
import { parseWithFriendlyError, perstackConfigSchema } from "@perstack/core"
import { startHandler } from "@perstack/tui"
import { Command } from "commander"
import { startHandler } from "perstack/start"
import TOML from "smol-toml"

const tomlPath = new URL("../perstack.toml", import.meta.url)
Expand Down
2 changes: 1 addition & 1 deletion apps/create-expert/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
},
"dependencies": {
"@perstack/core": "workspace:*",
"@perstack/tui": "workspace:*",
"commander": "^14.0.2",
"perstack": "workspace:*",
"smol-toml": "^1.6.0"
},
"devDependencies": {
Expand Down
13 changes: 1 addition & 12 deletions apps/perstack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,8 @@
"author": "Wintermute Technologies, Inc.",
"license": "Apache-2.0",
"type": "module",
"exports": {
"./start": "./src/start.ts"
},
"publishConfig": {
"access": "public",
"exports": {
"./start": "./dist/src/start.js"
},
"bin": {
"perstack": "dist/bin/cli.js"
}
Expand All @@ -29,20 +23,15 @@
"@paralleldrive/cuid2": "^3.0.6",
"@perstack/api-client": "^0.0.54",
"@perstack/core": "workspace:*",
"@perstack/react": "workspace:*",
"@perstack/runtime": "workspace:*",
"commander": "^14.0.2",
"dotenv": "^17.2.3",
"ink": "^6.6.0",
"react": "^19.2.3",
"smol-toml": "^1.6.0"
},
"devDependencies": {
"@perstack/filesystem-storage": "workspace:*",
"@perstack/tui-components": "workspace:*",
"@perstack/tui": "workspace:*",
"@tsconfig/node22": "^22.0.5",
"@types/node": "^25.0.10",
"@types/react": "^19.2.9",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^4.0.18"
Expand Down
4 changes: 2 additions & 2 deletions apps/perstack/src/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import {
type Skill,
} from "@perstack/core"
import { collectToolDefinitionsForExpert } from "@perstack/runtime"
import { getEnv } from "@perstack/tui/get-env"
import { getPerstackConfig } from "@perstack/tui/perstack-toml"
import { Command } from "commander"
import TOML from "smol-toml"
import { getEnv } from "./lib/get-env.js"
import { getPerstackConfig } from "./lib/perstack-toml.js"

async function findConfigPath(configPath?: string): Promise<string> {
if (configPath) {
Expand Down
6 changes: 3 additions & 3 deletions apps/perstack/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ import {
storeJob,
} from "@perstack/filesystem-storage"
import { findLockfile, loadLockfile, run as perstackRun } from "@perstack/runtime"
import { Command } from "commander"
import { resolveRunContext } from "./lib/context.js"
import { resolveRunContext } from "@perstack/tui/context"
import {
parseInteractiveToolCallResult,
parseInteractiveToolCallResultJson,
} from "./lib/interactive.js"
} from "@perstack/tui/interactive"
import { Command } from "commander"

const defaultEventListener = (event: RunEvent | RuntimeEvent) => console.log(JSON.stringify(event))

Expand Down
248 changes: 1 addition & 247 deletions apps/perstack/src/start.ts
Original file line number Diff line number Diff line change
@@ -1,251 +1,5 @@
import { createId } from "@paralleldrive/cuid2"
import {
defaultMaxRetries,
defaultTimeout,
type PerstackConfig,
parseWithFriendlyError,
startCommandInputSchema,
} from "@perstack/core"
import {
createInitialJob,
defaultRetrieveCheckpoint,
defaultStoreCheckpoint,
defaultStoreEvent,
retrieveJob,
storeJob,
} from "@perstack/filesystem-storage"
import { findLockfile, loadLockfile, run as perstackRun, runtimeVersion } from "@perstack/runtime"
import { startHandler } from "@perstack/tui"
import { Command } from "commander"
import { resolveRunContext } from "./lib/context.js"
import { parseInteractiveToolCallResult } from "./lib/interactive.js"
import {
getAllEventContentsForJob,
getAllJobs,
getCheckpointById,
getCheckpointsWithDetails,
type getEventContents,
getRecentExperts,
} from "./lib/run-manager.js"
import { renderExecution } from "./tui/execution/index.js"
import { renderSelection } from "./tui/selection/index.js"
import type { CheckpointHistoryItem, JobHistoryItem } from "./tui/types/index.js"

const CONTINUE_TIMEOUT_MS = 60_000

export interface StartHandlerOptions {
perstackConfig?: PerstackConfig
additionalEnv?: (env: Record<string, string>) => Record<string, string>
}

export async function startHandler(
expertKey: string | undefined,
query: string | undefined,
options: Record<string, unknown>,
handlerOptions?: StartHandlerOptions,
): Promise<void> {
const input = parseWithFriendlyError(startCommandInputSchema, { expertKey, query, options })

try {
// Phase 1: Initialize context
const { perstackConfig, checkpoint, env, providerConfig, model, experts } =
await resolveRunContext({
configPath: input.options.config,
provider: input.options.provider,
model: input.options.model,
envPath: input.options.envPath,
continue: input.options.continue,
continueJob: input.options.continueJob,
resumeFrom: input.options.resumeFrom,
expertKey: input.expertKey,
perstackConfig: handlerOptions?.perstackConfig,
})

if (handlerOptions?.additionalEnv) {
Object.assign(env, handlerOptions.additionalEnv(env))
}

const maxSteps = input.options.maxSteps ?? perstackConfig.maxSteps
const maxRetries = input.options.maxRetries ?? perstackConfig.maxRetries ?? defaultMaxRetries
const timeout = input.options.timeout ?? perstackConfig.timeout ?? defaultTimeout

// Prepare expert lists
const configuredExperts = Object.keys(perstackConfig.experts ?? {}).map((key) => ({
key,
name: key,
}))
const recentExperts = getRecentExperts(10)

// Prepare history jobs (only if browsing is needed)
const showHistory = !input.expertKey && !input.query && !checkpoint
const historyJobs: JobHistoryItem[] = showHistory
? getAllJobs().map((j) => ({
jobId: j.id,
status: j.status,
expertKey: j.coordinatorExpertKey,
totalSteps: j.totalSteps,
startedAt: j.startedAt,
finishedAt: j.finishedAt,
}))
: []

// Phase 2: Selection - get expert, query, and optional checkpoint
const selection = await renderSelection({
showHistory,
initialExpertKey: input.expertKey,
initialQuery: input.query,
initialCheckpoint: checkpoint
? {
id: checkpoint.id,
jobId: checkpoint.jobId,
runId: checkpoint.runId,
stepNumber: checkpoint.stepNumber,
contextWindowUsage: checkpoint.contextWindowUsage ?? 0,
}
: undefined,
configuredExperts,
recentExperts,
historyJobs,
onLoadCheckpoints: async (j: JobHistoryItem): Promise<CheckpointHistoryItem[]> => {
const checkpoints = getCheckpointsWithDetails(j.jobId)
return checkpoints.map((cp) => ({ ...cp, jobId: j.jobId }))
},
})

// Validate selection
if (!selection.expertKey) {
console.error("Expert key is required")
return
}
if (!selection.query && !selection.checkpoint) {
console.error("Query is required")
return
}

// Resolve checkpoint if selected from TUI
let currentCheckpoint = selection.checkpoint
? getCheckpointById(selection.checkpoint.jobId, selection.checkpoint.id)
: checkpoint

if (currentCheckpoint && currentCheckpoint.expert.key !== selection.expertKey) {
console.error(
`Checkpoint expert key ${currentCheckpoint.expert.key} does not match input expert key ${selection.expertKey}`,
)
return
}

// Load lockfile if present
const lockfilePath = findLockfile()
const lockfile = lockfilePath ? (loadLockfile(lockfilePath) ?? undefined) : undefined

// Phase 3: Execution loop
let currentQuery: string | null = selection.query
let currentJobId = currentCheckpoint?.jobId ?? input.options.jobId ?? createId()
// Track if the next query should be treated as an interactive tool result
let isNextQueryInteractiveToolResult = input.options.interactiveToolCallResult ?? false

// Track whether this is the first iteration (for historical events display)
// On first iteration, load all events for the job up to the checkpoint
// On subsequent iterations, skip historical events (previous TUI already displayed them)
let isFirstIteration = true
const initialHistoricalEvents: ReturnType<typeof getEventContents> | undefined =
currentCheckpoint
? getAllEventContentsForJob(currentCheckpoint.jobId, currentCheckpoint.stepNumber)
: undefined

while (currentQuery !== null) {
// Only pass historical events on first iteration
// Subsequent iterations: previous TUI output remains on screen
const historicalEvents = isFirstIteration ? initialHistoricalEvents : undefined

// Generate a new runId for each iteration
const runId = createId()

// Start execution TUI
const { result: executionResult, eventListener } = renderExecution({
expertKey: selection.expertKey,
query: currentQuery,
config: {
runtimeVersion,
model,
maxSteps,
maxRetries,
timeout,
contextWindowUsage: currentCheckpoint?.contextWindowUsage ?? 0,
},
continueTimeoutMs: CONTINUE_TIMEOUT_MS,
historicalEvents,
})

// Run the expert
const runResult = await perstackRun(
{
setting: {
jobId: currentJobId,
runId,
expertKey: selection.expertKey,
input:
isNextQueryInteractiveToolResult && currentCheckpoint
? parseInteractiveToolCallResult(currentQuery, currentCheckpoint)
: { text: currentQuery },
experts,
model,
providerConfig,
reasoningBudget: input.options.reasoningBudget ?? perstackConfig.reasoningBudget,
maxSteps: input.options.maxSteps ?? perstackConfig.maxSteps,
maxRetries: input.options.maxRetries ?? perstackConfig.maxRetries,
timeout: input.options.timeout ?? perstackConfig.timeout,
perstackApiBaseUrl: perstackConfig.perstackApiBaseUrl,
perstackApiKey: env.PERSTACK_API_KEY,
perstackBaseSkillCommand: perstackConfig.perstackBaseSkillCommand,
env,
verbose: input.options.verbose,
},
checkpoint: currentCheckpoint,
},
{
eventListener,
storeCheckpoint: defaultStoreCheckpoint,
storeEvent: defaultStoreEvent,
retrieveCheckpoint: defaultRetrieveCheckpoint,
storeJob,
retrieveJob,
createJob: createInitialJob,
lockfile,
},
)

// Wait for execution TUI to complete (user input or timeout)
const result = await executionResult

// Check if user wants to continue
const canContinue =
runResult.status === "completed" ||
runResult.status === "stoppedByExceededMaxSteps" ||
runResult.status === "stoppedByError" ||
runResult.status === "stoppedByInteractiveTool"

if (result.nextQuery && canContinue) {
currentQuery = result.nextQuery
currentCheckpoint = runResult
currentJobId = runResult.jobId

// If the run stopped for interactive tool, the next query is an interactive tool result
isNextQueryInteractiveToolResult = runResult.status === "stoppedByInteractiveTool"

// Mark first iteration as complete (subsequent TUIs won't show historical events)
isFirstIteration = false
} else {
currentQuery = null
}
}
} catch (error) {
if (error instanceof Error) {
console.error(error.message)
} else {
console.error(error)
}
}
}

export const startCommand = new Command()
.command("start")
Expand Down
6 changes: 0 additions & 6 deletions apps/perstack/src/tui/utils/error-handling.ts

This file was deleted.

2 changes: 0 additions & 2 deletions apps/perstack/src/tui/utils/index.ts

This file was deleted.

2 changes: 1 addition & 1 deletion apps/perstack/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
"resolveJsonModule": true,
"jsx": "react-jsx"
},
"include": ["**/*.ts", "**/*.tsx"],
"include": ["**/*.ts"],
"exclude": ["node_modules", "dist"]
}
2 changes: 1 addition & 1 deletion apps/perstack/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export const cliConfig: Options = {
dts: false,
entry: {
"bin/cli": "bin/cli.ts",
"src/start": "src/start.ts",
},
external: ["react-devtools-core"],
}

export default defineConfig(cliConfig)
4 changes: 4 additions & 0 deletions packages/tui-components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,14 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@perstack/core": "workspace:*",
"@perstack/react": "workspace:*",
"ink": "^6.6.0",
"react": "^19.2.3"
},
"peerDependencies": {
"@perstack/core": "*",
"@perstack/react": "*",
"ink": ">=6.0.0",
"react": ">=18.0.0"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useListNavigation } from "@perstack/tui-components"
import type { Key } from "ink"
import { Box, Text, useInput } from "ink"
import type React from "react"
import { useMemo } from "react"
import { INDICATOR, UI_CONSTANTS } from "../constants.js"
import { useListNavigation } from "../hooks/use-list-navigation.js"

type ListBrowserProps<T> = {
title: string
Expand Down
Loading