@sixb/cli 0.1.24 → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +5 -5
  2. package/dist/commands/agent.d.ts +16 -0
  3. package/dist/commands/agent.d.ts.map +1 -0
  4. package/dist/commands/dev-runner.d.ts +0 -1
  5. package/dist/commands/dev-runner.d.ts.map +1 -1
  6. package/dist/commands/worker-group.d.ts +0 -1
  7. package/dist/commands/worker-group.d.ts.map +1 -1
  8. package/dist/commands/worker.d.ts +0 -1
  9. package/dist/commands/worker.d.ts.map +1 -1
  10. package/dist/lib/command-line.d.ts +16 -6
  11. package/dist/lib/command-line.d.ts.map +1 -1
  12. package/dist/lib/deploy-release.d.ts.map +1 -1
  13. package/dist/lib/github-ci.d.ts.map +1 -1
  14. package/dist/lib/runtime.d.ts +0 -1
  15. package/dist/lib/runtime.d.ts.map +1 -1
  16. package/dist/lib/worker-registry.d.ts +0 -1
  17. package/dist/lib/worker-registry.d.ts.map +1 -1
  18. package/dist/tui/app.d.ts +19 -0
  19. package/dist/tui/app.d.ts.map +1 -0
  20. package/dist/tui/brand.d.ts +7 -0
  21. package/dist/tui/brand.d.ts.map +1 -0
  22. package/dist/tui/computer.d.ts +3 -0
  23. package/dist/tui/computer.d.ts.map +1 -0
  24. package/dist/tui/connection.d.ts +45 -0
  25. package/dist/tui/connection.d.ts.map +1 -0
  26. package/dist/tui/folders.d.ts +7 -0
  27. package/dist/tui/folders.d.ts.map +1 -0
  28. package/dist/tui/format.d.ts +33 -0
  29. package/dist/tui/format.d.ts.map +1 -0
  30. package/dist/tui/index.d.ts +12 -0
  31. package/dist/tui/index.d.ts.map +1 -0
  32. package/dist/tui/palette.d.ts +25 -0
  33. package/dist/tui/palette.d.ts.map +1 -0
  34. package/dist/tui/parts.d.ts +66 -0
  35. package/dist/tui/parts.d.ts.map +1 -0
  36. package/dist/tui/runner.d.ts +52 -0
  37. package/dist/tui/runner.d.ts.map +1 -0
  38. package/dist/tui/settings.d.ts +44 -0
  39. package/dist/tui/settings.d.ts.map +1 -0
  40. package/dist/tui/slash.d.ts +14 -0
  41. package/dist/tui/slash.d.ts.map +1 -0
  42. package/dist/tui/theme.d.ts +39 -0
  43. package/dist/tui/theme.d.ts.map +1 -0
  44. package/dist/tui/transcript.d.ts +52 -0
  45. package/dist/tui/transcript.d.ts.map +1 -0
  46. package/dist/tui/ui.d.ts +35 -0
  47. package/dist/tui/ui.d.ts.map +1 -0
  48. package/package.json +17 -15
  49. package/src/commands/agent.ts +337 -0
  50. package/src/commands/dev-runner.ts +0 -4
  51. package/src/commands/worker-group.ts +0 -4
  52. package/src/commands/worker.ts +0 -4
  53. package/src/index.tsx +57 -5
  54. package/src/lib/command-line.ts +52 -15
  55. package/src/lib/deploy-release.ts +0 -11
  56. package/src/lib/github-ci.ts +3 -1
  57. package/src/lib/runtime.ts +0 -2
  58. package/src/lib/worker-registry.ts +0 -2
  59. package/src/tui/app.tsx +1198 -0
  60. package/src/tui/brand.tsx +51 -0
  61. package/src/tui/computer.ts +54 -0
  62. package/src/tui/connection.ts +149 -0
  63. package/src/tui/folders.ts +41 -0
  64. package/src/tui/format.ts +260 -0
  65. package/src/tui/index.tsx +353 -0
  66. package/src/tui/palette.tsx +183 -0
  67. package/src/tui/parts.ts +254 -0
  68. package/src/tui/runner.ts +173 -0
  69. package/src/tui/settings.ts +127 -0
  70. package/src/tui/slash.ts +32 -0
  71. package/src/tui/theme.ts +111 -0
  72. package/src/tui/transcript.tsx +555 -0
  73. package/src/tui/ui.tsx +148 -0
  74. package/dist/lib/agent-turn-timeout.d.ts +0 -8
  75. package/dist/lib/agent-turn-timeout.d.ts.map +0 -1
  76. package/src/lib/agent-turn-timeout.ts +0 -46
