|
| 1 | +import { write, fg, style } from "./terminal" |
| 2 | +import { select } from "./select" |
| 3 | +import { Session } from "../../session" |
| 4 | +import { Instance } from "../../project/instance" |
| 5 | +import { Agent } from "../../agent/agent" |
| 6 | +import { Provider } from "../../provider/provider" |
| 7 | +import { Command } from "../../command" |
| 8 | +import path from "path" |
| 9 | +import { Global } from "../../global" |
| 10 | + |
| 11 | +export interface ModelRecent { |
| 12 | + providerID: string |
| 13 | + modelID: string |
| 14 | +} |
| 15 | + |
| 16 | +interface ModelData { |
| 17 | + recent: ModelRecent[] |
| 18 | + favorite: ModelRecent[] |
| 19 | +} |
| 20 | + |
| 21 | +export async function loadRecentModels(): Promise<ModelRecent[]> { |
| 22 | + const statePath = Global.Path.state |
| 23 | + const modelFile = path.join(statePath, "model.json") |
| 24 | + const file = Bun.file(modelFile) |
| 25 | + const exists = await file.exists() |
| 26 | + |
| 27 | + if (!exists) return [] |
| 28 | + |
| 29 | + const data = (await file.json()) as ModelData |
| 30 | + return data.recent || [] |
| 31 | +} |
| 32 | + |
| 33 | +export async function saveRecentModels(recent: ModelRecent[]): Promise<void> { |
| 34 | + const statePath = Global.Path.state |
| 35 | + const modelFile = path.join(statePath, "model.json") |
| 36 | + const file = Bun.file(modelFile) |
| 37 | + const exists = await file.exists() |
| 38 | + |
| 39 | + let data: ModelData = { recent: [], favorite: [] } |
| 40 | + if (exists) { |
| 41 | + data = (await file.json()) as ModelData |
| 42 | + } |
| 43 | + |
| 44 | + data.recent = recent |
| 45 | + await Bun.write(modelFile, JSON.stringify(data)) |
| 46 | +} |
| 47 | + |
| 48 | +export async function addRecentModel(providerID: string, modelID: string): Promise<void> { |
| 49 | + const recent = await loadRecentModels() |
| 50 | + const newEntry = { providerID, modelID } |
| 51 | + const filtered = recent.filter((r) => !(r.providerID === providerID && r.modelID === modelID)) |
| 52 | + filtered.unshift(newEntry) |
| 53 | + const trimmed = filtered.slice(0, 10) |
| 54 | + await saveRecentModels(trimmed) |
| 55 | +} |
| 56 | + |
| 57 | +async function listSessions(): Promise<Session.Info[]> { |
| 58 | + const sessions: Session.Info[] = [] |
| 59 | + for await (const session of Session.list()) { |
| 60 | + sessions.push(session) |
| 61 | + if (sessions.length >= 10) break |
| 62 | + } |
| 63 | + return sessions.reverse() |
| 64 | +} |
| 65 | + |
| 66 | +export async function getAllModels() { |
| 67 | + const providers = await Provider.list() |
| 68 | + const recent = await loadRecentModels() |
| 69 | + const recentSet = new Set(recent.map((r) => `${r.providerID}/${r.modelID}`)) |
| 70 | + const allModels: Array<{ label: string; value: string; description?: string }> = [] |
| 71 | + |
| 72 | + for (const [providerID, provider] of Object.entries(providers)) { |
| 73 | + for (const [modelID, model] of Object.entries(provider.models)) { |
| 74 | + allModels.push({ |
| 75 | + label: `${model.name} (${providerID})`, |
| 76 | + value: `${providerID}/${modelID}`, |
| 77 | + description: `${model.family || ""}${model.cost.input > 0 ? " • Paid" : " • Free"}`.trim(), |
| 78 | + }) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + const options: Array<{ |
| 83 | + label?: string |
| 84 | + value?: string |
| 85 | + description?: string |
| 86 | + current?: boolean |
| 87 | + section?: string |
| 88 | + separator?: boolean |
| 89 | + }> = [] |
| 90 | + |
| 91 | + const modelMap = new Map(allModels.map((m) => [m.value, m])) |
| 92 | + const recentModels: Array<{ label: string; value: string; description?: string }> = [] |
| 93 | + for (const r of recent) { |
| 94 | + const key = `${r.providerID}/${r.modelID}` |
| 95 | + const model = modelMap.get(key) |
| 96 | + if (model) { |
| 97 | + recentModels.push(model) |
| 98 | + } |
| 99 | + } |
| 100 | + const otherModels = allModels.filter((m) => !recentSet.has(m.value)) |
| 101 | + |
| 102 | + if (recentModels.length > 0) { |
| 103 | + options.push({ section: "Recent", separator: true }) |
| 104 | + for (const model of recentModels) { |
| 105 | + options.push({ ...model, separator: false }) |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + if (otherModels.length > 0) { |
| 110 | + if (recentModels.length > 0) { |
| 111 | + options.push({ section: "All Models", separator: true }) |
| 112 | + } |
| 113 | + for (const model of otherModels) { |
| 114 | + options.push({ ...model, separator: false }) |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + return options |
| 119 | +} |
| 120 | + |
| 121 | +interface State { |
| 122 | + currentSessionID: string | null |
| 123 | + currentModel: string | null |
| 124 | + currentAgent: string | undefined |
| 125 | +} |
| 126 | + |
| 127 | +interface SetState { |
| 128 | + setSessionID: (id: string | null) => void |
| 129 | + setModel: (model: string | null) => void |
| 130 | + setAgent: (agent: string | undefined) => void |
| 131 | +} |
| 132 | + |
| 133 | +export async function handleSessions(state: State, setState: SetState, setParentSession: (id: string) => void) { |
| 134 | + const sessions = await listSessions() |
| 135 | + if (sessions.length === 0) { |
| 136 | + write(`${fg.yellow}No sessions found${style.reset}\n\n`) |
| 137 | + return |
| 138 | + } |
| 139 | + |
| 140 | + const options = sessions.map((session) => ({ |
| 141 | + label: session.title, |
| 142 | + value: session.id, |
| 143 | + description: new Date(session.time.created).toLocaleDateString(), |
| 144 | + })) |
| 145 | + |
| 146 | + const selected = await select(options, `${fg.cyan}Select a session:${style.reset}`) |
| 147 | + if (selected) { |
| 148 | + setState.setSessionID(selected) |
| 149 | + setParentSession(selected) |
| 150 | + write(`${fg.green}Session switched${style.reset}\n\n`) |
| 151 | + } else { |
| 152 | + write("\n") |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +export async function handleNew(setState: SetState, setParentSession: (id: string) => void) { |
| 157 | + const session = await Session.createNext({ |
| 158 | + directory: Instance.directory, |
| 159 | + }) |
| 160 | + setState.setSessionID(session.id) |
| 161 | + setState.setModel(null) |
| 162 | + setParentSession(session.id) |
| 163 | + write(`${fg.green}New session started${style.reset}\n\n`) |
| 164 | +} |
| 165 | + |
| 166 | +export async function handleAgents(state: State, setState: SetState) { |
| 167 | + const all = await Agent.list() |
| 168 | + const filtered = all.filter((a) => a.mode !== "subagent" && !a.hidden) |
| 169 | + |
| 170 | + if (filtered.length === 0) { |
| 171 | + write(`${fg.red}No agents available${style.reset}\n\n`) |
| 172 | + return |
| 173 | + } |
| 174 | + |
| 175 | + const options = filtered.map((agent) => ({ |
| 176 | + label: `${agent.name} — ${agent.description ?? ""}`, |
| 177 | + value: agent.name, |
| 178 | + current: agent.name === state.currentAgent, |
| 179 | + })) |
| 180 | + |
| 181 | + const selected = await select(options, `${fg.cyan}Select an agent:${style.reset}`) |
| 182 | + if (selected) { |
| 183 | + setState.setAgent(selected) |
| 184 | + write(`${fg.green}Agent switched to ${selected}${style.reset}\n\n`) |
| 185 | + } else { |
| 186 | + write("\n") |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +export async function handleModels(setState: SetState) { |
| 191 | + const models = await getAllModels() |
| 192 | + if (models.length === 0) { |
| 193 | + write(`${fg.yellow}No models available${style.reset}\n\n`) |
| 194 | + return |
| 195 | + } |
| 196 | + const selected = await select(models, `${fg.cyan}Select a model:${style.reset}`) |
| 197 | + if (selected) { |
| 198 | + setState.setModel(selected) |
| 199 | + const parts = selected.split("/") |
| 200 | + if (parts.length === 2) { |
| 201 | + await addRecentModel(parts[0], parts[1]) |
| 202 | + } |
| 203 | + write(`${fg.green}Model switched to ${selected}${style.reset}\n\n`) |
| 204 | + } else { |
| 205 | + write("\n") |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +export async function handleSubagentModel() { |
| 210 | + const models = await getAllModels() |
| 211 | + if (models.length === 0) { |
| 212 | + write(`${fg.yellow}No models available${style.reset}\n\n`) |
| 213 | + return |
| 214 | + } |
| 215 | + const selected = await select(models, `${fg.cyan}Select model for subagents:${style.reset}`) |
| 216 | + if (selected) { |
| 217 | + process.env.SUBAGENT_MODEL = selected |
| 218 | + write(`${fg.green}Subagent model set to ${selected}${style.reset}\n\n`) |
| 219 | + } else { |
| 220 | + write("\n") |
| 221 | + } |
| 222 | +} |
| 223 | + |
| 224 | +export async function handleCustomCommand( |
| 225 | + name: string, |
| 226 | + args: string, |
| 227 | + command: (name: string, args: string, options: any) => AsyncIterable<any>, |
| 228 | + streamResponse: (source: AsyncIterable<any>, options: any) => Promise<void>, |
| 229 | + state: State, |
| 230 | + setOperationInProgress: (inProgress: boolean) => void, |
| 231 | + freezeBlock: () => void, |
| 232 | +) { |
| 233 | + const options = { |
| 234 | + model: state.currentModel || undefined, |
| 235 | + agent: state.currentAgent, |
| 236 | + sessionID: state.currentSessionID || undefined, |
| 237 | + } |
| 238 | + |
| 239 | + setOperationInProgress(true) |
| 240 | + try { |
| 241 | + const source = command(name, args, options) |
| 242 | + await streamResponse(source, options) |
| 243 | + } catch (err) { |
| 244 | + freezeBlock() |
| 245 | + const msg = err instanceof Error ? err.message : String(err) |
| 246 | + write(`\n${fg.red}Error: ${msg}${style.reset}\n\n`) |
| 247 | + } finally { |
| 248 | + setOperationInProgress(false) |
| 249 | + } |
| 250 | +} |
0 commit comments