@silvery/examples 0.4.2

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 (37) hide show
  1. package/bin/cli.ts +286 -0
  2. package/examples/apps/aichat/components.tsx +469 -0
  3. package/examples/apps/aichat/index.tsx +207 -0
  4. package/examples/apps/aichat/script.ts +460 -0
  5. package/examples/apps/aichat/state.ts +326 -0
  6. package/examples/apps/aichat/types.ts +19 -0
  7. package/examples/apps/app-todo.tsx +201 -0
  8. package/examples/apps/async-data.tsx +208 -0
  9. package/examples/apps/cli-wizard.tsx +332 -0
  10. package/examples/apps/clipboard.tsx +183 -0
  11. package/examples/apps/components.tsx +463 -0
  12. package/examples/apps/data-explorer.tsx +490 -0
  13. package/examples/apps/dev-tools.tsx +379 -0
  14. package/examples/apps/explorer.tsx +731 -0
  15. package/examples/apps/gallery.tsx +653 -0
  16. package/examples/apps/inline-bench.tsx +136 -0
  17. package/examples/apps/kanban.tsx +267 -0
  18. package/examples/apps/layout-ref.tsx +185 -0
  19. package/examples/apps/outline.tsx +171 -0
  20. package/examples/apps/panes/index.tsx +205 -0
  21. package/examples/apps/paste-demo.tsx +198 -0
  22. package/examples/apps/scroll.tsx +77 -0
  23. package/examples/apps/search-filter.tsx +240 -0
  24. package/examples/apps/task-list.tsx +271 -0
  25. package/examples/apps/terminal.tsx +800 -0
  26. package/examples/apps/textarea.tsx +103 -0
  27. package/examples/apps/theme.tsx +515 -0
  28. package/examples/apps/transform.tsx +242 -0
  29. package/examples/apps/virtual-10k.tsx +405 -0
  30. package/examples/components/counter.tsx +45 -0
  31. package/examples/components/hello.tsx +34 -0
  32. package/examples/components/progress-bar.tsx +48 -0
  33. package/examples/components/select-list.tsx +50 -0
  34. package/examples/components/spinner.tsx +40 -0
  35. package/examples/components/text-input.tsx +57 -0
  36. package/examples/components/virtual-list.tsx +52 -0
  37. package/package.json +27 -0
