-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.ts
More file actions
633 lines (548 loc) · 19.8 KB
/
commands.ts
File metadata and controls
633 lines (548 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/**
* CLI Commands
*
* Defines the CLI interface for the chat application.
*/
import { type Prompt, Telemetry } from "@effect/ai"
import { Command, Options, Prompt as CliPrompt } from "@effect/cli"
import { type Error as PlatformError, FileSystem, HttpServer, type Terminal } from "@effect/platform"
import { BunHttpServer, BunStream } from "@effect/platform-bun"
import { Chunk, Console, DateTime, Effect, Fiber, Layer, Option, Schema, Stream } from "effect"
import { AgentRegistry } from "../agent-registry.ts"
import { AppConfig, resolveBaseDir } from "../config.ts"
import {
type AgentName,
type AssistantMessageEvent,
ContextEvent,
makeEventId,
type TextDeltaEvent,
UserMessageEvent
} from "../domain.ts"
import { EventStore } from "../event-store.ts"
import { makeRouter } from "../http-routes.ts"
import { layercodeCommand } from "../layercode/index.ts"
import { printTraceLinks } from "../tracing.ts"
const encodeEvent = Schema.encodeSync(ContextEvent)
export const configFileOption = Options.file("config").pipe(
Options.withAlias("c"),
Options.withDescription("Path to YAML config file"),
Options.optional
)
export const cwdOption = Options.directory("cwd").pipe(
Options.withDescription("Working directory override"),
Options.optional
)
export const stdoutLogLevelOption = Options.choice("stdout-log-level", [
"trace",
"debug",
"info",
"warn",
"error",
"none"
]).pipe(
Options.withDescription("Stdout log level (overrides config)"),
Options.optional
)
export const llmOption = Options.text("llm").pipe(
Options.withDescription(
"LLM provider:model (e.g., openai:gpt-4.1-mini, anthropic:claude-sonnet-4-5-20250929). " +
"See README for full model list. Can also be set via LLM env var."
),
Options.optional
)
const nameOption = Options.text("name").pipe(
Options.withAlias("n"),
Options.withDescription("Context name (slug identifier for the conversation)"),
Options.optional
)
const messageOption = Options.text("message").pipe(
Options.withAlias("m"),
Options.withDescription("Message to send (non-interactive single-turn mode)"),
Options.optional
)
const rawOption = Options.boolean("raw").pipe(
Options.withAlias("r"),
Options.withDescription("Output events as JSON objects, one per line"),
Options.withDefault(false)
)
const showEphemeralOption = Options.boolean("show-ephemeral").pipe(
Options.withAlias("e"),
Options.withDescription("Include ephemeral events (streaming deltas) in output"),
Options.withDefault(false)
)
const scriptOption = Options.boolean("script").pipe(
Options.withAlias("s"),
Options.withDescription("Script mode: read JSONL events from stdin, output JSONL events"),
Options.withDefault(false)
)
const imageOption = Options.file("image").pipe(
Options.withAlias("i"),
Options.withDescription("Path to an image file to include with the message"),
Options.repeated
)
interface OutputOptions {
raw: boolean
showEphemeral: boolean
}
/**
* Handle a single context event based on output options.
*/
const handleEvent = (
event: ContextEvent,
options: OutputOptions
): Effect.Effect<void, PlatformError.PlatformError, Terminal.Terminal> =>
Effect.gen(function*() {
if (options.raw) {
// Raw mode outputs all events as JSON (no filtering)
yield* Console.log(JSON.stringify(encodeEvent(event)))
return
}
// Non-raw mode: output streaming deltas and final message
// Use _tag check directly since events from stream may be plain objects
if (event._tag === "TextDeltaEvent") {
yield* Console.log((event as TextDeltaEvent).delta)
return
}
if (event._tag === "AssistantMessageEvent") {
yield* Console.log((event as AssistantMessageEvent).content)
return
}
})
/** Run the event stream, handling each event */
const runEventStream = (
contextName: string,
userMessage: string,
options: OutputOptions,
images: ReadonlyArray<string> = []
) =>
Effect.gen(function*() {
const registry = yield* AgentRegistry
const agent = yield* registry.getOrCreate(contextName as AgentName)
// Get existing events first (includes SessionStartedEvent emitted during agent creation)
const existingEvents = yield* agent.getEvents
for (const event of existingEvents) {
yield* handleEvent(event, options)
}
// Get current context to build proper event
const ctx = yield* agent.getReducedContext
// Create user event with triggersAgentTurn=true
const userEvent = new UserMessageEvent({
id: makeEventId(agent.contextName, ctx.nextEventNumber),
timestamp: DateTime.unsafeNow(),
agentName: agent.agentName,
parentEventId: Option.none(),
triggersAgentTurn: true,
content: userMessage,
images: images.length > 0 ? images : undefined
})
// Subscribe to events - wait for turn completion first
const turnFiber = yield* agent.events.pipe(
Stream.takeUntil((e) => e._tag === "AgentTurnCompletedEvent" || e._tag === "AgentTurnFailedEvent"),
Stream.runForEach((event) => handleEvent(event, options)),
Effect.fork
)
// Add event to agent - triggers LLM turn
yield* agent.addEvent(userEvent)
// Wait for turn to complete
yield* Fiber.join(turnFiber).pipe(Effect.catchAllCause(() => Effect.void))
// Subscribe to capture SessionEndedEvent
const sessionEndFiber = yield* agent.events.pipe(
Stream.takeUntil((e) => e._tag === "SessionEndedEvent"),
Stream.runForEach((event) => handleEvent(event, options)),
Effect.fork
)
// End session (emits SessionEndedEvent)
yield* agent.endSession
// Wait for SessionEndedEvent
yield* Fiber.join(sessionEndFiber).pipe(Effect.catchAllCause(() => Effect.void))
})
/** CLI interaction mode - determines how input/output is handled */
const InteractionMode = Schema.Literal("single-turn", "pipe", "script", "tty-interactive")
type InteractionMode = typeof InteractionMode.Type
const determineMode = (options: {
message: Option.Option<string>
script: boolean
}): InteractionMode => {
const hasMessage = Option.isSome(options.message) &&
Option.getOrElse(options.message, () => "").trim() !== ""
if (hasMessage) return "single-turn"
if (options.script) return "script"
if (process.stdin.isTTY) return "tty-interactive"
return "pipe"
}
const utf8Decoder = new TextDecoder("utf-8")
const readAllStdin: Effect.Effect<string> = BunStream.stdin.pipe(
Stream.mapChunks(Chunk.map((bytes) => utf8Decoder.decode(bytes))),
Stream.runCollect,
Effect.map((chunks) => Chunk.join(chunks, "").trim())
)
/** Simple input message schema - accepts minimal fields */
const SimpleInputMessage = Schema.Struct({
_tag: Schema.Union(
Schema.Literal("UserMessage"),
Schema.Literal("UserMessageEvent"),
Schema.Literal("SystemPrompt"),
Schema.Literal("SystemPromptEvent")
),
content: Schema.String
})
type SimpleInputMessage = typeof SimpleInputMessage.Type
const stdinEvents = BunStream.stdin.pipe(
Stream.mapChunks(Chunk.map((bytes) => utf8Decoder.decode(bytes))),
Stream.splitLines,
Stream.filter((line) => line.trim() !== ""),
Stream.mapEffect((line) =>
Effect.try(() => JSON.parse(line) as unknown).pipe(
Effect.flatMap((json) => Schema.decodeUnknown(SimpleInputMessage)(json))
)
)
)
const scriptInteractiveLoop = (contextName: string, options: OutputOptions) =>
Effect.gen(function*() {
const registry = yield* AgentRegistry
const agent = yield* registry.getOrCreate(contextName as AgentName)
// Output existing events first (includes SessionStartedEvent)
const existingEvents = yield* agent.getEvents
for (const event of existingEvents) {
yield* handleEvent(event, options)
}
yield* stdinEvents.pipe(
Stream.mapEffect((inputMsg) =>
Effect.gen(function*() {
yield* Console.log(JSON.stringify(inputMsg))
const isUserMessage = inputMsg._tag === "UserMessage" || inputMsg._tag === "UserMessageEvent"
if (isUserMessage) {
// Get current context
const ctx = yield* agent.getReducedContext
// Create proper event with triggersAgentTurn
const userEvent = new UserMessageEvent({
id: makeEventId(agent.contextName, ctx.nextEventNumber),
timestamp: DateTime.unsafeNow(),
agentName: agent.agentName,
parentEventId: Option.none(),
triggersAgentTurn: true,
content: inputMsg.content
})
// Subscribe to events - wait for turn completion to process next message
const eventFiber = yield* agent.events.pipe(
Stream.takeUntil((e) => e._tag === "AgentTurnCompletedEvent" || e._tag === "AgentTurnFailedEvent"),
Stream.runForEach((outputEvent) => handleEvent(outputEvent, options)),
Effect.fork
)
yield* agent.addEvent(userEvent)
yield* Fiber.join(eventFiber).pipe(Effect.catchAllCause(() => Effect.void))
} else {
yield* Effect.logDebug("SystemPrompt events in script mode are echoed but not persisted")
}
})
),
Stream.runDrain
)
// Subscribe to capture SessionEndedEvent
const sessionEndFiber = yield* agent.events.pipe(
Stream.takeUntil((e) => e._tag === "SessionEndedEvent"),
Stream.runForEach((event) => handleEvent(event, options)),
Effect.fork
)
yield* agent.endSession
yield* Fiber.join(sessionEndFiber).pipe(Effect.catchAllCause(() => Effect.void))
})
const NEW_CONTEXT_VALUE = "__new__"
const selectOrCreateContext = Effect.gen(function*() {
const store = yield* EventStore
const contextNames = yield* store.list()
// Convert context names (e.g. "my-agent-v1") to agent names (e.g. "my-agent")
const agentNames = contextNames
.map((name) => name.replace(/-v1$/, ""))
.filter((name, index, arr) => arr.indexOf(name) === index) as Array<AgentName>
if (agentNames.length === 0) {
yield* Console.log("No existing contexts found.")
return yield* CliPrompt.text({ message: "Enter a name for your new context" })
}
const choices = [
{
title: "+ New context",
value: NEW_CONTEXT_VALUE,
description: "Start fresh with a new context"
},
...agentNames.map((name) => ({
title: name,
value: name,
description: "Continue with this context"
}))
]
const selected = yield* CliPrompt.select({
message: "Select context",
choices
})
if (selected === NEW_CONTEXT_VALUE) {
return yield* CliPrompt.text({ message: "Enter a name for your new conversation" })
}
return selected
})
const generateRandomContextName = (): string => {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
const suffix = Array.from({ length: 5 }, () => chars[Math.floor(Math.random() * chars.length)]).join("")
return `chat-${suffix}`
}
const makeChatUILayer = () =>
Layer.unwrapEffect(
Effect.gen(function*() {
const { ChatUI } = yield* Effect.promise(() => import("./chat-ui.ts"))
return ChatUI.Default
})
)
/** Read an image file and return as base64 data URI */
const readImageAsDataUri = (imagePath: string) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const data = yield* fs.readFile(imagePath)
// Detect media type from extension
const ext = imagePath.toLowerCase().split(".").pop() ?? ""
const mediaType = ext === "png" ?
"image/png"
: ext === "gif" ?
"image/gif"
: ext === "webp" ?
"image/webp"
: "image/jpeg"
// Convert to base64
const base64 = Buffer.from(data).toString("base64")
return `data:${mediaType};base64,${base64}`
})
const runChat = (options: {
name: Option.Option<string>
message: Option.Option<string>
raw: boolean
script: boolean
showEphemeral: boolean
images: ReadonlyArray<string>
}) =>
Effect.gen(function*() {
yield* Effect.logDebug("Starting chat session")
const mode = determineMode(options)
const contextName = Option.getOrElse(options.name, generateRandomContextName)
const outputOptions: OutputOptions = {
raw: mode === "script" || options.raw,
showEphemeral: mode === "script" || options.showEphemeral
}
// Convert image paths to data URIs
const imageDataUris = options.images.length > 0
? yield* Effect.all(options.images.map(readImageAsDataUri))
: []
switch (mode) {
case "single-turn": {
const message = Option.getOrElse(options.message, () => "")
yield* runEventStream(contextName, message, outputOptions, imageDataUris)
if (!outputOptions.raw) {
yield* printTraceLinks
}
break
}
case "pipe": {
const input = yield* readAllStdin
if (input !== "") {
yield* runEventStream(contextName, input, { raw: false, showEphemeral: false }, imageDataUris)
}
break
}
case "script": {
yield* scriptInteractiveLoop(contextName, outputOptions)
break
}
case "tty-interactive": {
const resolvedName = Option.isSome(options.name)
? contextName
: yield* selectOrCreateContext
const { ChatUI } = yield* Effect.promise(() => import("./chat-ui.ts"))
const chatUI = yield* ChatUI
yield* chatUI.runChat(resolvedName).pipe(
Effect.catchAllCause(() => Effect.void),
Effect.ensuring(printTraceLinks.pipe(Effect.flatMap(() => Console.log("\nGoodbye!"))))
)
break
}
}
}).pipe(
Effect.provide(makeChatUILayer()),
Effect.withSpan("chat-session")
)
const collectText = (parts: ReadonlyArray<{ type: string; text?: string }>) =>
parts
.filter((p): p is typeof p & { text: string } => p.type === "text" && !!p.text)
.map((p) => p.text)
.join("")
interface CleanMessage {
role: "system" | "user" | "assistant"
content: string
}
const promptToCleanMessages = (prompt: Prompt.Prompt): Array<CleanMessage> => {
const raw: Array<CleanMessage> = []
for (const msg of prompt.content) {
if (msg.role === "system") {
raw.push({ role: "system", content: msg.content })
} else if (msg.role === "user" || msg.role === "assistant") {
const text = collectText(msg.content)
if (text) raw.push({ role: msg.role, content: text })
}
}
if (raw.length === 0) return []
const result: Array<CleanMessage> = []
let current = { ...raw[0]! }
for (let i = 1; i < raw.length; i++) {
const msg = raw[i]!
if (msg.role === current.role) {
current.content += msg.content
} else {
result.push(current)
current = { ...msg }
}
}
result.push(current)
return result
}
const extractResponseText = (parts: ReadonlyArray<{ type: string; text?: string; delta?: string }>): string =>
parts
.filter((p): p is typeof p & { text: string } | typeof p & { delta: string } =>
(p.type === "text" && !!p.text) || (p.type === "text-delta" && !!p.delta)
)
.map((p) => ("text" in p && p.text) ? p.text : ("delta" in p && p.delta) ? p.delta : "")
.join("")
export const GenAISpanTransformerLayer = Layer.succeed(
Telemetry.CurrentSpanTransformer,
({ prompt, response, span }) => {
const input = promptToCleanMessages(prompt)
const outputText = extractResponseText(response as ReadonlyArray<{ type: string; text?: string; delta?: string }>)
const output = outputText ? [{ role: "assistant", content: outputText }] : []
span.attribute("input", JSON.stringify(input))
span.attribute("output", JSON.stringify(output))
}
)
const chatCommand = Command.make(
"chat",
{
name: nameOption,
message: messageOption,
raw: rawOption,
script: scriptOption,
showEphemeral: showEphemeralOption,
images: imageOption
},
({ images, message, name, raw, script, showEphemeral }) =>
runChat({ images, message, name, raw, script, showEphemeral })
).pipe(Command.withDescription("Chat with an AI assistant using persistent context history"))
const logTestCommand = Command.make(
"log-test",
{},
() =>
Effect.gen(function*() {
yield* Effect.logTrace("TRACE_MESSAGE")
yield* Effect.logDebug("DEBUG_MESSAGE")
yield* Effect.logInfo("INFO_MESSAGE")
yield* Effect.logWarning("WARN_MESSAGE")
yield* Effect.logError("ERROR_MESSAGE")
yield* Console.log("LOG_TEST_DONE")
})
).pipe(Command.withDescription("Emit test log messages at all levels (for testing logging config)"))
const traceTestCommand = Command.make(
"trace-test",
{},
() =>
Effect.gen(function*() {
yield* Console.log("Trace-test command executed")
}).pipe(Effect.withSpan("trace-test-command"))
).pipe(Command.withDescription("Simple command for testing tracing"))
const clearCommand = Command.make(
"clear",
{},
() =>
Effect.gen(function*() {
const config = yield* AppConfig
const baseDir = resolveBaseDir(config)
const fs = yield* FileSystem.FileSystem
const exists = yield* fs.exists(baseDir)
if (!exists) {
yield* Console.log(`No data directory found at ${baseDir}`)
return
}
yield* fs.remove(baseDir, { recursive: true })
yield* Console.log(`Deleted ${baseDir}`)
})
).pipe(Command.withDescription("Delete the .mini-agent data directory"))
const portOption = Options.integer("port").pipe(
Options.withAlias("p"),
Options.withDescription("Port to listen on"),
Options.optional
)
const hostOption = Options.text("host").pipe(
Options.withDescription("Host to bind to"),
Options.optional
)
/** Generic serve command - starts HTTP server with /agent/:agentName endpoint */
export const serveCommand = Command.make(
"serve",
{
port: portOption,
host: hostOption
},
({ host, port }) =>
Effect.gen(function*() {
const config = yield* AppConfig
const actualPort = Option.getOrElse(port, () => config.port)
const actualHost = Option.getOrElse(host, () => config.host)
yield* Console.log(`Starting HTTP server on http://${actualHost}:${actualPort}`)
yield* Console.log("")
yield* Console.log("Endpoints:")
yield* Console.log(" POST /agent/:agentName")
yield* Console.log(" Send user message, receive SSE stream of events")
yield* Console.log("")
yield* Console.log(" GET /agent/:agentName/events")
yield* Console.log(" Subscribe to agent event stream (SSE)")
yield* Console.log("")
yield* Console.log(" GET /agent/:agentName/state")
yield* Console.log(" Get current agent state")
yield* Console.log("")
yield* Console.log(" GET /health")
yield* Console.log(" Health check endpoint")
yield* Console.log("")
yield* Console.log("Example:")
yield* Console.log(` curl -X POST http://${actualHost}:${actualPort}/agent/test \\`)
yield* Console.log(` -H "Content-Type: application/json" \\`)
yield* Console.log(` -d '{"_tag":"UserMessageEvent","content":"hello"}'`)
yield* Console.log("")
// Create server layer with configured port/host
// Set idleTimeout high for SSE streaming - Bun defaults to 10s which kills long-running streams
const serverLayer = BunHttpServer.layer({ port: actualPort, hostname: actualHost, idleTimeout: 120 })
// Use Layer.launch to keep the server running
return yield* Layer.launch(
HttpServer.serve(makeRouter).pipe(
Layer.provide(serverLayer)
)
)
})
).pipe(
Command.withDescription("Start generic HTTP server for agent requests")
)
const rootCommand = Command.make(
"mini-agent",
{
configFile: configFileOption,
cwd: cwdOption,
stdoutLogLevel: stdoutLogLevelOption,
llm: llmOption
}
).pipe(
Command.withSubcommands([
chatCommand,
serveCommand,
layercodeCommand,
logTestCommand,
traceTestCommand,
clearCommand
]),
Command.withDescription("AI assistant with persistent context and comprehensive configuration")
)
export const cli = Command.run(rootCommand, {
name: "mini-agent",
version: "1.0.0"
})