@@ -0,0 +1,254 @@
1
+ import type {
2
+ AgentRunStreamEvent,
3
+ ListAgentThreadMessagesResponses,
4
+ ModelUiChunk,
5
+ } from "@sixb/client"
6
+
7
+ // What a message shows, whether it was stored or is still streaming: the stored transcript and the
8
+ // live run both reduce to these parts, so one view renders either.
9
+
10
+ export type StoredMessage = ListAgentThreadMessagesResponses[200]["messages"][number]
11
+
12
+ export type ToolState = "running" | "done" | "error"
13
+
14
+ export type Part =
15
+ | { readonly kind: "text"; readonly text: string }
16
+ | { readonly kind: "reasoning"; readonly text: string; readonly done: boolean }
17
+ | {
18
+ readonly kind: "tool"
19
+ readonly id: string
20
+ readonly name: string
21
+ readonly state: ToolState
22
+ readonly input?: unknown
23
+ /** The input while the model still writes it, as JSON text. */
24
+ readonly inputText?: string
25
+ readonly output?: unknown
26
+ readonly error?: string
27
+ }
28
+ | { readonly kind: "file"; readonly name: string; readonly mediaType?: string }
29
+
30
+ type ApprovalOutcomePart = Extract<StoredMessage["parts"][number], { type: "approval-outcome" }>
31
+
32
+ /** How a held call ended, as the message that resumed or followed its turn told the agent. */
33
+ export interface ApprovalOutcome {
34
+ readonly approvalId: string
35
+ readonly status: ApprovalOutcomePart["status"]
36
+ readonly outcome?: ApprovalOutcomePart["outcome"]
37
+ }
38
+
39
+ export interface ShownMessage {
40
+ readonly id: string
41
+ readonly role: "user" | "assistant"
42
+ readonly runId: string | null
43
+ readonly parts: readonly Part[]
44
+ /** How the held calls before it ended: not shown, but the calls' own lines say it. */
45
+ readonly outcomes: readonly ApprovalOutcome[]
46
+ readonly createdAt: string
47
+ }
48
+
49
+ /** A stored message as shown: what is context for the agent alone stays hidden. */
50
+ export function shownMessage(message: StoredMessage): ShownMessage | null {
51
+ if (message.role === "system") return null
52
+
53
+ const outcomes = message.parts.flatMap((part): ApprovalOutcome[] =>
54
+ part.type === "approval-outcome"
55
+ ? [
56
+ {
57
+ approvalId: part.approvalId,
58
+ status: part.status,
59
+ ...(part.outcome === undefined ? {} : { outcome: part.outcome }),
60
+ },
61
+ ]
62
+ : []
63
+ )
64
+
65
+ const parts = message.parts.flatMap((part): Part[] => {
66
+ switch (part.type) {
67
+ case "text":
68
+ return part.text.trim() ? [{ kind: "text", text: part.text }] : []
69
+ case "reasoning":
70
+ return part.text.trim() ? [{ kind: "reasoning", text: part.text, done: true }] : []
71
+ case "tool-call":
72
+ return [
73
+ part.state === "output-available"
74
+ ? {
75
+ kind: "tool",
76
+ id: part.toolCallId,
77
+ name: part.toolName,
78
+ state: "done",
79
+ input: part.input,
80
+ output: part.output,
81
+ }
82
+ : {
83
+ kind: "tool",
84
+ id: part.toolCallId,
85
+ name: part.toolName,
86
+ state: "error",
87
+ input: part.input,
88
+ error: part.errorText,
89
+ },
90
+ ]
91
+ case "file":
92
+ return [
93
+ {
94
+ kind: "file",
95
+ name: part.fileRef.fileName ?? "file",
96
+ ...(part.fileRef.mediaType === undefined ? {} : { mediaType: part.fileRef.mediaType }),
97
+ },
98
+ ]
99
+ default:
100
+ return []
101
+ }
102
+ })
103
+ // A turn resumed after approvals starts from a message the person never wrote: it shows
104
+ // nothing, and is kept for how its held calls ended.
105
+ if (message.role === "user" && parts.length === 0 && outcomes.length === 0) return null
106
+ return {
107
+ id: message.id,
108
+ role: message.role,
109
+ runId: message.runId,
110
+ parts,
111
+ outcomes,
112
+ createdAt: message.createdAt,
113
+ }
114
+ }
115
+
116
+ /** How each held call of a transcript ended, by its approval's id. */
117
+ export function approvalOutcomes(
118
+ messages: readonly ShownMessage[]
119
+ ): ReadonlyMap<string, ApprovalOutcome> {
120
+ return new Map(
121
+ messages.flatMap((message) => message.outcomes.map((outcome) => [outcome.approvalId, outcome]))
122
+ )
123
+ }
124
+
125
+ /** A run as it streams: its parts so far, and whether it still works. */
126
+ export interface LiveRun {
127
+ readonly runId: string
128
+ readonly parts: readonly Part[]
129
+ readonly keys: readonly string[]
130
+ readonly step: number
131
+ readonly working: boolean
132
+ readonly compacting: boolean
133
+ /** Set once the run's answer is stored: the transcript then shows it. */
134
+ readonly finalized: boolean
135
+ readonly finished?: { readonly status: string; readonly error?: string }
136
+ }
137
+
138
+ export function liveRun(runId: string): LiveRun {
139
+ return {
140
+ runId,
141
+ parts: [],
142
+ keys: [],
143
+ step: 0,
144
+ working: true,
145
+ compacting: false,
146
+ finalized: false,
147
+ }
148
+ }
149
+
150
+ export function reduceLive(state: LiveRun, event: AgentRunStreamEvent): LiveRun {
151
+ switch (event.type) {
152
+ case "agent.run.started":
153
+ return { ...state, working: true }
154
+ case "agent.compaction.started":
155
+ return { ...state, compacting: true }
156
+ case "agent.compaction.completed":
157
+ case "agent.compaction.failed":
158
+ return { ...state, compacting: false }
159
+ case "agent.ui.chunk":
160
+ return reduceChunk(state, event.chunk)
161
+ case "agent.message.finalized":
162
+ return { ...state, finalized: true }
163
+ case "agent.run.finished":
164
+ return {
165
+ ...state,
166
+ working: false,
167
+ compacting: false,
168
+ finished: {
169
+ status: event.status,
170
+ ...(event.error ? { error: event.error.message } : {}),
171
+ },
172
+ }
173
+ default:
174
+ return state
175
+ }
176
+ }
177
+
178
+ function reduceChunk(state: LiveRun, chunk: ModelUiChunk): LiveRun {
179
+ switch (chunk.type) {
180
+ case "start-step":
181
+ return { ...state, step: state.step + 1 }
182
+ case "text-delta": {
183
+ if (!chunk.delta) return state
184
+ const key = `text#${state.step}#${chunk.id}`
185
+ if (!state.keys.includes(key) && !chunk.delta.trim()) return state
186
+ return upsert(state, key, { kind: "text", text: chunk.delta }, (part) =>
187
+ part.kind === "text" ? { ...part, text: part.text + chunk.delta } : part
188
+ )
189
+ }
190
+ case "reasoning-delta":
191
+ return upsert(
192
+ state,
193
+ `reasoning#${state.step}#${chunk.id}`,
194
+ { kind: "reasoning", text: chunk.delta, done: false },
195
+ (part) => (part.kind === "reasoning" ? { ...part, text: part.text + chunk.delta } : part)
196
+ )
197
+ case "reasoning-end":
198
+ return upsert(
199
+ state,
200
+ `reasoning#${state.step}#${chunk.id}`,
201
+ { kind: "reasoning", text: "", done: true },
202
+ (part) => (part.kind === "reasoning" ? { ...part, done: true } : part)
203
+ )
204
+ case "tool-input-start":
205
+ case "tool-input-delta":
206
+ case "tool-input-available":
207
+ case "tool-input-error":
208
+ case "tool-output-available":
209
+ case "tool-output-error": {
210
+ const created: Part = {
211
+ kind: "tool",
212
+ id: chunk.toolCallId,
213
+ name: "toolName" in chunk && chunk.toolName ? chunk.toolName : "tool",
214
+ state: "running",
215
+ }
216
+ return upsert(state, `tool#${chunk.toolCallId}`, created, (part) =>
217
+ part.kind === "tool" ? applyToolChunk(part, chunk) : part
218
+ )
219
+ }
220
+ default:
221
+ return state
222
+ }
223
+ }
224
+
225
+ type ToolPart = Extract<Part, { readonly kind: "tool" }>
226
+
227
+ function applyToolChunk(part: ToolPart, chunk: ModelUiChunk): ToolPart {
228
+ const named = "toolName" in chunk && chunk.toolName ? { ...part, name: chunk.toolName } : part
229
+ switch (chunk.type) {
230
+ case "tool-input-delta":
231
+ return { ...named, inputText: (named.inputText ?? "") + chunk.inputTextDelta }
232
+ case "tool-input-available":
233
+ return { ...named, input: chunk.input }
234
+ case "tool-input-error":
235
+ return { ...named, state: "error", input: chunk.input, error: chunk.errorText }
236
+ case "tool-output-available":
237
+ return { ...named, state: "done", output: chunk.output }
238
+ case "tool-output-error":
239
+ return { ...named, state: "error", error: chunk.errorText }
240
+ default:
241
+ return named
242
+ }
243
+ }
244
+
245
+ /** Append a part under a new key, or change the one already there, keeping their order. */
246
+ function upsert(state: LiveRun, key: string, created: Part, update: (part: Part) => Part): LiveRun {
247
+ const index = state.keys.indexOf(key)
248
+ if (index === -1) {
249
+ return { ...state, parts: [...state.parts, created], keys: [...state.keys, key] }
250
+ }
251
+ const parts = state.parts.slice()
252
+ parts[index] = update(parts[index] as Part)
253
+ return { ...state, parts }
254
+ }
@@ -0,0 +1,173 @@
1
+ import { homedir, tmpdir } from "node:os"
2
+ import { dirname, join } from "node:path"
3
+ import { ComputerRunner } from "@sixb/agent"
4
+ import { type GetAgentThreadResponses, getAgentRun, getAgentThread } from "@sixb/client"
5
+ import { LocalSandboxFactory } from "@sixb/sandboxes-local"
6
+ import { resolveConfigPath } from "../lib/profiles"
7
+ import { thisComputerId } from "./computer"
8
+ import type { Connection } from "./connection"
9
+ import { folderOf } from "./folders"
10
+
11
+ /** How long a closed terminal waits for a turn running here to record its end. */
12
+ const HANG_UP_WAIT_MS = 10_000
13
+
14
+ /**
15
+ * What the agent's commands never read on this computer, whatever the folder: the CLI's own
16
+ * sign-in, and the credentials SSH and AWS keep.
17
+ */
18
+ export function deniedPaths(): readonly string[] {
19
+ return [dirname(resolveConfigPath()), join(homedir(), ".ssh"), join(homedir(), ".aws")]
20
+ }
21
+
22
+ /**
23
+ * This computer as a runner: it claims its owner's turns from the project and runs them in the
24
+ * folder `sixb` was opened in, one at a time per turn, each until it ends or is stopped.
25
+ */
26
+ export class LocalRunner {
27
+ private readonly runner: ComputerRunner
28
+ private readonly running = new Map<
29
+ string,
30
+ { readonly stop: AbortController; readonly done: Promise<boolean> }
31
+ >()
32
+
33
+ constructor(
34
+ private readonly connection: Connection,
35
+ readonly folder: string,
36
+ private readonly onFailure: (error: unknown) => void
37
+ ) {
38
+ this.runner = new ComputerRunner({
39
+ apiUrl: connection.apiUrl,
40
+ authorization: () => connection.authorization(),
41
+ computerId: thisComputerId,
42
+ folder,
43
+ runFilesRoot: join(tmpdir(), "sixb-agent"),
44
+ onFailure,
45
+ openSandbox: ({ workingDirectory, runFiles, credential, signal }) =>
46
+ new LocalSandboxFactory({
47
+ readWritePaths: [runFiles],
48
+ denyReadPaths: deniedPaths(),
49
+ network: { mode: "all" },
50
+ }).create({
51
+ ...(workingDirectory === undefined ? {} : { workingDirectory }),
52
+ network: { mode: "all" },
53
+ requestCredentials: [credential],
54
+ signal,
55
+ }),
56
+ })
57
+ }
58
+
59
+ /** Whether this computer runs `runId` now. */
60
+ runs(runId: string): boolean {
61
+ return this.running.has(runId)
62
+ }
63
+
64
+ /**
65
+ * Claim a queued turn and run it, unless this computer runs it already. Resolves once the turn
66
+ * ended here: false when it was not this computer's to run, or could not be claimed.
67
+ */
68
+ claim(runId: string): Promise<boolean> {
69
+ const running = this.running.get(runId)
70
+ if (running) return running.done
71
+ const stop = new AbortController()
72
+ const done = this.runner
73
+ .runTurn(runId, stop.signal)
74
+ .catch((error: unknown) => {
75
+ this.onFailure(error)
76
+ return false
77
+ })
78
+ .finally(() => this.running.delete(runId))
79
+ this.running.set(runId, { stop, done })
80
+ return done
81
+ }
82
+
83
+ /**
84
+ * Claim a conversation's turn when this computer runs it: its owner's, on this computer and in
85
+ * this folder, and still queued. A running turn is another sixb's, or one whose sixb closed,
86
+ * which the API ends interrupted: claiming it again would run its commands twice.
87
+ */
88
+ async claimIfHere(threadId: string, runId?: string): Promise<void> {
89
+ if ((await folderOf(threadId)) !== this.folder) return
90
+ const { client } = this.connection
91
+ const { data: thread } = await getAgentThread({ client, path: { threadId } })
92
+ if (thread?.runsOn !== "computer" || !owns(this.connection, thread)) return
93
+ if (!runsOnThisComputer(thread, await thisComputerId())) return
94
+
95
+ const turn = runId ?? thread.activeRunId
96
+ if (!turn) return
97
+ const { data: run } = await getAgentRun({ client, path: { runId: turn } })
98
+ if (run?.status === "queued") void this.claim(turn)
99
+ }
100
+
101
+ /** After a stop was asked for: the turn hears it now, not at its next lease renewal. */
102
+ hearStop(runId: string): void {
103
+ this.runner.renewNow(runId)
104
+ }
105
+
106
+ /** Whether a turn runs here now. */
107
+ get busy(): boolean {
108
+ return this.running.size > 0
109
+ }
110
+
111
+ /** Stop every turn this computer runs: each ends interrupted, its end recorded. */
112
+ async stop(): Promise<void> {
113
+ const running = [...this.running.values()]
114
+ for (const { stop } of running) stop.abort()
115
+ await Promise.allSettled(running.map(({ done }) => done))
116
+ await this.runner.drain()
117
+ }
118
+ }
119
+
120
+ /** Whether the person signed in owns `thread`: with sign-in off, the system owns what it starts. */
121
+ export function owns(
122
+ connection: Pick<Connection, "user">,
123
+ thread: Pick<GetAgentThreadResponses[200], "ownerPrincipal">
124
+ ): boolean {
125
+ const owner = thread.ownerPrincipal
126
+ return connection.user
127
+ ? owner.type === "user" && owner.id === connection.user.id
128
+ : owner.type === "system"
129
+ }
130
+
131
+ /**
132
+ * Whether this computer runs a computer's thread: the one it runs on. A thread none claimed a turn
133
+ * of yet runs on the first that does, the one it started on.
134
+ */
135
+ export function runsOnThisComputer(
136
+ thread: Pick<GetAgentThreadResponses[200], "computerId">,
137
+ computerId: string
138
+ ): boolean {
139
+ return thread.computerId === undefined || thread.computerId === computerId
140
+ }
141
+
142
+ /**
143
+ * A closed terminal, or a kill, ends sixb as quitting does: the turns running here stop, each
144
+ * ending interrupted with its end recorded, instead of renewing their lease from a process nobody
145
+ * sees. Then `exit`, after a bounded wait. Returns the removal of the handlers.
146
+ */
147
+ export function stopOnHangUp(
148
+ runner: () => Pick<LocalRunner, "busy" | "stop"> | null,
149
+ exit: (signal: "SIGHUP" | "SIGTERM") => void
150
+ ): () => void {
151
+ const hangUp = (signal: "SIGHUP" | "SIGTERM") => {
152
+ const running = runner()
153
+ if (!running?.busy) return exit(signal)
154
+
155
+ let timer: ReturnType<typeof setTimeout> | undefined
156
+ const waited = new Promise<void>((resolve) => {
157
+ timer = setTimeout(resolve, HANG_UP_WAIT_MS)
158
+ })
159
+ void Promise.race([running.stop(), waited]).finally(() => {
160
+ clearTimeout(timer)
161
+ exit(signal)
162
+ })
163
+ }
164
+
165
+ const onHangUp = () => hangUp("SIGHUP")
166
+ const onTerminate = () => hangUp("SIGTERM")
167
+ process.on("SIGHUP", onHangUp)
168
+ process.on("SIGTERM", onTerminate)
169
+ return () => {
170
+ process.off("SIGHUP", onHangUp)
171
+ process.off("SIGTERM", onTerminate)
172
+ }
173
+ }
@@ -0,0 +1,127 @@
1
+ import { readFile, writeFile } from "node:fs/promises"
2
+ import { type as osType } from "node:os"
3
+ import { dirname, join } from "node:path"
4
+ import type { ListModelsResponses } from "@sixb/client"
5
+ import { resolveConfigPath } from "../lib/profiles"
6
+
7
+ export type ApprovalMode = "manual" | "accept-edits" | "auto"
8
+ export type Place = "computer" | "cloud"
9
+ export type LanguageModel = ListModelsResponses[200]["language"][number]
10
+ export type ReasoningLevel = LanguageModel["reasoningLevels"][number]
11
+
12
+ /** What the next message is sent with. Remembered between sessions, per computer. */
13
+ export interface Settings {
14
+ /** Where a new conversation runs; a conversation keeps where it started. */
15
+ readonly place: Place
16
+ /** The mode a new conversation starts in; in a conversation, the thread's applies. */
17
+ readonly approvalMode: ApprovalMode
18
+ /** A model the person picked; absent follows the project: Auto with tiers, else its default. */
19
+ readonly model?: { readonly provider: string; readonly modelId: string }
20
+ readonly reasoning?: ReasoningLevel
21
+ }
22
+
23
+ export const DEFAULT_SETTINGS: Settings = { place: "computer", approvalMode: "manual" }
24
+
25
+ export const APPROVAL_MODES: readonly {
26
+ readonly mode: ApprovalMode
27
+ readonly label: string
28
+ readonly description: string
29
+ }[] = [
30
+ {
31
+ mode: "manual",
32
+ label: "Ask first",
33
+ description: "Checks with you before each action or workflow.",
34
+ },
35
+ {
36
+ mode: "accept-edits",
37
+ label: "Allow edits",
38
+ description:
39
+ "Changes your data on its own. Asks before reaching other systems or starting workflows.",
40
+ },
41
+ {
42
+ mode: "auto",
43
+ label: "Full access",
44
+ description: "Runs every action and workflow without asking.",
45
+ },
46
+ ]
47
+
48
+ export function approvalLabel(mode: ApprovalMode): string {
49
+ return APPROVAL_MODES.find((entry) => entry.mode === mode)?.label ?? mode
50
+ }
51
+
52
+ /** What this computer is called where the person picks where a conversation runs. */
53
+ export function computerName(): string {
54
+ return osType() === "Darwin" ? "This Mac" : "This computer"
55
+ }
56
+
57
+ export function placeLabel(place: Place): string {
58
+ return place === "computer" ? computerName() : "Cloud"
59
+ }
60
+
61
+ const SETTINGS_FILE = () => join(dirname(resolveConfigPath()), "tui.json")
62
+
63
+ export async function loadSettings(): Promise<Settings> {
64
+ try {
65
+ const stored = JSON.parse(await readFile(SETTINGS_FILE(), "utf8")) as Partial<Settings>
66
+ return {
67
+ place: stored.place === "cloud" ? "cloud" : "computer",
68
+ approvalMode: APPROVAL_MODES.some((entry) => entry.mode === stored.approvalMode)
69
+ ? (stored.approvalMode as ApprovalMode)
70
+ : DEFAULT_SETTINGS.approvalMode,
71
+ ...(stored.model?.provider && stored.model.modelId ? { model: stored.model } : {}),
72
+ ...(stored.reasoning ? { reasoning: stored.reasoning } : {}),
73
+ }
74
+ } catch {
75
+ return DEFAULT_SETTINGS
76
+ }
77
+ }
78
+
79
+ export async function saveSettings(settings: Settings): Promise<void> {
80
+ await writeFile(SETTINGS_FILE(), `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600 }).catch(
81
+ () => {}
82
+ )
83
+ }
84
+
85
+ /** The model the next message runs on, as the composer names it. */
86
+ export function modelLabel(
87
+ models: readonly LanguageModel[],
88
+ settings: Settings
89
+ ): { readonly name: string; readonly reasoning?: string } {
90
+ const chosen = settings.model
91
+ ? models.find(
92
+ (model) =>
93
+ model.provider === settings.model?.provider && model.modelId === settings.model.modelId
94
+ )
95
+ : undefined
96
+ const tiers = models.some((model) => model.tier !== undefined)
97
+ const model =
98
+ chosen ?? (tiers ? undefined : (models.find((entry) => entry.isDefault) ?? models[0]))
99
+ const reasoning =
100
+ settings.reasoning && model?.reasoningLevels.includes(settings.reasoning)
101
+ ? settings.reasoning
102
+ : undefined
103
+ return { name: model?.name ?? "Auto", ...(reasoning ? { reasoning } : {}) }
104
+ }
105
+
106
+ /** What a message asks the server for: only what the person chose. */
107
+ export function messageSelection(
108
+ models: readonly LanguageModel[],
109
+ settings: Settings
110
+ ): { readonly model?: { provider: string; modelId: string }; readonly reasoning?: ReasoningLevel } {
111
+ const chosen = settings.model
112
+ ? models.find(
113
+ (model) =>
114
+ model.provider === settings.model?.provider && model.modelId === settings.model.modelId
115
+ )
116
+ : undefined
117
+ const tiers = models.some((model) => model.tier !== undefined)
118
+ const reasoningModel = chosen ?? (tiers ? undefined : models.find((entry) => entry.isDefault))
119
+ const reasoning =
120
+ settings.reasoning && reasoningModel?.reasoningLevels.includes(settings.reasoning)
121
+ ? settings.reasoning
122
+ : undefined
123
+ return {
124
+ ...(chosen ? { model: { provider: chosen.provider, modelId: chosen.modelId } } : {}),
125
+ ...(reasoning ? { reasoning } : {}),
126
+ }
127
+ }
@@ -0,0 +1,32 @@
1
+ // Commands typed in the composer: `/model`, `/new`. A message that names one runs it instead of
2
+ // reaching the agent.
3
+
4
+ /** A command typed in the composer, as `/model`. */
5
+ export interface SlashCommand {
6
+ readonly name: string
7
+ readonly description: string
8
+ run(): void
9
+ }
10
+
11
+ /** The commands a composer's text starts to name: all of them for a lone `/`. */
12
+ export function slashMatches(
13
+ commands: readonly SlashCommand[],
14
+ text: string
15
+ ): readonly SlashCommand[] {
16
+ if (!text.startsWith("/") || /\s/.test(text)) return []
17
+ const typed = text.slice(1).toLowerCase()
18
+ return commands.filter((command) => command.name.startsWith(typed))
19
+ }
20
+
21
+ /**
22
+ * The command a message runs when it is sent: the one chosen in the menu its text opens, the first
23
+ * when none was. Undefined for anything else, which is sent to the agent.
24
+ */
25
+ export function pickSlash(
26
+ commands: readonly SlashCommand[],
27
+ text: string,
28
+ chosen = 0
29
+ ): SlashCommand | undefined {
30
+ const matches = slashMatches(commands, text.trim())
31
+ return matches[Math.min(chosen, matches.length - 1)]
32
+ }
@@ -0,0 +1,111 @@
1
+ import { palette } from "../ui/theme"
2
+
3
+ /**
4
+ * The full-screen app's colors. It paints no background of its own: the terminal's shows through,
5
+ * and panels are the terminal's background with a little of its foreground mixed in, so they sit
6
+ * right on any theme. Blue is for what is live or chosen, amber for what waits on you.
7
+ */
8
+ export interface TuiColors {
9
+ /** Always the terminal's own. */
10
+ readonly background: string
11
+ /** Panels: the composer, a user's message, a dialog. */
12
+ readonly surface: string
13
+ /** A panel's selected row. */
14
+ readonly raised: string
15
+ readonly border: string
16
+ readonly text: string
17
+ readonly muted: string
18
+ readonly faint: string
19
+ readonly blue: string
20
+ readonly water: readonly string[]
21
+ /** The wordmark's blues, palest first, deep enough to read on this background. */
22
+ readonly wordmark: readonly string[]
23
+ /** Inline code in the agent's answers. */
24
+ readonly code: string
25
+ readonly green: string
26
+ readonly amber: string
27
+ readonly red: string
28
+ }
29
+
30
+ /** What the terminal says its own colors are, when it answers. */
31
+ export interface TerminalColors {
32
+ readonly background: string
33
+ readonly foreground: string
34
+ }
35
+
36
+ const night: TuiColors = {
37
+ background: "transparent",
38
+ surface: "#1a1c20",
39
+ raised: "#24272d",
40
+ border: "#2b2e35",
41
+ text: "#eceef2",
42
+ muted: "#8b919a",
43
+ faint: "#5a6069",
44
+ blue: palette.blue,
45
+ water: palette.water,
46
+ wordmark: palette.water.slice(1),
47
+ code: "#8fbefc",
48
+ green: palette.green,
49
+ amber: palette.amber,
50
+ red: palette.red,
51
+ }
52
+
53
+ const day: TuiColors = {
54
+ background: "transparent",
55
+ surface: "#f2f4f7",
56
+ raised: "#e6e9ef",
57
+ border: "#dfe3e9",
58
+ text: "#17181c",
59
+ muted: "#626873",
60
+ faint: "#9aa0a9",
61
+ blue: "#007aff",
62
+ water: ["#a6cbfb", "#6fb0fc", "#3d95fd", "#007aff"],
63
+ wordmark: ["#2f8bf5", "#0a74e8", "#0062cc"],
64
+ code: "#0062cc",
65
+ green: "#1f9d48",
66
+ amber: "#c77700",
67
+ red: "#e5332a",
68
+ }
69
+
70
+ /**
71
+ * The colors for this terminal: from its own background and foreground when it reports them, else
72
+ * Sixb's night or day colors for the mode it reports.
73
+ */
74
+ export function tuiColors(
75
+ mode: "light" | "dark" | null,
76
+ terminal: TerminalColors | null = null
77
+ ): TuiColors {
78
+ if (!terminal) return mode === "light" ? day : night
79
+ const { background, foreground } = terminal
80
+ const dark = luminance(background) < 0.5
81
+ const base = dark ? night : day
82
+ return {
83
+ ...base,
84
+ surface: mix(background, foreground, dark ? 0.07 : 0.05),
85
+ raised: mix(background, foreground, dark ? 0.13 : 0.1),
86
+ border: mix(background, foreground, dark ? 0.18 : 0.14),
87
+ text: foreground,
88
+ muted: mix(background, foreground, 0.6),
89
+ faint: mix(background, foreground, 0.38),
90
+ }
91
+ }
92
+
93
+ /** `amount` of `to` mixed into `from`, both `#rrggbb`. */
94
+ export function mix(from: string, to: string, amount: number): string {
95
+ const a = channels(from)
96
+ const b = channels(to)
97
+ return `#${a
98
+ .map((value, index) => Math.round(value + ((b[index] ?? value) - value) * amount))
99
+ .map((value) => value.toString(16).padStart(2, "0"))
100
+ .join("")}`
101
+ }
102
+
103
+ function luminance(hex: string): number {
104
+ const [r = 0, g = 0, b = 0] = channels(hex)
105
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255
106
+ }
107
+
108
+ function channels(hex: string): number[] {
109
+ const value = hex.replace("#", "").slice(0, 6).padEnd(6, "0")
110
+ return [0, 2, 4].map((offset) => Number.parseInt(value.slice(offset, offset + 2), 16) || 0)
111
+ }