@arcforge/core 2.0.166

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 (39) hide show
  1. package/README.md +31 -0
  2. package/package.json +37 -0
  3. package/src/Axon.ts +260 -0
  4. package/src/cognet/cognet.ts +318 -0
  5. package/src/cognet/index.ts +4 -0
  6. package/src/index.ts +11 -0
  7. package/src/modules/context.ts +90 -0
  8. package/src/modules/index.ts +6 -0
  9. package/src/modules/load.ts +119 -0
  10. package/src/modules/modules.ts +87 -0
  11. package/src/modules/setup.ts +91 -0
  12. package/src/platform/blueprint.ts +201 -0
  13. package/src/platform/boot.ts +160 -0
  14. package/src/platform/bus.ts +207 -0
  15. package/src/platform/hooks.ts +30 -0
  16. package/src/platform/index.ts +18 -0
  17. package/src/platform/inject.ts +236 -0
  18. package/src/runtime/handle.ts +283 -0
  19. package/src/runtime/index.ts +2 -0
  20. package/src/runtime/inference.ts +221 -0
  21. package/src/runtime/runtime.ts +207 -0
  22. package/src/runtime/server/connect-auth.ts +123 -0
  23. package/src/runtime/server/endpoints.ts +257 -0
  24. package/src/runtime/server/h3.ts +33 -0
  25. package/src/runtime/server/index.ts +8 -0
  26. package/src/runtime/server/middleware.ts +59 -0
  27. package/src/runtime/server/plugins.ts +23 -0
  28. package/src/runtime/server/routes.ts +33 -0
  29. package/src/runtime/server/server.ts +138 -0
  30. package/src/runtime/server/session-view.ts +100 -0
  31. package/src/runtime/server/sse.ts +45 -0
  32. package/src/runtime/server/streams.ts +186 -0
  33. package/src/runtime/source/context.ts +67 -0
  34. package/src/runtime/source/render.ts +90 -0
  35. package/src/runtime/source/scripts.ts +55 -0
  36. package/src/tools/index.ts +11 -0
  37. package/src/tools/load.ts +119 -0
  38. package/src/tools/mediate.ts +92 -0
  39. package/src/tools/tools.ts +88 -0