@@ -0,0 +1,326 @@
1
+ /**
2
+ * TEA state machine for the AI coding agent demo.
3
+ *
4
+ * Pure (state, msg) → [state, effects] — all side effects are timer-based.
5
+ * The update function is created via factory to close over script/mode config.
6
+ */
7
+
8
+ import { fx } from "silvery"
9
+ import type { TeaResult, TimerEffect } from "silvery"
10
+ import type { Exchange, ScriptEntry } from "./types.js"
11
+ import { RANDOM_AGENT_RESPONSES, INPUT_COST_PER_M, OUTPUT_COST_PER_M, CONTEXT_WINDOW } from "./script.js"
12
+
13
+ // ============================================================================
14
+ // Types
15
+ // ============================================================================
16
+
17
+ /** Streaming phases: thinking -> streaming text -> tool calls -> done */
18
+ export type StreamPhase = "thinking" | "streaming" | "tools" | "done"
19
+
20
+ export type DemoState = {
21
+ exchanges: Exchange[]
22
+ scriptIdx: number
23
+ streamPhase: StreamPhase
24
+ revealFraction: number
25
+ done: boolean
26
+ compacting: boolean
27
+ pulse: boolean
28
+ ctrlDPending: boolean
29
+ contextBaseline: number
30
+ offScript: boolean
31
+ nextId: number
32
+ autoTyping: { full: string; revealed: number } | null
33
+ }
34
+
35
+ export type DemoMsg =
36
+ | { type: "mount" }
37
+ | { type: "advance" }
38
+ | { type: "endThinking" }
39
+ | { type: "streamTick" }
40
+ | { type: "endTools" }
41
+ | { type: "submit"; text: string }
42
+ | { type: "compact" }
43
+ | { type: "compactDone" }
44
+ | { type: "pulse" }
45
+ | { type: "autoAdvance" }
46
+ | { type: "typingTick" }
47
+ | { type: "autoTypingDone" }
48
+ | { type: "respondRandom" }
49
+ | { type: "setCtrlDPending"; pending: boolean }
50
+
51
+ export type DemoEffect = TimerEffect<DemoMsg>
52
+ export type DemoResult = TeaResult<DemoState, DemoEffect>
53
+
54
+ // ============================================================================
55
+ // Constants
56
+ // ============================================================================
57
+
58
+ const INTRO_TEXT = [
59
+ "Coding agent simulation showcasing ScrollbackList:",
60
+ " • ScrollbackList — declarative list with automatic scrollback",
61
+ " • Auto-freeze — items freeze when they scroll off-screen",
62
+ " • OSC 8 hyperlinks — clickable file paths and URLs",
63
+ " • OSC 133 markers — Cmd+↑/↓ to jump between exchanges",
64
+ " • $token theme colors — semantic color tokens",
65
+ ].join("\n")
66
+
67
+ export const INIT_STATE: DemoState = {
68
+ exchanges: [{ id: 0, role: "system", content: INTRO_TEXT }],
69
+ scriptIdx: 0,
70
+ streamPhase: "done",
71
+ revealFraction: 1,
72
+ done: false,
73
+ compacting: false,
74
+ pulse: false,
75
+ ctrlDPending: false,
76
+ contextBaseline: 0,
77
+ offScript: false,
78
+ nextId: 1,
79
+ autoTyping: null,
80
+ }
81
+
82
+ // ============================================================================
83
+ // Token & Cost Utilities
84
+ // ============================================================================
85
+
86
+ export function formatTokens(n: number): string {
87
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
88
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}K`
89
+ return String(n)
90
+ }
91
+
92
+ export function formatCost(inputTokens: number, outputTokens: number): string {
93
+ const cost = (inputTokens * INPUT_COST_PER_M + outputTokens * OUTPUT_COST_PER_M) / 1_000_000
94
+ if (cost < 0.01) return `$${cost.toFixed(4)}`
95
+ return `$${cost.toFixed(2)}`
96
+ }
97
+
98
+ /**
99
+ * Compute token stats for display and compaction.
100
+ *
101
+ * Token values in the script are CUMULATIVE — each exchange's `input` represents
102
+ * the total context consumed at that point. So:
103
+ * - `currentContext`: the LAST exchange's input tokens (= current context window usage)
104
+ * - `totalCost`: sum of all (input + output) for cost calculation (each API call costs)
105
+ */
106
+ export function computeCumulativeTokens(exchanges: Exchange[]): {
107
+ input: number
108
+ output: number
109
+ currentContext: number
110
+ } {
111
+ let input = 0
112
+ let output = 0
113
+ let currentContext = 0
114
+ for (const ex of exchanges) {
115
+ if (ex.tokens) {
116
+ input += ex.tokens.input
117
+ output += ex.tokens.output
118
+ if (ex.tokens.input > currentContext) currentContext = ex.tokens.input
119
+ }
120
+ }
121
+ return { input, output, currentContext }
122
+ }
123
+
124
+ /** Next scripted user message for footer placeholder. */
125
+ export function getNextMessage(state: DemoState, script: ScriptEntry[], autoMode: boolean): string {
126
+ if (autoMode || state.done || state.offScript || state.streamPhase !== "done" || state.exchanges.length === 0)
127
+ return ""
128
+ const entry = script[state.scriptIdx]
129
+ return entry?.role === "user" ? entry.content : ""
130
+ }
131
+
132
+ // ============================================================================
133
+ // Update Factory
134
+ // ============================================================================
135
+
136
+ export function createDemoUpdate(script: ScriptEntry[], fastMode: boolean, autoMode: boolean) {
137
+ function addExchange(state: DemoState, entry: ScriptEntry): DemoState {
138
+ const exchange: Exchange = { ...entry, id: state.nextId }
139
+ return { ...state, exchanges: [...state.exchanges, exchange], nextId: state.nextId + 1 }
140
+ }
141
+
142
+ function startStreaming(state: DemoState, entry: ScriptEntry): [DemoState, DemoEffect[]] {
143
+ const s = addExchange(state, entry)
144
+ if (entry.role !== "agent" || fastMode) {
145
+ return [{ ...s, streamPhase: "done", revealFraction: 1 }, []]
146
+ }
147
+ if (entry.thinking) {
148
+ return [{ ...s, streamPhase: "thinking", revealFraction: 0 }, [fx.delay(1200, { type: "endThinking" })]]
149
+ }
150
+ return [{ ...s, streamPhase: "streaming", revealFraction: 0 }, [fx.interval(50, { type: "streamTick" }, "reveal")]]
151
+ }
152
+
153
+ function autoAdvanceEffects(state: DemoState): DemoEffect[] {
154
+ if (state.done || state.compacting || state.streamPhase !== "done") return []
155
+ const next = script[state.scriptIdx]
156
+ if (!next) return autoMode ? [fx.delay(0, { type: "autoAdvance" })] : []
157
+ if (autoMode || next.role !== "user") return [fx.delay(fastMode ? 100 : 400, { type: "autoAdvance" })]
158
+ return []
159
+ }
160
+
161
+ function doAdvance(state: DemoState, extraEffects: DemoEffect[] = []): DemoResult {
162
+ if (state.done || state.compacting || state.streamPhase !== "done") return state
163
+ if (state.scriptIdx >= script.length) {
164
+ return autoMode ? { ...state, done: true } : state
165
+ }
166
+
167
+ const entry = script[state.scriptIdx]!
168
+ let s: DemoState = {
169
+ ...state,
170
+ scriptIdx: state.scriptIdx + 1,
171
+ }
172
+ const effects = [...extraEffects]
173
+ let streamFx: DemoEffect[]
174
+
175
+ ;[s, streamFx] = startStreaming(s, entry)
176
+ effects.push(...streamFx)
177
+
178
+ if (fastMode) {
179
+ while (s.scriptIdx < script.length && script[s.scriptIdx]!.role !== "user") {
180
+ ;[s, streamFx] = startStreaming({ ...s, scriptIdx: s.scriptIdx + 1 }, script[s.scriptIdx]!)
181
+ effects.push(...streamFx)
182
+ }
183
+ effects.push(...autoAdvanceEffects(s))
184
+ } else if (entry.role === "user") {
185
+ if (s.scriptIdx < script.length && script[s.scriptIdx]!.role === "agent") {
186
+ ;[s, streamFx] = startStreaming({ ...s, scriptIdx: s.scriptIdx + 1 }, script[s.scriptIdx]!)
187
+ effects.push(...streamFx)
188
+ }
189
+ }
190
+
191
+ return [s, effects]
192
+ }
193
+
194
+ return function update(state: DemoState, msg: DemoMsg): DemoResult {
195
+ switch (msg.type) {
196
+ case "mount":
197
+ return doAdvance(state, [fx.interval(400, { type: "pulse" }, "pulse")])
198
+
199
+ case "advance":
200
+ case "autoAdvance": {
201
+ if (autoMode && !fastMode && state.streamPhase === "done" && !state.done && !state.compacting) {
202
+ const next = script[state.scriptIdx]
203
+ if (next?.role === "user") {
204
+ return [
205
+ { ...state, autoTyping: { full: next.content, revealed: 0 } },
206
+ [fx.interval(30, { type: "typingTick" }, "typing")],
207
+ ]
208
+ }
209
+ }
210
+ if (autoMode && state.scriptIdx >= script.length && state.streamPhase === "done") {
211
+ return { ...state, done: true }
212
+ }
213
+ return doAdvance(state)
214
+ }
215
+
216
+ case "typingTick": {
217
+ if (!state.autoTyping) return state
218
+ const next = state.autoTyping.revealed + 1
219
+ if (next >= state.autoTyping.full.length) {
220
+ return [
221
+ {
222
+ ...state,
223
+ autoTyping: { ...state.autoTyping, revealed: state.autoTyping.full.length },
224
+ },
225
+ [fx.cancel("typing"), fx.delay(300, { type: "autoTypingDone" })],
226
+ ]
227
+ }
228
+ return { ...state, autoTyping: { ...state.autoTyping, revealed: next } }
229
+ }
230
+
231
+ case "autoTypingDone":
232
+ return doAdvance({ ...state, autoTyping: null })
233
+
234
+ case "endThinking":
235
+ return [
236
+ { ...state, streamPhase: "streaming", revealFraction: 0 },
237
+ [fx.interval(50, { type: "streamTick" }, "reveal")],
238
+ ]
239
+
240
+ case "streamTick": {
241
+ const last = state.exchanges[state.exchanges.length - 1]
242
+ const rate = last?.thinking ? 0.08 : 0.12
243
+ const frac = Math.min(state.revealFraction + rate, 1)
244
+ if (frac < 1) return { ...state, revealFraction: frac }
245
+
246
+ const tools = last?.toolCalls ?? []
247
+ if (tools.length > 0) {
248
+ const s = { ...state, streamPhase: "tools" as StreamPhase, revealFraction: 1 }
249
+ return [s, [fx.cancel("reveal"), fx.delay(600 * tools.length, { type: "endTools" })]]
250
+ }
251
+ const s = { ...state, streamPhase: "done" as StreamPhase, revealFraction: 1 }
252
+ return [s, [fx.cancel("reveal"), ...autoAdvanceEffects(s)]]
253
+ }
254
+
255
+ case "endTools": {
256
+ const s = { ...state, streamPhase: "done" as StreamPhase }
257
+ return [s, autoAdvanceEffects(s)]
258
+ }
259
+
260
+ case "submit": {
261
+ // Fast-forward streaming if still animating
262
+ const base =
263
+ state.streamPhase !== "done"
264
+ ? { ...state, streamPhase: "done" as StreamPhase, revealFraction: 1, autoTyping: null }
265
+ : state.autoTyping
266
+ ? { ...state, autoTyping: null }
267
+ : state
268
+ const cancelEffects: DemoEffect[] =
269
+ state.streamPhase !== "done" ? [fx.cancel("reveal"), fx.cancel("typing")] : [fx.cancel("typing")]
270
+
271
+ // Empty submit just fast-forwards (no text to queue)
272
+ if (!msg.text.trim()) return [base, cancelEffects]
273
+ if (base.done) return base
274
+
275
+ const s = addExchange(base, {
276
+ role: "user",
277
+ content: msg.text,
278
+ tokens: { input: msg.text.length * 4, output: 0 },
279
+ })
280
+
281
+ if (s.scriptIdx < script.length) {
282
+ let nextIdx = s.scriptIdx
283
+ while (nextIdx < script.length && script[nextIdx]!.role === "user") nextIdx++
284
+ return [{ ...s, scriptIdx: nextIdx }, [...cancelEffects, fx.delay(150, { type: "autoAdvance" })]]
285
+ }
286
+
287
+ return [{ ...s, offScript: true }, [...cancelEffects, fx.delay(150, { type: "respondRandom" })]]
288
+ }
289
+
290
+ case "respondRandom": {
291
+ const resp = RANDOM_AGENT_RESPONSES[Math.floor(Math.random() * RANDOM_AGENT_RESPONSES.length)]!
292
+ const [s, effects] = startStreaming(state, resp)
293
+ return [{ ...s, offScript: true }, effects]
294
+ }
295
+
296
+ case "compact": {
297
+ if (state.done || state.compacting) return state
298
+ const cumulative = computeCumulativeTokens(state.exchanges)
299
+ return [
300
+ {
301
+ ...state,
302
+ streamPhase: "done",
303
+ revealFraction: 1,
304
+ compacting: true,
305
+ contextBaseline: cumulative.currentContext,
306
+ exchanges: state.exchanges,
307
+ autoTyping: null,
308
+ },
309
+ [fx.cancel("reveal"), fx.cancel("typing"), fx.delay(fastMode ? 300 : 3000, { type: "compactDone" })],
310
+ ]
311
+ }
312
+
313
+ case "compactDone":
314
+ return doAdvance({ ...state, compacting: false })
315
+
316
+ case "pulse":
317
+ return { ...state, pulse: !state.pulse }
318
+
319
+ case "setCtrlDPending":
320
+ return { ...state, ctrlDPending: msg.pending }
321
+
322
+ default:
323
+ return state
324
+ }
325
+ }
326
+ }
@@ -0,0 +1,19 @@
1
+ /** Tool call in an exchange (Read, Edit, Bash, etc.). */
2
+ export interface ToolCall {
3
+ tool: string
4
+ args: string
5
+ output: string[]
6
+ }
7
+
8
+ /** A single exchange in the conversation. */
9
+ export interface Exchange {
10
+ id: number
11
+ role: "user" | "agent" | "system"
12
+ content: string
13
+ thinking?: string
14
+ toolCalls?: ToolCall[]
15
+ tokens?: { input: number; output: number }
16
+ }
17
+
18
+ /** Script entry — exchange data before id is assigned. */
19
+ export type ScriptEntry = Omit<Exchange, "id">
@@ -0,0 +1,201 @@
1
+ /**
2
+ * App Todo - Layer 3 Example
3
+ *
4
+ * Demonstrates pipe() composition with createApp(), withReact(), and
5
+ * withTerminal() — the canonical pattern for building full apps.
6
+ *
7
+ * The plugin system separates concerns:
8
+ * - createApp() — store + event handlers (what the app does)
9
+ * - withReact() — element binding (what the app renders)
10
+ * - withTerminal() — I/O binding (where the app runs)
11
+ *
12
+ * pipe() composes them left-to-right: each plugin enhances the
13
+ * app object, wrapping run() so the final call needs no arguments.
14
+ *
15
+ * Usage: bun examples/apps/app-todo.tsx
16
+ *
17
+ * Controls:
18
+ * j/k - Move cursor down/up
19
+ * a - Add new todo
20
+ * x - Toggle completed
21
+ * d - Delete todo
22
+ * Esc/q - Quit
23
+ */
24
+
25
+ import React from "react"
26
+ import { Box, Text, Muted, Kbd } from "../../src/index.js"
27
+ import { createApp, useApp, type AppHandle } from "@silvery/tea/create-app"
28
+ import { pipe, withReact, withTerminal } from "@silvery/tea/plugins"
29
+ import { ExampleBanner, type ExampleMeta } from "../_banner.js"
30
+
31
+ export const meta: ExampleMeta = {
32
+ name: "Todo App",
33
+ description: "Layer 3: pipe() + createApp() + withReact() + withTerminal()",
34
+ features: ["pipe()", "createApp()", "withReact()", "withTerminal()"],
35
+ }
36
+
37
+ // ============================================================================
38
+ // Types
39
+ // ============================================================================
40
+
41
+ type Todo = {
42
+ id: number
43
+ text: string
44
+ completed: boolean
45
+ }
46
+
47
+ type State = {
48
+ todos: Todo[]
49
+ cursor: number
50
+ nextId: number
51
+ addTodo: (text: string) => void
52
+ toggleTodo: () => void
53
+ deleteTodo: () => void
54
+ moveCursor: (delta: number) => void
55
+ }
56
+
57
+ // ============================================================================
58
+ // Components
59
+ // ============================================================================
60
+
61
+ function TodoItem({ todo, isCursor }: { todo: Todo; isCursor: boolean }) {
62
+ return (
63
+ <Box>
64
+ <Text color={isCursor ? "$primary" : undefined}>{isCursor ? "› " : " "}</Text>
65
+ <Text color={todo.completed ? "$success" : undefined} strikethrough={todo.completed}>
66
+ {todo.completed ? "✓" : "○"} {todo.text}
67
+ </Text>
68
+ </Box>
69
+ )
70
+ }
71
+
72
+ function TodoList() {
73
+ const todos = useApp((s: State) => s.todos)
74
+ const cursor = useApp((s: State) => s.cursor)
75
+
76
+ return (
77
+ <Box flexDirection="column">
78
+ {todos.map((todo, i) => (
79
+ <TodoItem key={todo.id} todo={todo} isCursor={i === cursor} />
80
+ ))}
81
+ {todos.length === 0 && <Muted>No todos. Press 'a' to add one.</Muted>}
82
+ </Box>
83
+ )
84
+ }
85
+
86
+ function TodoApp() {
87
+ return (
88
+ <Box flexDirection="column" padding={1}>
89
+ <TodoList />
90
+ <Text> </Text>
91
+ <Muted>
92
+ <Kbd>j/k</Kbd> move <Kbd>x</Kbd> toggle <Kbd>a</Kbd> add <Kbd>d</Kbd> delete <Kbd>Esc/q</Kbd> quit
93
+ </Muted>
94
+ </Box>
95
+ )
96
+ }
97
+
98
+ // ============================================================================
99
+ // App — pipe() composition
100
+ // ============================================================================
101
+
102
+ // 1. createApp() defines the store and event handlers
103
+ const baseApp = createApp<Record<string, unknown>, State>(
104
+ () => (set, get) => ({
105
+ todos: [
106
+ { id: 1, text: "Learn silvery plugin composition", completed: true },
107
+ { id: 2, text: "Build an app with pipe()", completed: false },
108
+ { id: 3, text: "Ship to production", completed: false },
109
+ ],
110
+ cursor: 0,
111
+ nextId: 4,
112
+
113
+ addTodo: (text: string) =>
114
+ set((s) => ({
115
+ todos: [...s.todos, { id: s.nextId, text, completed: false }],
116
+ nextId: s.nextId + 1,
117
+ })),
118
+
119
+ toggleTodo: () =>
120
+ set((s) => ({
121
+ todos: s.todos.map((t, i) => (i === s.cursor ? { ...t, completed: !t.completed } : t)),
122
+ })),
123
+
124
+ deleteTodo: () =>
125
+ set((s) => {
126
+ const newTodos = s.todos.filter((_, i) => i !== s.cursor)
127
+ return {
128
+ todos: newTodos,
129
+ cursor: Math.min(s.cursor, newTodos.length - 1),
130
+ }
131
+ }),
132
+
133
+ moveCursor: (delta: number) =>
134
+ set((s) => ({
135
+ cursor: Math.max(0, Math.min(s.cursor + delta, s.todos.length - 1)),
136
+ })),
137
+ }),
138
+
139
+ {
140
+ "term:key": (data, ctx) => {
141
+ const { input: k, key } = data as {
142
+ input: string
143
+ key: { escape: boolean }
144
+ }
145
+ const state = ctx.get() as State
146
+ if (key.escape) return "exit"
147
+ switch (k) {
148
+ case "j":
149
+ state.moveCursor(1)
150
+ break
151
+ case "k":
152
+ state.moveCursor(-1)
153
+ break
154
+ case "x":
155
+ state.toggleTodo()
156
+ break
157
+ case "d":
158
+ if (state.todos.length > 0) state.deleteTodo()
159
+ break
160
+ case "a":
161
+ state.addTodo(`New todo ${state.nextId}`)
162
+ break
163
+ case "q":
164
+ return "exit"
165
+ }
166
+ },
167
+ },
168
+ )
169
+
170
+ // 2. pipe() composes plugins left-to-right:
171
+ // - withReact() binds the element, so run() needs no JSX argument
172
+ // - withTerminal() binds stdin/stdout, so run() needs no options
173
+ // Note: pipe() type composition requires casts at plugin boundaries
174
+ // because AppDefinition's typed run() doesn't structurally match
175
+ // the generic RunnableApp constraint used by plugins.
176
+ const app = pipe(
177
+ baseApp as any,
178
+ withReact(
179
+ <ExampleBanner meta={meta} controls="j/k move x toggle a add d delete Esc/q quit">
180
+ <TodoApp />
181
+ </ExampleBanner>,
182
+ ),
183
+ withTerminal(process as any),
184
+ )
185
+
186
+ // ============================================================================
187
+ // Main
188
+ // ============================================================================
189
+
190
+ async function main() {
191
+ // 3. run() needs no arguments — element and terminal are already bound
192
+ const handle = (await app.run()) as AppHandle<State>
193
+
194
+ await handle.waitUntilExit()
195
+
196
+ console.log("\nFinal state:", handle.store.getState().todos.length, "todos")
197
+ }
198
+
199
+ if (import.meta.main) {
200
+ main().catch(console.error)
201
+ }