@castari/cli 0.0.4 β†’ 0.0.6

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.
@@ -1 +1,5 @@
1
- export declare function init(): Promise<void>;
1
+ type InitOptions = {
2
+ demo?: boolean;
3
+ };
4
+ export declare function init(options?: InitOptions): Promise<void>;
5
+ export {};
@@ -2,7 +2,10 @@ import inquirer from 'inquirer';
2
2
  import { writeFile, mkdir } from 'fs/promises';
3
3
  import { join } from 'path';
4
4
  import chalk from 'chalk';
5
- export async function init() {
5
+ export async function init(options = {}) {
6
+ if (options.demo) {
7
+ return initDemo();
8
+ }
6
9
  console.log(chalk.blue('πŸ€– Initializing new Castari agent project...'));
7
10
  const answers = await inquirer.prompt([
8
11
  {
@@ -71,3 +74,620 @@ serve({
71
74
  console.log(chalk.green('βœ… Project initialized!'));
72
75
  console.log(chalk.white('Run `bun install` to install dependencies.'));
73
76
  }
77
+ async function initDemo() {
78
+ console.log(chalk.blue('🎨 Initializing Castari demo (web + agent)...'));
79
+ const demoRoot = 'castari_demo';
80
+ const agentDir = join(demoRoot, 'agent');
81
+ const webDir = join(demoRoot, 'web');
82
+ const writeJson = async (path, obj) => writeFile(path, JSON.stringify(obj, null, 2));
83
+ // Agent scaffold
84
+ await mkdir(join(agentDir, 'src'), { recursive: true });
85
+ await writeJson(join(agentDir, 'package.json'), {
86
+ name: 'castari-demo-agent',
87
+ version: '0.1.0',
88
+ private: true,
89
+ type: 'module',
90
+ scripts: {
91
+ dev: 'bun run src/agent.ts',
92
+ deploy: 'castari deploy',
93
+ start: 'bun run src/agent.ts',
94
+ },
95
+ dependencies: {
96
+ '@castari/sdk': '^0.0.4',
97
+ '@anthropic-ai/claude-agent-sdk': '^0.1.50',
98
+ },
99
+ castari: {
100
+ volume: 'castari-demo-workspace',
101
+ },
102
+ });
103
+ await writeJson(join(agentDir, 'tsconfig.json'), {
104
+ compilerOptions: {
105
+ target: 'ESNext',
106
+ module: 'ESNext',
107
+ moduleResolution: 'bundler',
108
+ strict: true,
109
+ skipLibCheck: true,
110
+ esModuleInterop: true,
111
+ },
112
+ include: ['src'],
113
+ });
114
+ await writeFile(join(agentDir, '.env.example'), 'ANTHROPIC_API_KEY=sk-ant-...\n# CASTARI_PLATFORM_URL=http://localhost:3000\n');
115
+ await writeFile(join(agentDir, 'src', 'agent.ts'), `import { serve } from '@castari/sdk'
116
+
117
+ serve({
118
+ systemPrompt: [
119
+ 'You are Castari Demo Agent.',
120
+ 'Keep responses concise and friendly.',
121
+ 'Feel free to explain how you can help with code or product questions.',
122
+ ].join(' '),
123
+ includePartialMessages: true,
124
+ })
125
+ `);
126
+ // Web scaffold
127
+ await mkdir(join(webDir, 'app', 'api', 'chat'), { recursive: true });
128
+ await mkdir(join(webDir, 'lib'), { recursive: true });
129
+ await writeJson(join(webDir, 'package.json'), {
130
+ name: 'castari-demo-web',
131
+ version: '0.1.0',
132
+ private: true,
133
+ scripts: {
134
+ dev: 'next dev',
135
+ build: 'next build',
136
+ start: 'next start',
137
+ },
138
+ dependencies: {
139
+ '@castari/sdk': '^0.0.4',
140
+ next: '14.2.3',
141
+ react: '18.3.1',
142
+ 'react-dom': '18.3.1',
143
+ },
144
+ devDependencies: {
145
+ '@types/node': '^20.11.0',
146
+ '@types/react': '^18.2.0',
147
+ '@types/react-dom': '^18.2.0',
148
+ typescript: '^5.6.3',
149
+ },
150
+ });
151
+ await writeJson(join(webDir, 'tsconfig.json'), {
152
+ compilerOptions: {
153
+ target: 'ES2020',
154
+ lib: ['dom', 'dom.iterable', 'esnext'],
155
+ allowJs: true,
156
+ skipLibCheck: true,
157
+ strict: true,
158
+ noEmit: true,
159
+ esModuleInterop: true,
160
+ module: 'esnext',
161
+ moduleResolution: 'bundler',
162
+ resolveJsonModule: true,
163
+ isolatedModules: true,
164
+ jsx: 'preserve',
165
+ incremental: true,
166
+ types: ['node'],
167
+ baseUrl: '.',
168
+ paths: {
169
+ '@/*': ['./*'],
170
+ },
171
+ },
172
+ include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],
173
+ exclude: ['node_modules'],
174
+ });
175
+ await writeFile(join(webDir, 'next-env.d.ts'), `/// <reference types="next" />
176
+ /// <reference types="next/types/global" />
177
+ /// <reference types="next/image-types/global" />
178
+
179
+ // NOTE: This file should not be edited
180
+ `);
181
+ await writeFile(join(webDir, 'next.config.mjs'), `/** @type {import('next').NextConfig} */
182
+ const nextConfig = {
183
+ experimental: {
184
+ serverActions: false
185
+ }
186
+ }
187
+
188
+ export default nextConfig
189
+ `);
190
+ await writeFile(join(webDir, '.env.example'), 'ANTHROPIC_API_KEY=sk-ant-...\n# CASTARI_PLATFORM_URL=http://localhost:3000\n# CASTARI_DEBUG=false\n');
191
+ await writeFile(join(webDir, 'app', 'globals.css'), `:root {
192
+ color-scheme: light;
193
+ background: #f5f5f5;
194
+ font-family: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
195
+ }
196
+
197
+ * {
198
+ box-sizing: border-box;
199
+ }
200
+
201
+ body {
202
+ margin: 0;
203
+ background: radial-gradient(circle at 20% 20%, #f7f0ff 0, #f5f5f5 35%), radial-gradient(circle at 80% 0%, #e0f4ff 0, #f5f5f5 30%);
204
+ color: #0f172a;
205
+ min-height: 100vh;
206
+ }
207
+
208
+ a {
209
+ color: inherit;
210
+ text-decoration: none;
211
+ }
212
+
213
+ .chat-container {
214
+ max-width: 760px;
215
+ margin: 0 auto;
216
+ padding: 32px 16px 64px;
217
+ display: flex;
218
+ flex-direction: column;
219
+ gap: 16px;
220
+ }
221
+
222
+ .card {
223
+ background: rgba(255, 255, 255, 0.85);
224
+ backdrop-filter: blur(6px);
225
+ border: 1px solid rgba(15, 23, 42, 0.06);
226
+ border-radius: 16px;
227
+ box-shadow: 0 20px 60px rgba(15, 23, 42, 0.12);
228
+ padding: 24px;
229
+ }
230
+
231
+ .heading {
232
+ display: flex;
233
+ align-items: center;
234
+ gap: 12px;
235
+ font-size: 22px;
236
+ font-weight: 700;
237
+ }
238
+
239
+ .badge {
240
+ font-size: 12px;
241
+ font-weight: 600;
242
+ color: #0ea5e9;
243
+ background: rgba(14, 165, 233, 0.1);
244
+ padding: 6px 10px;
245
+ border-radius: 999px;
246
+ border: 1px solid rgba(14, 165, 233, 0.2);
247
+ }
248
+
249
+ .messages {
250
+ display: flex;
251
+ flex-direction: column;
252
+ gap: 12px;
253
+ }
254
+
255
+ .bubble {
256
+ padding: 14px 16px;
257
+ border-radius: 14px;
258
+ max-width: 90%;
259
+ line-height: 1.5;
260
+ font-size: 15px;
261
+ }
262
+
263
+ .bubble.assistant {
264
+ background: #0f172a;
265
+ color: white;
266
+ align-self: flex-start;
267
+ border-bottom-left-radius: 4px;
268
+ }
269
+
270
+ .bubble.user {
271
+ background: white;
272
+ color: #0f172a;
273
+ border: 1px solid rgba(15, 23, 42, 0.06);
274
+ align-self: flex-end;
275
+ border-bottom-right-radius: 4px;
276
+ }
277
+
278
+ .form {
279
+ display: flex;
280
+ gap: 12px;
281
+ margin-top: 8px;
282
+ }
283
+
284
+ .input {
285
+ flex: 1;
286
+ padding: 14px 16px;
287
+ border-radius: 12px;
288
+ border: 1px solid rgba(15, 23, 42, 0.08);
289
+ font-size: 15px;
290
+ outline: none;
291
+ transition: border-color 0.15s ease;
292
+ }
293
+
294
+ .input:focus {
295
+ border-color: #0ea5e9;
296
+ box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.12);
297
+ }
298
+
299
+ .button {
300
+ background: linear-gradient(135deg, #0ea5e9, #6366f1);
301
+ color: white;
302
+ border: none;
303
+ border-radius: 12px;
304
+ padding: 12px 18px;
305
+ font-weight: 700;
306
+ cursor: pointer;
307
+ box-shadow: 0 12px 25px rgba(99, 102, 241, 0.35);
308
+ min-width: 110px;
309
+ transition: transform 0.12s ease, box-shadow 0.12s ease, opacity 0.12s ease;
310
+ }
311
+
312
+ .button:disabled {
313
+ opacity: 0.6;
314
+ cursor: not-allowed;
315
+ box-shadow: none;
316
+ }
317
+
318
+ .button:not(:disabled):hover {
319
+ transform: translateY(-1px);
320
+ box-shadow: 0 16px 30px rgba(99, 102, 241, 0.45);
321
+ }
322
+
323
+ .status {
324
+ font-size: 13px;
325
+ color: #475569;
326
+ margin-top: 6px;
327
+ }
328
+
329
+ .pill-row {
330
+ display: flex;
331
+ gap: 8px;
332
+ flex-wrap: wrap;
333
+ }
334
+
335
+ .pill {
336
+ padding: 6px 10px;
337
+ border-radius: 999px;
338
+ background: rgba(15, 23, 42, 0.06);
339
+ font-size: 12px;
340
+ color: #0f172a;
341
+ border: 1px solid rgba(15, 23, 42, 0.08);
342
+ }
343
+ `);
344
+ await writeFile(join(webDir, 'app', 'layout.tsx'), `import './globals.css'
345
+ import { ReactNode } from 'react'
346
+
347
+ export default function RootLayout({ children }: { children: ReactNode }) {
348
+ return (
349
+ <html lang="en">
350
+ <head>
351
+ <title>Castari Demo Chat</title>
352
+ </head>
353
+ <body>{children}</body>
354
+ </html>
355
+ )
356
+ }
357
+ `);
358
+ await writeFile(join(webDir, 'app', 'page.tsx'), `"use client"
359
+
360
+ import { FormEvent, useState } from 'react'
361
+
362
+ type ChatMessage = {
363
+ role: 'assistant' | 'user'
364
+ content: string
365
+ }
366
+
367
+ export default function Home() {
368
+ const [messages, setMessages] = useState<ChatMessage[]>([
369
+ {
370
+ role: 'assistant',
371
+ content:
372
+ 'Hi! I am the Castari demo agent. Ask me anything about your code, architecture, or how this demo works.',
373
+ },
374
+ ])
375
+ const [input, setInput] = useState('')
376
+ const [status, setStatus] = useState<string | null>(null)
377
+ const [sending, setSending] = useState(false)
378
+
379
+ const sendMessage = async (event: FormEvent) => {
380
+ event.preventDefault()
381
+ if (!input.trim() || sending) return
382
+
383
+ const userMessage: ChatMessage = { role: 'user', content: input.trim() }
384
+ setMessages(prev => [...prev, userMessage])
385
+ setInput('')
386
+ setSending(true)
387
+ setStatus('Connecting to your sandbox...')
388
+
389
+ // Add assistant placeholder immediately so we can stream into it
390
+ let assistantIndex = -1
391
+ setMessages(prev => {
392
+ assistantIndex = prev.length
393
+ return [...prev, { role: 'assistant', content: '' }]
394
+ })
395
+
396
+ try {
397
+ const response = await fetch('/api/chat', {
398
+ method: 'POST',
399
+ headers: { 'Content-Type': 'application/json' },
400
+ body: JSON.stringify({ message: userMessage.content }),
401
+ })
402
+
403
+ if (!response.ok || !response.body) {
404
+ const errorText = await response.text()
405
+ throw new Error(errorText || 'Request failed')
406
+ }
407
+
408
+ const reader = response.body.getReader()
409
+ const decoder = new TextDecoder()
410
+
411
+ while (true) {
412
+ const { value, done } = await reader.read()
413
+ if (done) break
414
+ const chunk = decoder.decode(value, { stream: true })
415
+ if (!chunk) continue
416
+ const idx = assistantIndex
417
+ setMessages(prev =>
418
+ prev.map((m, i) => (i === idx ? { ...m, content: m.content + chunk } : m)),
419
+ )
420
+ }
421
+
422
+ setStatus(null)
423
+ } catch (err) {
424
+ const message =
425
+ err instanceof Error ? err.message : 'Something went wrong talking to the agent.'
426
+ setMessages(prev =>
427
+ prev.map((m, i) =>
428
+ i === assistantIndex
429
+ ? { ...m, content: \`I hit an error: \${message}\` }
430
+ : m,
431
+ ),
432
+ )
433
+ setStatus('Temporary hiccup. Try again in a moment.')
434
+ } finally {
435
+ setSending(false)
436
+ }
437
+ }
438
+
439
+ return (
440
+ <main className="chat-container">
441
+ <div className="card">
442
+ <div className="heading">
443
+ <span>Castari Demo Chat</span>
444
+ <span className="badge">Single sandbox</span>
445
+ </div>
446
+ <p style={{ margin: '8px 0 16px', color: '#475569' }}>
447
+ This UI connects to a Castari agent running in a Daytona sandbox. Messages reuse the same
448
+ sandbox (via labels) so the conversation stays warm while the sandbox is alive.
449
+ </p>
450
+
451
+ <div className="pill-row" style={{ marginBottom: 12 }}>
452
+ <span className="pill">Snapshot: castari-demo-agent</span>
453
+ <span className="pill">Volume: castari-demo-workspace</span>
454
+ <span className="pill">Labels: app=castari-demo, env=local</span>
455
+ </div>
456
+
457
+ <div className="messages">
458
+ {messages.map((m, idx) => (
459
+ <div key={idx} className={\`bubble \${m.role}\`}>
460
+ {m.content}
461
+ </div>
462
+ ))}
463
+ </div>
464
+
465
+ <form className="form" onSubmit={sendMessage}>
466
+ <input
467
+ className="input"
468
+ placeholder="Ask the Castari agent anything..."
469
+ value={input}
470
+ onChange={e => setInput(e.target.value)}
471
+ />
472
+ <button className="button" type="submit" disabled={sending}>
473
+ {sending ? 'Talking…' : 'Send'}
474
+ </button>
475
+ </form>
476
+ {status && <div className="status">{status}</div>}
477
+ </div>
478
+ </main>
479
+ )
480
+ }
481
+ `);
482
+ await writeFile(join(webDir, 'lib', 'castari-client.ts'), `import { CastariClient, type WSOutputMessage } from '@castari/sdk/client'
483
+
484
+ const SNAPSHOT = 'castari-demo-agent'
485
+ const LABELS = { app: 'castari-demo', env: 'local' }
486
+ const VOLUME = 'castari-demo-workspace'
487
+
488
+ let clientPromise: Promise<CastariClient> | null = null
489
+
490
+ async function createClient() {
491
+ const anthropicApiKey = process.env.ANTHROPIC_API_KEY
492
+ if (!anthropicApiKey) {
493
+ throw new Error('ANTHROPIC_API_KEY is required to contact the Castari agent')
494
+ }
495
+
496
+ const client = new CastariClient({
497
+ snapshot: SNAPSHOT,
498
+ volume: VOLUME,
499
+ labels: LABELS,
500
+ platformUrl: process.env.CASTARI_PLATFORM_URL,
501
+ anthropicApiKey,
502
+ debug: process.env.CASTARI_DEBUG === 'true',
503
+ })
504
+
505
+ await client.start()
506
+ return client
507
+ }
508
+
509
+ async function getClient() {
510
+ if (!clientPromise) {
511
+ clientPromise = createClient()
512
+ }
513
+ return clientPromise
514
+ }
515
+
516
+ function extractText(content: unknown): string {
517
+ if (typeof content === 'string') return content
518
+ if (Array.isArray(content)) {
519
+ return content
520
+ .map(block => {
521
+ if (typeof block === 'string') return block
522
+ if (block && typeof block === 'object' && 'text' in block) {
523
+ return (block as { text?: string }).text ?? ''
524
+ }
525
+ return ''
526
+ })
527
+ .join('\\n')
528
+ }
529
+ if (content && typeof content === 'object' && 'text' in (content as any)) {
530
+ return (content as any).text ?? ''
531
+ }
532
+ return ''
533
+ }
534
+
535
+ function extractStreamDelta(event: any): string {
536
+ if (!event || typeof event !== 'object') return ''
537
+ if (event.type === 'content_block_delta' && event.delta?.text) {
538
+ return String(event.delta.text)
539
+ }
540
+ if (event.type === 'content_block_start' && event.content_block?.text) {
541
+ return String(event.content_block.text)
542
+ }
543
+ if (event.type === 'message_delta' && event.delta?.text) {
544
+ return String(event.delta.text)
545
+ }
546
+ return ''
547
+ }
548
+
549
+ export async function streamMessageToAgent(
550
+ message: string,
551
+ handlers: {
552
+ onChunk?: (text: string) => void
553
+ },
554
+ ): Promise<void> {
555
+ const client = await getClient()
556
+
557
+ return new Promise((resolve, reject) => {
558
+ const timeout = setTimeout(() => {
559
+ cleanup()
560
+ reject(new Error('Timed out waiting for agent response'))
561
+ }, 60000)
562
+
563
+ let sawStreamChunk = false
564
+
565
+ const unsubscribe = client.onMessage((msg: WSOutputMessage) => {
566
+ if (msg.type !== 'sdk_message') return
567
+ const data: any = msg.data
568
+
569
+ if (data.type === 'stream_event') {
570
+ const deltaText = extractStreamDelta(data.event)
571
+ if (deltaText) {
572
+ sawStreamChunk = true
573
+ handlers.onChunk?.(deltaText)
574
+ }
575
+ } else if (data.type === 'assistant_message') {
576
+ finish()
577
+ } else if (data.type === 'result' && data.subtype === 'success') {
578
+ if (!sawStreamChunk) {
579
+ const text =
580
+ typeof data.result === 'string'
581
+ ? data.result
582
+ : extractText(data.result?.output || data.result?.message || '')
583
+ if (text) handlers.onChunk?.(text)
584
+ }
585
+ finish()
586
+ } else if (data.type === 'error') {
587
+ cleanup()
588
+ reject(new Error(data.error || 'Agent returned an error'))
589
+ }
590
+ })
591
+
592
+ const cleanup = () => {
593
+ clearTimeout(timeout)
594
+ unsubscribe()
595
+ }
596
+
597
+ const finish = () => {
598
+ cleanup()
599
+ resolve()
600
+ }
601
+
602
+ try {
603
+ client.send({
604
+ type: 'user_message',
605
+ data: {
606
+ type: 'user',
607
+ message: { role: 'user', content: message },
608
+ } as any,
609
+ })
610
+ } catch (err) {
611
+ cleanup()
612
+ reject(err)
613
+ }
614
+ })
615
+ }
616
+ `);
617
+ await writeFile(join(webDir, 'app', 'api', 'chat', 'route.ts'), `export const runtime = 'nodejs'
618
+
619
+ import { streamMessageToAgent } from '@/lib/castari-client'
620
+
621
+ export async function POST(request: Request) {
622
+ const body = (await request.json()) as { message?: string }
623
+ const message = body.message?.trim()
624
+
625
+ if (!message) {
626
+ return new Response(JSON.stringify({ error: 'message is required' }), {
627
+ status: 400,
628
+ headers: { 'Content-Type': 'application/json' },
629
+ })
630
+ }
631
+
632
+ const encoder = new TextEncoder()
633
+
634
+ const stream = new ReadableStream({
635
+ async start(controller) {
636
+ try {
637
+ await streamMessageToAgent(message, {
638
+ onChunk: text => controller.enqueue(encoder.encode(text)),
639
+ })
640
+ controller.close()
641
+ } catch (err) {
642
+ controller.error(err)
643
+ }
644
+ },
645
+ })
646
+
647
+ return new Response(stream, {
648
+ headers: {
649
+ 'Content-Type': 'text/plain; charset=utf-8',
650
+ 'Transfer-Encoding': 'chunked',
651
+ },
652
+ })
653
+ }
654
+ `);
655
+ // Demo README
656
+ await writeFile(join(demoRoot, 'README.md'), `# Castari Demo (Web + Agent)
657
+
658
+ This demo pairs a minimal Castari agent with a simple Next.js chat UI.
659
+
660
+ Structure:
661
+ - \`agent/\` – Castari agent you deploy to the platform.
662
+ - \`web/\` – Next.js app that chats with the agent via \`CastariClient\`.
663
+
664
+ ## Prerequisites
665
+ - Bun (for the Castari CLI and scripts)
666
+ - Node 18+ (for the Next.js app)
667
+ - \`ANTHROPIC_API_KEY\`
668
+ - Castari Platform running locally or reachable via \`CASTARI_PLATFORM_URL\`
669
+
670
+ ## 1) Prepare and deploy the agent
671
+ \`\`\`bash
672
+ cd castari_demo/agent
673
+ cp .env.example .env # add ANTHROPIC_API_KEY (and CASTARI_PLATFORM_URL if self-hosted)
674
+ bun install # pulls @castari/sdk from npm
675
+ castari deploy # builds snapshot castari-demo-agent (CLI must be installed)
676
+ # Optional: bun run src/agent.ts # run locally without the CLI
677
+ \`\`\`
678
+
679
+ ## 2) Run the web app
680
+ \`\`\`bash
681
+ cd ../web
682
+ cp .env.example .env # add ANTHROPIC_API_KEY and CASTARI_PLATFORM_URL if needed
683
+ npm install # or bun install
684
+ npm run dev # opens http://localhost:3000
685
+ \`\`\`
686
+
687
+ The web app uses a single sandbox labeled \`{ app: 'castari-demo', env: 'local' }\`. That keeps the same sandbox alive across requests so chats stay in memory as long as you don’t delete it (\`stop({ delete: false })\` behavior).
688
+ `);
689
+ console.log(chalk.green('βœ… Demo scaffold created at ./castari_demo'));
690
+ console.log(chalk.white('Next steps:'));
691
+ console.log(chalk.white(' 1) cd castari_demo/agent && bun install && castari deploy'));
692
+ console.log(chalk.white(' 2) cd ../web && npm install && npm run dev'));
693
+ }
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { dev } from './commands/dev';
7
7
  const cli = cac('castari');
8
8
  cli
9
9
  .command('init', 'Initialize a new Castari agent project')
10
+ .option('--demo', 'Generate a Castari demo (web + agent) scaffold')
10
11
  .action(init);
11
12
  cli
12
13
  .command('deploy', 'Deploy the agent to the Castari Platform')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@castari/cli",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "castari": "./dist/index.js"