@@ -0,0 +1,59 @@
1
+ import { createApp, defineEventHandler, createError } from "h3"
2
+ import type { AxonMiddleware } from "@arcforge/types"
3
+
4
+ type MiddlewareOpts = {
5
+ h3: ReturnType<typeof createApp>
6
+ entries: AxonMiddleware[]
7
+ }
8
+
9
+ /**
10
+ * Applies pre-resolved, pre-ordered middleware. No discovery, no conflict
11
+ * resolution.
12
+ *
13
+ * ── A middleware that failed to load BLOCKS, it does not vanish ─────────────
14
+ *
15
+ * An entry carrying `failed` is one a module shipped that would not load. It
16
+ * is replaced with a handler that refuses every request rather than dropped
17
+ * from the chain — the single most dangerous degradation available here would
18
+ * be to skip it, because middleware commonly carries auth and validation and a
19
+ * skipped one is a request path running without the checks its author wrote.
20
+ *
21
+ * That is a security hole wearing the costume of a working server, and it is
22
+ * exactly the failure mode a reverse proxy exists to prevent: nginx answers
23
+ * 502 for a backend it cannot reach, it does not serve the request without it.
24
+ *
25
+ * The agent is unaffected — it boots, thinks and replies. Only the HTTP
26
+ * surface fails closed, because only the HTTP surface was guarded.
27
+ */
28
+ export function Middleware(opts: MiddlewareOpts) {
29
+ for (const entry of opts.entries) {
30
+ if (entry.failed !== undefined) {
31
+ opts.h3.use(defineEventHandler(() => {
32
+ throw createError({
33
+ statusCode: 503,
34
+ statusMessage: "Middleware Unavailable",
35
+ // The reason goes in `data`, not `message`: h3 strips
36
+ // `message` outside dev to avoid leaking internals, and a
37
+ // bare 503 sends the reader looking at the route instead of
38
+ // at the guard that did not load.
39
+ //
40
+ // Naming it is not a leak worth avoiding — whoever receives
41
+ // this is the operator of the agent that failed to boot its
42
+ // own middleware, and they are the only person who can fix
43
+ // it.
44
+ data: {
45
+ middleware: entry.name,
46
+ reason: entry.failed,
47
+ },
48
+ })
49
+ }))
50
+ continue
51
+ }
52
+ if (entry.handler) opts.h3.use(entry.handler)
53
+ }
54
+
55
+ return {
56
+ registered: opts.entries.filter(e => e.failed === undefined).map(e => e.name),
57
+ blocked: opts.entries.filter(e => e.failed !== undefined).map(e => e.name),
58
+ }
59
+ }
@@ -0,0 +1,23 @@
1
+ import { err } from "@arcforge/err"
2
+ import type { AxonHandle, AxonPlugin } from "@arcforge/types"
3
+
4
+ type PluginsOpts = {
5
+ entries: AxonPlugin[]
6
+ /** THIS runtime's handle, passed to each plugin — never a global, so plugins stay bound to their own Axon() instance. */
7
+ axon: AxonHandle
8
+ }
9
+
10
+ /**
11
+ * Runs plugins in order, before routes are mounted. A throwing plugin aborts
12
+ * boot — plugins are the one place in server/ where failure must be fatal,
13
+ * not warned-and-skipped (unlike middleware/route loading upstream).
14
+ */
15
+ export async function Plugins(opts: PluginsOpts) {
16
+ for (const entry of opts.entries) {
17
+ try {
18
+ await entry.fn(opts.axon)
19
+ } catch (cause) {
20
+ throw err("PLUGIN_BOOT_FAILED", { detail: `plugin "${entry.name}" failed during boot`, context: { name: entry.name }, cause })
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,33 @@
1
+ import { createRouter } from "h3"
2
+ import type { AxonRoute } from "@arcforge/types"
3
+ import { H3T } from "./h3"
4
+
5
+ type RoutesOpts = {
6
+ h3: H3T
7
+ entries: AxonRoute[]
8
+ }
9
+
10
+ /**
11
+ * Mounts agent-owned routes onto the router. These are the routes that
12
+ * already won any conflict against module routes upstream — always
13
+ * mounted, never skipped.
14
+ */
15
+ export function Routes(opts: RoutesOpts) {
16
+ const h3 = opts.h3
17
+
18
+ for (const route of opts.entries) {
19
+ mountRoute(h3.router, route)
20
+ }
21
+
22
+ return {
23
+ mounted: opts.entries.map(r => `${r.method} ${r.path}`),
24
+ }
25
+ }
26
+
27
+ export function mountRoute(router: ReturnType<typeof createRouter>, route: AxonRoute) {
28
+ if (route.method === "WS" || route.method === "ANY") {
29
+ router.use(route.path, route.handler)
30
+ return
31
+ }
32
+ router[route.method.toLowerCase() as "get" | "post" | "put" | "patch" | "delete"](route.path, route.handler)
33
+ }
@@ -0,0 +1,138 @@
1
+ import { getResponseStatus } from "h3"
2
+ import { Endpoints } from "./endpoints"
3
+ import { H3 } from "./h3"
4
+ import { Middleware } from "./middleware"
5
+ import { Plugins } from "./plugins"
6
+ import { Routes } from "./routes"
7
+ import type { AxonBlueprint, AxonHandle } from "@arcforge/types"
8
+ import { AxonBusT, AxonHooksT } from "../../platform"
9
+ import type { AxonSessionT } from "@arcforge/session"
10
+ import type { EnginesT } from "@arcforge/engines/catalogue"
11
+
12
+ type ServerOpts = {
13
+ blueprint: AxonBlueprint
14
+ hooks: AxonHooksT
15
+ /** The runtime handle, forwarded to each server plugin's fn — passed, never global. */
16
+ axon: AxonHandle
17
+ /**
18
+ * The raw event bus. Trusted-host-only and deliberately absent from
19
+ * AxonHandle — /_axon/events bridges it to SSE, which is the one place the
20
+ * server needs it. Passed explicitly rather than widening the handle.
21
+ */
22
+ bus: AxonBusT
23
+ /** Environmental — the request log commits here, same as every other runtime fact. */
24
+ session: AxonSessionT
25
+ /** Resolved inference roles — the health endpoint reports the primary binding. */
26
+ engines?: EnginesT
27
+ }
28
+
29
+ /**
30
+ * Axon Server factory.
31
+ *
32
+ * Everything here is a pure applier — the blueprint arrives fully resolved
33
+ * (conflict resolution, ordering, discovery, and module merging all happened
34
+ * upstream in the CLI/manifest build step). There is no module-specific
35
+ * mounting step here — module routes are already merged into
36
+ * blueprint.server.routes. Order below matters:
37
+ * env -> middleware -> plugins (pre-route hook) -> routes
38
+ *
39
+ * @orchestrator - this should not contain low level logic
40
+ * @behaviour - all error handling should exist in lower layers
41
+ */
42
+ export async function AxonServer(opts: ServerOpts) {
43
+ const h3 = H3()
44
+
45
+ // framework-level hook point — ahead of user middleware, so request:before
46
+ // observes every request regardless of what user middleware does with it
47
+ h3.app.use((event) => opts.hooks.callHook("request:before", event))
48
+
49
+ const middleware = Middleware({
50
+ h3: h3.app,
51
+ entries: opts.blueprint.server.middleware,
52
+ })
53
+
54
+ // AxonServer() is rebuilt whole on every reload, and Plugins() reruns in
55
+ // full — reset first or a plugin's hook.hook() calls accumulate one extra
56
+ // registration per reload (same handler firing N times for one event).
57
+ opts.hooks.reset()
58
+
59
+ await Plugins({
60
+ entries: opts.blueprint.server.plugins,
61
+ axon: opts.axon,
62
+ })
63
+
64
+ // Framework-reserved /_axon/* surface — mounted BEFORE user routes so it
65
+ // is always present and can never be shadowed. This is the normalized wire
66
+ // contract AxonCloud.attach() speaks to, independent of authored routes.
67
+ const endpoints = Endpoints({
68
+ h3: h3,
69
+ axon: opts.axon,
70
+ bus: opts.bus,
71
+ blueprint: opts.blueprint,
72
+ ...(opts.engines ? { engines: opts.engines } : {}),
73
+ })
74
+
75
+ const routes = Routes({
76
+ h3: h3,
77
+ entries: opts.blueprint.server.routes,
78
+ })
79
+
80
+ // request:after must run once the route handler has actually resolved —
81
+ // h3's layer stack is sequential, not onion-style, so this can't be a
82
+ // plain .use() registered before the router (that would fire alongside
83
+ // request:before, ahead of the route). Wrap the router's own handler instead.
84
+ //
85
+ // The same wrapper commits the request record: this is the one point that
86
+ // sees a request both arrive and settle, so it is the only honest place to
87
+ // measure it. Recorded as a single settled fact rather than a span — one
88
+ // line per request is what a server log wants, and a request has no
89
+ // interesting interior for a flame graph to nest inside.
90
+ h3.mount(async (event) => {
91
+ const started = Date.now()
92
+ const method = event.method
93
+ const path = event.path
94
+ try {
95
+ const response = await h3.router.handler(event)
96
+ await opts.hooks.callHook("request:after", event)
97
+ await commitRequest(method, path, getResponseStatus(event), started)
98
+ return response
99
+ } catch (cause) {
100
+ // h3 turns a thrown H3Error into a real response upstream of this
101
+ // wrapper, so the record must be written here or a failed request
102
+ // leaves no trace at all. The throw is re-raised untouched.
103
+ const status = (cause as { statusCode?: number }).statusCode ?? 500
104
+ await commitRequest(method, path, status, started)
105
+ throw cause
106
+ }
107
+ })
108
+
109
+ /**
110
+ * One durable line per request, whatever the outcome — except for the
111
+ * framework's own /_axon/* surface.
112
+ *
113
+ * That surface IS the observability plane (health polls, session
114
+ * hydration, the SSE event stream). Recording a request to /_axon/events
115
+ * into the very log /_axon/events serves is self-referential: a connected
116
+ * client generates log lines by observing, a health poll every second
117
+ * writes a line a second forever, and real application traffic drowns in
118
+ * it. The log exists to answer "what did my agent's HTTP surface do",
119
+ * and the devtools plane is not part of that answer.
120
+ */
121
+ async function commitRequest(method: string, path: string, status: number, started: number): Promise<void> {
122
+ if (path.startsWith("/_axon/")) return
123
+ await opts.session.commit("axon:server:request", {
124
+ method,
125
+ path,
126
+ status,
127
+ durationMs: Date.now() - started,
128
+ })
129
+ }
130
+
131
+ return {
132
+ middleware: middleware,
133
+ endpoints: endpoints,
134
+ routes: routes,
135
+ /** Web-standard fetch handler — bind it to a port with Bun.serve or any web-fetch runtime. */
136
+ handler: h3.toFetchHandler(),
137
+ }
138
+ }
@@ -0,0 +1,100 @@
1
+ import { createError } from "h3"
2
+ import type { AxonHandle, AxonSessionQuery, AxonSessionScope, AxonSessionSnapshot } from "@arcforge/types"
3
+
4
+ /**
5
+ * SessionView — projecting the live session onto the wire.
6
+ *
7
+ * Owns one concern completely: turning an untrusted query string into a
8
+ * bounded, cursor-carrying view of the session. Both read endpoints use it —
9
+ * /_axon/session for the snapshot, /_axon/events for the same filters over
10
+ * the replay — so the two can never disagree about what `since`, `limit` and
11
+ * `include` mean.
12
+ */
13
+
14
+ /** The three session views a client may ask for. Derived from nothing else — this IS the list. */
15
+ export const SCOPES: AxonSessionScope[] = ["entries", "log", "kernelLog"]
16
+
17
+ /**
18
+ * Narrow untrusted query params into AxonSessionQuery at the boundary. A
19
+ * malformed value is a 400 here rather than a surprise downstream — an
20
+ * unparseable `since` silently treated as 0 would re-send the entire history
21
+ * and look like duplicated messages in the client.
22
+ */
23
+ export function parseQuery(raw: Record<string, unknown>): AxonSessionQuery {
24
+ const query: AxonSessionQuery = {}
25
+
26
+ for (const key of ["since", "limit"] as const) {
27
+ const value = raw[key]
28
+ if (value === undefined) continue
29
+ const parsed = Number(value)
30
+ if (!Number.isInteger(parsed) || parsed < 0) {
31
+ // `message`, not `statusMessage`: h3 will sanitize the latter, which
32
+ // would strip the detail that makes a 400 actionable.
33
+ throw createError({ statusCode: 400, message: `_axon/session: ${key} must be a non-negative integer` })
34
+ }
35
+ query[key] = parsed
36
+ }
37
+
38
+ if (raw.include !== undefined) {
39
+ const names = String(raw.include).split(",").map(name => name.trim()).filter(Boolean)
40
+ const invalid = names.filter(name => !SCOPES.includes(name as AxonSessionScope))
41
+ if (invalid.length > 0) {
42
+ throw createError({
43
+ statusCode: 400,
44
+ message: `_axon/session: unknown include "${invalid.join(", ")}" — expected ${SCOPES.join(", ")}`,
45
+ })
46
+ }
47
+ query.include = names as AxonSessionScope[]
48
+ }
49
+
50
+ return query
51
+ }
52
+
53
+ /**
54
+ * Build the wire snapshot from the live session.
55
+ *
56
+ * `since` filters on `time.seq` — the monotonic per-session counter — so a
57
+ * client can ask for "everything after what I already have" and get an exact
58
+ * delta rather than a best-effort time window. `limit` keeps the most recent
59
+ * events and reports `truncated`, because a tail that claims to be a full
60
+ * history is a lie the UI cannot detect.
61
+ */
62
+ export function snapshot(axon: AxonHandle, query: AxonSessionQuery): AxonSessionSnapshot {
63
+ const include = query.include ?? SCOPES
64
+ // undefined (no since=) means "everything"; a NUMBER means "strictly after
65
+ // that seq" — including since=0, which is a real cursor because the first
66
+ // event of every session carries seq 0.
67
+ const since = query.since
68
+ const limit = query.limit
69
+
70
+ function select<T extends { time: { seq: number } }>(source: readonly T[], scope: AxonSessionScope): { rows: T[]; capped: boolean } {
71
+ if (!include.includes(scope)) return { rows: [], capped: false }
72
+ const filtered = since === undefined ? [...source] : source.filter(event => event.time.seq > since)
73
+ if (limit !== undefined && filtered.length > limit) {
74
+ return { rows: filtered.slice(-limit), capped: true }
75
+ }
76
+ return { rows: filtered, capped: false }
77
+ }
78
+
79
+ const entries = select(axon.session.entries, "entries")
80
+ const log = select(axon.session.log, "log")
81
+ const kernelLog = select(axon.session.kernelLog, "kernelLog")
82
+
83
+ // The cursor is the high-water mark across everything RETURNED, so a client
84
+ // that omitted kernelLog does not skip past kernel events it never received.
85
+ const cursor = Math.max(
86
+ 0,
87
+ ...entries.rows.map(event => event.time.seq),
88
+ ...log.rows.map(event => event.time.seq),
89
+ ...kernelLog.rows.map(event => event.time.seq),
90
+ )
91
+
92
+ return {
93
+ id: axon.session.id,
94
+ entries: entries.rows,
95
+ log: log.rows,
96
+ kernelLog: kernelLog.rows,
97
+ cursor,
98
+ truncated: entries.capped || log.capped || kernelLog.capped,
99
+ }
100
+ }
@@ -0,0 +1,45 @@
1
+ import { getResponseHeaders, setResponseHeader } from "h3"
2
+
3
+ /**
4
+ * Sse — the one place this runtime speaks Server-Sent Events.
5
+ *
6
+ * Both streaming endpoints (/_axon/stream and /_axon/events) need the same
7
+ * three things: the SSE response headers, a frame encoder, and the awkward
8
+ * copy of h3's accumulated headers onto a real Response. Owning them here
9
+ * means an endpoint writes only what is actually different about its stream
10
+ * — what it replays, what it forwards, what closes it.
11
+ */
12
+
13
+ /** h3's event object, as the header helpers accept it. */
14
+ type H3Event = Parameters<typeof setResponseHeader>[0]
15
+
16
+ const encoder = new TextEncoder()
17
+
18
+ /** One SSE frame. `id` lets a browser EventSource resume via Last-Event-ID. */
19
+ export function frame(data: unknown, opts?: { id?: number | string; event?: string }): Uint8Array {
20
+ const lines: string[] = []
21
+ if (opts?.id !== undefined) lines.push(`id: ${opts.id}`)
22
+ if (opts?.event !== undefined) lines.push(`event: ${opts.event}`)
23
+ lines.push(`data: ${JSON.stringify(data)}`)
24
+ return encoder.encode(lines.join("\n") + "\n\n")
25
+ }
26
+
27
+ /**
28
+ * Open an SSE response over a body stream.
29
+ *
30
+ * Sets the content-type/cache/connection headers on the h3 event, then copies
31
+ * everything h3 accumulated onto the returned Response — h3's header state and
32
+ * a web Response are two different places, and only the latter reaches the
33
+ * client.
34
+ */
35
+ export function sseResponse(event: H3Event, body: ReadableStream<Uint8Array>): Response {
36
+ setResponseHeader(event, "content-type", "text/event-stream")
37
+ setResponseHeader(event, "cache-control", "no-cache")
38
+ setResponseHeader(event, "connection", "keep-alive")
39
+
40
+ const headers: Record<string, string> = {}
41
+ for (const [key, value] of Object.entries(getResponseHeaders(event))) {
42
+ if (typeof value === "string") headers[key] = value
43
+ }
44
+ return new Response(body, { headers })
45
+ }
@@ -0,0 +1,186 @@
1
+ import type { setResponseHeader } from "h3"
2
+ import type { AxonEventView, AxonHandle, AxonSessionQuery } from "@arcforge/types"
3
+ import { classifyEvent } from "@arcforge/types"
4
+ import type { AxonBusT } from "../../platform"
5
+ import { frame, sseResponse } from "./sse"
6
+
7
+ /**
8
+ * Streams — the two live wires the runtime serves.
9
+ *
10
+ * `runStream` is request-scoped: it follows ONE wake and closes when that
11
+ * wake ends. `eventStream` is session-scoped: it carries everything happening
12
+ * in the session, including between turns. Both are SSE, and both are built
13
+ * here so the difference between them is the only thing either one states.
14
+ */
15
+
16
+ type H3Event = Parameters<typeof setResponseHeader>[0]
17
+
18
+ /** Anything carrying the ordering counter — i.e. a real enveloped event. */
19
+ type Sequenced = { time: { seq: number } }
20
+
21
+ /**
22
+ * An SSE comment, sent on an idle event stream to keep the connection open.
23
+ *
24
+ * A comment rather than an event on purpose: the spec says a line beginning
25
+ * `:` is ignored, so this is invisible to every consumer while still being
26
+ * bytes on the wire — which is the only thing an idle timeout measures.
27
+ * Inventing a `ping` event type instead would put a frame on the stream that
28
+ * every client had to learn to discard.
29
+ */
30
+ const HEARTBEAT = new TextEncoder().encode(": keepalive\n\n")
31
+
32
+ /**
33
+ * How often to send it. Comfortably inside Bun's 10s default idleTimeout,
34
+ * with room for a slow link — the cost is ~13 bytes per interval per attached
35
+ * client, against a reconnect loop if it is ever missed.
36
+ */
37
+ const HEARTBEAT_MS = 5_000
38
+
39
+ function isSequenced(payload: unknown): payload is Sequenced {
40
+ if (typeof payload !== "object" || payload === null) return false
41
+ const time = (payload as { time?: unknown }).time
42
+ return typeof time === "object" && time !== null && typeof (time as { seq?: unknown }).seq === "number"
43
+ }
44
+
45
+ /**
46
+ * Stream one wake's entries to the client.
47
+ *
48
+ * A terminal `event: done` frame closes the stream cleanly so the client knows
49
+ * the run finished rather than the socket dropping. A mid-stream failure emits
50
+ * an `event: error` frame before closing — the client must be able to tell
51
+ * "completed" from "broke".
52
+ */
53
+ export function runStream(event: H3Event, run: ReturnType<AxonHandle["stream"]>): Response {
54
+ const body = new ReadableStream<Uint8Array>({
55
+ async start(controller) {
56
+ try {
57
+ for await (const entry of run.stream) {
58
+ controller.enqueue(frame(entry))
59
+ }
60
+ controller.enqueue(frame({}, { event: "done" }))
61
+ } catch (cause) {
62
+ const message = cause instanceof Error ? cause.message : String(cause)
63
+ controller.enqueue(frame({ message }, { event: "error" }))
64
+ } finally {
65
+ controller.close()
66
+ }
67
+ },
68
+ cancel() {
69
+ // Client disconnected — cancel the underlying wake so the agent
70
+ // stops working on a response nobody is listening for.
71
+ run.interrupt()
72
+ },
73
+ })
74
+
75
+ return sseResponse(event, body)
76
+ }
77
+
78
+ type EventStreamOpts = {
79
+ bus: AxonBusT
80
+ session: AxonHandle["session"]
81
+ query: AxonSessionQuery
82
+ }
83
+
84
+ /**
85
+ * Bridge the runtime bus to SSE, replaying history first.
86
+ *
87
+ * Replay-then-live is what makes reconnection trivial: a client passes the
88
+ * cursor it already has, gets the gap from the session log, and continues into
89
+ * the live feed with no separate hydrate call and no window where events fall
90
+ * between the two. The subscription is attached BEFORE the replay is written,
91
+ * and live events arriving during replay are buffered rather than dropped —
92
+ * otherwise the gap this endpoint exists to close would reopen inside it.
93
+ *
94
+ * Every frame carries `id: <seq>`, so a browser's EventSource reconnect sends
95
+ * `Last-Event-ID` and resumes exactly where it left off for free.
96
+ */
97
+ export function eventStream(event: H3Event, opts: EventStreamOpts): Response {
98
+ const { bus, session, query } = opts
99
+ const { include, since } = query
100
+
101
+ function wanted(view: AxonEventView): boolean {
102
+ return include === undefined || include.includes(view)
103
+ }
104
+
105
+ let unsubscribe: (() => void) | null = null
106
+ let heartbeat: ReturnType<typeof setInterval> | null = null
107
+
108
+ const body = new ReadableStream<Uint8Array>({
109
+ start(controller) {
110
+ let live = false
111
+ const pending: Sequenced[] = []
112
+
113
+ // Subscribe first. Anything emitted while the replay is being
114
+ // written lands in `pending` and is flushed after it, in order.
115
+ unsubscribe = bus.onAny((type, payload) => {
116
+ if (!isSequenced(payload)) return // transient bus traffic with no envelope
117
+ if (!wanted(classifyEvent(type))) return
118
+ if (live) controller.enqueue(frame(payload, { id: payload.time.seq }))
119
+ else pending.push(payload)
120
+ })
121
+
122
+ const history = [
123
+ ...(wanted("entries") ? session.entries : []),
124
+ ...(wanted("log") ? session.log : []),
125
+ ...(wanted("kernelLog") ? session.kernelLog : []),
126
+ ]
127
+ .filter(item => since === undefined || item.time.seq > since)
128
+ .sort((a, b) => a.time.seq - b.time.seq)
129
+
130
+ const replay = query.limit !== undefined ? history.slice(-query.limit) : history
131
+ for (const item of replay) controller.enqueue(frame(item, { id: item.time.seq }))
132
+
133
+ // Tell the client where replay ended, so it can distinguish
134
+ // "caught up" from "still receiving history" — a UI showing a
135
+ // loading state needs that edge.
136
+ const cursor = replay.at(-1)?.time.seq ?? since ?? null
137
+ controller.enqueue(frame({ cursor }, { event: "live" }))
138
+
139
+ // Flush anything that arrived mid-replay, skipping what replay
140
+ // already covered, then go live.
141
+ const highWater = replay.at(-1)?.time.seq ?? -1
142
+ for (const item of pending) {
143
+ if (item.time.seq > highWater) controller.enqueue(frame(item, { id: item.time.seq }))
144
+ }
145
+ pending.length = 0
146
+ live = true
147
+
148
+ // ── Heartbeat ───────────────────────────────────────────────────
149
+ //
150
+ // An ambient event stream is IDLE most of the time — that is its
151
+ // normal state, not a fault. Nothing is emitted while a user reads
152
+ // the last answer, and Bun closes a connection that has sent
153
+ // nothing for its idleTimeout (10s by default), which surfaces
154
+ // server-side as "request timed out after 10 seconds".
155
+ //
156
+ // The client cannot tell that apart from the agent dying, so it
157
+ // reconnects, sits idle, and is cut off again — a reconnect loop
158
+ // on a perfectly healthy agent, every ten seconds, forever.
159
+ //
160
+ // An SSE COMMENT (`:` prefix) is the standard answer: it is bytes
161
+ // on the wire, which is all the timeout wants, and every SSE parser
162
+ // — including this repo's own parseFrames, which requires a
163
+ // `data:` line — ignores it. So no consumer sees a frame that is
164
+ // not an event, and none needed changing.
165
+ heartbeat = setInterval(() => {
166
+ try {
167
+ controller.enqueue(HEARTBEAT)
168
+ } catch {
169
+ // The stream is already closed (client gone, or cancel()
170
+ // raced this tick). Nothing to report — the timer is
171
+ // cleared below and the subscription with it.
172
+ if (heartbeat) clearInterval(heartbeat)
173
+ heartbeat = null
174
+ }
175
+ }, HEARTBEAT_MS)
176
+ },
177
+ cancel() {
178
+ unsubscribe?.()
179
+ unsubscribe = null
180
+ if (heartbeat) clearInterval(heartbeat)
181
+ heartbeat = null
182
+ },
183
+ })
184
+
185
+ return sseResponse(event, body)
186
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The scope a `.vue` / `.prompt` template renders in. Agent-authored
3
+ * templates are treated with the same scope as the rest of the agent's
4
+ * code — `axon` (the live runtime handle), the agent's tools, and
5
+ * `process.env` (the agent's resolved environment) are all in scope,
6
+ * exactly as they are in a tool or script.
7
+ *
8
+ * TOOLS ARE IN SCOPE, and the reason is worth stating because it used to be
9
+ * a boundary rather than a choice: cognet, kernel, tools, scripts and
10
+ * templates now share one heap, so a tool is a function call from here. A
11
+ * template composing real content — a board, a file, a search — should read
12
+ * it the same way every other piece of agent code does.
13
+ *
14
+ * The constraint is Vue's, not ours: a template interpolates VALUES, so
15
+ * async work belongs in `<script setup>`, which may use top-level `await`.
16
+ *
17
+ * ```vue
18
+ * <script setup lang="ts">
19
+ * const board = await fs.read("kanban/index.md")
20
+ * </script>
21
+ * <template><pre>{{ board }}</pre></template>
22
+ * ```
23
+ *
24
+ * `{{ fs.read("x") }}` in a template interpolates a Promise — which reaches
25
+ * the model as `[object Promise]`. See typegen's template lint, which is
26
+ * what catches that before a render ever happens.
27
+ *
28
+ * `process` is NOT shimmed. It is the agent's own process — the one the
29
+ * runtime already overlays the agent's declared `.env` onto (see the
30
+ * capsule's env application), so `process.env.MY_KEY` reads the keys given
31
+ * to this agent explicitly, alongside the ambient environment it needs.
32
+ * `process.run()` and `process.spawn()` are there too, exactly as they are
33
+ * in a script or a tool.
34
+ *
35
+ * It used to be a minimal `{ env }` shim here, which was correct only while
36
+ * templates rendered outside the agent's process and could not be trusted
37
+ * with the real one. In one heap that reasoning is gone, and the shim was
38
+ * the last thing making a prompt's scope differ from every other context's.
39
+ *
40
+ * The rest is read lazily off globalThis: the runtime handle is wired
41
+ * after the constructs that render templates exist, so it can't be captured
42
+ * by reference — by the time a template actually renders, inject.runtime()
43
+ * has fired and the global is live. Tools follow the same rule for a second
44
+ * reason: a reload rebuilds the handle and RETRACTS the previous namespaces
45
+ * (see installToolGlobals), so a context that captured them by value would
46
+ * hand templates namespaces that no longer exist.
47
+ */
48
+ export function promptContext(): Record<string, unknown> {
49
+ const axon = (globalThis as { axon?: { tools?: Record<string, unknown> } }).axon
50
+
51
+ // Namespaces only, never flattened members. A template's scope is built
52
+ // from the DECLARED tool surface, so a name here always says which
53
+ // module it came from — and cannot collide with a `<script setup>`
54
+ // binding the way a bare `read` would.
55
+ const tools: Record<string, unknown> = {}
56
+ for (const [namespace, members] of Object.entries(axon?.tools ?? {})) {
57
+ if (members && typeof members === "object") tools[namespace] = members
58
+ }
59
+
60
+ return {
61
+ ...tools,
62
+ axon: axon,
63
+ // After the spread: a tool namespace must not shadow the handle or
64
+ // the process, which every context is entitled to reach.
65
+ process: process,
66
+ }
67
+ }