-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-routes.ts
More file actions
194 lines (156 loc) · 6.42 KB
/
http-routes.ts
File metadata and controls
194 lines (156 loc) · 6.42 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
/**
* HTTP Routes.
*
* Endpoints:
* - POST /agent/:agentName - Send message, receive SSE stream of events
* - GET /agent/:agentName/events - Subscribe to agent events (SSE)
* - GET /agent/:agentName/state - Get reduced agent state
* - GET /health - Health check
*/
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "@effect/platform"
import { Chunk, Effect, Fiber, Schema, Stream } from "effect"
import { AgentRegistry } from "./agent-registry.ts"
import { type AgentName, ContextEvent, makeBaseEventFields, UserMessageEvent } from "./domain.ts"
const encodeEvent = Schema.encodeSync(ContextEvent)
/** Encode a ContextEvent as an SSE data line */
const encodeSSE = (event: ContextEvent): Uint8Array =>
new TextEncoder().encode(`data: ${JSON.stringify(encodeEvent(event))}\n\n`)
/** Input message schema - accepts both legacy and new tag names */
const InputMessage = Schema.Struct({
_tag: Schema.Union(Schema.Literal("UserMessage"), Schema.Literal("UserMessageEvent")),
content: Schema.String
})
type InputMessage = typeof InputMessage.Type
/** Parse JSON body into InputMessage */
const parseBody = (body: string) =>
Effect.gen(function*() {
const json = yield* Effect.try({
try: () => JSON.parse(body) as unknown,
catch: (e) => new Error(`Invalid JSON: ${e instanceof Error ? e.message : String(e)}`)
})
return yield* Schema.decodeUnknown(InputMessage)(json)
})
/** Handler for POST /agent/:agentName */
const agentHandler = Effect.gen(function*() {
const request = yield* HttpServerRequest.HttpServerRequest
const registry = yield* AgentRegistry
const params = yield* HttpRouter.params
const agentName = params.agentName
if (!agentName) {
return HttpServerResponse.text("Missing agentName", { status: 400 })
}
yield* Effect.logDebug("POST /agent/:agentName", { agentName })
// Read body
const body = yield* request.text
if (body.trim() === "") {
return HttpServerResponse.text("Empty request body", { status: 400 })
}
const parseResult = yield* parseBody(body).pipe(Effect.either)
if (parseResult._tag === "Left") {
return HttpServerResponse.text(parseResult.left.message, { status: 400 })
}
const message = parseResult.right
// Get or create agent
const agent = yield* registry.getOrCreate(agentName as AgentName)
// Get existing events to include initial session events
const existingEvents = yield* agent.getEvents
const ctx = yield* agent.getReducedContext
// Prepare user event
const userEvent = new UserMessageEvent({
...makeBaseEventFields(agentName as AgentName, agent.contextName, ctx.nextEventNumber, true),
content: message.content
})
// Subscribe BEFORE adding event to guarantee we catch all events
// PubSub.subscribe guarantees subscription is established when this completes
const liveEvents = yield* agent.subscribe
// Fork collection before adding event
const eventFiber = yield* liveEvents.pipe(
Stream.takeUntil((e) =>
e._tag === "AgentTurnCompletedEvent" ||
e._tag === "AgentTurnFailedEvent" ||
e._tag === "AgentTurnInterruptedEvent"
),
Stream.runCollect,
Effect.fork
)
yield* agent.addEvent(userEvent)
// Wait for the turn to complete and get all new events
const newEventsChunk = yield* Fiber.join(eventFiber).pipe(
Effect.catchAll(() => Effect.succeed(Chunk.empty<ContextEvent>()))
)
const newEvents = Chunk.toArray(newEventsChunk)
// Build SSE stream: existing events + user event + new events from turn
const allEvents: Array<ContextEvent> = [...existingEvents, userEvent, ...newEvents]
const sseStream = Stream.fromIterable(allEvents).pipe(
Stream.map(encodeSSE)
)
return HttpServerResponse.stream(sseStream, {
contentType: "text/event-stream",
headers: {
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
})
})
/** Handler for GET /agent/:agentName/events - Subscribe to agent event stream */
const agentEventsHandler = Effect.gen(function*() {
const registry = yield* AgentRegistry
const params = yield* HttpRouter.params
const agentName = params.agentName
if (!agentName) {
return HttpServerResponse.text("Missing agentName", { status: 400 })
}
yield* Effect.logDebug("GET /agent/:agentName/events", { agentName })
const agent = yield* registry.getOrCreate(agentName as AgentName)
// Subscribe to live events FIRST to guarantee we don't miss any
// PubSub.subscribe guarantees subscription is established when this completes
const liveEvents = yield* agent.subscribe
// Get existing events (captured at subscription time)
const existingEvents = yield* agent.getEvents
const existingStream = Stream.fromIterable(existingEvents)
// Stream terminates when SessionEndedEvent is received
const sseStream = Stream.concat(existingStream, liveEvents).pipe(
Stream.takeUntil((e) => e._tag === "SessionEndedEvent"),
Stream.map(encodeSSE)
)
return HttpServerResponse.stream(sseStream, {
contentType: "text/event-stream",
headers: {
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
})
})
/** Handler for GET /agent/:agentName/state - Get reduced agent state */
const agentStateHandler = Effect.gen(function*() {
const registry = yield* AgentRegistry
const params = yield* HttpRouter.params
const agentName = params.agentName
if (!agentName) {
return HttpServerResponse.text("Missing agentName", { status: 400 })
}
yield* Effect.logDebug("GET /agent/:agentName/state", { agentName })
const agent = yield* registry.getOrCreate(agentName as AgentName)
const reducedContext = yield* agent.getReducedContext
return yield* HttpServerResponse.json({
agentName,
contextName: agent.contextName,
nextEventNumber: reducedContext.nextEventNumber,
currentTurnNumber: reducedContext.currentTurnNumber,
messageCount: reducedContext.messages.length,
hasLlmConfig: reducedContext.llmConfig._tag === "Some",
isAgentTurnInProgress: reducedContext.agentTurnStartedAtEventId._tag === "Some"
})
})
/** Health check endpoint */
const healthHandler = Effect.gen(function*() {
yield* Effect.logDebug("GET /health")
return yield* HttpServerResponse.json({ status: "ok" })
})
/** HTTP router */
export const makeRouter = HttpRouter.empty.pipe(
HttpRouter.post("/agent/:agentName", agentHandler),
HttpRouter.get("/agent/:agentName/events", agentEventsHandler),
HttpRouter.get("/agent/:agentName/state", agentStateHandler),
HttpRouter.get("/health", healthHandler)
)